From 1bd45642167b567f2890ba8854b93d5d3486c93a Mon Sep 17 00:00:00 2001 From: "Denis S. Soldatov aka General-Beck" Date: Mon, 4 Mar 2019 21:59:20 +0300 Subject: [PATCH 01/27] CI publish to aws (#10446) * move publish aws from gitlab.yml to gitlab scripts * gitlab.yml cleaning move publish AWS to gitlab scripts remove dependencies from android build --- .gitlab-ci.yml | 15 ++------------- scripts/gitlab/publish-aws.sh | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 13 deletions(-) create mode 100755 scripts/gitlab/publish-aws.sh diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 73dbf5ce07c..71019c387f0 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -176,19 +176,7 @@ publish-awss3-release: - build-darwin - build-windows script: - - echo "__________Push binaries to AWS S3____________" - - case "${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" in - (beta|stable|nightly) - export BUCKET=releases.parity.io/ethereum; - ;; - (*) - export BUCKET=builds-parity; - ;; - esac - - aws s3 sync ./artifacts s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ - after_script: - - aws s3 ls s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ - --recursive --human-readable --summarize + - scripts/gitlab/publish-aws.sh tags: - linux-docker @@ -209,6 +197,7 @@ build-android: image: parity/rust-android:gitlab-ci variables: CARGO_TARGET: armv7-linux-androideabi + dependencies: script: - scripts/gitlab/build-unix.sh tags: diff --git a/scripts/gitlab/publish-aws.sh b/scripts/gitlab/publish-aws.sh new file mode 100755 index 00000000000..395a3bd777f --- /dev/null +++ b/scripts/gitlab/publish-aws.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -e # fail on any error +set -u # treat unset variables as error + +echo "__________Push binaries to AWS S3____________" +case "${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" in + (beta|stable|nightly) + export BUCKET=releases.parity.io/ethereum; + ;; + (*) + export BUCKET=builds-parity; + ;; + esac +aws s3 sync ./artifacts s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ +echo "__________Read from S3____________" +aws s3 ls s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ + --recursive --human-readable --summarize From 701464281554adf9ceb14709b221e17d0301f60a Mon Sep 17 00:00:00 2001 From: Axel Chalon Date: Mon, 4 Mar 2019 20:24:53 +0100 Subject: [PATCH 02/27] Implement parity_versionInfo & parity_setChain on LC; fix parity_setChain (#10312) * Light client: implement parity_versionInfo RPC * Light client: implement set_exit_handler & parity_setChain RPC * parity_setChain RPC: return an error if failed (instead of `true`) * Implement eth_subscribe('syncing') RPC for full node & light node * Fix indentation * Revert commit: Implement eth_subscribe('syncing') * Revert change to Cr callback function --- ethcore/light/src/client/mod.rs | 25 +++++++++++++++++++++++++ ethcore/src/client/client.rs | 6 ++++-- ethcore/src/client/test_client.rs | 2 +- ethcore/src/client/traits.rs | 2 +- parity/rpc_apis.rs | 2 +- parity/run.rs | 8 ++++++-- rpc/src/v1/helpers/errors.rs | 9 +++++++++ rpc/src/v1/impls/light/parity.rs | 5 +++-- rpc/src/v1/impls/light/parity_set.rs | 9 ++++++--- rpc/src/v1/impls/parity_set.rs | 5 ++--- 10 files changed, 58 insertions(+), 15 deletions(-) diff --git a/ethcore/light/src/client/mod.rs b/ethcore/light/src/client/mod.rs index 90ebba39aa2..8205ae2ab3b 100644 --- a/ethcore/light/src/client/mod.rs +++ b/ethcore/light/src/client/mod.rs @@ -116,6 +116,9 @@ pub trait LightChainClient: Send + Sync { /// Query whether a block is known. fn is_known(&self, hash: &H256) -> bool; + /// Set the chain via a spec name. + fn set_spec_name(&self, new_spec_name: String) -> Result<(), ()>; + /// Clear the queue. fn clear_queue(&self); @@ -164,6 +167,8 @@ pub struct Client { listeners: RwLock>>, fetcher: T, verify_full: bool, + /// A closure to call when we want to restart the client + exit_handler: Mutex>>, } impl Client { @@ -190,6 +195,7 @@ impl Client { listeners: RwLock::new(vec![]), fetcher, verify_full: config.verify_full, + exit_handler: Mutex::new(None), }) } @@ -360,6 +366,14 @@ impl Client { self.chain.heap_size_of_children() } + /// Set a closure to call when the client wants to be restarted. + /// + /// The parameter passed to the callback is the name of the new chain spec to use after + /// the restart. + pub fn set_exit_handler(&self, f: F) where F: Fn(String) + 'static + Send { + *self.exit_handler.lock() = Some(Box::new(f)); + } + /// Get a handle to the verification engine. pub fn engine(&self) -> &Arc { &self.engine @@ -563,6 +577,17 @@ impl LightChainClient for Client { Client::engine(self) } + fn set_spec_name(&self, new_spec_name: String) -> Result<(), ()> { + trace!(target: "mode", "Client::set_spec_name({:?})", new_spec_name); + if let Some(ref h) = *self.exit_handler.lock() { + (*h)(new_spec_name); + Ok(()) + } else { + warn!("Not hypervised; cannot change chain."); + Err(()) + } + } + fn is_known(&self, hash: &H256) -> bool { self.status(hash) == BlockStatus::InChain } diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index d40fc30330a..0be48a636e6 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -1706,15 +1706,17 @@ impl BlockChainClient for Client { self.config.spec_name.clone() } - fn set_spec_name(&self, new_spec_name: String) { + fn set_spec_name(&self, new_spec_name: String) -> Result<(), ()> { trace!(target: "mode", "Client::set_spec_name({:?})", new_spec_name); if !self.enabled.load(AtomicOrdering::Relaxed) { - return; + return Err(()); } if let Some(ref h) = *self.exit_handler.lock() { (*h)(new_spec_name); + Ok(()) } else { warn!("Not hypervised; cannot change chain."); + Err(()) } } diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 5236f7cd409..fbad806fdff 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -863,7 +863,7 @@ impl BlockChainClient for TestBlockChainClient { fn spec_name(&self) -> String { "foundation".into() } - fn set_spec_name(&self, _: String) { unimplemented!(); } + fn set_spec_name(&self, _: String) -> Result<(), ()> { unimplemented!(); } fn disable(&self) { self.disabled.store(true, AtomicOrder::Relaxed); } diff --git a/ethcore/src/client/traits.rs b/ethcore/src/client/traits.rs index 2bc7026220d..8e4abc01cde 100644 --- a/ethcore/src/client/traits.rs +++ b/ethcore/src/client/traits.rs @@ -360,7 +360,7 @@ pub trait BlockChainClient : Sync + Send + AccountData + BlockChain + CallContra fn spec_name(&self) -> String; /// Set the chain via a spec name. - fn set_spec_name(&self, spec_name: String); + fn set_spec_name(&self, spec_name: String) -> Result<(), ()>; /// Disable the client from importing blocks. This cannot be undone in this session and indicates /// that a subsystem has reason to believe this executable incapable of syncing the chain. diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index 4413e6a779a..9287f62720b 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -634,7 +634,7 @@ impl LightDependencies { handler.extend_with(ParityAccounts::to_delegate(ParityAccountsClient::new(&self.accounts))); } Api::ParitySet => handler.extend_with( - light::ParitySetClient::new(self.sync.clone(), self.fetch.clone()) + light::ParitySetClient::new(self.client.clone(), self.sync.clone(), self.fetch.clone()) .to_delegate(), ), Api::Traces => handler.extend_with(light::TracesClient.to_delegate()), diff --git a/parity/run.rs b/parity/run.rs index 13e93c1e215..c4a3c75120e 100644 --- a/parity/run.rs +++ b/parity/run.rs @@ -165,7 +165,9 @@ impl ::local_store::NodeInfo for FullNodeInfo { type LightClient = ::light::client::Client<::light_helpers::EpochFetch>; // helper for light execution. -fn execute_light_impl(cmd: RunCmd, logger: Arc) -> Result { +fn execute_light_impl(cmd: RunCmd, logger: Arc, on_client_rq: Cr) -> Result + where Cr: Fn(String) + 'static + Send +{ use light::client as light_client; use sync::{LightSyncParams, LightSync, ManageNetwork}; use parking_lot::{Mutex, RwLock}; @@ -367,6 +369,8 @@ fn execute_light_impl(cmd: RunCmd, logger: Arc) -> Result(cmd: RunCmd, logger: Arc, Rr: Fn() + 'static + Send { if cmd.light { - execute_light_impl(cmd, logger) + execute_light_impl(cmd, logger, on_client_rq) } else { execute_impl(cmd, logger, on_client_rq, on_updater_rq) } diff --git a/rpc/src/v1/helpers/errors.rs b/rpc/src/v1/helpers/errors.rs index eebd76dbe3c..1ff40f979b7 100644 --- a/rpc/src/v1/helpers/errors.rs +++ b/rpc/src/v1/helpers/errors.rs @@ -59,6 +59,7 @@ mod codes { pub const NO_PEERS: i64 = -32066; pub const DEPRECATED: i64 = -32070; pub const EXPERIMENTAL_RPC: i64 = -32071; + pub const CANNOT_RESTART: i64 = -32080; } pub fn unimplemented(details: Option) -> Error { @@ -125,6 +126,14 @@ pub fn account(error: &str, details: T) -> Error { } } +pub fn cannot_restart() -> Error { + Error { + code: ErrorCode::ServerError(codes::CANNOT_RESTART), + message: "Parity could not be restarted. This feature is disabled in development mode and if the binary name isn't parity.".into(), + data: None, + } +} + /// Internal error signifying a logic error in code. /// Should not be used when function can just fail /// because of invalid parameters or incomplete node state. diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index da7425e1f4c..24dba420e4a 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -24,6 +24,7 @@ use crypto::DEFAULT_MAC; use ethkey::{crypto::ecies, Brain, Generator}; use ethstore::random_phrase; use sync::{LightSyncInfo, LightSyncProvider, LightNetworkDispatcher, ManageNetwork}; +use updater::VersionInfo as UpdaterVersionInfo; use ethereum_types::{H64, H160, H256, H512, U64, U256}; use ethcore_logger::RotatingLogger; @@ -299,7 +300,7 @@ where } fn version_info(&self) -> Result { - Err(errors::light_unimplemented(None)) + Ok(UpdaterVersionInfo::this().into()) } fn releases_info(&self) -> Result> { @@ -389,7 +390,7 @@ where } fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture> { - let filter = match filter.try_into() { + let filter = match filter.try_into() { Ok(value) => value, Err(err) => return Box::new(future::err(err)), }; diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index 080e9402a1b..f129f86b3c9 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -23,6 +23,7 @@ use std::sync::Arc; use ethereum_types::{H160, H256, U256}; use fetch::{self, Fetch}; use hash::keccak_buffer; +use light::client::LightChainClient; use sync::ManageNetwork; use jsonrpc_core::{Result, BoxFuture}; @@ -33,14 +34,16 @@ use v1::types::{Bytes, ReleaseInfo, Transaction}; /// Parity-specific rpc interface for operations altering the settings. pub struct ParitySetClient { + client: Arc, net: Arc, fetch: F, } impl ParitySetClient { /// Creates new `ParitySetClient` with given `Fetch`. - pub fn new(net: Arc, fetch: F) -> Self { + pub fn new(client: Arc, net: Arc, fetch: F) -> Self { ParitySetClient { + client: client, net: net, fetch: fetch, } @@ -118,8 +121,8 @@ impl ParitySet for ParitySetClient { Err(errors::light_unimplemented(None)) } - fn set_spec_name(&self, _spec_name: String) -> Result { - Err(errors::light_unimplemented(None)) + fn set_spec_name(&self, spec_name: String) -> Result { + self.client.set_spec_name(spec_name).map(|_| true).map_err(|()| errors::cannot_restart()) } fn hash_content(&self, url: String) -> BoxFuture { diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index a50138eb19d..16ef8d54327 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -211,8 +211,7 @@ impl ParitySet for ParitySetClient where } fn set_spec_name(&self, spec_name: String) -> Result { - self.client.set_spec_name(spec_name); - Ok(true) + self.client.set_spec_name(spec_name).map(|_| true).map_err(|()| errors::cannot_restart()) } fn hash_content(&self, url: String) -> BoxFuture { @@ -240,7 +239,7 @@ impl ParitySet for ParitySetClient where let hash = hash.into(); Ok(self.miner.remove_transaction(&hash) - .map(|t| Transaction::from_pending(t.pending().clone())) + .map(|t| Transaction::from_pending(t.pending().clone())) ) } } From 3e1d73126c41779e36a05383a4278822ccc6023a Mon Sep 17 00:00:00 2001 From: "Denis S. Soldatov aka General-Beck" Date: Tue, 5 Mar 2019 20:33:10 +0300 Subject: [PATCH 03/27] CI aws git checkout (#10451) * Updating the CI system with the publication of releases and binary files on github Signed-off-by: Denis S. Soldatov aka General-Beck * move publish aws from gitlab.yml to gitlab scripts Signed-off-by: Denis S. Soldatov aka General-Beck * gitlab.yml cleaning move publish AWS to gitlab scripts remove dependencies from android build Signed-off-by: Denis S. Soldatov aka General-Beck * Revert "Updating the CI system with the publication of releases and binary files on github" This reverts commit da87e06f2e4751dbca08a898b52926aef5ad0aba. * remove no-git for aws * microfix * no need in no_git then --- .gitlab-ci.yml | 10 ++-------- scripts/gitlab/publish-aws.sh | 4 ++-- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 71019c387f0..579d0463725 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -12,11 +12,6 @@ variables: CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" CARGO_TARGET: x86_64-unknown-linux-gnu -.no_git: &no_git - variables: - GIT_STRATEGY: none - GIT_SUBMODULE_STRATEGY: none - .releaseable_branches: # list of git refs for building GitLab artifacts (think "pre-release binaries") only: &releaseable_branches @@ -102,7 +97,7 @@ build-windows: script: - sh scripts/gitlab/build-windows.sh tags: - - rust-windows + - rust-windows <<: *collect_artifacts publish-docker: @@ -169,7 +164,6 @@ publish-awss3-release: image: parity/awscli:latest stage: publish only: *releaseable_branches - <<: *no_git cache: {} dependencies: - build-linux @@ -197,7 +191,7 @@ build-android: image: parity/rust-android:gitlab-ci variables: CARGO_TARGET: armv7-linux-androideabi - dependencies: + dependencies: [] script: - scripts/gitlab/build-unix.sh tags: diff --git a/scripts/gitlab/publish-aws.sh b/scripts/gitlab/publish-aws.sh index 395a3bd777f..56572657bd3 100755 --- a/scripts/gitlab/publish-aws.sh +++ b/scripts/gitlab/publish-aws.sh @@ -6,10 +6,10 @@ set -u # treat unset variables as error echo "__________Push binaries to AWS S3____________" case "${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" in (beta|stable|nightly) - export BUCKET=releases.parity.io/ethereum; + BUCKET=releases.parity.io/ethereum; ;; (*) - export BUCKET=builds-parity; + BUCKET=builds-parity; ;; esac aws s3 sync ./artifacts s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ From 91933d857da2d30692276ad3a3b043067c3ff568 Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Wed, 6 Mar 2019 15:30:35 +0100 Subject: [PATCH 04/27] perf(ethcore): `micro-opt` (#10405) Mostly fixes that changes `eagerly eval` to `lazy eval` --- ethcore/light/src/on_demand/mod.rs | 6 +----- ethcore/src/client/client.rs | 2 +- ethcore/src/engines/authority_round/mod.rs | 24 ++++++++++++++------- ethcore/src/engines/validator_set/multi.rs | 4 ++-- ethcore/src/error.rs | 4 ++-- ethcore/src/executed.rs | 2 +- ethcore/src/externalities.rs | 2 +- ethcore/src/machine.rs | 2 +- ethcore/src/snapshot/consensus/authority.rs | 6 +++--- ethcore/src/snapshot/consensus/work.rs | 4 ++-- ethcore/src/snapshot/mod.rs | 4 ++-- ethcore/src/spec/spec.rs | 2 +- ethcore/src/state/mod.rs | 8 +++---- ethcore/src/verification/verification.rs | 2 +- ethcore/types/src/ids.rs | 2 +- 15 files changed, 39 insertions(+), 35 deletions(-) diff --git a/ethcore/light/src/on_demand/mod.rs b/ethcore/light/src/on_demand/mod.rs index 609868ecb45..c04c687947a 100644 --- a/ethcore/light/src/on_demand/mod.rs +++ b/ethcore/light/src/on_demand/mod.rs @@ -24,7 +24,6 @@ use std::marker::PhantomData; use std::sync::Arc; use std::time::Duration; -use ethcore::executed::{Executed, ExecutionError}; use futures::{Poll, Future, Async}; use futures::sync::oneshot::{self, Receiver}; use network::PeerId; @@ -41,10 +40,10 @@ use cache::Cache; use request::{self as basic_request, Request as NetworkRequest}; use self::request::CheckedRequest; +pub use ethcore::executed::ExecutionResult; pub use self::request::{Request, Response, HeaderRef, Error as ValidityError}; pub use self::request_guard::{RequestGuard, Error as RequestError}; pub use self::response_guard::{ResponseGuard, Error as ResponseGuardError, Inner as ResponseGuardInner}; - pub use types::request::ResponseError; #[cfg(test)] @@ -54,9 +53,6 @@ pub mod request; mod request_guard; mod response_guard; -/// The result of execution -pub type ExecutionResult = Result; - /// The initial backoff interval for OnDemand queries pub const DEFAULT_REQUEST_MIN_BACKOFF_DURATION: Duration = Duration::from_secs(10); /// The maximum request interval for OnDemand queries diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 0be48a636e6..9eab30f3420 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -1149,7 +1149,7 @@ impl Client { pub fn take_snapshot(&self, writer: W, at: BlockId, p: &snapshot::Progress) -> Result<(), EthcoreError> { let db = self.state_db.read().journal_db().boxed_clone(); let best_block_number = self.chain_info().best_block_number; - let block_number = self.block_number(at).ok_or(snapshot::Error::InvalidStartingBlock(at))?; + let block_number = self.block_number(at).ok_or_else(|| snapshot::Error::InvalidStartingBlock(at))?; if db.is_pruned() && self.pruning_info().earliest_state > block_number { return Err(snapshot::Error::OldBlockPrunedDB.into()); diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index 2a42acfe23f..ef439b5d4ba 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -512,15 +512,19 @@ fn header_expected_seal_fields(header: &Header, empty_steps_transition: u64) -> } fn header_step(header: &Header, empty_steps_transition: u64) -> Result { - let expected_seal_fields = header_expected_seal_fields(header, empty_steps_transition); - Rlp::new(&header.seal().get(0).expect( - &format!("was either checked with verify_block_basic or is genesis; has {} fields; qed (Make sure the spec file has a correct genesis seal)", expected_seal_fields))).as_val() + Rlp::new(&header.seal().get(0).unwrap_or_else(|| + panic!("was either checked with verify_block_basic or is genesis; has {} fields; qed (Make sure the spec + file has a correct genesis seal)", header_expected_seal_fields(header, empty_steps_transition)) + )) + .as_val() } fn header_signature(header: &Header, empty_steps_transition: u64) -> Result { - let expected_seal_fields = header_expected_seal_fields(header, empty_steps_transition); - Rlp::new(&header.seal().get(1).expect( - &format!("was checked with verify_block_basic; has {} fields; qed", expected_seal_fields))).as_val::().map(Into::into) + Rlp::new(&header.seal().get(1).unwrap_or_else(|| + panic!("was checked with verify_block_basic; has {} fields; qed", + header_expected_seal_fields(header, empty_steps_transition)) + )) + .as_val::().map(Into::into) } // extracts the raw empty steps vec from the header seal. should only be called when there are 3 fields in the seal @@ -934,8 +938,12 @@ impl Engine for AuthorityRound { return BTreeMap::default(); } - let step = header_step(header, self.empty_steps_transition).as_ref().map(ToString::to_string).unwrap_or("".into()); - let signature = header_signature(header, self.empty_steps_transition).as_ref().map(ToString::to_string).unwrap_or("".into()); + let step = header_step(header, self.empty_steps_transition).as_ref() + .map(ToString::to_string) + .unwrap_or_default(); + let signature = header_signature(header, self.empty_steps_transition).as_ref() + .map(ToString::to_string) + .unwrap_or_default(); let mut info = map![ "step".into() => step, diff --git a/ethcore/src/engines/validator_set/multi.rs b/ethcore/src/engines/validator_set/multi.rs index 8aa7aa3deed..b9ef6774784 100644 --- a/ethcore/src/engines/validator_set/multi.rs +++ b/ethcore/src/engines/validator_set/multi.rs @@ -74,7 +74,7 @@ impl Multi { impl ValidatorSet for Multi { fn default_caller(&self, block_id: BlockId) -> Box { self.correct_set(block_id).map(|set| set.default_caller(block_id)) - .unwrap_or(Box::new(|_, _| Err("No validator set for given ID.".into()))) + .unwrap_or_else(|| Box::new(|_, _| Err("No validator set for given ID.".into()))) } fn on_epoch_begin(&self, _first: bool, header: &Header, call: &mut SystemCall) -> Result<(), ::error::Error> { @@ -141,7 +141,7 @@ impl ValidatorSet for Multi { *self.block_number.write() = Box::new(move |id| client .upgrade() .ok_or_else(|| "No client!".into()) - .and_then(|c| c.block_number(id).ok_or("Unknown block".into()))); + .and_then(|c| c.block_number(id).ok_or_else(|| "Unknown block".into()))); } } diff --git a/ethcore/src/error.rs b/ethcore/src/error.rs index c3ffc904386..d5aa45ba0ef 100644 --- a/ethcore/src/error.rs +++ b/ethcore/src/error.rs @@ -37,7 +37,7 @@ use engines::EngineError; pub use executed::{ExecutionError, CallError}; -#[derive(Debug, PartialEq, Clone, Copy, Eq)] +#[derive(Debug, PartialEq, Clone, Eq)] /// Errors concerning block processing. pub enum BlockError { /// Block has too many uncles. @@ -88,7 +88,7 @@ pub enum BlockError { /// Timestamp header field is too far in future. TemporarilyInvalid(OutOfBounds), /// Log bloom header field is invalid. - InvalidLogBloom(Mismatch), + InvalidLogBloom(Box>), /// Number field of header is invalid. InvalidNumber(Mismatch), /// Block number isn't sensible. diff --git a/ethcore/src/executed.rs b/ethcore/src/executed.rs index f9be002ff85..0f46ee1decd 100644 --- a/ethcore/src/executed.rs +++ b/ethcore/src/executed.rs @@ -197,4 +197,4 @@ impl fmt::Display for CallError { } /// Transaction execution result. -pub type ExecutionResult = Result; +pub type ExecutionResult = Result, ExecutionError>; diff --git a/ethcore/src/externalities.rs b/ethcore/src/externalities.rs index a2f35b6ded8..23a4a83c3d1 100644 --- a/ethcore/src/externalities.rs +++ b/ethcore/src/externalities.rs @@ -117,7 +117,7 @@ impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B> { fn initial_storage_at(&self, key: &H256) -> vm::Result { if self.state.is_base_storage_root_unchanged(&self.origin_info.address)? { - self.state.checkpoint_storage_at(0, &self.origin_info.address, key).map(|v| v.unwrap_or(H256::zero())).map_err(Into::into) + self.state.checkpoint_storage_at(0, &self.origin_info.address, key).map(|v| v.unwrap_or_default()).map_err(Into::into) } else { warn!(target: "externalities", "Detected existing account {:#x} where a forced contract creation happened.", self.origin_info.address); Ok(H256::zero()) diff --git a/ethcore/src/machine.rs b/ethcore/src/machine.rs index a14cb3bd296..c0eae63d1e1 100644 --- a/ethcore/src/machine.rs +++ b/ethcore/src/machine.rs @@ -173,7 +173,7 @@ impl EthereumMachine { origin: SYSTEM_ADDRESS, gas, gas_price: 0.into(), - value: value.unwrap_or(ActionValue::Transfer(0.into())), + value: value.unwrap_or_else(|| ActionValue::Transfer(0.into())), code, code_hash, data, diff --git a/ethcore/src/snapshot/consensus/authority.rs b/ethcore/src/snapshot/consensus/authority.rs index 909e00281c2..4423e074019 100644 --- a/ethcore/src/snapshot/consensus/authority.rs +++ b/ethcore/src/snapshot/consensus/authority.rs @@ -76,7 +76,7 @@ impl SnapshotComponents for PoaSnapshot { } let header = chain.block_header_data(&transition.block_hash) - .ok_or(Error::BlockNotFound(transition.block_hash))?; + .ok_or_else(|| Error::BlockNotFound(transition.block_hash))?; let entry = { let mut entry_stream = RlpStream::new_list(2); @@ -101,12 +101,12 @@ impl SnapshotComponents for PoaSnapshot { let (block, receipts) = chain.block(&block_at) .and_then(|b| chain.block_receipts(&block_at).map(|r| (b, r))) - .ok_or(Error::BlockNotFound(block_at))?; + .ok_or_else(|| Error::BlockNotFound(block_at))?; let block = block.decode()?; let parent_td = chain.block_details(block.header.parent_hash()) .map(|d| d.total_difficulty) - .ok_or(Error::BlockNotFound(block_at))?; + .ok_or_else(|| Error::BlockNotFound(block_at))?; rlps.push({ let mut stream = RlpStream::new_list(5); diff --git a/ethcore/src/snapshot/consensus/work.rs b/ethcore/src/snapshot/consensus/work.rs index 0293d1a2fd4..106fe4474c0 100644 --- a/ethcore/src/snapshot/consensus/work.rs +++ b/ethcore/src/snapshot/consensus/work.rs @@ -116,7 +116,7 @@ impl<'a> PowWorker<'a> { let (block, receipts) = self.chain.block(&self.current_hash) .and_then(|b| self.chain.block_receipts(&self.current_hash).map(|r| (b, r))) - .ok_or(Error::BlockNotFound(self.current_hash))?; + .ok_or_else(|| Error::BlockNotFound(self.current_hash))?; let abridged_rlp = AbridgedBlock::from_block_view(&block.view()).into_inner(); @@ -160,7 +160,7 @@ impl<'a> PowWorker<'a> { let (last_header, last_details) = self.chain.block_header_data(&last) .and_then(|n| self.chain.block_details(&last).map(|d| (n, d))) - .ok_or(Error::BlockNotFound(last))?; + .ok_or_else(|| Error::BlockNotFound(last))?; let parent_number = last_header.number() - 1; let parent_hash = last_header.parent_hash(); diff --git a/ethcore/src/snapshot/mod.rs b/ethcore/src/snapshot/mod.rs index c05d0de6a3a..19a5f8ce6e0 100644 --- a/ethcore/src/snapshot/mod.rs +++ b/ethcore/src/snapshot/mod.rs @@ -157,7 +157,7 @@ pub fn take_snapshot( processing_threads: usize, ) -> Result<(), Error> { let start_header = chain.block_header_data(&block_at) - .ok_or(Error::InvalidStartingBlock(BlockId::Hash(block_at)))?; + .ok_or_else(|| Error::InvalidStartingBlock(BlockId::Hash(block_at)))?; let state_root = start_header.state_root(); let number = start_header.number(); @@ -512,7 +512,7 @@ fn rebuild_accounts( // fill out the storage trie and code while decoding. let (acc, maybe_code) = { let mut acct_db = AccountDBMut::from_hash(db, hash); - let storage_root = known_storage_roots.get(&hash).cloned().unwrap_or(H256::zero()); + let storage_root = known_storage_roots.get(&hash).cloned().unwrap_or_default(); account::from_fat_rlp(&mut acct_db, fat_rlp, storage_root)? }; diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 4bd46b2bb63..2726ed4fd52 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -515,7 +515,7 @@ fn load_from(spec_params: SpecParams, s: ethjson::spec::Spec) -> Result), } #[derive(Eq, PartialEq, Clone, Copy, Debug)] @@ -218,7 +218,7 @@ pub fn check_proof( let options = TransactOptions::with_no_tracing().save_output_from_contract(); match state.execute(env_info, machine, transaction, options, true) { - Ok(executed) => ProvedExecution::Complete(executed), + Ok(executed) => ProvedExecution::Complete(Box::new(executed)), Err(ExecutionError::Internal(_)) => ProvedExecution::BadProof, Err(e) => ProvedExecution::Failed(e), } @@ -1254,7 +1254,7 @@ impl State { let trie = TrieDB::new(db, &self.root)?; let maybe_account: Option = { let panicky_decoder = |bytes: &[u8]| { - ::rlp::decode(bytes).expect(&format!("prove_account, could not query trie for account key={}", &account_key)) + ::rlp::decode(bytes).unwrap_or_else(|_| panic!("prove_account, could not query trie for account key={}", &account_key)) }; let query = (&mut recorder, panicky_decoder); trie.get_with(&account_key, query)? diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 3f5008a2b86..2ce9f9de304 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -274,7 +274,7 @@ pub fn verify_block_final(expected: &Header, got: &Header) -> Result<(), Error> return Err(From::from(BlockError::InvalidGasUsed(Mismatch { expected: *expected.gas_used(), found: *got.gas_used() }))) } if expected.log_bloom() != got.log_bloom() { - return Err(From::from(BlockError::InvalidLogBloom(Mismatch { expected: *expected.log_bloom(), found: *got.log_bloom() }))) + return Err(From::from(BlockError::InvalidLogBloom(Box::new(Mismatch { expected: *expected.log_bloom(), found: *got.log_bloom() })))) } if expected.receipts_root() != got.receipts_root() { return Err(From::from(BlockError::InvalidReceiptsRoot(Mismatch { expected: *expected.receipts_root(), found: *got.receipts_root() }))) diff --git a/ethcore/types/src/ids.rs b/ethcore/types/src/ids.rs index dccb240d94b..1f099be57da 100644 --- a/ethcore/types/src/ids.rs +++ b/ethcore/types/src/ids.rs @@ -17,7 +17,7 @@ //! Unique identifiers. use ethereum_types::H256; -use {BlockNumber}; +use BlockNumber; /// Uniquely identifies block. #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] From 742a6007fec36b053c802debf89dd114c5be6840 Mon Sep 17 00:00:00 2001 From: "Denis S. Soldatov aka General-Beck" Date: Thu, 7 Mar 2019 14:45:35 +0300 Subject: [PATCH 05/27] Revert "CI aws git checkout (#10451)" (#10456) * Revert "CI aws git checkout (#10451)" This reverts commit 3e1d73126c41779e36a05383a4278822ccc6023a. * Update .gitlab-ci.yml revert aws script with small fixes * Delete publish-aws.sh --- .gitlab-ci.yml | 20 ++++++++++++++++++-- scripts/gitlab/publish-aws.sh | 18 ------------------ 2 files changed, 18 insertions(+), 20 deletions(-) delete mode 100755 scripts/gitlab/publish-aws.sh diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 579d0463725..19885642338 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -12,6 +12,10 @@ variables: CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" CARGO_TARGET: x86_64-unknown-linux-gnu +.no_git: &no_git #disable git strategy + variables: + GIT_STRATEGY: none + GIT_SUBMODULE_STRATEGY: none .releaseable_branches: # list of git refs for building GitLab artifacts (think "pre-release binaries") only: &releaseable_branches @@ -21,7 +25,7 @@ variables: - schedules -.collect_artifacts: &collect_artifacts +.collect_artifacts: &collect_artifacts artifacts: name: "${CI_JOB_NAME}_${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" when: on_success @@ -164,13 +168,25 @@ publish-awss3-release: image: parity/awscli:latest stage: publish only: *releaseable_branches + <<: *no_git cache: {} dependencies: - build-linux - build-darwin - build-windows script: - - scripts/gitlab/publish-aws.sh + - echo "__________Push binaries to AWS S3____________" + - case "${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" in + (beta|stable|nightly) + export BUCKET=releases.parity.io/ethereum; + ;; + (*) + export BUCKET=builds-parity; + ;; + esac + - aws s3 sync ./artifacts s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ + - echo "__________Read from S3____________" + - aws s3 ls s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}} --recursive --human-readable --summarize tags: - linux-docker diff --git a/scripts/gitlab/publish-aws.sh b/scripts/gitlab/publish-aws.sh deleted file mode 100755 index 56572657bd3..00000000000 --- a/scripts/gitlab/publish-aws.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -set -e # fail on any error -set -u # treat unset variables as error - -echo "__________Push binaries to AWS S3____________" -case "${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" in - (beta|stable|nightly) - BUCKET=releases.parity.io/ethereum; - ;; - (*) - BUCKET=builds-parity; - ;; - esac -aws s3 sync ./artifacts s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ -echo "__________Read from S3____________" -aws s3 ls s3://${BUCKET}/${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}/ - --recursive --human-readable --summarize From ab27848dc473023d84af819df6812e11e7da9576 Mon Sep 17 00:00:00 2001 From: 5chdn <5chdn@users.noreply.github.com> Date: Thu, 7 Mar 2019 21:11:58 +0100 Subject: [PATCH 06/27] docs: update changelogs for 2.2.{8,9,10,11}, 2.3.{1,2,3,4,5}, and 2.4.0 (#10389) * docs: move changelog 2-3 to docs/ * docs: fix changelog 2-3 path * docs: add changelogs for 2.2.{8,9,10,11} * docs: add changelogs for 2.3.{1,2,3,4} * Update CHANGELOG.md * Update CHANGELOG-2.3.md * Update CHANGELOG.md * Update CHANGELOG.md --- CHANGELOG.md | 260 ++++++++++++++++++------------------------ docs/CHANGELOG-2.2.md | 75 ++++++++++++ docs/CHANGELOG-2.3.md | 255 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 438 insertions(+), 152 deletions(-) create mode 100644 docs/CHANGELOG-2.3.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 62119ce7ab1..1ef1c68399d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,162 +1,118 @@ -## Parity-Ethereum [v2.3.0](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.0) (2019-01-16) +## Parity-Ethereum [v2.4.0](https://github.com/paritytech/parity-ethereum/releases/tag/v2.4.0) (2019-02-25) -Parity-Ethereum 2.3.0-beta is a consensus-relevant security release that reverts Constantinople on the Ethereum network. Upgrading is mandatory for Ethereum, and strongly recommended for other networks. +Parity-Ethereum 2.4.0-beta is our trifortnightly minor version release coming with a lot of new features as well as bugfixes and performance improvements. -- **Consensus** - Ethereum Network: Pull Constantinople protocol upgrade on Ethereum (#10189) - - Read more: [Security Alert: Ethereum Constantinople Postponement](https://blog.ethereum.org/2019/01/15/security-alert-ethereum-constantinople-postponement/) -- **Networking** - All networks: Ping nodes from discovery (#10167) -- **Wasm** - Kovan Network: Update pwasm-utils to 0.6.1 (#10134) - -Other notable changes: - -- Existing blocks in the database are now kept when restoring a Snapshot. (#8643) -- Block and transaction propagation is improved significantly. (#9954) -- The ERC-191 Signed Data Standard is now supported by `personal_sign191`. (#9701) -- Add support for ERC-191/712 `eth_signTypedData` as a standard for machine-verifiable and human-readable typed data signing with Ethereum keys. (#9631) -- Add support for ERC-1186 `eth_getProof` (#9001) -- Add experimental RPCs flag to enable ERC-191, ERC-712, and ERC-1186 APIs via `--jsonrpc-experimental` (#9928) -- Make `CALLCODE` to trace value to be the code address. (#9881) - -Configuration changes: - -- The EIP-98 transition is now disabled by default. If you previously had no `eip98transition` specified in your chain specification, you would enable this now manually on block `0x0`. (#9955) -- Also, unknown fields in chain specs are now rejected. (#9972) -- The Tendermint engine was removed from Parity Ethereum and is no longer available and maintained. (#9980) -- Ropsten testnet data and keys moved from `test/` to `ropsten/` subdir. To reuse your old keys and data either copy or symlink them to the new location. (#10123) -- Strict empty steps validation (#10041) - - If you have a chain with`empty_steps` already running, some blocks most likely contain non-strict entries (unordered or duplicated empty steps). In this release `strict_empty_steps_transition` is enabled by default at block `0x0` for any chain with `empty_steps`. - - If your network uses `empty_steps` you **must** (A) plan a hard fork and change `strict_empty_steps_transition` to the desired fork block and (B) update the clients of the whole network to 2.2.7-stable / 2.3.0-beta. If for some reason you don't want to do this please set`strict_empty_steps_transition` to `0xfffffffff` to disable it. - -_Note:_ This release marks Parity 2.3 as _beta_. All versions of Parity 2.2 are now considered _stable_. +Notable changes: +- Account management is now deprecated ([#10213](https://github.com/paritytech/parity-ethereum/pull/10213)) +- Local accounts can now be specified via CLI ([#9960](https://github.com/paritytech/parity-ethereum/pull/9960)) +- Chains can now be reset to a particular block via CLI ([#9782](https://github.com/paritytech/parity-ethereum/pull/9782)) +- Ethash now additionally implements ProgPoW ([#9762](https://github.com/paritytech/parity-ethereum/pull/9762)) +- The `eip1283DisableTransition` flag was added to revert EIP-1283 ([#10214](https://github.com/paritytech/parity-ethereum/pull/10214)) The full list of included changes: - -- Backports for 2.3.0 beta ([#10164](https://github.com/paritytech/parity-ethereum/pull/10164)) -- Snap: fix path in script ([#10157](https://github.com/paritytech/parity-ethereum/pull/10157)) -- Make sure parent block is not in importing queue when importing ancient blocks ([#10138](https://github.com/paritytech/parity-ethereum/pull/10138)) -- Ci: re-enable snap publishing ([#10142](https://github.com/paritytech/parity-ethereum/pull/10142)) -- Hf in POA Core (2019-01-18) - Constantinople ([#10155](https://github.com/paritytech/parity-ethereum/pull/10155)) -- Update EWF's tobalaba chainspec ([#10152](https://github.com/paritytech/parity-ethereum/pull/10152)) -- Replace ethcore-logger with env-logger. ([#10102](https://github.com/paritytech/parity-ethereum/pull/10102)) -- Finality: dont require chain head to be in the chain ([#10054](https://github.com/paritytech/parity-ethereum/pull/10054)) -- Remove caching for node connections ([#10143](https://github.com/paritytech/parity-ethereum/pull/10143)) -- Blooms file iterator empty on out of range position. ([#10145](https://github.com/paritytech/parity-ethereum/pull/10145)) -- Autogen docs for the "Configuring Parity Ethereum" wiki page. ([#10067](https://github.com/paritytech/parity-ethereum/pull/10067)) -- Misc: bump license header to 2019 ([#10135](https://github.com/paritytech/parity-ethereum/pull/10135)) -- Hide most of the logs from cpp example. ([#10139](https://github.com/paritytech/parity-ethereum/pull/10139)) -- Don't try to send oversized packets ([#10042](https://github.com/paritytech/parity-ethereum/pull/10042)) -- Private tx enabled flag added into STATUS packet ([#9999](https://github.com/paritytech/parity-ethereum/pull/9999)) -- Update pwasm-utils to 0.6.1 ([#10134](https://github.com/paritytech/parity-ethereum/pull/10134)) -- Extract blockchain from ethcore ([#10114](https://github.com/paritytech/parity-ethereum/pull/10114)) -- Ethcore: update hardcoded headers ([#10123](https://github.com/paritytech/parity-ethereum/pull/10123)) -- Identity fix ([#10128](https://github.com/paritytech/parity-ethereum/pull/10128)) -- Use LenCachingMutex to optimize verification. ([#10117](https://github.com/paritytech/parity-ethereum/pull/10117)) -- Pyethereum keystore support ([#9710](https://github.com/paritytech/parity-ethereum/pull/9710)) -- Bump rocksdb-sys to 0.5.5 ([#10124](https://github.com/paritytech/parity-ethereum/pull/10124)) -- Parity-clib: `async C bindings to RPC requests` + `subscribe/unsubscribe to websocket events` ([#9920](https://github.com/paritytech/parity-ethereum/pull/9920)) -- Refactor (hardware wallet) : reduce the number of threads ([#9644](https://github.com/paritytech/parity-ethereum/pull/9644)) -- Hf in POA Sokol (2019-01-04) ([#10077](https://github.com/paritytech/parity-ethereum/pull/10077)) -- Fix broken links ([#10119](https://github.com/paritytech/parity-ethereum/pull/10119)) -- Follow-up to [#10105](https://github.com/paritytech/parity-ethereum/issues/10105) ([#10107](https://github.com/paritytech/parity-ethereum/pull/10107)) -- Move EIP-712 crate back to parity-ethereum ([#10106](https://github.com/paritytech/parity-ethereum/pull/10106)) -- Move a bunch of stuff around ([#10101](https://github.com/paritytech/parity-ethereum/pull/10101)) -- Revert "Add --frozen when running cargo ([#10081](https://github.com/paritytech/parity-ethereum/pull/10081))" ([#10105](https://github.com/paritytech/parity-ethereum/pull/10105)) -- Fix left over small grumbles on whitespaces ([#10084](https://github.com/paritytech/parity-ethereum/pull/10084)) -- Add --frozen when running cargo ([#10081](https://github.com/paritytech/parity-ethereum/pull/10081)) -- Fix pubsub new_blocks notifications to include all blocks ([#9987](https://github.com/paritytech/parity-ethereum/pull/9987)) -- Update some dependencies for compilation with pc-windows-gnu ([#10082](https://github.com/paritytech/parity-ethereum/pull/10082)) -- Fill transaction hash on ethGetLog of light client. ([#9938](https://github.com/paritytech/parity-ethereum/pull/9938)) -- Update changelog update for 2.2.5-beta and 2.1.10-stable ([#10064](https://github.com/paritytech/parity-ethereum/pull/10064)) -- Implement len caching for parking_lot RwLock ([#10032](https://github.com/paritytech/parity-ethereum/pull/10032)) -- Update parking_lot to 0.7 ([#10050](https://github.com/paritytech/parity-ethereum/pull/10050)) -- Bump crossbeam. ([#10048](https://github.com/paritytech/parity-ethereum/pull/10048)) -- Ethcore: enable constantinople on ethereum ([#10031](https://github.com/paritytech/parity-ethereum/pull/10031)) -- Strict empty steps validation ([#10041](https://github.com/paritytech/parity-ethereum/pull/10041)) -- Center the Subtitle, use some CAPS ([#10034](https://github.com/paritytech/parity-ethereum/pull/10034)) -- Change test miner max memory to malloc reports. ([#10024](https://github.com/paritytech/parity-ethereum/pull/10024)) -- Sort the storage for private state ([#10018](https://github.com/paritytech/parity-ethereum/pull/10018)) -- Fix: test corpus_inaccessible panic ([#10019](https://github.com/paritytech/parity-ethereum/pull/10019)) -- Ci: move future releases to ethereum subdir on s3 ([#10017](https://github.com/paritytech/parity-ethereum/pull/10017)) -- Light(on_demand): decrease default time window to 10 secs ([#10016](https://github.com/paritytech/parity-ethereum/pull/10016)) -- Light client : failsafe crate (circuit breaker) ([#9790](https://github.com/paritytech/parity-ethereum/pull/9790)) -- Lencachingmutex ([#9988](https://github.com/paritytech/parity-ethereum/pull/9988)) -- Version and notification for private contract wrapper added ([#9761](https://github.com/paritytech/parity-ethereum/pull/9761)) -- Handle failing case for update account cache in require ([#9989](https://github.com/paritytech/parity-ethereum/pull/9989)) -- Add tokio runtime to ethcore io worker ([#9979](https://github.com/paritytech/parity-ethereum/pull/9979)) -- Move daemonize before creating account provider ([#10003](https://github.com/paritytech/parity-ethereum/pull/10003)) -- Docs: update changelogs ([#9990](https://github.com/paritytech/parity-ethereum/pull/9990)) -- Fix daemonize ([#10000](https://github.com/paritytech/parity-ethereum/pull/10000)) -- Fix Bloom migration ([#9992](https://github.com/paritytech/parity-ethereum/pull/9992)) -- Remove tendermint engine support ([#9980](https://github.com/paritytech/parity-ethereum/pull/9980)) -- Calculate gas for deployment transaction ([#9840](https://github.com/paritytech/parity-ethereum/pull/9840)) -- Fix unstable peers and slowness in sync ([#9967](https://github.com/paritytech/parity-ethereum/pull/9967)) -- Adds parity_verifySignature RPC method ([#9507](https://github.com/paritytech/parity-ethereum/pull/9507)) -- Improve block and transaction propagation ([#9954](https://github.com/paritytech/parity-ethereum/pull/9954)) -- Deny unknown fields for chainspec ([#9972](https://github.com/paritytech/parity-ethereum/pull/9972)) -- Fix docker build ([#9971](https://github.com/paritytech/parity-ethereum/pull/9971)) -- Ci: rearrange pipeline by logic ([#9970](https://github.com/paritytech/parity-ethereum/pull/9970)) -- Add changelogs for 2.0.9, 2.1.4, 2.1.6, and 2.2.1 ([#9963](https://github.com/paritytech/parity-ethereum/pull/9963)) -- Add Error message when sync is still in progress. ([#9475](https://github.com/paritytech/parity-ethereum/pull/9475)) -- Make CALLCODE to trace value to be the code address ([#9881](https://github.com/paritytech/parity-ethereum/pull/9881)) -- Fix light client informant while syncing ([#9932](https://github.com/paritytech/parity-ethereum/pull/9932)) -- Add a optional json dump state to evm-bin ([#9706](https://github.com/paritytech/parity-ethereum/pull/9706)) -- Disable EIP-98 transition by default ([#9955](https://github.com/paritytech/parity-ethereum/pull/9955)) -- Remove secret_store runtimes. ([#9888](https://github.com/paritytech/parity-ethereum/pull/9888)) -- Fix a deadlock ([#9952](https://github.com/paritytech/parity-ethereum/pull/9952)) -- Chore(eip712): remove unused `failure-derive` ([#9958](https://github.com/paritytech/parity-ethereum/pull/9958)) -- Do not use the home directory as the working dir in docker ([#9834](https://github.com/paritytech/parity-ethereum/pull/9834)) -- Prevent silent errors in daemon mode, closes [#9367](https://github.com/paritytech/parity-ethereum/issues/9367) ([#9946](https://github.com/paritytech/parity-ethereum/pull/9946)) -- Fix empty steps ([#9939](https://github.com/paritytech/parity-ethereum/pull/9939)) -- Adjust requests costs for light client ([#9925](https://github.com/paritytech/parity-ethereum/pull/9925)) -- Eip-1186: add `eth_getProof` RPC-Method ([#9001](https://github.com/paritytech/parity-ethereum/pull/9001)) -- Missing blocks in filter_changes RPC ([#9947](https://github.com/paritytech/parity-ethereum/pull/9947)) -- Allow rust-nightly builds fail in nightly builds ([#9944](https://github.com/paritytech/parity-ethereum/pull/9944)) -- Update eth-secp256k1 to include fix for BSDs ([#9935](https://github.com/paritytech/parity-ethereum/pull/9935)) -- Unbreak build on rust -stable ([#9934](https://github.com/paritytech/parity-ethereum/pull/9934)) -- Keep existing blocks when restoring a Snapshot ([#8643](https://github.com/paritytech/parity-ethereum/pull/8643)) -- Add experimental RPCs flag ([#9928](https://github.com/paritytech/parity-ethereum/pull/9928)) -- Clarify poll lifetime ([#9922](https://github.com/paritytech/parity-ethereum/pull/9922)) -- Docs(require rust 1.30) ([#9923](https://github.com/paritytech/parity-ethereum/pull/9923)) -- Use block header for building finality ([#9914](https://github.com/paritytech/parity-ethereum/pull/9914)) -- Simplify cargo audit ([#9918](https://github.com/paritytech/parity-ethereum/pull/9918)) -- Light-fetch: Differentiate between out-of-gas/manual throw and use required gas from response on failure ([#9824](https://github.com/paritytech/parity-ethereum/pull/9824)) -- Eip 191 ([#9701](https://github.com/paritytech/parity-ethereum/pull/9701)) -- Fix(logger): `reqwest` no longer a dependency ([#9908](https://github.com/paritytech/parity-ethereum/pull/9908)) -- Remove rust-toolchain file ([#9906](https://github.com/paritytech/parity-ethereum/pull/9906)) -- Foundation: 6692865, ropsten: 4417537, kovan: 9363457 ([#9907](https://github.com/paritytech/parity-ethereum/pull/9907)) -- Ethcore: use Machine::verify_transaction on parent block ([#9900](https://github.com/paritytech/parity-ethereum/pull/9900)) -- Chore(rpc-tests): remove unused rand ([#9896](https://github.com/paritytech/parity-ethereum/pull/9896)) -- Fix: Intermittent failing CI due to addr in use ([#9885](https://github.com/paritytech/parity-ethereum/pull/9885)) -- Chore(bump docopt): 0.8 -> 1.0 ([#9889](https://github.com/paritytech/parity-ethereum/pull/9889)) -- Use expect ([#9883](https://github.com/paritytech/parity-ethereum/pull/9883)) -- Use Weak reference in PubSubClient ([#9886](https://github.com/paritytech/parity-ethereum/pull/9886)) -- Ci: nuke the gitlab caches ([#9855](https://github.com/paritytech/parity-ethereum/pull/9855)) -- Remove unused code ([#9884](https://github.com/paritytech/parity-ethereum/pull/9884)) -- Fix json tracer overflow ([#9873](https://github.com/paritytech/parity-ethereum/pull/9873)) -- Allow to seal work on latest block ([#9876](https://github.com/paritytech/parity-ethereum/pull/9876)) -- Fix docker script ([#9854](https://github.com/paritytech/parity-ethereum/pull/9854)) -- Health endpoint ([#9847](https://github.com/paritytech/parity-ethereum/pull/9847)) -- Gitlab-ci: make android release build succeed ([#9743](https://github.com/paritytech/parity-ethereum/pull/9743)) -- Clean up existing benchmarks ([#9839](https://github.com/paritytech/parity-ethereum/pull/9839)) -- Update Callisto block reward code to support HF1 ([#9811](https://github.com/paritytech/parity-ethereum/pull/9811)) -- Option to disable keep alive for JSON-RPC http transport ([#9848](https://github.com/paritytech/parity-ethereum/pull/9848)) -- Classic.json Bootnode Update ([#9828](https://github.com/paritytech/parity-ethereum/pull/9828)) -- Support MIX. ([#9767](https://github.com/paritytech/parity-ethereum/pull/9767)) -- Ci: remove failing tests for android, windows, and macos ([#9788](https://github.com/paritytech/parity-ethereum/pull/9788)) -- Implement NoProof for json tests and update tests reference (replaces [#9744](https://github.com/paritytech/parity-ethereum/issues/9744)) ([#9814](https://github.com/paritytech/parity-ethereum/pull/9814)) -- Chore(bump regex) ([#9842](https://github.com/paritytech/parity-ethereum/pull/9842)) -- Ignore global cache for patched accounts ([#9752](https://github.com/paritytech/parity-ethereum/pull/9752)) -- Move state root verification before gas used ([#9841](https://github.com/paritytech/parity-ethereum/pull/9841)) -- Fix(docker-aarch64) : cross-compile config ([#9798](https://github.com/paritytech/parity-ethereum/pull/9798)) -- Version: bump nightly to 2.3.0 ([#9819](https://github.com/paritytech/parity-ethereum/pull/9819)) -- Tests modification for windows CI ([#9671](https://github.com/paritytech/parity-ethereum/pull/9671)) -- Eip-712 implementation ([#9631](https://github.com/paritytech/parity-ethereum/pull/9631)) -- Fix typo ([#9826](https://github.com/paritytech/parity-ethereum/pull/9826)) -- Clean up serde rename and use rename_all = camelCase when possible ([#9823](https://github.com/paritytech/parity-ethereum/pull/9823)) +- More Backports for Beta 2.4.0 ([#10431](https://github.com/paritytech/parity-ethereum/pull/10431)) + - Revert some changes, could be buggy ([#10399](https://github.com/paritytech/parity-ethereum/pull/10399)) + - Ci: clean up gitlab-ci.yml leftovers from previous merge ([#10429](https://github.com/paritytech/parity-ethereum/pull/10429)) + - 10000 > 5000 ([#10422](https://github.com/paritytech/parity-ethereum/pull/10422)) + - Fix underflow in pip, closes [#10419](https://github.com/paritytech/parity-ethereum/pull/10419) ([#10423](https://github.com/paritytech/parity-ethereum/pull/10423)) + - Fix panic when logging directory does not exist, closes [#10420](https://github.com/paritytech/parity-ethereum/pull/10420) ([#10424](https://github.com/paritytech/parity-ethereum/pull/10424)) + - Update hardcoded headers for Foundation, Ropsten, Kovan and Classic ([#10417](https://github.com/paritytech/parity-ethereum/pull/10417)) +- Backports for Beta 2.4.0 ([#10416](https://github.com/paritytech/parity-ethereum/pull/10416)) + - No-git for publish jobs, empty artifacts dir ([#10393](https://github.com/paritytech/parity-ethereum/pull/10393)) + - Snap: reenable i386, arm64, armhf architecture publishing ([#10386](https://github.com/paritytech/parity-ethereum/pull/10386)) + - Tx pool: always accept local transactions ([#10375](https://github.com/paritytech/parity-ethereum/pull/10375)) + - Fix to_pod storage trie value decoding ([#10368](https://github.com/paritytech/parity-ethereum/pull/10368)) +- Version: mark 2.4.0 beta +- Update to latest mem-db, hash-db and trie-db. ([#10314](https://github.com/paritytech/parity-ethereum/pull/10314)) +- Tx pool: always accept local transactions ([#10375](https://github.com/paritytech/parity-ethereum/pull/10375)) +- Fix(trace_main! macro): don't re-export ([#10384](https://github.com/paritytech/parity-ethereum/pull/10384)) +- Exchanged old(azure) bootnodes with new(ovh) ones ([#10309](https://github.com/paritytech/parity-ethereum/pull/10309)) +- Ethash: implement Progpow ([#9762](https://github.com/paritytech/parity-ethereum/pull/9762)) +- Snap: add the removable-media plug ([#10377](https://github.com/paritytech/parity-ethereum/pull/10377)) +- Add message to IO errors ([#10324](https://github.com/paritytech/parity-ethereum/pull/10324)) +- Chore(bump parity-daemonize): require rust >= 1.31 ([#10359](https://github.com/paritytech/parity-ethereum/pull/10359)) +- Secretstore: use in-memory transport in cluster tests ([#9850](https://github.com/paritytech/parity-ethereum/pull/9850)) +- Add fields to `memzero`'s Cargo.toml ([#10362](https://github.com/paritytech/parity-ethereum/pull/10362)) +- Snap: release untagged versions from branches to the candidate snap channel ([#10357](https://github.com/paritytech/parity-ethereum/pull/10357)) +- Fix(compilation warns): `no-default-features` ([#10346](https://github.com/paritytech/parity-ethereum/pull/10346)) +- No volumes are needed, just run -v volume:/path/in/the/container ([#10345](https://github.com/paritytech/parity-ethereum/pull/10345)) +- Fixed misstype ([#10351](https://github.com/paritytech/parity-ethereum/pull/10351)) +- Snap: prefix version and populate candidate channel ([#10343](https://github.com/paritytech/parity-ethereum/pull/10343)) +- Bundle protocol and packet_id together in chain sync ([#10315](https://github.com/paritytech/parity-ethereum/pull/10315)) +- Role back docker build image and docker deploy image to ubuntu:xenial… ([#10338](https://github.com/paritytech/parity-ethereum/pull/10338)) +- Change docker image based on debian instead of ubuntu due to the chan… ([#10336](https://github.com/paritytech/parity-ethereum/pull/10336)) +- Don't add discovery initiators to the node table ([#10305](https://github.com/paritytech/parity-ethereum/pull/10305)) +- Fix(docker): fix not receives SIGINT ([#10059](https://github.com/paritytech/parity-ethereum/pull/10059)) +- Snap: official image / test ([#10168](https://github.com/paritytech/parity-ethereum/pull/10168)) +- Fix(add helper for timestamp overflows) ([#10330](https://github.com/paritytech/parity-ethereum/pull/10330)) +- Additional error for invalid gas ([#10327](https://github.com/paritytech/parity-ethereum/pull/10327)) +- Revive parity_setMinGasPrice RPC call ([#10294](https://github.com/paritytech/parity-ethereum/pull/10294)) +- Add Statetest support for Constantinople Fix ([#10323](https://github.com/paritytech/parity-ethereum/pull/10323)) +- Fix(parity-clib): grumbles that were not addressed in [#9920](https://github.com/paritytech/parity-ethereum/pull/9920) ([#10154](https://github.com/paritytech/parity-ethereum/pull/10154)) +- Fix(light-rpc): Make `light_sync` generic ([#10238](https://github.com/paritytech/parity-ethereum/pull/10238)) +- Fix publish job ([#10317](https://github.com/paritytech/parity-ethereum/pull/10317)) +- Secure WS-RPC: grant access to all apis ([#10246](https://github.com/paritytech/parity-ethereum/pull/10246)) +- Make specification of protocol in SyncRequester::send_request explicit ([#10295](https://github.com/paritytech/parity-ethereum/pull/10295)) +- Fix: parity-clib/examples/cpp/CMakeLists.txt ([#10313](https://github.com/paritytech/parity-ethereum/pull/10313)) +- Ci optimizations ([#10297](https://github.com/paritytech/parity-ethereum/pull/10297)) +- Increase number of requested block bodies in chain sync ([#10247](https://github.com/paritytech/parity-ethereum/pull/10247)) +- Deprecate account management ([#10213](https://github.com/paritytech/parity-ethereum/pull/10213)) +- Properly handle check_epoch_end_signal errors ([#10015](https://github.com/paritytech/parity-ethereum/pull/10015)) +- Fix(osx and windows builds): bump parity-daemonize ([#10291](https://github.com/paritytech/parity-ethereum/pull/10291)) +- Add missing step for Using `systemd` service file ([#10175](https://github.com/paritytech/parity-ethereum/pull/10175)) +- Call private contract methods from another private contract (read-onl… ([#10086](https://github.com/paritytech/parity-ethereum/pull/10086)) +- Update ring to 0.14 ([#10262](https://github.com/paritytech/parity-ethereum/pull/10262)) +- Fix(secret-store): deprecation warning ([#10301](https://github.com/paritytech/parity-ethereum/pull/10301)) +- Update to jsonrpc-derive 10.0.2, fixes aliases bug ([#10300](https://github.com/paritytech/parity-ethereum/pull/10300)) +- Convert to jsonrpc-derive, use jsonrpc-* from crates.io ([#10298](https://github.com/paritytech/parity-ethereum/pull/10298)) +- Fix Windows build ([#10284](https://github.com/paritytech/parity-ethereum/pull/10284)) +- Don't run the CPP example on CI ([#10285](https://github.com/paritytech/parity-ethereum/pull/10285)) +- Additional tests for uint deserialization. ([#10279](https://github.com/paritytech/parity-ethereum/pull/10279)) +- Prevent silent errors in daemon mode ([#10007](https://github.com/paritytech/parity-ethereum/pull/10007)) +- Fix join-set test to be deterministic. ([#10263](https://github.com/paritytech/parity-ethereum/pull/10263)) +- Update CHANGELOG-2.2.md ([#10254](https://github.com/paritytech/parity-ethereum/pull/10254)) +- Macos heapsize force jemalloc ([#10234](https://github.com/paritytech/parity-ethereum/pull/10234)) +- Allow specifying local accounts via CLI ([#9960](https://github.com/paritytech/parity-ethereum/pull/9960)) +- Take in account zero gas price certification when doing transact_cont… ([#10232](https://github.com/paritytech/parity-ethereum/pull/10232)) +- Update CHANGELOG.md ([#10249](https://github.com/paritytech/parity-ethereum/pull/10249)) +- Fix typo: CHANGELOG-2.1 -> CHANGELOG-2.2 ([#10233](https://github.com/paritytech/parity-ethereum/pull/10233)) +- Update copyright year to 2019. ([#10181](https://github.com/paritytech/parity-ethereum/pull/10181)) +- Fixed: types::transaction::SignedTransaction; ([#10229](https://github.com/paritytech/parity-ethereum/pull/10229)) +- Fix(ManageNetwork): replace Range with RangeInclusive ([#10209](https://github.com/paritytech/parity-ethereum/pull/10209)) +- Import rpc transactions sequentially ([#10051](https://github.com/paritytech/parity-ethereum/pull/10051)) +- Enable St-Peters-Fork ("Constantinople Fix") ([#10223](https://github.com/paritytech/parity-ethereum/pull/10223)) +- Add EIP-1283 disable transition ([#10214](https://github.com/paritytech/parity-ethereum/pull/10214)) +- Echo CORS request headers by default ([#10221](https://github.com/paritytech/parity-ethereum/pull/10221)) +- Happy New Year! ([#10211](https://github.com/paritytech/parity-ethereum/pull/10211)) +- Perform stripping during build ([#10208](https://github.com/paritytech/parity-ethereum/pull/10208)) +- Remove CallContract and RegistryInfo re-exports from `ethcore/client` ([#10205](https://github.com/paritytech/parity-ethereum/pull/10205)) +- Extract CallContract and RegistryInfo traits into their own crate ([#10178](https://github.com/paritytech/parity-ethereum/pull/10178)) +- Update the changelogs for 2.1.11, 2.2.6, 2.2.7, and 2.3.0 ([#10197](https://github.com/paritytech/parity-ethereum/pull/10197)) +- Cancel Constantinople HF on POA Core ([#10198](https://github.com/paritytech/parity-ethereum/pull/10198)) +- Adds cli interface to allow reseting chain to a particular block ([#9782](https://github.com/paritytech/parity-ethereum/pull/9782)) +- Run all `igd` methods in its own thread ([#10195](https://github.com/paritytech/parity-ethereum/pull/10195)) +- Pull constantinople on ethereum network ([#10189](https://github.com/paritytech/parity-ethereum/pull/10189)) +- Update for Android cross-compilation. ([#10180](https://github.com/paritytech/parity-ethereum/pull/10180)) +- Version: bump fork blocks for kovan and foundation ([#10186](https://github.com/paritytech/parity-ethereum/pull/10186)) +- Handle the case for contract creation on an empty but exist account w… ([#10065](https://github.com/paritytech/parity-ethereum/pull/10065)) +- Align personal_unlockAccount behaviour when permanent unlock is disab… ([#10060](https://github.com/paritytech/parity-ethereum/pull/10060)) +- Drop `runtime` after others (especially `ws_server`) ([#10179](https://github.com/paritytech/parity-ethereum/pull/10179)) +- Version: bump nightly to 2.4 ([#10165](https://github.com/paritytech/parity-ethereum/pull/10165)) +- Skip locking in statedb for non-canon blocks ([#10141](https://github.com/paritytech/parity-ethereum/pull/10141)) +- Remove reference to ui-interface command-line option ([#10170](https://github.com/paritytech/parity-ethereum/pull/10170)) +- Fix [#9822](https://github.com/paritytech/parity-ethereum/pull/9822): trace_filter does not return failed contract creation ([#10140](https://github.com/paritytech/parity-ethereum/pull/10140)) +- Fix _cannot recursively call into `Core`_ issue ([#10144](https://github.com/paritytech/parity-ethereum/pull/10144)) +- Fix(whisper): correct PoW calculation ([#10166](https://github.com/paritytech/parity-ethereum/pull/10166)) +- Bump JSON-RPC ([#10151](https://github.com/paritytech/parity-ethereum/pull/10151)) +- Ping nodes from discovery ([#10167](https://github.com/paritytech/parity-ethereum/pull/10167)) +- Fix(android): remove dependency to libusb ([#10161](https://github.com/paritytech/parity-ethereum/pull/10161)) +- Refactor(trim_right_matches -> trim_end_matches) ([#10159](https://github.com/paritytech/parity-ethereum/pull/10159)) +- Merge Machine and WithRewards ([#10071](https://github.com/paritytech/parity-ethereum/pull/10071)) ## Previous releases -- [CHANGELOG-2.2](docs/CHANGELOG-2.2.md) (_stable_) +- [CHANGELOG-2.3](docs/CHANGELOG-2.3.md) (_stable_) +- [CHANGELOG-2.2](docs/CHANGELOG-2.2.md) (EOL: 2019-02-25) - [CHANGELOG-2.1](docs/CHANGELOG-2.1.md) (EOL: 2019-01-16) - [CHANGELOG-2.0](docs/CHANGELOG-2.0.md) (EOL: 2018-11-15) - [CHANGELOG-1.11](docs/CHANGELOG-1.11.md) (EOL: 2018-09-19) diff --git a/docs/CHANGELOG-2.2.md b/docs/CHANGELOG-2.2.md index b9fce500075..69d6a0dcb7b 100644 --- a/docs/CHANGELOG-2.2.md +++ b/docs/CHANGELOG-2.2.md @@ -1,3 +1,78 @@ +Note: Parity Ethereum 2.2 reached End-of-Life on 2019-02-25 (EOL). + +## Parity-Ethereum [v2.2.11](https://github.com/paritytech/parity-ethereum/releases/tag/v2.2.11) (2019-02-21) + +Parity-Ethereum 2.2.11-stable is a maintenance release that fixes snap and docker installations. + +The full list of included changes: + +- Stable: snap: release untagged versions from branches to the candidate ([#10357](https://github.com/paritytech/parity-ethereum/pull/10357)) ([#10372](https://github.com/paritytech/parity-ethereum/pull/10372)) + - Snap: release untagged versions from branches to the candidate snap channel ([#10357](https://github.com/paritytech/parity-ethereum/pull/10357)) + - Snap: add the removable-media plug ([#10377](https://github.com/paritytech/parity-ethereum/pull/10377)) + - Exchanged old(azure) bootnodes with new(ovh) ones ([#10309](https://github.com/paritytech/parity-ethereum/pull/10309)) +- Stable Backports ([#10353](https://github.com/paritytech/parity-ethereum/pull/10353)) + - Version: bump stable to 2.2.11 + - Snap: prefix version and populate candidate channel ([#10343](https://github.com/paritytech/parity-ethereum/pull/10343)) + - Snap: populate candidate releases with beta snaps to avoid stale channel + - Snap: prefix version with v* + - No volumes are needed, just run -v volume:/path/in/the/container ([#10345](https://github.com/paritytech/parity-ethereum/pull/10345)) + +## Parity-Ethereum [v2.2.10](https://github.com/paritytech/parity-ethereum/releases/tag/v2.2.10) (2019-02-13) + +Parity-Ethereum 2.2.10-stable is a security-relevant release. A bug in the JSONRPC-deserialization module can cause crashes of all versions of Parity Ethereum nodes if an attacker is able to submit a specially-crafted RPC to certain publicly available endpoints. + +- https://www.parity.io/new-parity-ethereum-update-fixes-several-rpc-vulnerabilities/ + +The full list of included changes: + +- Additional error for invalid gas ([#10327](https://github.com/paritytech/parity-ethereum/pull/10327)) ([#10329](https://github.com/paritytech/parity-ethereum/pull/10329)) +- Backports for Stable 2.2.10 ([#10332](https://github.com/paritytech/parity-ethereum/pull/10332)) + - fix(docker-aarch64) : cross-compile config ([#9798](https://github.com/paritytech/parity-ethereum/pull/9798)) + - import rpc transactions sequentially ([#10051](https://github.com/paritytech/parity-ethereum/pull/10051)) + - fix(docker): fix not receives SIGINT ([#10059](https://github.com/paritytech/parity-ethereum/pull/10059)) + - snap: official image / test ([#10168](https://github.com/paritytech/parity-ethereum/pull/10168)) + - perform stripping during build ([#10208](https://github.com/paritytech/parity-ethereum/pull/10208)) + - Additional tests for uint/hash/bytes deserialization. ([#10279](https://github.com/paritytech/parity-ethereum/pull/10279)) + - Don't run the CPP example on CI ([#10285](https://github.com/paritytech/parity-ethereum/pull/10285)) + - CI optimizations ([#10297](https://github.com/paritytech/parity-ethereum/pull/10297)) + - fix publish job ([#10317](https://github.com/paritytech/parity-ethereum/pull/10317)) + - Add Statetest support for Constantinople Fix ([#10323](https://github.com/paritytech/parity-ethereum/pull/10323)) + - Add helper for Timestamp overflows ([#10330](https://github.com/paritytech/parity-ethereum/pull/10330)) + - Don't add discovery initiators to the node table ([#10305](https://github.com/paritytech/parity-ethereum/pull/10305)) + - change docker image based on debian instead of ubuntu due to the chan ([#10336](https://github.com/paritytech/parity-ethereum/pull/10336)) + - role back docker build image and docker deploy image to ubuntu:xenial based ([#10338](https://github.com/paritytech/parity-ethereum/pull/10338)) + +## Parity-Ethereum [v2.2.9](https://github.com/paritytech/parity-ethereum/releases/tag/v2.2.9) (2019-02-03) + +Parity-Ethereum 2.2.9-stable is a security-relevant release. A bug in the JSONRPC-deserialization module can cause crashes of all versions of Parity Ethereum nodes if an attacker is able to submit a specially-crafted RPC to certain publicly available endpoints. + +- https://www.parity.io/security-alert-parity-ethereum-03-02/ + +The full list of included changes: + +- Additional tests for uint deserialization. ([#10279](https://github.com/paritytech/parity-ethereum/pull/10279)) ([#10281](https://github.com/paritytech/parity-ethereum/pull/10281)) +- Version: bump stable to 2.2.9 ([#10282](https://github.com/paritytech/parity-ethereum/pull/10282)) + +## Parity-Ethereum [v2.2.8](https://github.com/paritytech/parity-ethereum/releases/tag/v2.2.8) (2019-02-01) + +Parity-Ethereum 2.2.8-stable is a consensus-relevant release that enables _St. Petersfork_ on: + +- Ethereum Block `7280000` (along with Constantinople) +- Kovan Block `10255201` +- Ropsten Block `4939394` +- POA Sokol Block `7026400` + +In addition to this, Constantinople is cancelled for the POA Core network. Upgrading is mandatory for clients on any of these chains. + +The full list of included changes: + +- Backports for stable 2.2.8 ([#10224](https://github.com/paritytech/parity-ethereum/pull/10224)) + - Update for Android cross-compilation. ([#10180](https://github.com/paritytech/parity-ethereum/pull/10180)) + - Cancel Constantinople HF on POA Core ([#10198](https://github.com/paritytech/parity-ethereum/pull/10198)) + - Add EIP-1283 disable transition ([#10214](https://github.com/paritytech/parity-ethereum/pull/10214)) + - Enable St-Peters-Fork ("Constantinople Fix") ([#10223](https://github.com/paritytech/parity-ethereum/pull/10223)) +- Stable: Macos heapsize force jemalloc ([#10234](https://github.com/paritytech/parity-ethereum/pull/10234)) ([#10258](https://github.com/paritytech/parity-ethereum/pull/10258)) + ## Parity-Ethereum [v2.2.7](https://github.com/paritytech/parity-ethereum/releases/tag/v2.2.7) (2019-01-15) Parity-Ethereum 2.2.7-stable is a consensus-relevant security release that reverts Constantinople on the Ethereum network. Upgrading is mandatory for Ethereum, and strongly recommended for other networks. diff --git a/docs/CHANGELOG-2.3.md b/docs/CHANGELOG-2.3.md new file mode 100644 index 00000000000..f7e75d4427a --- /dev/null +++ b/docs/CHANGELOG-2.3.md @@ -0,0 +1,255 @@ +## Parity-Ethereum [v2.3.5](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.5) (2019-02-25) + +Parity-Ethereum 2.3.5-stable is a bugfix release that improves performance and stability. + +Note, all 2.2 releases and older are now unsupported and upgrading is recommended. + +The full list of included changes: + +- More Backports for Stable 2.3.5 ([#10430](https://github.com/paritytech/parity-ethereum/pull/10430)) + - Revert some changes, could be buggy ([#10399](https://github.com/paritytech/parity-ethereum/pull/10399)) + - Ci: clean up gitlab-ci.yml leftovers from previous merge ([#10429](https://github.com/paritytech/parity-ethereum/pull/10429)) + - 10000 > 5000 ([#10422](https://github.com/paritytech/parity-ethereum/pull/10422)) + - Fix underflow in pip, closes [#10419](https://github.com/paritytech/parity-ethereum/pull/10419) ([#10423](https://github.com/paritytech/parity-ethereum/pull/10423)) + - Fix panic when logging directory does not exist, closes [#10420](https://github.com/paritytech/parity-ethereum/pull/10420) ([#10424](https://github.com/paritytech/parity-ethereum/pull/10424)) + - Update hardcoded headers for Foundation, Ropsten, Kovan and Classic ([#10417](https://github.com/paritytech/parity-ethereum/pull/10417)) +- Backports for Stable 2.3.5 ([#10414](https://github.com/paritytech/parity-ethereum/pull/10414)) + - No-git for publish jobs, empty artifacts dir ([#10393](https://github.com/paritytech/parity-ethereum/pull/10393)) + - Snap: reenable i386, arm64, armhf architecture publishing ([#10386](https://github.com/paritytech/parity-ethereum/pull/10386)) + - Tx pool: always accept local transactions ([#10375](https://github.com/paritytech/parity-ethereum/pull/10375)) + - Fix to_pod storage trie value decoding ([#10368)](https://github.com/paritytech/parity-ethereum/pull/10368)) +- Version: mark 2.3.5 as stable + +## Parity-Ethereum [v2.3.4](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.4) (2019-02-21) + +Parity-Ethereum 2.3.4-beta is a maintenance release that fixes snap and docker installations. + +The full list of included changes: +- Beta: snap: release untagged versions from branches to the candidate ([#10357](https://github.com/paritytech/parity-ethereum/pull/10357)) ([#10373](https://github.com/paritytech/parity-ethereum/pull/10373)) + - Snap: release untagged versions from branches to the candidate snap channel ([#10357](https://github.com/paritytech/parity-ethereum/pull/10357)) + - Snap: add the removable-media plug ([#10377](https://github.com/paritytech/parity-ethereum/pull/10377)) + - Exchanged old(azure) bootnodes with new(ovh) ones ([#10309](https://github.com/paritytech/parity-ethereum/pull/10309)) +- Beta Backports ([#10354](https://github.com/paritytech/parity-ethereum/pull/10354)) + - Version: bump beta to 2.3.4 + - Snap: prefix version and populate candidate channel ([#10343](https://github.com/paritytech/parity-ethereum/pull/10343)) + - Snap: populate candidate releases with beta snaps to avoid stale channel + - Snap: prefix version with v* + - No volumes are needed, just run -v volume:/path/in/the/container ([#10345](https://github.com/paritytech/parity-ethereum/pull/10345)) + +## Parity-Ethereum [v2.3.3](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.3) (2019-02-13) + +Parity-Ethereum 2.3.3-beta is a security-relevant release. A bug in the JSONRPC-deserialization module can cause crashes of all versions of Parity Ethereum nodes if an attacker is able to submit a specially-crafted RPC to certain publicly available endpoints. + +- https://www.parity.io/new-parity-ethereum-update-fixes-several-rpc-vulnerabilities/ + +The full list of included changes: + +- Additional error for invalid gas ([#10327](https://github.com/paritytech/parity-ethereum/pull/10327)) ([#10328](https://github.com/paritytech/parity-ethereum/pull/10328)) +- Backports for Beta 2.3.3 ([#10333](https://github.com/paritytech/parity-ethereum/pull/10333)) + - Properly handle check_epoch_end_signal errors ([#10015](https://github.com/paritytech/parity-ethereum/pull/10015)) + - import rpc transactions sequentially ([#10051](https://github.com/paritytech/parity-ethereum/pull/10051)) + - fix(docker): fix not receives SIGINT ([#10059](https://github.com/paritytech/parity-ethereum/pull/10059)) + - snap: official image / test ([#10168](https://github.com/paritytech/parity-ethereum/pull/10168)) + - Extract CallContract and RegistryInfo traits into their own crate ([#10178](https://github.com/paritytech/parity-ethereum/pull/10178)) + - perform stripping during build ([#10208](https://github.com/paritytech/parity-ethereum/pull/10208)) + - Remove CallContract and RegistryInfo re-exports from `ethcore/client` ([#10205](https://github.com/paritytech/parity-ethereum/pull/10205)) + - fixed: types::transaction::SignedTransaction; ([#10229](https://github.com/paritytech/parity-ethereum/pull/10229)) + - Additional tests for uint/hash/bytes deserialization. ([#10279](https://github.com/paritytech/parity-ethereum/pull/10279)) + - Fix Windows build ([#10284](https://github.com/paritytech/parity-ethereum/pull/10284)) + - Don't run the CPP example on CI ([#10285](https://github.com/paritytech/parity-ethereum/pull/10285)) + - CI optimizations ([#10297](https://github.com/paritytech/parity-ethereum/pull/10297)) + - fix publish job ([#10317](https://github.com/paritytech/parity-ethereum/pull/10317)) + - Add Statetest support for Constantinople Fix ([#10323](https://github.com/paritytech/parity-ethereum/pull/10323)) + - Add helper for Timestamp overflows ([#10330](https://github.com/paritytech/parity-ethereum/pull/10330)) + - Don't add discovery initiators to the node table ([#10305](https://github.com/paritytech/parity-ethereum/pull/10305)) + - change docker image based on debian instead of ubuntu due to the chan ([#10336](https://github.com/paritytech/parity-ethereum/pull/10336)) + - role back docker build image and docker deploy image to ubuntu:xenial based ([#10338](https://github.com/paritytech/parity-ethereum/pull/10338)) + +## Parity-Ethereum [v2.3.2](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.2) (2019-02-03) + +Parity-Ethereum 2.3.2-stable is a security-relevant release. A bug in the JSONRPC-deserialization module can cause crashes of all versions of Parity Ethereum nodes if an attacker is able to submit a specially-crafted RPC to certain publicly available endpoints. + +- https://www.parity.io/security-alert-parity-ethereum-03-02/ + +The full list of included changes: +- Version: bump beta to 2.3.2 ([#10283](https://github.com/paritytech/parity-ethereum/pull/10283)) +- Additional tests for uint deserialization. ([#10279](https://github.com/paritytech/parity-ethereum/pull/10279)) ([#10280](https://github.com/paritytech/parity-ethereum/pull/10280)) +- Backport [#10285](https://github.com/paritytech/parity-ethereum/pull/10285) to beta ([#10286](https://github.com/paritytech/parity-ethereum/pull/10286)) + +## Parity-Ethereum [v2.3.1](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.1) (2019-02-01) + +Parity-Ethereum 2.3.1-beta is a consensus-relevant release that enables _St. Petersfork_ on: + +- Ethereum Block `7280000` (along with Constantinople) +- Kovan Block `10255201` +- Ropsten Block `4939394` +- POA Sokol Block `7026400` + +In addition to this, Constantinople is cancelled for the POA Core network. Upgrading is mandatory for clients on any of these chains. + +The full list of included changes: + +- Backports for beta 2.3.1 ([#10225](https://github.com/paritytech/parity-ethereum/pull/10225)) + - Fix _cannot recursively call into `Core`_ issue ([#10144](https://github.com/paritytech/parity-ethereum/pull/10144)) + - Update for Android cross-compilation. ([#10180](https://github.com/paritytech/parity-ethereum/pull/10180)) + - Fix _cannot recursively call into `Core`_ - Part 2 ([#10195](https://github.com/paritytech/parity-ethereum/pull/10195)) + - Cancel Constantinople HF on POA Core ([#10198](https://github.com/paritytech/parity-ethereum/pull/10198)) + - Add EIP-1283 disable transition ([#10214](https://github.com/paritytech/parity-ethereum/pull/10214)) + - Enable St-Peters-Fork ("Constantinople Fix") ([#10223](https://github.com/paritytech/parity-ethereum/pull/10223)) +- Beta: Macos heapsize force jemalloc ([#10234](https://github.com/paritytech/parity-ethereum/pull/10234)) ([#10259](https://github.com/paritytech/parity-ethereum/pull/10259)) + +## Parity-Ethereum [v2.3.0](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.0) (2019-01-16) + +Parity-Ethereum 2.3.0-beta is a consensus-relevant security release that reverts Constantinople on the Ethereum network. Upgrading is mandatory for Ethereum, and strongly recommended for other networks. + +- **Consensus** - Ethereum Network: Pull Constantinople protocol upgrade on Ethereum ([#10189](https://github.com/paritytech/parity-ethereum/pull/10189)) + - Read more: [Security Alert: Ethereum Constantinople Postponement](https://blog.ethereum.org/2019/01/15/security-alert-ethereum-constantinople-postponement/) +- **Networking** - All networks: Ping nodes from discovery ([#10167](https://github.com/paritytech/parity-ethereum/pull/10167)) +- **Wasm** - Kovan Network: Update pwasm-utils to 0.6.1 ([#10134](https://github.com/paritytech/parity-ethereum/pull/10134)) + +Other notable changes: + +- Existing blocks in the database are now kept when restoring a Snapshot. ([#8643](https://github.com/paritytech/parity-ethereum/pull/8643)) +- Block and transaction propagation is improved significantly. ([#9954](https://github.com/paritytech/parity-ethereum/pull/9954)) +- The ERC-191 Signed Data Standard is now supported by `personal_sign191`. ([#9701](https://github.com/paritytech/parity-ethereum/pull/9701)) +- Add support for ERC-191/712 `eth_signTypedData` as a standard for machine-verifiable and human-readable typed data signing with Ethereum keys. ([#9631](https://github.com/paritytech/parity-ethereum/pull/9631)) +- Add support for ERC-1186 `eth_getProof` ([#9001](https://github.com/paritytech/parity-ethereum/pull/9001)) +- Add experimental RPCs flag to enable ERC-191, ERC-712, and ERC-1186 APIs via `--jsonrpc-experimental` ([#9928](https://github.com/paritytech/parity-ethereum/pull/9928)) +- Make `CALLCODE` to trace value to be the code address. ([#9881](https://github.com/paritytech/parity-ethereum/pull/9881)) + +Configuration changes: + +- The EIP-98 transition is now disabled by default. If you previously had no `eip98transition` specified in your chain specification, you would enable this now manually on block `0x0`. ([#9955](https://github.com/paritytech/parity-ethereum/pull/9955)) +- Also, unknown fields in chain specs are now rejected. ([#9972](https://github.com/paritytech/parity-ethereum/pull/9972)) +- The Tendermint engine was removed from Parity Ethereum and is no longer available and maintained. ([#9980](https://github.com/paritytech/parity-ethereum/pull/9980)) +- Ropsten testnet data and keys moved from `test/` to `ropsten/` subdir. To reuse your old keys and data either copy or symlink them to the new location. ([#10123](https://github.com/paritytech/parity-ethereum/pull/10123)) +- Strict empty steps validation ([#10041](https://github.com/paritytech/parity-ethereum/pull/10041)) + - If you have a chain with`empty_steps` already running, some blocks most likely contain non-strict entries (unordered or duplicated empty steps). In this release `strict_empty_steps_transition` is enabled by default at block `0x0` for any chain with `empty_steps`. + - If your network uses `empty_steps` you **must** (A) plan a hard fork and change `strict_empty_steps_transition` to the desired fork block and (B) update the clients of the whole network to 2.2.7-stable / 2.3.0-beta. If for some reason you don't want to do this please set`strict_empty_steps_transition` to `0xfffffffff` to disable it. + +_Note:_ This release marks Parity 2.3 as _beta_. All versions of Parity 2.2 are now considered _stable_. + +The full list of included changes: + +- Backports for 2.3.0 beta ([#10164](https://github.com/paritytech/parity-ethereum/pull/10164)) +- Snap: fix path in script ([#10157](https://github.com/paritytech/parity-ethereum/pull/10157)) +- Make sure parent block is not in importing queue when importing ancient blocks ([#10138](https://github.com/paritytech/parity-ethereum/pull/10138)) +- Ci: re-enable snap publishing ([#10142](https://github.com/paritytech/parity-ethereum/pull/10142)) +- Hf in POA Core (2019-01-18) - Constantinople ([#10155](https://github.com/paritytech/parity-ethereum/pull/10155)) +- Update EWF's tobalaba chainspec ([#10152](https://github.com/paritytech/parity-ethereum/pull/10152)) +- Replace ethcore-logger with env-logger. ([#10102](https://github.com/paritytech/parity-ethereum/pull/10102)) +- Finality: dont require chain head to be in the chain ([#10054](https://github.com/paritytech/parity-ethereum/pull/10054)) +- Remove caching for node connections ([#10143](https://github.com/paritytech/parity-ethereum/pull/10143)) +- Blooms file iterator empty on out of range position. ([#10145](https://github.com/paritytech/parity-ethereum/pull/10145)) +- Autogen docs for the "Configuring Parity Ethereum" wiki page. ([#10067](https://github.com/paritytech/parity-ethereum/pull/10067)) +- Misc: bump license header to 2019 ([#10135](https://github.com/paritytech/parity-ethereum/pull/10135)) +- Hide most of the logs from cpp example. ([#10139](https://github.com/paritytech/parity-ethereum/pull/10139)) +- Don't try to send oversized packets ([#10042](https://github.com/paritytech/parity-ethereum/pull/10042)) +- Private tx enabled flag added into STATUS packet ([#9999](https://github.com/paritytech/parity-ethereum/pull/9999)) +- Update pwasm-utils to 0.6.1 ([#10134](https://github.com/paritytech/parity-ethereum/pull/10134)) +- Extract blockchain from ethcore ([#10114](https://github.com/paritytech/parity-ethereum/pull/10114)) +- Ethcore: update hardcoded headers ([#10123](https://github.com/paritytech/parity-ethereum/pull/10123)) +- Identity fix ([#10128](https://github.com/paritytech/parity-ethereum/pull/10128)) +- Use LenCachingMutex to optimize verification. ([#10117](https://github.com/paritytech/parity-ethereum/pull/10117)) +- Pyethereum keystore support ([#9710](https://github.com/paritytech/parity-ethereum/pull/9710)) +- Bump rocksdb-sys to 0.5.5 ([#10124](https://github.com/paritytech/parity-ethereum/pull/10124)) +- Parity-clib: `async C bindings to RPC requests` + `subscribe/unsubscribe to websocket events` ([#9920](https://github.com/paritytech/parity-ethereum/pull/9920)) +- Refactor (hardware wallet) : reduce the number of threads ([#9644](https://github.com/paritytech/parity-ethereum/pull/9644)) +- Hf in POA Sokol (2019-01-04) ([#10077](https://github.com/paritytech/parity-ethereum/pull/10077)) +- Fix broken links ([#10119](https://github.com/paritytech/parity-ethereum/pull/10119)) +- Follow-up to [#10105](https://github.com/paritytech/parity-ethereum/issues/10105) ([#10107](https://github.com/paritytech/parity-ethereum/pull/10107)) +- Move EIP-712 crate back to parity-ethereum ([#10106](https://github.com/paritytech/parity-ethereum/pull/10106)) +- Move a bunch of stuff around ([#10101](https://github.com/paritytech/parity-ethereum/pull/10101)) +- Revert "Add --frozen when running cargo ([#10081](https://github.com/paritytech/parity-ethereum/pull/10081))" ([#10105](https://github.com/paritytech/parity-ethereum/pull/10105)) +- Fix left over small grumbles on whitespaces ([#10084](https://github.com/paritytech/parity-ethereum/pull/10084)) +- Add --frozen when running cargo ([#10081](https://github.com/paritytech/parity-ethereum/pull/10081)) +- Fix pubsub new_blocks notifications to include all blocks ([#9987](https://github.com/paritytech/parity-ethereum/pull/9987)) +- Update some dependencies for compilation with pc-windows-gnu ([#10082](https://github.com/paritytech/parity-ethereum/pull/10082)) +- Fill transaction hash on ethGetLog of light client. ([#9938](https://github.com/paritytech/parity-ethereum/pull/9938)) +- Update changelog update for 2.2.5-beta and 2.1.10-stable ([#10064](https://github.com/paritytech/parity-ethereum/pull/10064)) +- Implement len caching for parking_lot RwLock ([#10032](https://github.com/paritytech/parity-ethereum/pull/10032)) +- Update parking_lot to 0.7 ([#10050](https://github.com/paritytech/parity-ethereum/pull/10050)) +- Bump crossbeam. ([#10048](https://github.com/paritytech/parity-ethereum/pull/10048)) +- Ethcore: enable constantinople on ethereum ([#10031](https://github.com/paritytech/parity-ethereum/pull/10031)) +- Strict empty steps validation ([#10041](https://github.com/paritytech/parity-ethereum/pull/10041)) +- Center the Subtitle, use some CAPS ([#10034](https://github.com/paritytech/parity-ethereum/pull/10034)) +- Change test miner max memory to malloc reports. ([#10024](https://github.com/paritytech/parity-ethereum/pull/10024)) +- Sort the storage for private state ([#10018](https://github.com/paritytech/parity-ethereum/pull/10018)) +- Fix: test corpus_inaccessible panic ([#10019](https://github.com/paritytech/parity-ethereum/pull/10019)) +- Ci: move future releases to ethereum subdir on s3 ([#10017](https://github.com/paritytech/parity-ethereum/pull/10017)) +- Light(on_demand): decrease default time window to 10 secs ([#10016](https://github.com/paritytech/parity-ethereum/pull/10016)) +- Light client : failsafe crate (circuit breaker) ([#9790](https://github.com/paritytech/parity-ethereum/pull/9790)) +- Lencachingmutex ([#9988](https://github.com/paritytech/parity-ethereum/pull/9988)) +- Version and notification for private contract wrapper added ([#9761](https://github.com/paritytech/parity-ethereum/pull/9761)) +- Handle failing case for update account cache in require ([#9989](https://github.com/paritytech/parity-ethereum/pull/9989)) +- Add tokio runtime to ethcore io worker ([#9979](https://github.com/paritytech/parity-ethereum/pull/9979)) +- Move daemonize before creating account provider ([#10003](https://github.com/paritytech/parity-ethereum/pull/10003)) +- Docs: update changelogs ([#9990](https://github.com/paritytech/parity-ethereum/pull/9990)) +- Fix daemonize ([#10000](https://github.com/paritytech/parity-ethereum/pull/10000)) +- Fix Bloom migration ([#9992](https://github.com/paritytech/parity-ethereum/pull/9992)) +- Remove tendermint engine support ([#9980](https://github.com/paritytech/parity-ethereum/pull/9980)) +- Calculate gas for deployment transaction ([#9840](https://github.com/paritytech/parity-ethereum/pull/9840)) +- Fix unstable peers and slowness in sync ([#9967](https://github.com/paritytech/parity-ethereum/pull/9967)) +- Adds parity_verifySignature RPC method ([#9507](https://github.com/paritytech/parity-ethereum/pull/9507)) +- Improve block and transaction propagation ([#9954](https://github.com/paritytech/parity-ethereum/pull/9954)) +- Deny unknown fields for chainspec ([#9972](https://github.com/paritytech/parity-ethereum/pull/9972)) +- Fix docker build ([#9971](https://github.com/paritytech/parity-ethereum/pull/9971)) +- Ci: rearrange pipeline by logic ([#9970](https://github.com/paritytech/parity-ethereum/pull/9970)) +- Add changelogs for 2.0.9, 2.1.4, 2.1.6, and 2.2.1 ([#9963](https://github.com/paritytech/parity-ethereum/pull/9963)) +- Add Error message when sync is still in progress. ([#9475](https://github.com/paritytech/parity-ethereum/pull/9475)) +- Make CALLCODE to trace value to be the code address ([#9881](https://github.com/paritytech/parity-ethereum/pull/9881)) +- Fix light client informant while syncing ([#9932](https://github.com/paritytech/parity-ethereum/pull/9932)) +- Add a optional json dump state to evm-bin ([#9706](https://github.com/paritytech/parity-ethereum/pull/9706)) +- Disable EIP-98 transition by default ([#9955](https://github.com/paritytech/parity-ethereum/pull/9955)) +- Remove secret_store runtimes. ([#9888](https://github.com/paritytech/parity-ethereum/pull/9888)) +- Fix a deadlock ([#9952](https://github.com/paritytech/parity-ethereum/pull/9952)) +- Chore(eip712): remove unused `failure-derive` ([#9958](https://github.com/paritytech/parity-ethereum/pull/9958)) +- Do not use the home directory as the working dir in docker ([#9834](https://github.com/paritytech/parity-ethereum/pull/9834)) +- Prevent silent errors in daemon mode, closes [#9367](https://github.com/paritytech/parity-ethereum/issues/9367) ([#9946](https://github.com/paritytech/parity-ethereum/pull/9946)) +- Fix empty steps ([#9939](https://github.com/paritytech/parity-ethereum/pull/9939)) +- Adjust requests costs for light client ([#9925](https://github.com/paritytech/parity-ethereum/pull/9925)) +- Eip-1186: add `eth_getProof` RPC-Method ([#9001](https://github.com/paritytech/parity-ethereum/pull/9001)) +- Missing blocks in filter_changes RPC ([#9947](https://github.com/paritytech/parity-ethereum/pull/9947)) +- Allow rust-nightly builds fail in nightly builds ([#9944](https://github.com/paritytech/parity-ethereum/pull/9944)) +- Update eth-secp256k1 to include fix for BSDs ([#9935](https://github.com/paritytech/parity-ethereum/pull/9935)) +- Unbreak build on rust -stable ([#9934](https://github.com/paritytech/parity-ethereum/pull/9934)) +- Keep existing blocks when restoring a Snapshot ([#8643](https://github.com/paritytech/parity-ethereum/pull/8643)) +- Add experimental RPCs flag ([#9928](https://github.com/paritytech/parity-ethereum/pull/9928)) +- Clarify poll lifetime ([#9922](https://github.com/paritytech/parity-ethereum/pull/9922)) +- Docs(require rust 1.30) ([#9923](https://github.com/paritytech/parity-ethereum/pull/9923)) +- Use block header for building finality ([#9914](https://github.com/paritytech/parity-ethereum/pull/9914)) +- Simplify cargo audit ([#9918](https://github.com/paritytech/parity-ethereum/pull/9918)) +- Light-fetch: Differentiate between out-of-gas/manual throw and use required gas from response on failure ([#9824](https://github.com/paritytech/parity-ethereum/pull/9824)) +- Eip 191 ([#9701](https://github.com/paritytech/parity-ethereum/pull/9701)) +- Fix(logger): `reqwest` no longer a dependency ([#9908](https://github.com/paritytech/parity-ethereum/pull/9908)) +- Remove rust-toolchain file ([#9906](https://github.com/paritytech/parity-ethereum/pull/9906)) +- Foundation: 6692865, ropsten: 4417537, kovan: 9363457 ([#9907](https://github.com/paritytech/parity-ethereum/pull/9907)) +- Ethcore: use Machine::verify_transaction on parent block ([#9900](https://github.com/paritytech/parity-ethereum/pull/9900)) +- Chore(rpc-tests): remove unused rand ([#9896](https://github.com/paritytech/parity-ethereum/pull/9896)) +- Fix: Intermittent failing CI due to addr in use ([#9885](https://github.com/paritytech/parity-ethereum/pull/9885)) +- Chore(bump docopt): 0.8 -> 1.0 ([#9889](https://github.com/paritytech/parity-ethereum/pull/9889)) +- Use expect ([#9883](https://github.com/paritytech/parity-ethereum/pull/9883)) +- Use Weak reference in PubSubClient ([#9886](https://github.com/paritytech/parity-ethereum/pull/9886)) +- Ci: nuke the gitlab caches ([#9855](https://github.com/paritytech/parity-ethereum/pull/9855)) +- Remove unused code ([#9884](https://github.com/paritytech/parity-ethereum/pull/9884)) +- Fix json tracer overflow ([#9873](https://github.com/paritytech/parity-ethereum/pull/9873)) +- Allow to seal work on latest block ([#9876](https://github.com/paritytech/parity-ethereum/pull/9876)) +- Fix docker script ([#9854](https://github.com/paritytech/parity-ethereum/pull/9854)) +- Health endpoint ([#9847](https://github.com/paritytech/parity-ethereum/pull/9847)) +- Gitlab-ci: make android release build succeed ([#9743](https://github.com/paritytech/parity-ethereum/pull/9743)) +- Clean up existing benchmarks ([#9839](https://github.com/paritytech/parity-ethereum/pull/9839)) +- Update Callisto block reward code to support HF1 ([#9811](https://github.com/paritytech/parity-ethereum/pull/9811)) +- Option to disable keep alive for JSON-RPC http transport ([#9848](https://github.com/paritytech/parity-ethereum/pull/9848)) +- Classic.json Bootnode Update ([#9828](https://github.com/paritytech/parity-ethereum/pull/9828)) +- Support MIX. ([#9767](https://github.com/paritytech/parity-ethereum/pull/9767)) +- Ci: remove failing tests for android, windows, and macos ([#9788](https://github.com/paritytech/parity-ethereum/pull/9788)) +- Implement NoProof for json tests and update tests reference (replaces [#9744](https://github.com/paritytech/parity-ethereum/issues/9744)) ([#9814](https://github.com/paritytech/parity-ethereum/pull/9814)) +- Chore(bump regex) ([#9842](https://github.com/paritytech/parity-ethereum/pull/9842)) +- Ignore global cache for patched accounts ([#9752](https://github.com/paritytech/parity-ethereum/pull/9752)) +- Move state root verification before gas used ([#9841](https://github.com/paritytech/parity-ethereum/pull/9841)) +- Fix(docker-aarch64) : cross-compile config ([#9798](https://github.com/paritytech/parity-ethereum/pull/9798)) +- Version: bump nightly to 2.3.0 ([#9819](https://github.com/paritytech/parity-ethereum/pull/9819)) +- Tests modification for windows CI ([#9671](https://github.com/paritytech/parity-ethereum/pull/9671)) +- Eip-712 implementation ([#9631](https://github.com/paritytech/parity-ethereum/pull/9631)) +- Fix typo ([#9826](https://github.com/paritytech/parity-ethereum/pull/9826)) +- Clean up serde rename and use rename_all = camelCase when possible ([#9823](https://github.com/paritytech/parity-ethereum/pull/9823)) From 23d977eccefe471adbcd9dfdd50cd6415420c154 Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Mon, 11 Mar 2019 11:37:48 +0100 Subject: [PATCH 07/27] simplify ethcore machine by removing redundant traits (#10454) --- ethcore/src/engines/instant_seal.rs | 11 ++++------ ethcore/src/engines/mod.rs | 12 +++++------ ethcore/src/engines/null_engine.rs | 10 ++++----- ethcore/src/machine.rs | 3 +-- ethcore/types/src/header.rs | 27 +++++------------------ machine/src/lib.rs | 33 ----------------------------- 6 files changed, 20 insertions(+), 76 deletions(-) diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index 595805c1997..189015f0815 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -15,7 +15,8 @@ // along with Parity Ethereum. If not, see . use engines::{Engine, Seal}; -use parity_machine::{Machine, Transactions, TotalScoredHeader}; +use parity_machine::{Machine, Transactions}; +use types::header::ExtendedHeader; /// `InstantSeal` params. #[derive(Default, Debug, PartialEq)] @@ -48,11 +49,7 @@ impl InstantSeal { } } -impl Engine for InstantSeal - where M::LiveBlock: Transactions, - M::ExtendedHeader: TotalScoredHeader, - ::Value: Ord -{ +impl Engine for InstantSeal where M::LiveBlock: Transactions { fn name(&self) -> &str { "InstantSeal" } @@ -84,7 +81,7 @@ impl Engine for InstantSeal header_timestamp >= parent_timestamp } - fn fork_choice(&self, new: &M::ExtendedHeader, current: &M::ExtendedHeader) -> super::ForkChoice { + fn fork_choice(&self, new: &ExtendedHeader, current: &ExtendedHeader) -> super::ForkChoice { super::total_difficulty_fork_choice(new, current) } } diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 9cced0a0da9..a63c69039ca 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -44,13 +44,13 @@ use builtin::Builtin; use vm::{EnvInfo, Schedule, CreateContractAddress, CallType, ActionValue}; use error::Error; use types::BlockNumber; -use types::header::Header; +use types::header::{Header, ExtendedHeader}; use snapshot::SnapshotComponents; use spec::CommonParams; use types::transaction::{self, UnverifiedTransaction, SignedTransaction}; use ethkey::{Signature}; -use parity_machine::{Machine, LocalizedMachine as Localized, TotalScoredHeader}; +use parity_machine::{Machine, LocalizedMachine as Localized}; use ethereum_types::{H256, U256, Address}; use unexpected::{Mismatch, OutOfBounds}; use bytes::Bytes; @@ -255,7 +255,7 @@ pub trait Engine: Sync + Send { &self, _block: &mut M::LiveBlock, _epoch_begin: bool, - _ancestry: &mut Iterator, + _ancestry: &mut Iterator, ) -> Result<(), M::Error> { Ok(()) } @@ -421,16 +421,16 @@ pub trait Engine: Sync + Send { /// Gather all ancestry actions. Called at the last stage when a block is committed. The Engine must guarantee that /// the ancestry exists. - fn ancestry_actions(&self, _header: &M::Header, _ancestry: &mut Iterator) -> Vec { + fn ancestry_actions(&self, _header: &M::Header, _ancestry: &mut Iterator) -> Vec { Vec::new() } /// Check whether the given new block is the best block, after finalization check. - fn fork_choice(&self, new: &M::ExtendedHeader, best: &M::ExtendedHeader) -> ForkChoice; + fn fork_choice(&self, new: &ExtendedHeader, best: &ExtendedHeader) -> ForkChoice; } /// Check whether a given block is the best block based on the default total difficulty rule. -pub fn total_difficulty_fork_choice(new: &T, best: &T) -> ForkChoice where ::Value: Ord { +pub fn total_difficulty_fork_choice(new: &ExtendedHeader, best: &ExtendedHeader) -> ForkChoice { if new.total_score() > best.total_score() { ForkChoice::New } else { diff --git a/ethcore/src/engines/null_engine.rs b/ethcore/src/engines/null_engine.rs index 4a2610259c4..74eb2dae809 100644 --- a/ethcore/src/engines/null_engine.rs +++ b/ethcore/src/engines/null_engine.rs @@ -18,8 +18,9 @@ use engines::Engine; use engines::block_reward::{self, RewardKind}; use ethereum_types::U256; use machine::WithRewards; -use parity_machine::{Machine, Header, LiveBlock, TotalScoredHeader}; +use parity_machine::{Machine, Header, LiveBlock}; use types::BlockNumber; +use types::header::ExtendedHeader; /// Params for a null engine. #[derive(Clone, Default)] @@ -58,10 +59,7 @@ impl Default for NullEngine { } } -impl Engine for NullEngine - where M::ExtendedHeader: TotalScoredHeader, - ::Value: Ord -{ +impl Engine for NullEngine { fn name(&self) -> &str { "NullEngine" } @@ -105,7 +103,7 @@ impl Engine for NullEngine Some(Box::new(::snapshot::PowSnapshot::new(10000, 10000))) } - fn fork_choice(&self, new: &M::ExtendedHeader, current: &M::ExtendedHeader) -> super::ForkChoice { + fn fork_choice(&self, new: &ExtendedHeader, current: &ExtendedHeader) -> super::ForkChoice { super::total_difficulty_fork_choice(new, current) } } diff --git a/ethcore/src/machine.rs b/ethcore/src/machine.rs index c0eae63d1e1..c273fc84cff 100644 --- a/ethcore/src/machine.rs +++ b/ethcore/src/machine.rs @@ -24,7 +24,7 @@ use ethereum_types::{U256, H256, Address}; use rlp::Rlp; use types::transaction::{self, SYSTEM_ADDRESS, UNSIGNED_SENDER, UnverifiedTransaction, SignedTransaction}; use types::BlockNumber; -use types::header::{Header, ExtendedHeader}; +use types::header::Header; use vm::{CallType, ActionParams, ActionValue, ParamsType}; use vm::{EnvInfo, Schedule, CreateContractAddress}; @@ -430,7 +430,6 @@ pub enum AuxiliaryRequest { impl ::parity_machine::Machine for EthereumMachine { type Header = Header; - type ExtendedHeader = ExtendedHeader; type LiveBlock = ExecutedBlock; type EngineClient = ::client::EngineClient; diff --git a/ethcore/types/src/header.rs b/ethcore/types/src/header.rs index 829776f013e..e2b90e754a7 100644 --- a/ethcore/types/src/header.rs +++ b/ethcore/types/src/header.rs @@ -376,13 +376,6 @@ impl ::parity_machine::Header for Header { fn number(&self) -> BlockNumber { Header::number(self) } } -impl ::parity_machine::ScoredHeader for Header { - type Value = U256; - - fn score(&self) -> &U256 { self.difficulty() } - fn set_score(&mut self, score: U256) { self.set_difficulty(score) } -} - impl ::parity_machine::Header for ExtendedHeader { fn bare_hash(&self) -> H256 { self.header.bare_hash() } fn hash(&self) -> H256 { self.header.hash() } @@ -391,21 +384,11 @@ impl ::parity_machine::Header for ExtendedHeader { fn number(&self) -> BlockNumber { self.header.number() } } -impl ::parity_machine::ScoredHeader for ExtendedHeader { - type Value = U256; - - fn score(&self) -> &U256 { self.header.difficulty() } - fn set_score(&mut self, score: U256) { self.header.set_difficulty(score) } -} - -impl ::parity_machine::TotalScoredHeader for ExtendedHeader { - type Value = U256; - - fn total_score(&self) -> U256 { self.parent_total_difficulty + *self.header.difficulty() } -} - -impl ::parity_machine::FinalizableHeader for ExtendedHeader { - fn is_finalized(&self) -> bool { self.is_finalized } +impl ExtendedHeader { + /// Returns combined difficulty of all ancestors together with the difficulty of this header. + pub fn total_score(&self) -> U256 { + self.parent_total_difficulty + *self.header.difficulty() + } } #[cfg(test)] diff --git a/machine/src/lib.rs b/machine/src/lib.rs index b7054ca038e..bf2b35e8b62 100644 --- a/machine/src/lib.rs +++ b/machine/src/lib.rs @@ -40,37 +40,6 @@ pub trait Header { fn number(&self) -> u64; } -/// A header with an associated score (difficulty in PoW terms) -pub trait ScoredHeader: Header { - type Value; - - /// Get the score of this header. - fn score(&self) -> &Self::Value; - - /// Set the score of this header. - fn set_score(&mut self, score: Self::Value); -} - -/// A header with associated total score. -pub trait TotalScoredHeader: Header { - type Value; - - /// Get the total score of this header. - fn total_score(&self) -> Self::Value; -} - -/// A header with finalized information. -pub trait FinalizableHeader: Header { - /// Get whether this header is considered finalized, so that it will never be replaced in reorganization. - fn is_finalized(&self) -> bool; -} - -/// A header with metadata information. -pub trait WithMetadataHeader: Header { - /// Get the current header metadata. - fn metadata(&self) -> Option<&[u8]>; -} - /// A "live" block is one which is in the process of the transition. /// The state of this block can be mutated by arbitrary rules of the /// state transition function. @@ -101,8 +70,6 @@ pub trait Machine: for<'a> LocalizedMachine<'a> { type Header: Header; /// The live block type. type LiveBlock: LiveBlock; - /// Block header with metadata information. - type ExtendedHeader: Header; /// A handle to a blockchain client for this machine. type EngineClient: ?Sized; /// A description of needed auxiliary data. From 4320c9bc4f8e94c4199c2fc10099896d2f5485ff Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Mon, 11 Mar 2019 11:48:01 +0100 Subject: [PATCH 08/27] docs(spec): remove link to obsolete issue (#10464) --- ethcore/src/spec/spec.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 2726ed4fd52..82dd5da5c4b 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -999,7 +999,6 @@ mod tests { use types::view; use types::views::BlockView; - // https://github.com/paritytech/parity-ethereum/issues/1840 #[test] fn test_load_empty() { let tempdir = TempDir::new("").unwrap(); From 82a148a99b2e73de7365a8e095b5e7d498e70b5b Mon Sep 17 00:00:00 2001 From: TriplEight Date: Mon, 11 Mar 2019 15:26:35 +0100 Subject: [PATCH 09/27] Tests parallelized (#10452) * tests splitted, phase 1 * typo * fix wrong launch commands * typos * rearrangements * use `nproc` function for threads * use nproc for threads * let theads be auto, build-andriod no more in regular run * split val chain and cargo check * renamed some files * wrong phase * check rust files before test jobs * lint error * rust files modivied var * test except changes * add rust_changes except * lint error * fixes * .gitlab-ci.yml can't be excluded * pipeline shouldn't start * pipeline must go * pipeline must go 2 * pipeline must go 3 * pipeline must go 4 * pipeline must go 5 * pipeline must go 6 * pipeline must go 7 * pipeline must not go 1 * pipeline must go 8 * avoid skippng tests yet, reintroducing them after the caching * test theory * parallelized cargo check with combusting helicopters * less uploads * alias for cargo checks * nice template --- .gitlab-ci.yml | 69 +++++++++++----- .../gitlab/{build-unix.sh => build-linux.sh} | 0 .../gitlab/{test-all.sh => rust-changes.sh} | 4 +- scripts/gitlab/test-cpp.sh | 17 ++++ scripts/gitlab/test-linux.sh | 12 +++ .../validate-chainspecs.sh} | 9 ++- test.sh | 79 ------------------- 7 files changed, 87 insertions(+), 103 deletions(-) rename scripts/gitlab/{build-unix.sh => build-linux.sh} (100%) rename scripts/gitlab/{test-all.sh => rust-changes.sh} (87%) create mode 100755 scripts/gitlab/test-cpp.sh create mode 100755 scripts/gitlab/test-linux.sh rename scripts/{validate_chainspecs.sh => gitlab/validate-chainspecs.sh} (51%) delete mode 100755 test.sh diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 19885642338..079b8ed8f8e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -24,8 +24,7 @@ variables: - tags - schedules - -.collect_artifacts: &collect_artifacts +.collect_artifacts: &collect_artifacts artifacts: name: "${CI_JOB_NAME}_${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}}" when: on_success @@ -33,34 +32,66 @@ variables: paths: - artifacts/ -test-linux: - stage: test - variables: - RUN_TESTS: all - script: - - scripts/gitlab/test-all.sh +.docker-cache-status: &docker-cache-status + dependencies: [] + before_script: + - sccache -s + after_script: - sccache -s tags: - linux-docker -test-audit: + +cargo-check 0 3: + stage: test + <<: *docker-cache-status + script: + - time cargo check --target $CARGO_TARGET --locked --no-default-features + +cargo-check 1 3: + stage: test + <<: *docker-cache-status + script: + - time cargo check --target $CARGO_TARGET --locked --manifest-path util/io/Cargo.toml --no-default-features + +cargo-check 2 3: + stage: test + <<: *docker-cache-status + script: + - time cargo check --target $CARGO_TARGET --locked --manifest-path util/io/Cargo.toml --features "mio" + +cargo-audit: stage: test script: - - set -e - - set -u - cargo audit tags: - linux-docker +validate-chainspecs: + stage: test + <<: *docker-cache-status + script: + - ./scripts/gitlab/validate-chainspecs.sh + +test-cpp: + stage: build + <<: *docker-cache-status + script: + - ./scripts/gitlab/test-cpp.sh + +test-linux: + stage: build + <<: *docker-cache-status + script: + - ./scripts/gitlab/test-linux.sh + build-linux: &build-linux stage: build only: *releaseable_branches + <<: *docker-cache-status script: - - scripts/gitlab/build-unix.sh - - sccache -s + - scripts/gitlab/build-linux.sh <<: *collect_artifacts - tags: - - linux-docker build-linux-i386: <<: *build-linux @@ -88,7 +119,7 @@ build-darwin: CC: gcc CXX: g++ script: - - scripts/gitlab/build-unix.sh + - scripts/gitlab/build-linux.sh tags: - rust-osx <<: *collect_artifacts @@ -203,14 +234,12 @@ publish-docs: - linux-docker build-android: - stage: optional + stage: build image: parity/rust-android:gitlab-ci variables: CARGO_TARGET: armv7-linux-androideabi - dependencies: [] script: - - scripts/gitlab/build-unix.sh + - scripts/gitlab/build-linux.sh tags: - linux-docker - allow_failure: true <<: *collect_artifacts diff --git a/scripts/gitlab/build-unix.sh b/scripts/gitlab/build-linux.sh similarity index 100% rename from scripts/gitlab/build-unix.sh rename to scripts/gitlab/build-linux.sh diff --git a/scripts/gitlab/test-all.sh b/scripts/gitlab/rust-changes.sh similarity index 87% rename from scripts/gitlab/test-all.sh rename to scripts/gitlab/rust-changes.sh index 925124b7ac2..236a20d59ee 100755 --- a/scripts/gitlab/test-all.sh +++ b/scripts/gitlab/rust-changes.sh @@ -1,7 +1,9 @@ #!/bin/bash +echo "________Running rust_changes.sh________" set -e # fail on any error set -u # treat unset variables as error +echo "__________Checking if Rust files were changed__________" git log --graph --oneline --decorate=short -n 10 case ${SCHEDULE_TAG:-${CI_COMMIT_REF_NAME}} in @@ -26,5 +28,3 @@ then fi rustup show - -exec ./test.sh diff --git a/scripts/gitlab/test-cpp.sh b/scripts/gitlab/test-cpp.sh new file mode 100755 index 00000000000..9f825ec8c70 --- /dev/null +++ b/scripts/gitlab/test-cpp.sh @@ -0,0 +1,17 @@ +#!/bin/bash +echo "________Running test-cpp.sh________" +set -e # fail on any error +set -u # treat unset variables as error +#use nproc `linux only +THREADS=$(nproc) + +echo "________Running the C++ example________" +DIR=parity-clib/examples/cpp/build +mkdir -p $DIR +cd $DIR +cmake .. +make -j $THREADS +# Note: we don't try to run the example because it tries to sync Kovan, and we don't want +# that to happen on CI +cd - +rm -rf $DIR diff --git a/scripts/gitlab/test-linux.sh b/scripts/gitlab/test-linux.sh new file mode 100755 index 00000000000..6a98d2f7bd5 --- /dev/null +++ b/scripts/gitlab/test-linux.sh @@ -0,0 +1,12 @@ +#!/bin/bash +echo "________Running test-linux.sh________" +set -e # fail on any error +set -u # treat unset variables as error + +FEATURES="json-tests,ci-skip-tests" +OPTIONS="--release" +#use nproc `linux only +THREADS=$(nproc) + +echo "________Running Parity Full Test Suite________" +time cargo test $OPTIONS --features "$FEATURES" --locked --all --target $CARGO_TARGET -- --test-threads $THREADS diff --git a/scripts/validate_chainspecs.sh b/scripts/gitlab/validate-chainspecs.sh similarity index 51% rename from scripts/validate_chainspecs.sh rename to scripts/gitlab/validate-chainspecs.sh index c350445dd9b..9b7ef39e727 100755 --- a/scripts/validate_chainspecs.sh +++ b/scripts/gitlab/validate-chainspecs.sh @@ -1,7 +1,12 @@ -#!/usr/bin/env sh +#!/bin/bash +set -e # fail on any error +set -u # treat unset variables as error +echo "________Running validate_chainspecs.sh________" ERR=0 -cargo build --release -p chainspec + +echo "________Validate chainspecs________" +time cargo build --release -p chainspec for spec in ethcore/res/*.json; do if ! ./target/release/chainspec "$spec"; then ERR=1; fi diff --git a/test.sh b/test.sh deleted file mode 100755 index e7d8e2a7890..00000000000 --- a/test.sh +++ /dev/null @@ -1,79 +0,0 @@ -#!/bin/sh -# Running Parity Full Test Suite -echo "________Running test.sh________" - -FEATURES="json-tests,ci-skip-tests" -OPTIONS="--release" -VALIDATE=1 -THREADS=8 - -set -e - - -validate () { - if [ "$VALIDATE" -eq "1" ] - then - echo "________Validate build________" - time cargo check $@ --locked --no-default-features - time cargo check $@ --locked --manifest-path util/io/Cargo.toml --no-default-features - time cargo check $@ --locked --manifest-path util/io/Cargo.toml --features "mio" - - # Validate chainspecs - echo "________Validate chainspecs________" - time ./scripts/validate_chainspecs.sh - else - echo "# not validating due to \$VALIDATE!=1" - fi -} - -cpp_test () { - case $CARGO_TARGET in - (x86_64-unknown-linux-gnu) - # Running the C++ example - echo "________Running the C++ example________" - DIR=parity-clib/examples/cpp/build - mkdir -p $DIR - cd $DIR - cmake .. - make -j $THREADS - # Note: we don't try to run the example because it tries to sync Kovan, and we don't want - # that to happen on CI - cd - - rm -rf $DIR - ;; - (*) - echo "________Skipping the C++ example________" - ;; - esac -} - -cargo_test () { - echo "________Running Parity Full Test Suite________" - git submodule update --init --recursive - time cargo test $OPTIONS --features "$FEATURES" --locked --all $@ -- --test-threads $THREADS -} - - -if [ "$CARGO_TARGET" ] -then - validate --target $CARGO_TARGET -else - validate -fi - -test "${RUN_TESTS}" = "all" && cpp_test - -if [ "$CARGO_TARGET" ] -then - - case "${RUN_TESTS}" in - (cargo|all) - cargo_test --target $CARGO_TARGET $@ - ;; - ('') - cargo_test --no-run --target $CARGO_TARGET $@ - ;; - esac -else - cargo_test $@ -fi From 595dac6c3f8f2d3799f96339a1092435e82bc2b8 Mon Sep 17 00:00:00 2001 From: Hernando Castano Date: Tue, 12 Mar 2019 19:16:29 +0100 Subject: [PATCH 10/27] Ensure static validator set changes are recognized (#10467) --- ethcore/src/engines/authority_round/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index ef439b5d4ba..31062d80f3d 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -1413,8 +1413,10 @@ impl Engine for AuthorityRound { let first = chain_head.number() == 0; - // apply immediate transitions. + // Apply transitions that don't require finality and should be enacted immediately (e.g from chain spec) if let Some(change) = self.validators.is_epoch_end(first, chain_head) { + info!(target: "engine", "Immediately applying validator set change signalled at block {}", chain_head.number()); + self.epoch_manager.lock().note_new_epoch(); let change = combine_proofs(chain_head.number(), &change, &[]); return Some(change) } From a16bad4175abc200269ceb6c2c11492fafdb9f4c Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Wed, 13 Mar 2019 11:36:13 +0100 Subject: [PATCH 11/27] simplify parity machine (#10469) * simplify ethcore machine by removing redundant traits * further ethereum machine simplifications * removed obsolete todo --- Cargo.lock | 9 --- ethcore/Cargo.toml | 1 - ethcore/src/block.rs | 20 ----- ethcore/src/engines/block_reward.rs | 22 ++++-- ethcore/src/engines/instant_seal.rs | 17 +++-- ethcore/src/engines/mod.rs | 75 +++++++++++++------ ethcore/src/engines/null_engine.rs | 20 ++--- ethcore/src/ethereum/ethash.rs | 12 +-- ethcore/src/lib.rs | 1 - ethcore/src/{machine.rs => machine/impls.rs} | 40 +--------- ethcore/src/machine/mod.rs | 7 ++ .../lib.rs => ethcore/src/machine/traits.rs | 56 +------------- ethcore/src/trace/types/trace.rs | 2 +- ethcore/types/Cargo.toml | 1 - ethcore/types/src/engines/epoch.rs | 25 ------- ethcore/types/src/header.rs | 16 ---- ethcore/types/src/lib.rs | 1 - machine/Cargo.toml | 8 -- 18 files changed, 109 insertions(+), 224 deletions(-) rename ethcore/src/{machine.rs => machine/impls.rs} (94%) create mode 100644 ethcore/src/machine/mod.rs rename machine/src/lib.rs => ethcore/src/machine/traits.rs (54%) delete mode 100644 machine/Cargo.toml diff --git a/Cargo.lock b/Cargo.lock index 71061696dee..b6c0b3ef61f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -306,7 +306,6 @@ dependencies = [ "heapsize 0.4.2 (git+https://github.com/cheme/heapsize.git?branch=ec-macfix)", "keccak-hash 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "parity-bytes 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-machine 0.1.0", "rlp 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "rlp_derive 0.1.0", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -739,7 +738,6 @@ dependencies = [ "num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-bytes 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-crypto 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-machine 0.1.0", "parity-runtime 0.1.0", "parity-snappy 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2600,13 +2598,6 @@ dependencies = [ "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "parity-machine" -version = "0.1.0" -dependencies = [ - "ethereum-types 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parity-path" version = "0.1.1" diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 0e3cea0fc6d..2d26ba03814 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -50,7 +50,6 @@ num = { version = "0.1", default-features = false, features = ["bigint"] } num_cpus = "1.2" parity-bytes = "0.1" parity-crypto = "0.3.0" -parity-machine = { path = "../machine" } parity-snappy = "0.1" parking_lot = "0.7" trie-db = "0.11.0" diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index e5fcb451617..9d3528bb0d5 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -195,26 +195,6 @@ impl IsBlock for ExecutedBlock { fn block(&self) -> &ExecutedBlock { self } } -impl ::parity_machine::LiveBlock for ExecutedBlock { - type Header = Header; - - fn header(&self) -> &Header { - &self.header - } - - fn uncles(&self) -> &[Header] { - &self.uncles - } -} - -impl ::parity_machine::Transactions for ExecutedBlock { - type Transaction = SignedTransaction; - - fn transactions(&self) -> &[SignedTransaction] { - &self.transactions - } -} - impl<'x> OpenBlock<'x> { /// Create a new `OpenBlock` ready for transaction pushing. pub fn new<'a>( diff --git a/ethcore/src/engines/block_reward.rs b/ethcore/src/engines/block_reward.rs index a95e3820ef7..58b55408ebe 100644 --- a/ethcore/src/engines/block_reward.rs +++ b/ethcore/src/engines/block_reward.rs @@ -24,11 +24,12 @@ use ethereum_types::{H160, Address, U256}; use std::sync::Arc; use hash::keccak; use error::Error; -use machine::WithRewards; -use parity_machine::Machine; +use machine::Machine; use trace; use types::BlockNumber; use super::{SystemOrCodeCall, SystemOrCodeCallKind}; +use trace::{Tracer, ExecutiveTracer, Tracing}; +use block::ExecutedBlock; use_contract!(block_reward_contract, "res/contracts/block_reward.json"); @@ -152,17 +153,26 @@ impl BlockRewardContract { /// Applies the given block rewards, i.e. adds the given balance to each beneficiary' address. /// If tracing is enabled the operations are recorded. -pub fn apply_block_rewards( +pub fn apply_block_rewards( rewards: &[(Address, RewardKind, U256)], - block: &mut M::LiveBlock, + block: &mut ExecutedBlock, machine: &M, ) -> Result<(), M::Error> { for &(ref author, _, ref block_reward) in rewards { machine.add_balance(block, author, block_reward)?; } - let rewards: Vec<_> = rewards.into_iter().map(|&(a, k, r)| (a, k.into(), r)).collect(); - machine.note_rewards(block, &rewards) + if let Tracing::Enabled(ref mut traces) = *block.traces_mut() { + let mut tracer = ExecutiveTracer::default(); + + for &(address, reward_kind, amount) in rewards { + tracer.trace_reward(address, amount, reward_kind.into()); + } + + traces.push(tracer.drain().into()); + } + + Ok(()) } #[cfg(test)] diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index 189015f0815..93e20196a46 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -15,8 +15,9 @@ // along with Parity Ethereum. If not, see . use engines::{Engine, Seal}; -use parity_machine::{Machine, Transactions}; -use types::header::ExtendedHeader; +use machine::Machine; +use types::header::{Header, ExtendedHeader}; +use block::ExecutedBlock; /// `InstantSeal` params. #[derive(Default, Debug, PartialEq)] @@ -49,7 +50,7 @@ impl InstantSeal { } } -impl Engine for InstantSeal where M::LiveBlock: Transactions { +impl Engine for InstantSeal { fn name(&self) -> &str { "InstantSeal" } @@ -58,11 +59,15 @@ impl Engine for InstantSeal where M::LiveBlock: Transactions { fn seals_internally(&self) -> Option { Some(true) } - fn generate_seal(&self, block: &M::LiveBlock, _parent: &M::Header) -> Seal { - if block.transactions().is_empty() { Seal::None } else { Seal::Regular(Vec::new()) } + fn generate_seal(&self, block: &ExecutedBlock, _parent: &Header) -> Seal { + if block.transactions.is_empty() { + Seal::None + } else { + Seal::Regular(Vec::new()) + } } - fn verify_local_seal(&self, _header: &M::Header) -> Result<(), M::Error> { + fn verify_local_seal(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index a63c69039ca..e7be7bebbab 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -27,14 +27,13 @@ pub mod signer; pub use self::authority_round::AuthorityRound; pub use self::basic_authority::BasicAuthority; -pub use self::epoch::{EpochVerifier, Transition as EpochTransition}; pub use self::instant_seal::{InstantSeal, InstantSealParams}; pub use self::null_engine::NullEngine; pub use self::signer::EngineSigner; // TODO [ToDr] Remove re-export (#10130) pub use types::engines::ForkChoice; -pub use types::engines::epoch; +pub use types::engines::epoch::{self, Transition as EpochTransition}; use std::sync::{Weak, Arc}; use std::collections::{BTreeMap, HashMap}; @@ -50,11 +49,13 @@ use spec::CommonParams; use types::transaction::{self, UnverifiedTransaction, SignedTransaction}; use ethkey::{Signature}; -use parity_machine::{Machine, LocalizedMachine as Localized}; +use machine::{Machine, LocalizedMachine as Localized}; use ethereum_types::{H256, U256, Address}; use unexpected::{Mismatch, OutOfBounds}; use bytes::Bytes; use types::ancestry_action::AncestryAction; +use block::ExecutedBlock; +use machine; /// Default EIP-210 contract code. /// As defined in https://github.com/ethereum/EIPs/pull/210 @@ -235,10 +236,10 @@ pub trait Engine: Sync + Send { fn machine(&self) -> &M; /// The number of additional header fields required for this engine. - fn seal_fields(&self, _header: &M::Header) -> usize { 0 } + fn seal_fields(&self, _header: &Header) -> usize { 0 } /// Additional engine-specific information for the user/developer concerning `header`. - fn extra_info(&self, _header: &M::Header) -> BTreeMap { BTreeMap::new() } + fn extra_info(&self, _header: &Header) -> BTreeMap { BTreeMap::new() } /// Maximum number of uncles a block is allowed to declare. fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 } @@ -253,7 +254,7 @@ pub trait Engine: Sync + Send { /// `epoch_begin` set to true if this block kicks off an epoch. fn on_new_block( &self, - _block: &mut M::LiveBlock, + _block: &mut ExecutedBlock, _epoch_begin: bool, _ancestry: &mut Iterator, ) -> Result<(), M::Error> { @@ -261,7 +262,7 @@ pub trait Engine: Sync + Send { } /// Block transformation functions, after the transactions. - fn on_close_block(&self, _block: &mut M::LiveBlock) -> Result<(), M::Error> { + fn on_close_block(&self, _block: &mut ExecutedBlock) -> Result<(), M::Error> { Ok(()) } @@ -279,7 +280,7 @@ pub trait Engine: Sync + Send { /// /// It is fine to require access to state or a full client for this function, since /// light clients do not generate seals. - fn generate_seal(&self, _block: &M::LiveBlock, _parent: &M::Header) -> Seal { Seal::None } + fn generate_seal(&self, _block: &ExecutedBlock, _parent: &Header) -> Seal { Seal::None } /// Verify a locally-generated seal of a header. /// @@ -291,25 +292,25 @@ pub trait Engine: Sync + Send { /// /// It is fine to require access to state or a full client for this function, since /// light clients do not generate seals. - fn verify_local_seal(&self, header: &M::Header) -> Result<(), M::Error>; + fn verify_local_seal(&self, header: &Header) -> Result<(), M::Error>; /// Phase 1 quick block verification. Only does checks that are cheap. Returns either a null `Ok` or a general error detailing the problem with import. /// The verification module can optionally avoid checking the seal (`check_seal`), if seal verification is disabled this method won't be called. - fn verify_block_basic(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) } + fn verify_block_basic(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } /// Phase 2 verification. Perform costly checks such as transaction signatures. Returns either a null `Ok` or a general error detailing the problem with import. /// The verification module can optionally avoid checking the seal (`check_seal`), if seal verification is disabled this method won't be called. - fn verify_block_unordered(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) } + fn verify_block_unordered(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } /// Phase 3 verification. Check block information against parent. Returns either a null `Ok` or a general error detailing the problem with import. - fn verify_block_family(&self, _header: &M::Header, _parent: &M::Header) -> Result<(), M::Error> { Ok(()) } + fn verify_block_family(&self, _header: &Header, _parent: &Header) -> Result<(), M::Error> { Ok(()) } /// Phase 4 verification. Verify block header against potentially external data. /// Should only be called when `register_client` has been called previously. - fn verify_block_external(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) } + fn verify_block_external(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } /// Genesis epoch data. - fn genesis_epoch_data<'a>(&self, _header: &M::Header, _state: &>::StateContext) -> Result, String> { Ok(Vec::new()) } + fn genesis_epoch_data<'a>(&self, _header: &Header, _state: &>::StateContext) -> Result, String> { Ok(Vec::new()) } /// Whether an epoch change is signalled at the given header but will require finality. /// If a change can be enacted immediately then return `No` from this function but @@ -320,7 +321,7 @@ pub trait Engine: Sync + Send { /// Return `Yes` or `No` when the answer is definitively known. /// /// Should not interact with state. - fn signals_epoch_end<'a>(&self, _header: &M::Header, _aux: >::AuxiliaryData) + fn signals_epoch_end<'a>(&self, _header: &Header, _aux: >::AuxiliaryData) -> EpochChange { EpochChange::No @@ -336,9 +337,9 @@ pub trait Engine: Sync + Send { /// Return optional transition proof. fn is_epoch_end( &self, - _chain_head: &M::Header, + _chain_head: &Header, _finalized: &[H256], - _chain: &Headers, + _chain: &Headers
, _transition_store: &PendingTransitionStore, ) -> Option> { None @@ -355,8 +356,8 @@ pub trait Engine: Sync + Send { /// Return optional transition proof. fn is_epoch_end_light( &self, - _chain_head: &M::Header, - _chain: &Headers, + _chain_head: &Header, + _chain: &Headers
, _transition_store: &PendingTransitionStore, ) -> Option> { None @@ -364,13 +365,13 @@ pub trait Engine: Sync + Send { /// Create an epoch verifier from validation proof and a flag indicating /// whether finality is required. - fn epoch_verifier<'a>(&self, _header: &M::Header, _proof: &'a [u8]) -> ConstructedVerifier<'a, M> { - ConstructedVerifier::Trusted(Box::new(self::epoch::NoOp)) + fn epoch_verifier<'a>(&self, _header: &Header, _proof: &'a [u8]) -> ConstructedVerifier<'a, M> { + ConstructedVerifier::Trusted(Box::new(NoOp)) } /// Populate a header's fields based on its parent's header. /// Usually implements the chain scoring rule based on weight. - fn populate_from_parent(&self, _header: &mut M::Header, _parent: &M::Header) { } + fn populate_from_parent(&self, _header: &mut Header, _parent: &Header) { } /// Handle any potential consensus messages; /// updating consensus state and potentially issuing a new one. @@ -378,7 +379,7 @@ pub trait Engine: Sync + Send { /// Find out if the block is a proposal block and should not be inserted into the DB. /// Takes a header of a fully verified block. - fn is_proposal(&self, _verified_header: &M::Header) -> bool { false } + fn is_proposal(&self, _verified_header: &Header) -> bool { false } /// Register a component which signs consensus messages. fn set_signer(&self, _signer: Box) {} @@ -421,7 +422,7 @@ pub trait Engine: Sync + Send { /// Gather all ancestry actions. Called at the last stage when a block is committed. The Engine must guarantee that /// the ancestry exists. - fn ancestry_actions(&self, _header: &M::Header, _ancestry: &mut Iterator) -> Vec { + fn ancestry_actions(&self, _header: &Header, _ancestry: &mut Iterator) -> Vec { Vec::new() } @@ -523,3 +524,29 @@ pub trait EthEngine: Engine<::machine::EthereumMachine> { // convenience wrappers for existing functions. impl EthEngine for T where T: Engine<::machine::EthereumMachine> { } + +/// Verifier for all blocks within an epoch with self-contained state. +pub trait EpochVerifier: Send + Sync { + /// Lightly verify the next block header. + /// This may not be a header belonging to a different epoch. + fn verify_light(&self, header: &Header) -> Result<(), M::Error>; + + /// Perform potentially heavier checks on the next block header. + fn verify_heavy(&self, header: &Header) -> Result<(), M::Error> { + self.verify_light(header) + } + + /// Check a finality proof against this epoch verifier. + /// Returns `Some(hashes)` if the proof proves finality of these hashes. + /// Returns `None` if the proof doesn't prove anything. + fn check_finality_proof(&self, _proof: &[u8]) -> Option> { + None + } +} + +/// Special "no-op" verifier for stateless, epoch-less engines. +pub struct NoOp; + +impl EpochVerifier for NoOp { + fn verify_light(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } +} diff --git a/ethcore/src/engines/null_engine.rs b/ethcore/src/engines/null_engine.rs index 74eb2dae809..27138985ad6 100644 --- a/ethcore/src/engines/null_engine.rs +++ b/ethcore/src/engines/null_engine.rs @@ -17,10 +17,10 @@ use engines::Engine; use engines::block_reward::{self, RewardKind}; use ethereum_types::U256; -use machine::WithRewards; -use parity_machine::{Machine, Header, LiveBlock}; +use machine::Machine; use types::BlockNumber; -use types::header::ExtendedHeader; +use types::header::{Header, ExtendedHeader}; +use block::ExecutedBlock; /// Params for a null engine. #[derive(Clone, Default)] @@ -59,23 +59,23 @@ impl Default for NullEngine { } } -impl Engine for NullEngine { +impl Engine for NullEngine { fn name(&self) -> &str { "NullEngine" } fn machine(&self) -> &M { &self.machine } - fn on_close_block(&self, block: &mut M::LiveBlock) -> Result<(), M::Error> { + fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), M::Error> { use std::ops::Shr; - let author = *LiveBlock::header(&*block).author(); - let number = LiveBlock::header(&*block).number(); + let author = *block.header.author(); + let number = block.header.number(); let reward = self.params.block_reward; if reward == U256::zero() { return Ok(()) } - let n_uncles = LiveBlock::uncles(&*block).len(); + let n_uncles = block.uncles.len(); let mut rewards = Vec::new(); @@ -84,7 +84,7 @@ impl Engine for NullEngine { rewards.push((author, RewardKind::Author, result_block_reward)); // bestow uncle rewards. - for u in LiveBlock::uncles(&*block) { + for u in &block.uncles { let uncle_author = u.author(); let result_uncle_reward = (reward * U256::from(8 + u.number() - number)).shr(3); rewards.push((*uncle_author, RewardKind::uncle(number, u.number()), result_uncle_reward)); @@ -95,7 +95,7 @@ impl Engine for NullEngine { fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 2 } - fn verify_local_seal(&self, _header: &M::Header) -> Result<(), M::Error> { + fn verify_local_seal(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 293009fdecf..561b3493be8 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -241,17 +241,16 @@ impl Engine for Arc { /// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current). fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { use std::ops::Shr; - use parity_machine::LiveBlock; - let author = *LiveBlock::header(&*block).author(); - let number = LiveBlock::header(&*block).number(); + let author = *block.header.author(); + let number = block.header.number(); let rewards = match self.ethash_params.block_reward_contract { Some(ref c) if number >= self.ethash_params.block_reward_contract_transition => { let mut beneficiaries = Vec::new(); beneficiaries.push((author, RewardKind::Author)); - for u in LiveBlock::uncles(&*block) { + for u in &block.uncles { let uncle_author = u.author(); beneficiaries.push((*uncle_author, RewardKind::uncle(number, u.number()))); } @@ -274,7 +273,8 @@ impl Engine for Arc { let eras_rounds = self.ethash_params.ecip1017_era_rounds; let (eras, reward) = ecip1017_eras_block_reward(eras_rounds, reward, number); - let n_uncles = LiveBlock::uncles(&*block).len(); + //let n_uncles = LiveBlock::uncles(&*block).len(); + let n_uncles = block.uncles.len(); // Bestow block rewards. let mut result_block_reward = reward + reward.shr(5) * U256::from(n_uncles); @@ -282,7 +282,7 @@ impl Engine for Arc { rewards.push((author, RewardKind::Author, result_block_reward)); // Bestow uncle rewards. - for u in LiveBlock::uncles(&*block) { + for u in &block.uncles { let uncle_author = u.author(); let result_uncle_reward = if eras == 0 { (reward * U256::from(8 + u.number() - number)).shr(3) diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 5ba6a26d013..17b33025a1c 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -89,7 +89,6 @@ extern crate num; extern crate num_cpus; extern crate parity_bytes as bytes; extern crate parity_crypto; -extern crate parity_machine; extern crate parity_snappy as snappy; extern crate parking_lot; extern crate trie_db as trie; diff --git a/ethcore/src/machine.rs b/ethcore/src/machine/impls.rs similarity index 94% rename from ethcore/src/machine.rs rename to ethcore/src/machine/impls.rs index c273fc84cff..4cb052b9fe7 100644 --- a/ethcore/src/machine.rs +++ b/ethcore/src/machine/impls.rs @@ -36,7 +36,7 @@ use error::Error; use executive::Executive; use spec::CommonParams; use state::{CleanupMode, Substate}; -use trace::{NoopTracer, NoopVMTracer, Tracer, ExecutiveTracer, RewardType, Tracing}; +use trace::{NoopTracer, NoopVMTracer}; use tx_filter::TransactionFilter; /// Parity tries to round block.gas_limit to multiple of this constant @@ -428,10 +428,7 @@ pub enum AuxiliaryRequest { Both, } -impl ::parity_machine::Machine for EthereumMachine { - type Header = Header; - - type LiveBlock = ExecutedBlock; +impl super::Machine for EthereumMachine { type EngineClient = ::client::EngineClient; type AuxiliaryRequest = AuxiliaryRequest; type AncestryAction = ::types::ancestry_action::AncestryAction; @@ -447,42 +444,11 @@ impl ::parity_machine::Machine for EthereumMachine { } } -impl<'a> ::parity_machine::LocalizedMachine<'a> for EthereumMachine { +impl<'a> super::LocalizedMachine<'a> for EthereumMachine { type StateContext = Call<'a>; type AuxiliaryData = AuxiliaryData<'a>; } -/// A state machine that uses block rewards. -pub trait WithRewards: ::parity_machine::Machine { - /// Note block rewards, traces each reward storing information about benefactor, amount and type - /// of reward. - fn note_rewards( - &self, - live: &mut Self::LiveBlock, - rewards: &[(Address, RewardType, U256)], - ) -> Result<(), Self::Error>; -} - -impl WithRewards for EthereumMachine { - fn note_rewards( - &self, - live: &mut Self::LiveBlock, - rewards: &[(Address, RewardType, U256)], - ) -> Result<(), Self::Error> { - if let Tracing::Enabled(ref mut traces) = *live.traces_mut() { - let mut tracer = ExecutiveTracer::default(); - - for &(address, ref reward_type, amount) in rewards { - tracer.trace_reward(address, amount, reward_type.clone()); - } - - traces.push(tracer.drain().into()); - } - - Ok(()) - } -} - // Try to round gas_limit a bit so that: // 1) it will still be in desired range // 2) it will be a nearest (with tendency to increase) multiple of PARITY_GAS_LIMIT_DETERMINANT diff --git a/ethcore/src/machine/mod.rs b/ethcore/src/machine/mod.rs new file mode 100644 index 00000000000..882dc011a20 --- /dev/null +++ b/ethcore/src/machine/mod.rs @@ -0,0 +1,7 @@ +//! Generalization of a state machine for a consensus engine. + +mod impls; +mod traits; + +pub use self::impls::*; +pub use self::traits::*; diff --git a/machine/src/lib.rs b/ethcore/src/machine/traits.rs similarity index 54% rename from machine/src/lib.rs rename to ethcore/src/machine/traits.rs index bf2b35e8b62..4d4004bffeb 100644 --- a/machine/src/lib.rs +++ b/ethcore/src/machine/traits.rs @@ -17,59 +17,11 @@ //! Generalization of a state machine for a consensus engine. //! This will define traits for the header, block, and state of a blockchain. -extern crate ethereum_types; - -use ethereum_types::{H256, U256, Address}; - -/// A header. This contains important metadata about the block, as well as a -/// "seal" that indicates validity to a consensus engine. -pub trait Header { - /// Cryptographic hash of the header, excluding the seal. - fn bare_hash(&self) -> H256; - - /// Cryptographic hash of the header, including the seal. - fn hash(&self) -> H256; - - /// Get a reference to the seal fields. - fn seal(&self) -> &[Vec]; - - /// The author of the header. - fn author(&self) -> &Address; - - /// The number of the header. - fn number(&self) -> u64; -} - -/// A "live" block is one which is in the process of the transition. -/// The state of this block can be mutated by arbitrary rules of the -/// state transition function. -pub trait LiveBlock: 'static { - /// The block header type; - type Header: Header; - - /// Get a reference to the header. - fn header(&self) -> &Self::Header; - - /// Get a reference to the uncle headers. If the block type doesn't - /// support uncles, return the empty slice. - fn uncles(&self) -> &[Self::Header]; -} - -/// Trait for blocks which have a transaction type. -pub trait Transactions: LiveBlock { - /// The transaction type. - type Transaction; - - /// Get a reference to the transactions in this block. - fn transactions(&self) -> &[Self::Transaction]; -} +use ethereum_types::{U256, Address}; +use block::ExecutedBlock; /// Generalization of types surrounding blockchain-suitable state machines. pub trait Machine: for<'a> LocalizedMachine<'a> { - /// The block header type. - type Header: Header; - /// The live block type. - type LiveBlock: LiveBlock; /// A handle to a blockchain client for this machine. type EngineClient: ?Sized; /// A description of needed auxiliary data. @@ -82,10 +34,10 @@ pub trait Machine: for<'a> LocalizedMachine<'a> { /// Get the balance, in base units, associated with an account. /// Extracts data from the live block. - fn balance(&self, live: &Self::LiveBlock, address: &Address) -> Result; + fn balance(&self, live: &ExecutedBlock, address: &Address) -> Result; /// Increment the balance of an account in the state of the live block. - fn add_balance(&self, live: &mut Self::LiveBlock, address: &Address, amount: &U256) -> Result<(), Self::Error>; + fn add_balance(&self, live: &mut ExecutedBlock, address: &Address, amount: &U256) -> Result<(), Self::Error>; } /// Machine-related types localized to a specific lifetime. diff --git a/ethcore/src/trace/types/trace.rs b/ethcore/src/trace/types/trace.rs index 18ec24a84f0..16084e94cbd 100644 --- a/ethcore/src/trace/types/trace.rs +++ b/ethcore/src/trace/types/trace.rs @@ -135,7 +135,7 @@ impl Create { } /// Reward type. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Clone, Copy)] pub enum RewardType { /// Block Block, diff --git a/ethcore/types/Cargo.toml b/ethcore/types/Cargo.toml index 855fd717287..e3f9bd1db63 100644 --- a/ethcore/types/Cargo.toml +++ b/ethcore/types/Cargo.toml @@ -11,7 +11,6 @@ ethkey = { path = "../../accounts/ethkey" } heapsize = "0.4" keccak-hash = "0.1" parity-bytes = "0.1" -parity-machine = { path = "../../machine" } rlp = { version = "0.3.0", features = ["ethereum"] } rlp_derive = { path = "../../util/rlp-derive" } unexpected = { path = "../../util/unexpected" } diff --git a/ethcore/types/src/engines/epoch.rs b/ethcore/types/src/engines/epoch.rs index 34054a193fc..2a43b47755c 100644 --- a/ethcore/types/src/engines/epoch.rs +++ b/ethcore/types/src/engines/epoch.rs @@ -71,28 +71,3 @@ impl Decodable for PendingTransition { } } -/// Verifier for all blocks within an epoch with self-contained state. -pub trait EpochVerifier: Send + Sync { - /// Lightly verify the next block header. - /// This may not be a header belonging to a different epoch. - fn verify_light(&self, header: &M::Header) -> Result<(), M::Error>; - - /// Perform potentially heavier checks on the next block header. - fn verify_heavy(&self, header: &M::Header) -> Result<(), M::Error> { - self.verify_light(header) - } - - /// Check a finality proof against this epoch verifier. - /// Returns `Some(hashes)` if the proof proves finality of these hashes. - /// Returns `None` if the proof doesn't prove anything. - fn check_finality_proof(&self, _proof: &[u8]) -> Option> { - None - } -} - -/// Special "no-op" verifier for stateless, epoch-less engines. -pub struct NoOp; - -impl EpochVerifier for NoOp { - fn verify_light(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) } -} diff --git a/ethcore/types/src/header.rs b/ethcore/types/src/header.rs index e2b90e754a7..3dfe6ab83b1 100644 --- a/ethcore/types/src/header.rs +++ b/ethcore/types/src/header.rs @@ -368,22 +368,6 @@ impl HeapSizeOf for Header { } } -impl ::parity_machine::Header for Header { - fn bare_hash(&self) -> H256 { Header::bare_hash(self) } - fn hash(&self) -> H256 { Header::hash(self) } - fn seal(&self) -> &[Vec] { Header::seal(self) } - fn author(&self) -> &Address { Header::author(self) } - fn number(&self) -> BlockNumber { Header::number(self) } -} - -impl ::parity_machine::Header for ExtendedHeader { - fn bare_hash(&self) -> H256 { self.header.bare_hash() } - fn hash(&self) -> H256 { self.header.hash() } - fn seal(&self) -> &[Vec] { self.header.seal() } - fn author(&self) -> &Address { self.header.author() } - fn number(&self) -> BlockNumber { self.header.number() } -} - impl ExtendedHeader { /// Returns combined difficulty of all ancestors together with the difficulty of this header. pub fn total_score(&self) -> U256 { diff --git a/ethcore/types/src/lib.rs b/ethcore/types/src/lib.rs index 4ca5c80dcf5..3223db72206 100644 --- a/ethcore/types/src/lib.rs +++ b/ethcore/types/src/lib.rs @@ -39,7 +39,6 @@ extern crate ethkey; extern crate heapsize; extern crate keccak_hash as hash; extern crate parity_bytes as bytes; -extern crate parity_machine; extern crate rlp; extern crate unexpected; diff --git a/machine/Cargo.toml b/machine/Cargo.toml deleted file mode 100644 index 2ebb5c40994..00000000000 --- a/machine/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "parity-machine" -version = "0.1.0" -description = "Generalization of a state machine for consensus engines" -authors = ["Parity Technologies "] - -[dependencies] -ethereum-types = "0.4" From c9db8ea21da87ca5432d75ffa974105a4c7142ef Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Thu, 14 Mar 2019 11:28:15 +0100 Subject: [PATCH 12/27] further simplify machine (#10472) * removed AuxiliaryRequest from Machin trait * removed AncestryAction from Machine trait * removed AuxiliaryData from Machine trait * removed LocalizedMachine trait --- ethcore/src/engines/mod.rs | 12 +++++------- ethcore/src/machine/impls.rs | 7 ------- ethcore/src/machine/traits.rs | 16 +--------------- 3 files changed, 6 insertions(+), 29 deletions(-) diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index e7be7bebbab..5e451b5e4f2 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -49,13 +49,12 @@ use spec::CommonParams; use types::transaction::{self, UnverifiedTransaction, SignedTransaction}; use ethkey::{Signature}; -use machine::{Machine, LocalizedMachine as Localized}; +use machine::{self, Machine, AuxiliaryRequest, AuxiliaryData}; use ethereum_types::{H256, U256, Address}; use unexpected::{Mismatch, OutOfBounds}; use bytes::Bytes; use types::ancestry_action::AncestryAction; use block::ExecutedBlock; -use machine; /// Default EIP-210 contract code. /// As defined in https://github.com/ethereum/EIPs/pull/210 @@ -177,8 +176,7 @@ pub type PendingTransitionStore<'a> = Fn(H256) -> Option: Send + Sync { /// Generate a proof, given the state. - // TODO: make this into an &M::StateContext - fn generate_proof<'a>(&self, state: &>::StateContext) -> Result, String>; + fn generate_proof<'a>(&self, state: &machine::Call) -> Result, String>; /// Check a proof generated elsewhere (potentially by a peer). // `engine` needed to check state proofs, while really this should // just be state machine params. @@ -218,7 +216,7 @@ impl<'a, M: Machine> ConstructedVerifier<'a, M> { /// Results of a query of whether an epoch change occurred at the given block. pub enum EpochChange { /// Cannot determine until more data is passed. - Unsure(M::AuxiliaryRequest), + Unsure(AuxiliaryRequest), /// No epoch change. No, /// The epoch will change, with proof. @@ -310,7 +308,7 @@ pub trait Engine: Sync + Send { fn verify_block_external(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) } /// Genesis epoch data. - fn genesis_epoch_data<'a>(&self, _header: &Header, _state: &>::StateContext) -> Result, String> { Ok(Vec::new()) } + fn genesis_epoch_data<'a>(&self, _header: &Header, _state: &machine::Call) -> Result, String> { Ok(Vec::new()) } /// Whether an epoch change is signalled at the given header but will require finality. /// If a change can be enacted immediately then return `No` from this function but @@ -321,7 +319,7 @@ pub trait Engine: Sync + Send { /// Return `Yes` or `No` when the answer is definitively known. /// /// Should not interact with state. - fn signals_epoch_end<'a>(&self, _header: &Header, _aux: >::AuxiliaryData) + fn signals_epoch_end<'a>(&self, _header: &Header, _aux: AuxiliaryData<'a>) -> EpochChange { EpochChange::No diff --git a/ethcore/src/machine/impls.rs b/ethcore/src/machine/impls.rs index 4cb052b9fe7..90d410c70d2 100644 --- a/ethcore/src/machine/impls.rs +++ b/ethcore/src/machine/impls.rs @@ -430,8 +430,6 @@ pub enum AuxiliaryRequest { impl super::Machine for EthereumMachine { type EngineClient = ::client::EngineClient; - type AuxiliaryRequest = AuxiliaryRequest; - type AncestryAction = ::types::ancestry_action::AncestryAction; type Error = Error; @@ -444,11 +442,6 @@ impl super::Machine for EthereumMachine { } } -impl<'a> super::LocalizedMachine<'a> for EthereumMachine { - type StateContext = Call<'a>; - type AuxiliaryData = AuxiliaryData<'a>; -} - // Try to round gas_limit a bit so that: // 1) it will still be in desired range // 2) it will be a nearest (with tendency to increase) multiple of PARITY_GAS_LIMIT_DETERMINANT diff --git a/ethcore/src/machine/traits.rs b/ethcore/src/machine/traits.rs index 4d4004bffeb..1523885e0e9 100644 --- a/ethcore/src/machine/traits.rs +++ b/ethcore/src/machine/traits.rs @@ -21,13 +21,9 @@ use ethereum_types::{U256, Address}; use block::ExecutedBlock; /// Generalization of types surrounding blockchain-suitable state machines. -pub trait Machine: for<'a> LocalizedMachine<'a> { +pub trait Machine: Send + Sync { /// A handle to a blockchain client for this machine. type EngineClient: ?Sized; - /// A description of needed auxiliary data. - type AuxiliaryRequest; - /// Actions taken on ancestry blocks when commiting a new block. - type AncestryAction; /// Errors which can occur when querying or interacting with the machine. type Error; @@ -39,13 +35,3 @@ pub trait Machine: for<'a> LocalizedMachine<'a> { /// Increment the balance of an account in the state of the live block. fn add_balance(&self, live: &mut ExecutedBlock, address: &Address, amount: &U256) -> Result<(), Self::Error>; } - -/// Machine-related types localized to a specific lifetime. -// TODO: this is a workaround for a lack of associated type constructors in the language. -pub trait LocalizedMachine<'a>: Sync + Send { - /// Definition of auxiliary data associated to a specific block. - type AuxiliaryData: 'a; - /// A context providing access to the state in a controlled capacity. - /// Generally also provides verifiable proofs. - type StateContext: ?Sized + 'a; -} From f875175325c227f06d74641a5908558e6578aaab Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Thu, 14 Mar 2019 13:40:59 +0100 Subject: [PATCH 13/27] remove unused Engine::is_proposal (#10475) --- ethcore/src/client/client.rs | 18 +++++------------- ethcore/src/engines/mod.rs | 4 ---- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 9eab30f3420..92c996982f5 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -298,19 +298,11 @@ impl Importer { match self.check_and_lock_block(&bytes, block, client) { Ok((closed_block, pending)) => { - if self.engine.is_proposal(&header) { - self.block_queue.mark_as_good(&[hash]); - proposed_blocks.push(bytes); - } else { - imported_blocks.push(hash); - - let transactions_len = closed_block.transactions().len(); - - let route = self.commit_block(closed_block, &header, encoded::Block::new(bytes), pending, client); - import_results.push(route); - - client.report.write().accrue_block(&header, transactions_len); - } + imported_blocks.push(hash); + let transactions_len = closed_block.transactions().len(); + let route = self.commit_block(closed_block, &header, encoded::Block::new(bytes), pending, client); + import_results.push(route); + client.report.write().accrue_block(&header, transactions_len); }, Err(err) => { self.bad_blocks.report(bytes, format!("{:?}", err)); diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 5e451b5e4f2..5d83bf0a3b8 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -375,10 +375,6 @@ pub trait Engine: Sync + Send { /// updating consensus state and potentially issuing a new one. fn handle_message(&self, _message: &[u8]) -> Result<(), EngineError> { Err(EngineError::UnexpectedMessage) } - /// Find out if the block is a proposal block and should not be inserted into the DB. - /// Takes a header of a fully verified block. - fn is_proposal(&self, _verified_header: &Header) -> bool { false } - /// Register a component which signs consensus messages. fn set_signer(&self, _signer: Box) {} From d83143d0ba7b3bc0c47519afd65b01fb4379cef6 Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Thu, 14 Mar 2019 21:34:26 +0100 Subject: [PATCH 14/27] remove unused Engine::maximum_uncle_age (#10476) --- ethcore/src/client/client.rs | 8 ++++---- ethcore/src/engines/mod.rs | 5 ++--- ethcore/src/verification/verification.rs | 6 +++--- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 92c996982f5..f0fdacfe86f 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -61,7 +61,7 @@ use client::{ IoClient, BadBlocks, }; use client::bad_blocks; -use engines::{EthEngine, EpochTransition, ForkChoice, EngineError}; +use engines::{MAX_UNCLE_AGE, EthEngine, EpochTransition, ForkChoice, EngineError}; use engines::epoch::PendingTransition; use error::{ ImportErrorKind, ExecutionError, CallError, BlockError, @@ -1918,7 +1918,7 @@ impl BlockChainClient for Client { } fn find_uncles(&self, hash: &H256) -> Option> { - self.chain.read().find_uncle_hashes(hash, self.engine.maximum_uncle_age()) + self.chain.read().find_uncle_hashes(hash, MAX_UNCLE_AGE) } fn state_data(&self, hash: &H256) -> Option { @@ -2282,7 +2282,7 @@ impl ReopenBlock for Client { let h = chain.best_block_hash(); // Add new uncles let uncles = chain - .find_uncle_hashes(&h, engine.maximum_uncle_age()) + .find_uncle_hashes(&h, MAX_UNCLE_AGE) .unwrap_or_else(Vec::new); for h in uncles { @@ -2326,7 +2326,7 @@ impl PrepareOpenBlock for Client { // Add uncles chain - .find_uncle_headers(&h, engine.maximum_uncle_age()) + .find_uncle_headers(&h, MAX_UNCLE_AGE) .unwrap_or_else(Vec::new) .into_iter() .take(engine.maximum_uncle_count(open_block.header().number())) diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 5d83bf0a3b8..06e6b522bed 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -59,6 +59,8 @@ use block::ExecutedBlock; /// Default EIP-210 contract code. /// As defined in https://github.com/ethereum/EIPs/pull/210 pub const DEFAULT_BLOCKHASH_CONTRACT: &'static str = "73fffffffffffffffffffffffffffffffffffffffe33141561006a5760014303600035610100820755610100810715156100455760003561010061010083050761010001555b6201000081071515610064576000356101006201000083050761020001555b5061013e565b4360003512151561008457600060405260206040f361013d565b61010060003543031315156100a857610100600035075460605260206060f361013c565b6101006000350715156100c55762010000600035430313156100c8565b60005b156100ea576101006101006000350507610100015460805260206080f361013b565b620100006000350715156101095763010000006000354303131561010c565b60005b1561012f57610100620100006000350507610200015460a052602060a0f361013a565b600060c052602060c0f35b5b5b5b5b"; +/// The number of generations back that uncles can be. +pub const MAX_UNCLE_AGE: usize = 6; /// Voting errors. #[derive(Debug)] @@ -242,9 +244,6 @@ pub trait Engine: Sync + Send { /// Maximum number of uncles a block is allowed to declare. fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 } - /// The number of generations back that uncles can be. - fn maximum_uncle_age(&self) -> usize { 6 } - /// Optional maximum gas limit. fn maximum_gas_limit(&self) -> Option { None } diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 2ce9f9de304..8a11f0ef45b 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -34,7 +34,7 @@ use unexpected::{Mismatch, OutOfBounds}; use blockchain::*; use call_contract::CallContract; use client::BlockInfo; -use engines::EthEngine; +use engines::{EthEngine, MAX_UNCLE_AGE}; use error::{BlockError, Error}; use types::{BlockNumber, header::Header}; use types::transaction::SignedTransaction; @@ -192,7 +192,7 @@ fn verify_uncles(block: &PreverifiedBlock, bc: &BlockProvider, engine: &EthEngin excluded.insert(header.hash()); let mut hash = header.parent_hash().clone(); excluded.insert(hash.clone()); - for _ in 0..engine.maximum_uncle_age() { + for _ in 0..MAX_UNCLE_AGE { match bc.block_details(&hash) { Some(details) => { excluded.insert(details.parent); @@ -225,7 +225,7 @@ fn verify_uncles(block: &PreverifiedBlock, bc: &BlockProvider, engine: &EthEngin // (8 Invalid) let depth = if header.number() > uncle.number() { header.number() - uncle.number() } else { 0 }; - if depth > engine.maximum_uncle_age() as u64 { + if depth > MAX_UNCLE_AGE as u64 { return Err(From::from(BlockError::UncleTooOld(OutOfBounds { min: Some(header.number() - depth), max: Some(header.number() - 1), found: uncle.number() }))); } else if depth < 1 { From a574df3132ceac41a36e5a246b0ad3be12178bab Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Fri, 15 Mar 2019 13:22:47 +0100 Subject: [PATCH 15/27] simplify block module and usage (#10479) * removed trait IsBlock and simplify block usage * removed redundant ClosedBlock::hash function --- ethcore/src/block.rs | 92 +++++++--------------- ethcore/src/client/client.rs | 28 +++---- ethcore/src/engines/authority_round/mod.rs | 56 ++++++------- ethcore/src/engines/basic_authority.rs | 4 +- ethcore/src/engines/instant_seal.rs | 2 +- ethcore/src/ethereum/ethash.rs | 12 +-- ethcore/src/machine/impls.rs | 14 ++-- ethcore/src/miner/miner.rs | 62 ++++++++------- ethcore/src/tests/client.rs | 3 +- rpc/src/v1/tests/helpers/miner_service.rs | 4 +- 10 files changed, 125 insertions(+), 152 deletions(-) diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index 9d3528bb0d5..bbcfa473eb7 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -31,7 +31,7 @@ //! `ExecutedBlock` is an underlaying data structure used by all structs above to store block //! related info. -use std::cmp; +use std::{cmp, ops}; use std::collections::HashSet; use std::sync::Arc; @@ -52,7 +52,6 @@ use vm::{EnvInfo, LastHashes}; use hash::keccak; use rlp::{RlpStream, Encodable, encode_list}; use types::transaction::{SignedTransaction, Error as TransactionError}; -use types::block::Block; use types::header::{Header, ExtendedHeader}; use types::receipt::{Receipt, TransactionOutcome}; @@ -155,46 +154,12 @@ impl ExecutedBlock { } } -/// Trait for a object that is a `ExecutedBlock`. -pub trait IsBlock { - /// Get the `ExecutedBlock` associated with this object. - fn block(&self) -> &ExecutedBlock; - - /// Get the base `Block` object associated with this. - fn to_base(&self) -> Block { - Block { - header: self.header().clone(), - transactions: self.transactions().iter().cloned().map(Into::into).collect(), - uncles: self.uncles().to_vec(), - } - } - - /// Get the header associated with this object's block. - fn header(&self) -> &Header { &self.block().header } - - /// Get the final state associated with this object's block. - fn state(&self) -> &State { &self.block().state } - - /// Get all information on transactions in this block. - fn transactions(&self) -> &[SignedTransaction] { &self.block().transactions } - - /// Get all information on receipts in this block. - fn receipts(&self) -> &[Receipt] { &self.block().receipts } - - /// Get all uncles in this block. - fn uncles(&self) -> &[Header] { &self.block().uncles } -} - /// Trait for an object that owns an `ExecutedBlock` pub trait Drain { /// Returns `ExecutedBlock` fn drain(self) -> ExecutedBlock; } -impl IsBlock for ExecutedBlock { - fn block(&self) -> &ExecutedBlock { self } -} - impl<'x> OpenBlock<'x> { /// Create a new `OpenBlock` ready for transaction pushing. pub fn new<'a>( @@ -250,7 +215,7 @@ impl<'x> OpenBlock<'x> { /// NOTE Will check chain constraints and the uncle number but will NOT check /// that the header itself is actually valid. pub fn push_uncle(&mut self, valid_uncle_header: Header) -> Result<(), BlockError> { - let max_uncles = self.engine.maximum_uncle_count(self.block.header().number()); + let max_uncles = self.engine.maximum_uncle_count(self.block.header.number()); if self.block.uncles.len() + 1 > max_uncles { return Err(BlockError::TooManyUncles(OutOfBounds{ min: None, @@ -264,11 +229,6 @@ impl<'x> OpenBlock<'x> { Ok(()) } - /// Get the environment info concerning this block. - pub fn env_info(&self) -> EnvInfo { - self.block.env_info() - } - /// Push a transaction into the block. /// /// If valid, it will be executed, and archived together with the receipt. @@ -277,7 +237,7 @@ impl<'x> OpenBlock<'x> { return Err(TransactionError::AlreadyImported.into()); } - let env_info = self.env_info(); + let env_info = self.block.env_info(); let outcome = self.block.state.apply(&env_info, self.engine.machine(), &t, self.block.traces.is_enabled())?; self.block.transactions_set.insert(h.unwrap_or_else(||t.hash())); @@ -374,22 +334,39 @@ impl<'x> OpenBlock<'x> { pub fn block_mut(&mut self) -> &mut ExecutedBlock { &mut self.block } } -impl<'x> IsBlock for OpenBlock<'x> { - fn block(&self) -> &ExecutedBlock { &self.block } +impl<'a> ops::Deref for OpenBlock<'a> { + type Target = ExecutedBlock; + + fn deref(&self) -> &Self::Target { + &self.block + } } -impl IsBlock for ClosedBlock { - fn block(&self) -> &ExecutedBlock { &self.block } +impl ops::Deref for ClosedBlock { + type Target = ExecutedBlock; + + fn deref(&self) -> &Self::Target { + &self.block + } } -impl IsBlock for LockedBlock { - fn block(&self) -> &ExecutedBlock { &self.block } +impl ops::Deref for LockedBlock { + type Target = ExecutedBlock; + + fn deref(&self) -> &Self::Target { + &self.block + } } -impl ClosedBlock { - /// Get the hash of the header without seal arguments. - pub fn hash(&self) -> H256 { self.header().bare_hash() } +impl ops::Deref for SealedBlock { + type Target = ExecutedBlock; + fn deref(&self) -> &Self::Target { + &self.block + } +} + +impl ClosedBlock { /// Turn this into a `LockedBlock`, unable to be reopened again. pub fn lock(self) -> LockedBlock { LockedBlock { @@ -423,18 +400,13 @@ impl LockedBlock { self.block.header.set_receipts_root( ordered_trie_root(self.block.receipts.iter().map(|r| r.rlp_bytes())) ); - // compute hash and cache it. - self.block.header.compute_hash(); } - /// Get the hash of the header without seal arguments. - pub fn hash(&self) -> H256 { self.header().bare_hash() } - /// Provide a valid seal in order to turn this into a `SealedBlock`. /// /// NOTE: This does not check the validity of `seal` with the engine. pub fn seal(self, engine: &EthEngine, seal: Vec) -> Result { - let expected_seal_fields = engine.seal_fields(self.header()); + let expected_seal_fields = engine.seal_fields(&self.block.header); let mut s = self; if seal.len() != expected_seal_fields { return Err(BlockError::InvalidSealArity( @@ -490,10 +462,6 @@ impl Drain for SealedBlock { } } -impl IsBlock for SealedBlock { - fn block(&self) -> &ExecutedBlock { &self.block } -} - /// Enact the block given by block header, transactions and uncles fn enact( header: Header, diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index f0fdacfe86f..29d642477ac 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -45,7 +45,7 @@ use types::receipt::{Receipt, LocalizedReceipt}; use types::{BlockNumber, header::{Header, ExtendedHeader}}; use vm::{EnvInfo, LastHashes}; -use block::{IsBlock, LockedBlock, Drain, ClosedBlock, OpenBlock, enact_verified, SealedBlock}; +use block::{LockedBlock, Drain, ClosedBlock, OpenBlock, enact_verified, SealedBlock}; use client::ancient_import::AncientVerifier; use client::{ Nonce, Balance, ChainInfo, BlockInfo, TransactionInfo, @@ -299,7 +299,7 @@ impl Importer { match self.check_and_lock_block(&bytes, block, client) { Ok((closed_block, pending)) => { imported_blocks.push(hash); - let transactions_len = closed_block.transactions().len(); + let transactions_len = closed_block.transactions.len(); let route = self.commit_block(closed_block, &header, encoded::Block::new(bytes), pending, client); import_results.push(route); client.report.write().accrue_block(&header, transactions_len); @@ -423,13 +423,13 @@ impl Importer { // if the expected receipts root header does not match. // (i.e. allow inconsistency in receipts outcome before the transition block) if header.number() < engine.params().validate_receipts_transition - && header.receipts_root() != locked_block.block().header().receipts_root() + && header.receipts_root() != locked_block.header.receipts_root() { locked_block.strip_receipts_outcomes(); } // Final Verification - if let Err(e) = self.verifier.verify_block_final(&header, locked_block.block().header()) { + if let Err(e) = self.verifier.verify_block_final(&header, &locked_block.header) { warn!(target: "client", "Stage 5 block verification failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e); bail!(e); } @@ -437,8 +437,8 @@ impl Importer { let pending = self.check_epoch_end_signal( &header, bytes, - locked_block.receipts(), - locked_block.state().db(), + &locked_block.receipts, + locked_block.state.db(), client )?; @@ -2276,8 +2276,8 @@ impl ReopenBlock for Client { fn reopen_block(&self, block: ClosedBlock) -> OpenBlock { let engine = &*self.engine; let mut block = block.reopen(engine); - let max_uncles = engine.maximum_uncle_count(block.header().number()); - if block.uncles().len() < max_uncles { + let max_uncles = engine.maximum_uncle_count(block.header.number()); + if block.uncles.len() < max_uncles { let chain = self.chain.read(); let h = chain.best_block_hash(); // Add new uncles @@ -2286,14 +2286,14 @@ impl ReopenBlock for Client { .unwrap_or_else(Vec::new); for h in uncles { - if !block.uncles().iter().any(|header| header.hash() == h) { + if !block.uncles.iter().any(|header| header.hash() == h) { let uncle = chain.block_header_data(&h).expect("find_uncle_hashes only returns hashes for existing headers; qed"); let uncle = uncle.decode().expect("decoding failure"); block.push_uncle(uncle).expect("pushing up to maximum_uncle_count; push_uncle is not ok only if more than maximum_uncle_count is pushed; so all push_uncle are Ok; qed"); - if block.uncles().len() >= max_uncles { break } + if block.uncles.len() >= max_uncles { break } } } @@ -2329,7 +2329,7 @@ impl PrepareOpenBlock for Client { .find_uncle_headers(&h, MAX_UNCLE_AGE) .unwrap_or_else(Vec::new) .into_iter() - .take(engine.maximum_uncle_count(open_block.header().number())) + .take(engine.maximum_uncle_count(open_block.header.number())) .foreach(|h| { open_block.push_uncle(h.decode().expect("decoding failure")).expect("pushing maximum_uncle_count; open_block was just created; @@ -2354,7 +2354,7 @@ impl ImportSealedBlock for Client { fn import_sealed_block(&self, block: SealedBlock) -> EthcoreResult { let start = Instant::now(); let raw = block.rlp_bytes(); - let header = block.header().clone(); + let header = block.header.clone(); let hash = header.hash(); self.notify(|n| n.block_pre_import(&raw, &hash, header.difficulty())); @@ -2377,8 +2377,8 @@ impl ImportSealedBlock for Client { let pending = self.importer.check_epoch_end_signal( &header, &block_data, - block.receipts(), - block.state().db(), + &block.receipts, + block.state.db(), self )?; let route = self.importer.commit_block( diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index 31062d80f3d..db25380aa85 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -1030,7 +1030,7 @@ impl Engine for AuthorityRound { return Seal::None; } - let header = block.header(); + let header = &block.header; let parent_step = header_step(parent, self.empty_steps_transition) .expect("Header has been verified; qed"); @@ -1076,7 +1076,7 @@ impl Engine for AuthorityRound { // `EmptyStep(step, parent_hash)` message. If we exceed the maximum amount of `empty_step` rounds we proceed // with the seal. if header.number() >= self.empty_steps_transition && - block.transactions().is_empty() && + block.transactions.is_empty() && empty_steps.len() < self.maximum_empty_steps { if self.step.can_propose.compare_and_swap(true, false, AtomicOrdering::SeqCst) { @@ -1146,7 +1146,7 @@ impl Engine for AuthorityRound { if self.immediate_transitions || !epoch_begin { return Ok(()) } // genesis is never a new block, but might as well check. - let header = block.header().clone(); + let header = block.header.clone(); let first = header.number() == 0; let mut call = |to, data| { @@ -1166,8 +1166,8 @@ impl Engine for AuthorityRound { /// Apply the block reward on finalisation of the block. fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { let mut beneficiaries = Vec::new(); - if block.header().number() >= self.empty_steps_transition { - let empty_steps = if block.header().seal().is_empty() { + if block.header.number() >= self.empty_steps_transition { + let empty_steps = if block.header.seal().is_empty() { // this is a new block, calculate rewards based on the empty steps messages we have accumulated let client = match self.client.read().as_ref().and_then(|weak| weak.upgrade()) { Some(client) => client, @@ -1177,7 +1177,7 @@ impl Engine for AuthorityRound { }, }; - let parent = client.block_header(::client::BlockId::Hash(*block.header().parent_hash())) + let parent = client.block_header(::client::BlockId::Hash(*block.header.parent_hash())) .expect("hash is from parent; parent header must exist; qed") .decode()?; @@ -1186,7 +1186,7 @@ impl Engine for AuthorityRound { self.empty_steps(parent_step.into(), current_step.into(), parent.hash()) } else { // we're verifying a block, extract empty steps from the seal - header_empty_steps(block.header())? + header_empty_steps(&block.header)? }; for empty_step in empty_steps { @@ -1195,11 +1195,11 @@ impl Engine for AuthorityRound { } } - let author = *block.header().author(); + let author = *block.header.author(); beneficiaries.push((author, RewardKind::Author)); let rewards: Vec<_> = match self.block_reward_contract { - Some(ref c) if block.header().number() >= self.block_reward_contract_transition => { + Some(ref c) if block.header.number() >= self.block_reward_contract_transition => { let mut call = super::default_system_or_code_call(&self.machine, block); let rewards = c.reward(&beneficiaries, &mut call)?; @@ -1634,17 +1634,17 @@ mod tests { let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - if let Seal::Regular(seal) = engine.generate_seal(b1.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b1, &genesis_header) { assert!(b1.clone().try_seal(engine, seal).is_ok()); // Second proposal is forbidden. - assert!(engine.generate_seal(b1.block(), &genesis_header) == Seal::None); + assert!(engine.generate_seal(&b1, &genesis_header) == Seal::None); } engine.set_signer(Box::new((tap, addr2, "2".into()))); - if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b2, &genesis_header) { assert!(b2.clone().try_seal(engine, seal).is_ok()); // Second proposal is forbidden. - assert!(engine.generate_seal(b2.block(), &genesis_header) == Seal::None); + assert!(engine.generate_seal(&b2, &genesis_header) == Seal::None); } } @@ -1668,13 +1668,13 @@ mod tests { let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - match engine.generate_seal(b1.block(), &genesis_header) { + match engine.generate_seal(&b1, &genesis_header) { Seal::None | Seal::Proposal(_) => panic!("wrong seal"), Seal::Regular(_) => { engine.step(); engine.set_signer(Box::new((tap.clone(), addr2, "0".into()))); - match engine.generate_seal(b2.block(), &genesis_header) { + match engine.generate_seal(&b2, &genesis_header) { Seal::Regular(_) | Seal::Proposal(_) => panic!("sealed despite wrong difficulty"), Seal::None => {} } @@ -1902,7 +1902,7 @@ mod tests { let b1 = b1.close_and_lock().unwrap(); // the block is empty so we don't seal and instead broadcast an empty step message - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); // spec starts with step 2 let empty_step_rlp = encode(&empty_step(engine, 2, &genesis_header.hash())); @@ -1912,7 +1912,7 @@ mod tests { let len = notify.messages.read().len(); // make sure that we don't generate empty step for the second time - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); assert_eq!(len, notify.messages.read().len()); } @@ -1941,7 +1941,7 @@ mod tests { // since the block is empty it isn't sealed and we generate empty steps engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); engine.step(); // step 3 @@ -1958,7 +1958,7 @@ mod tests { // we will now seal a block with 1tx and include the accumulated empty step message engine.set_signer(Box::new((tap.clone(), addr2, "0".into()))); - if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b2, &genesis_header) { engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash()); let empty_steps = ::rlp::encode_list(&vec![empty_step2]); @@ -1994,14 +1994,14 @@ mod tests { // since the block is empty it isn't sealed and we generate empty steps engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); engine.step(); // step 3 let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr2, "0".into()))); - assert_eq!(engine.generate_seal(b2.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b2, &genesis_header), Seal::None); engine.step(); // step 4 @@ -2010,7 +2010,7 @@ mod tests { let b3 = b3.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - if let Seal::Regular(seal) = engine.generate_seal(b3.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b3, &genesis_header) { let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash()); engine.set_signer(Box::new((tap.clone(), addr2, "0".into()))); let empty_step3 = sealed_empty_step(engine, 3, &genesis_header.hash()); @@ -2044,19 +2044,19 @@ mod tests { // since the block is empty it isn't sealed and we generate empty steps engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); engine.step(); // step 3 // the signer of the accumulated empty step message should be rewarded let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); - let addr1_balance = b2.block().state().balance(&addr1).unwrap(); + let addr1_balance = b2.state.balance(&addr1).unwrap(); // after closing the block `addr1` should be reward twice, one for the included empty step message and another for block creation let b2 = b2.close_and_lock().unwrap(); // the spec sets the block reward to 10 - assert_eq!(b2.block().state().balance(&addr1).unwrap(), addr1_balance + (10 * 2)) + assert_eq!(b2.state.balance(&addr1).unwrap(), addr1_balance + (10 * 2)) } #[test] @@ -2155,7 +2155,7 @@ mod tests { // since the block is empty it isn't sealed and we generate empty steps engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None); + assert_eq!(engine.generate_seal(&b1, &genesis_header), Seal::None); engine.step(); // step 3 @@ -2173,7 +2173,7 @@ mod tests { false, &mut Vec::new().into_iter(), ).unwrap(); - let addr1_balance = b2.block().state().balance(&addr1).unwrap(); + let addr1_balance = b2.state.balance(&addr1).unwrap(); // after closing the block `addr1` should be reward twice, one for the included empty step // message and another for block creation @@ -2181,7 +2181,7 @@ mod tests { // the contract rewards (1000 + kind) for each benefactor/reward kind assert_eq!( - b2.block().state().balance(&addr1).unwrap(), + b2.state.balance(&addr1).unwrap(), addr1_balance + (1000 + 0) + (1000 + 2), ) } diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index 1a4bdb55a90..e907e7834f3 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -104,7 +104,7 @@ impl Engine for BasicAuthority { /// Attempt to seal the block internally. fn generate_seal(&self, block: &ExecutedBlock, _parent: &Header) -> Seal { - let header = block.header(); + let header = &block.header; let author = header.author(); if self.validators.contains(header.parent_hash(), author) { // account should be pernamently unlocked, otherwise sealing will fail @@ -266,7 +266,7 @@ mod tests { let last_hashes = Arc::new(vec![genesis_header.hash()]); let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, addr, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); let b = b.close_and_lock().unwrap(); - if let Seal::Regular(seal) = engine.generate_seal(b.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) { assert!(b.try_seal(engine, seal).is_ok()); } } diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index 93e20196a46..e792c5860e7 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -110,7 +110,7 @@ mod tests { let last_hashes = Arc::new(vec![genesis_header.hash()]); let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::default(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); let b = b.close_and_lock().unwrap(); - if let Seal::Regular(seal) = engine.generate_seal(b.block(), &genesis_header) { + if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) { assert!(b.try_seal(engine, seal).is_ok()); } } diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 561b3493be8..226747acbb0 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -542,7 +542,7 @@ mod tests { let last_hashes = Arc::new(vec![genesis_header.hash()]); let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); let b = b.close().unwrap(); - assert_eq!(b.state().balance(&Address::zero()).unwrap(), U256::from_str("4563918244f40000").unwrap()); + assert_eq!(b.state.balance(&Address::zero()).unwrap(), U256::from_str("4563918244f40000").unwrap()); } #[test] @@ -596,8 +596,8 @@ mod tests { b.push_uncle(uncle).unwrap(); let b = b.close().unwrap(); - assert_eq!(b.state().balance(&Address::zero()).unwrap(), "478eae0e571ba000".into()); - assert_eq!(b.state().balance(&uncle_author).unwrap(), "3cb71f51fc558000".into()); + assert_eq!(b.state.balance(&Address::zero()).unwrap(), "478eae0e571ba000".into()); + assert_eq!(b.state.balance(&uncle_author).unwrap(), "3cb71f51fc558000".into()); } #[test] @@ -612,9 +612,9 @@ mod tests { let ubi_contract: Address = "00efdd5883ec628983e9063c7d969fe268bbf310".into(); let dev_contract: Address = "00756cf8159095948496617f5fb17ed95059f536".into(); - assert_eq!(b.state().balance(&Address::zero()).unwrap(), U256::from_str("d8d726b7177a80000").unwrap()); - assert_eq!(b.state().balance(&ubi_contract).unwrap(), U256::from_str("2b5e3af16b1880000").unwrap()); - assert_eq!(b.state().balance(&dev_contract).unwrap(), U256::from_str("c249fdd327780000").unwrap()); + assert_eq!(b.state.balance(&Address::zero()).unwrap(), U256::from_str("d8d726b7177a80000").unwrap()); + assert_eq!(b.state.balance(&ubi_contract).unwrap(), U256::from_str("2b5e3af16b1880000").unwrap()); + assert_eq!(b.state.balance(&dev_contract).unwrap(), U256::from_str("c249fdd327780000").unwrap()); } #[test] diff --git a/ethcore/src/machine/impls.rs b/ethcore/src/machine/impls.rs index 90d410c70d2..72f20ecdf7d 100644 --- a/ethcore/src/machine/impls.rs +++ b/ethcore/src/machine/impls.rs @@ -28,7 +28,7 @@ use types::header::Header; use vm::{CallType, ActionParams, ActionValue, ParamsType}; use vm::{EnvInfo, Schedule, CreateContractAddress}; -use block::{ExecutedBlock, IsBlock}; +use block::ExecutedBlock; use builtin::Builtin; use call_contract::CallContract; use client::BlockInfo; @@ -126,7 +126,7 @@ impl EthereumMachine { data: Option>, ) -> Result, Error> { let (code, code_hash) = { - let state = block.state(); + let state = &block.state; (state.code(&contract_address)?, state.code_hash(&contract_address)?) @@ -193,12 +193,12 @@ impl EthereumMachine { /// Push last known block hash to the state. fn push_last_hash(&self, block: &mut ExecutedBlock) -> Result<(), Error> { let params = self.params(); - if block.header().number() == params.eip210_transition { + if block.header.number() == params.eip210_transition { let state = block.state_mut(); state.init_code(¶ms.eip210_contract_address, params.eip210_contract_code.clone())?; } - if block.header().number() >= params.eip210_transition { - let parent_hash = block.header().parent_hash().clone(); + if block.header.number() >= params.eip210_transition { + let parent_hash = *block.header.parent_hash(); let _ = self.execute_as_system( block, params.eip210_contract_address, @@ -215,7 +215,7 @@ impl EthereumMachine { self.push_last_hash(block)?; if let Some(ref ethash_params) = self.ethash_extensions { - if block.header().number() == ethash_params.dao_hardfork_transition { + if block.header.number() == ethash_params.dao_hardfork_transition { let state = block.state_mut(); for child in ðash_params.dao_hardfork_accounts { let beneficiary = ðash_params.dao_hardfork_beneficiary; @@ -434,7 +434,7 @@ impl super::Machine for EthereumMachine { type Error = Error; fn balance(&self, live: &ExecutedBlock, address: &Address) -> Result { - live.state().balance(address).map_err(Into::into) + live.state.balance(address).map_err(Into::into) } fn add_balance(&self, live: &mut ExecutedBlock, address: &Address, amount: &U256) -> Result<(), Error> { diff --git a/ethcore/src/miner/miner.rs b/ethcore/src/miner/miner.rs index 7d6bcbe496d..ce1c9ef6ee7 100644 --- a/ethcore/src/miner/miner.rs +++ b/ethcore/src/miner/miner.rs @@ -46,7 +46,7 @@ use types::header::Header; use types::receipt::RichReceipt; use using_queue::{UsingQueue, GetAction}; -use block::{ClosedBlock, IsBlock, SealedBlock}; +use block::{ClosedBlock, SealedBlock}; use client::{ BlockChain, ChainInfo, BlockProducer, SealedBlockImporter, Nonce, TransactionInfo, TransactionId }; @@ -362,7 +362,7 @@ impl Miner { .and_then(|b| { // to prevent a data race between block import and updating pending block // we allow the number to be equal. - if b.block().header().number() >= latest_block_number { + if b.header.number() >= latest_block_number { Some(f(b)) } else { None @@ -392,7 +392,7 @@ impl Miner { // Open block let (mut open_block, original_work_hash) = { let mut sealing = self.sealing.lock(); - let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.block().header().hash()); + let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.header.hash()); let best_hash = chain_info.best_block_hash; // check to see if last ClosedBlock in would_seals is actually same parent block. @@ -401,7 +401,7 @@ impl Miner { // if at least one was pushed successfully, close and enqueue new ClosedBlock; // otherwise, leave everything alone. // otherwise, author a fresh block. - let mut open_block = match sealing.queue.get_pending_if(|b| b.block().header().parent_hash() == &best_hash) { + let mut open_block = match sealing.queue.get_pending_if(|b| b.header.parent_hash() == &best_hash) { Some(old_block) => { trace!(target: "miner", "prepare_block: Already have previous work; updating and returning"); // add transactions to old_block @@ -436,7 +436,7 @@ impl Miner { let mut invalid_transactions = HashSet::new(); let mut not_allowed_transactions = HashSet::new(); let mut senders_to_penalize = HashSet::new(); - let block_number = open_block.block().header().number(); + let block_number = open_block.header.number(); let mut tx_count = 0usize; let mut skipped_transactions = 0usize; @@ -453,7 +453,7 @@ impl Miner { let max_transactions = if min_tx_gas.is_zero() { usize::max_value() } else { - MAX_SKIPPED_TRANSACTIONS.saturating_add(cmp::min(*open_block.block().header().gas_limit() / min_tx_gas, u64::max_value().into()).as_u64() as usize) + MAX_SKIPPED_TRANSACTIONS.saturating_add(cmp::min(*open_block.header.gas_limit() / min_tx_gas, u64::max_value().into()).as_u64() as usize) }; let pending: Vec> = self.transaction_queue.pending( @@ -636,7 +636,7 @@ impl Miner { { { let sealing = self.sealing.lock(); - if block.transactions().is_empty() + if block.transactions.is_empty() && !self.forced_sealing() && Instant::now() <= sealing.next_mandatory_reseal { @@ -646,7 +646,7 @@ impl Miner { trace!(target: "miner", "seal_block_internally: attempting internal seal."); - let parent_header = match chain.block_header(BlockId::Hash(*block.header().parent_hash())) { + let parent_header = match chain.block_header(BlockId::Hash(*block.header.parent_hash())) { Some(h) => { match h.decode() { Ok(decoded_hdr) => decoded_hdr, @@ -656,7 +656,7 @@ impl Miner { None => return false, }; - match self.engine.generate_seal(block.block(), &parent_header) { + match self.engine.generate_seal(&block, &parent_header) { // Save proposal for later seal submission and broadcast it. Seal::Proposal(seal) => { trace!(target: "miner", "Received a Proposal seal."); @@ -705,11 +705,11 @@ impl Miner { /// Prepares work which has to be done to seal. fn prepare_work(&self, block: ClosedBlock, original_work_hash: Option) { let (work, is_new) = { - let block_header = block.block().header().clone(); + let block_header = block.header.clone(); let block_hash = block_header.hash(); let mut sealing = self.sealing.lock(); - let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.block().header().hash()); + let last_work_hash = sealing.queue.peek_last_ref().map(|pb| pb.header.hash()); trace!( target: "miner", @@ -742,7 +742,7 @@ impl Miner { trace!( target: "miner", "prepare_work: leaving (last={:?})", - sealing.queue.peek_last_ref().map(|b| b.block().header().hash()) + sealing.queue.peek_last_ref().map(|b| b.header.hash()) ); (work, is_new) }; @@ -994,7 +994,7 @@ impl miner::MinerService for Miner { let from_pending = || { self.map_existing_pending_block(|sealing| { - sealing.transactions() + sealing.transactions .iter() .map(|signed| signed.hash()) .collect() @@ -1041,7 +1041,7 @@ impl miner::MinerService for Miner { let from_pending = || { self.map_existing_pending_block(|sealing| { - sealing.transactions() + sealing.transactions .iter() .map(|signed| pool::VerifiedTransaction::from_pending_block_transaction(signed.clone())) .map(Arc::new) @@ -1086,9 +1086,9 @@ impl miner::MinerService for Miner { fn pending_receipts(&self, best_block: BlockNumber) -> Option> { self.map_existing_pending_block(|pending| { - let receipts = pending.receipts(); - pending.transactions() - .into_iter() + let receipts = &pending.receipts; + pending.transactions + .iter() .enumerate() .map(|(index, tx)| { let prev_gas = if index == 0 { Default::default() } else { receipts[index - 1].gas_used }; @@ -1102,7 +1102,7 @@ impl miner::MinerService for Miner { Action::Call(_) => None, Action::Create => { let sender = tx.sender(); - Some(contract_address(self.engine.create_address_scheme(pending.header().number()), &sender, &tx.nonce, &tx.data).0) + Some(contract_address(self.engine.create_address_scheme(pending.header.number()), &sender, &tx.nonce, &tx.data).0) } }, logs: receipt.logs.clone(), @@ -1139,7 +1139,7 @@ impl miner::MinerService for Miner { // refuse to seal the first block of the chain if it contains hard forks // which should be on by default. - if block.block().header().number() == 1 { + if block.header.number() == 1 { if let Some(name) = self.engine.params().nonzero_bugfix_hard_fork() { warn!("Your chain specification contains one or more hard forks which are required to be \ on by default. Please remove these forks and start your chain again: {}.", name); @@ -1180,7 +1180,7 @@ impl miner::MinerService for Miner { self.prepare_pending_block(chain); self.sealing.lock().queue.use_last_ref().map(|b| { - let header = b.header(); + let header = &b.header; (header.hash(), header.number(), header.timestamp(), *header.difficulty()) }) } @@ -1194,9 +1194,9 @@ impl miner::MinerService for Miner { } else { GetAction::Take }, - |b| &b.hash() == &block_hash + |b| &b.header.bare_hash() == &block_hash ) { - trace!(target: "miner", "Submitted block {}={}={} with seal {:?}", block_hash, b.hash(), b.header().bare_hash(), seal); + trace!(target: "miner", "Submitted block {}={} with seal {:?}", block_hash, b.header.bare_hash(), seal); b.lock().try_seal(&*self.engine, seal).or_else(|e| { warn!(target: "miner", "Mined solution rejected: {}", e); Err(ErrorKind::PowInvalid.into()) @@ -1207,8 +1207,8 @@ impl miner::MinerService for Miner { }; result.and_then(|sealed| { - let n = sealed.header().number(); - let h = sealed.header().hash(); + let n = sealed.header.number(); + let h = sealed.header.hash(); info!(target: "miner", "Submitted block imported OK. #{}: {}", Colour::White.bold().paint(format!("{}", n)), Colour::White.bold().paint(format!("{:x}", h))); Ok(sealed) }) @@ -1304,19 +1304,25 @@ impl miner::MinerService for Miner { } fn pending_state(&self, latest_block_number: BlockNumber) -> Option { - self.map_existing_pending_block(|b| b.state().clone(), latest_block_number) + self.map_existing_pending_block(|b| b.state.clone(), latest_block_number) } fn pending_block_header(&self, latest_block_number: BlockNumber) -> Option
{ - self.map_existing_pending_block(|b| b.header().clone(), latest_block_number) + self.map_existing_pending_block(|b| b.header.clone(), latest_block_number) } fn pending_block(&self, latest_block_number: BlockNumber) -> Option { - self.map_existing_pending_block(|b| b.to_base(), latest_block_number) + self.map_existing_pending_block(|b| { + Block { + header: b.header.clone(), + transactions: b.transactions.iter().cloned().map(Into::into).collect(), + uncles: b.uncles.to_vec(), + } + }, latest_block_number) } fn pending_transactions(&self, latest_block_number: BlockNumber) -> Option> { - self.map_existing_pending_block(|b| b.transactions().into_iter().cloned().collect(), latest_block_number) + self.map_existing_pending_block(|b| b.transactions.iter().cloned().collect(), latest_block_number) } } diff --git a/ethcore/src/tests/client.rs b/ethcore/src/tests/client.rs index 60ea5e1f0e9..4d12bb1385e 100644 --- a/ethcore/src/tests/client.rs +++ b/ethcore/src/tests/client.rs @@ -27,7 +27,6 @@ use types::filter::Filter; use types::view; use types::views::BlockView; -use block::IsBlock; use client::{BlockChainClient, Client, ClientConfig, BlockId, ChainInfo, BlockInfo, PrepareOpenBlock, ImportSealedBlock, ImportBlock}; use ethereum; use executive::{Executive, TransactOptions}; @@ -254,7 +253,7 @@ fn can_mine() { let b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]).unwrap().close().unwrap(); - assert_eq!(*b.block().header().parent_hash(), view!(BlockView, &dummy_blocks[0]).header_view().hash()); + assert_eq!(*b.header.parent_hash(), view!(BlockView, &dummy_blocks[0]).header_view().hash()); } #[test] diff --git a/rpc/src/v1/tests/helpers/miner_service.rs b/rpc/src/v1/tests/helpers/miner_service.rs index 77618c85328..b16651bd9c5 100644 --- a/rpc/src/v1/tests/helpers/miner_service.rs +++ b/rpc/src/v1/tests/helpers/miner_service.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use std::collections::{BTreeMap, BTreeSet, HashMap}; use bytes::Bytes; -use ethcore::block::{SealedBlock, IsBlock}; +use ethcore::block::SealedBlock; use ethcore::client::{Nonce, PrepareOpenBlock, StateClient, EngineInfo}; use ethcore::engines::{EthEngine, signer::EngineSigner}; use ethcore::error::Error; @@ -193,7 +193,7 @@ impl MinerService for TestMinerService { let params = self.authoring_params(); let open_block = chain.prepare_open_block(params.author, params.gas_range_target, params.extra_data).unwrap(); let closed = open_block.close().unwrap(); - let header = closed.header(); + let header = &closed.header; Some((header.hash(), header.number(), header.timestamp(), *header.difficulty())) } From fb461659c7a66005fd41028aa03aeef1914e804e Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Fri, 15 Mar 2019 15:43:54 +0100 Subject: [PATCH 16/27] OpenBlock::new take IntoIterator instead of mutable ref to Iterator (#10480) --- ethcore/src/block.rs | 14 +++++------ ethcore/src/client/client.rs | 2 +- ethcore/src/client/test_client.rs | 2 +- ethcore/src/engines/authority_round/mod.rs | 28 +++++++++++----------- ethcore/src/engines/basic_authority.rs | 2 +- ethcore/src/engines/instant_seal.rs | 2 +- ethcore/src/ethereum/ethash.rs | 6 ++--- ethcore/src/test_helpers.rs | 2 +- ethcore/src/tests/trace.rs | 6 ++--- 9 files changed, 32 insertions(+), 32 deletions(-) diff --git a/ethcore/src/block.rs b/ethcore/src/block.rs index bbcfa473eb7..c5311cbe01b 100644 --- a/ethcore/src/block.rs +++ b/ethcore/src/block.rs @@ -162,7 +162,7 @@ pub trait Drain { impl<'x> OpenBlock<'x> { /// Create a new `OpenBlock` ready for transaction pushing. - pub fn new<'a>( + pub fn new<'a, I: IntoIterator>( engine: &'x EthEngine, factories: Factories, tracing: bool, @@ -173,7 +173,7 @@ impl<'x> OpenBlock<'x> { gas_range_target: (U256, U256), extra_data: Bytes, is_epoch_begin: bool, - ancestry: &mut Iterator, + ancestry: I, ) -> Result { let number = parent.number() + 1; let state = State::from_existing(db, parent.state_root().clone(), engine.account_start_nonce(number), factories)?; @@ -195,7 +195,7 @@ impl<'x> OpenBlock<'x> { engine.populate_from_parent(&mut r.block.header, parent); engine.machine().on_new_block(&mut r.block)?; - engine.on_new_block(&mut r.block, is_epoch_begin, ancestry)?; + engine.on_new_block(&mut r.block, is_epoch_begin, &mut ancestry.into_iter())?; Ok(r) } @@ -592,7 +592,7 @@ mod tests { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, )?; b.populate_from(&header); @@ -627,7 +627,7 @@ mod tests { let genesis_header = spec.genesis_header(); let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(&*spec.engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b = OpenBlock::new(&*spec.engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b = b.close_and_lock().unwrap(); let _ = b.seal(&*spec.engine, vec![]); } @@ -641,7 +641,7 @@ mod tests { let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes.clone(), Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap() + let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes.clone(), Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap() .close_and_lock().unwrap().seal(engine, vec![]).unwrap(); let orig_bytes = b.rlp_bytes(); let orig_db = b.drain().state.drop().1; @@ -665,7 +665,7 @@ mod tests { let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let mut open_block = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes.clone(), Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let mut open_block = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes.clone(), Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let mut uncle1_header = Header::new(); uncle1_header.set_extra_data(b"uncle1".to_vec()); let mut uncle2_header = Header::new(); diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 29d642477ac..9680c19dfc6 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -2321,7 +2321,7 @@ impl PrepareOpenBlock for Client { gas_range_target, extra_data, is_epoch_begin, - &mut chain.ancestry_with_metadata_iter(best_header.hash()), + chain.ancestry_with_metadata_iter(best_header.hash()), )?; // Add uncles diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index fbad806fdff..502a9ee72b4 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -416,7 +416,7 @@ impl PrepareOpenBlock for TestBlockChainClient { gas_range_target, extra_data, false, - &mut Vec::new().into_iter(), + None, )?; // TODO [todr] Override timestamp for predictability open_block.set_timestamp(*self.latest_block_timestamp.read()); diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index db25380aa85..65ea2f77989 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -1628,9 +1628,9 @@ mod tests { let db1 = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let db2 = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); - let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); @@ -1662,9 +1662,9 @@ mod tests { let db2 = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); - let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); @@ -1898,7 +1898,7 @@ mod tests { engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); // the block is empty so we don't seal and instead broadcast an empty step message @@ -1936,7 +1936,7 @@ mod tests { engine.register_client(Arc::downgrade(&client) as _); // step 2 - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); // since the block is empty it isn't sealed and we generate empty steps @@ -1945,7 +1945,7 @@ mod tests { engine.step(); // step 3 - let mut b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let mut b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); b2.push_transaction(Transaction { action: Action::Create, nonce: U256::from(0), @@ -1989,7 +1989,7 @@ mod tests { engine.register_client(Arc::downgrade(&client) as _); // step 2 - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); // since the block is empty it isn't sealed and we generate empty steps @@ -1998,7 +1998,7 @@ mod tests { engine.step(); // step 3 - let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b2 = b2.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr2, "0".into()))); assert_eq!(engine.generate_seal(&b2, &genesis_header), Seal::None); @@ -2006,7 +2006,7 @@ mod tests { // step 4 // the spec sets the maximum_empty_steps to 2 so we will now seal an empty block and include the empty step messages - let b3 = OpenBlock::new(engine, Default::default(), false, db3, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b3 = OpenBlock::new(engine, Default::default(), false, db3, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b3 = b3.close_and_lock().unwrap(); engine.set_signer(Box::new((tap.clone(), addr1, "1".into()))); @@ -2039,7 +2039,7 @@ mod tests { engine.register_client(Arc::downgrade(&client) as _); // step 2 - let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b1 = b1.close_and_lock().unwrap(); // since the block is empty it isn't sealed and we generate empty steps @@ -2049,7 +2049,7 @@ mod tests { // step 3 // the signer of the accumulated empty step message should be rewarded - let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let addr1_balance = b2.state.balance(&addr1).unwrap(); // after closing the block `addr1` should be reward twice, one for the included empty step message and another for block creation @@ -2149,7 +2149,7 @@ mod tests { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); let b1 = b1.close_and_lock().unwrap(); @@ -2171,7 +2171,7 @@ mod tests { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); let addr1_balance = b2.state.balance(&addr1).unwrap(); diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index e907e7834f3..69b8d07c526 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -264,7 +264,7 @@ mod tests { let genesis_header = spec.genesis_header(); let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, addr, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, addr, (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b = b.close_and_lock().unwrap(); if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) { assert!(b.try_seal(engine, seal).is_ok()); diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index e792c5860e7..a578c990b30 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -108,7 +108,7 @@ mod tests { let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let genesis_header = spec.genesis_header(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::default(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::default(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b = b.close_and_lock().unwrap(); if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) { assert!(b.try_seal(engine, seal).is_ok()); diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 226747acbb0..698e23cf7e6 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -540,7 +540,7 @@ mod tests { let genesis_header = spec.genesis_header(); let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b = b.close().unwrap(); assert_eq!(b.state.balance(&Address::zero()).unwrap(), U256::from_str("4563918244f40000").unwrap()); } @@ -589,7 +589,7 @@ mod tests { let genesis_header = spec.genesis_header(); let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let mut b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let mut b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let mut uncle = Header::new(); let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into(); uncle.set_author(uncle_author); @@ -607,7 +607,7 @@ mod tests { let genesis_header = spec.genesis_header(); let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap(); let last_hashes = Arc::new(vec![genesis_header.hash()]); - let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap(); + let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false, None).unwrap(); let b = b.close().unwrap(); let ubi_contract: Address = "00efdd5883ec628983e9063c7d969fe268bbf310".into(); diff --git a/ethcore/src/test_helpers.rs b/ethcore/src/test_helpers.rs index ae4968080bc..b5575f36cd9 100644 --- a/ethcore/src/test_helpers.rs +++ b/ethcore/src/test_helpers.rs @@ -155,7 +155,7 @@ pub fn generate_dummy_client_with_spec_and_data(test_spec: F, block_number: u (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); rolling_timestamp += 10; b.set_timestamp(rolling_timestamp); diff --git a/ethcore/src/tests/trace.rs b/ethcore/src/tests/trace.rs index f687aac127f..c14f13cf59e 100644 --- a/ethcore/src/tests/trace.rs +++ b/ethcore/src/tests/trace.rs @@ -86,7 +86,7 @@ fn can_trace_block_and_uncle_reward() { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); rolling_timestamp += 10; root_block.set_timestamp(rolling_timestamp); @@ -115,7 +115,7 @@ fn can_trace_block_and_uncle_reward() { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); rolling_timestamp += 10; parent_block.set_timestamp(rolling_timestamp); @@ -143,7 +143,7 @@ fn can_trace_block_and_uncle_reward() { (3141562.into(), 31415620.into()), vec![], false, - &mut Vec::new().into_iter(), + None, ).unwrap(); rolling_timestamp += 10; block.set_timestamp(rolling_timestamp); From a8ee3c97e6f5cd9acab1604f2358c9daef4e1c27 Mon Sep 17 00:00:00 2001 From: TriplEight Date: Tue, 19 Mar 2019 01:14:59 +0100 Subject: [PATCH 17/27] =?UTF-8?q?=D0=A1aching=20through=20docker=20volume?= =?UTF-8?q?=20(#10477)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * _old codebase_ before docker update * before docker update, testing runnr * docker update, testing the caching * distributed job cargo homes * distributed job cargo homes 2 * distributed job cargo homes 3 * dockerfile with gitlab checkout, audit uses template * dockerfile gets repo in volume * change builds_dir * trying docker cache for repo * repo cached automatically * after script is not concatenated * check sccache non-cacheable reasons nature * watch cache * log sccache * log sccache 2 * debug log sccache * fix debug log sccache * fix debug log sccache 2 * debug log cache 3 * debug log cache 3 * trace log all sccache * test wo cargo cache * test w removed cargo cache * report non-cacheable reasons, cargo cache is back and empty * report non-cacheable reasons, cargo cache is back and empty 2 * report non-cacheable reasons, cargo cache is back and empty 3 * wrap into after_script * restore CI tags `qa` -> `linux-docker` * return to main runners, this will fail until config on runners And Dockerfile won't be updated * typo fix CI lint * return to docker tag --- .gitlab-ci.yml | 52 +++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 079b8ed8f8e..cab10b56a92 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -9,10 +9,9 @@ variables: GIT_STRATEGY: fetch GIT_SUBMODULE_STRATEGY: recursive CI_SERVER_NAME: "GitLab CI" - CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" CARGO_TARGET: x86_64-unknown-linux-gnu -.no_git: &no_git #disable git strategy +.no_git: &no_git # disable git strategy variables: GIT_STRATEGY: none GIT_SUBMODULE_STRATEGY: none @@ -32,12 +31,17 @@ variables: paths: - artifacts/ -.docker-cache-status: &docker-cache-status - dependencies: [] +.docker-cache-status: &docker-cache-status + variables: + CARGO_HOME: "/cargo/${CI_JOB_NAME}" before_script: + - SCCACHE_ERROR_LOG=/builds/parity/parity-ethereum/sccache_error.log RUST_LOG=sccache::server=debug sccache --start-server - sccache -s after_script: - - sccache -s + - echo "All crate-types:" + - grep 'parse_arguments.*--crate-type' sccache_error.log | sed -re 's/.*"--crate-type", "([^"]+)".*/\1/' | sort | uniq -c + - echo "Non-cacheable reasons:" + - grep CannotCache sccache_error.log | sed -re 's/.*CannotCache\((.+)\).*/\1/' | sort | uniq -c tags: - linux-docker @@ -47,43 +51,60 @@ cargo-check 0 3: <<: *docker-cache-status script: - time cargo check --target $CARGO_TARGET --locked --no-default-features + - sccache -s cargo-check 1 3: stage: test <<: *docker-cache-status script: - time cargo check --target $CARGO_TARGET --locked --manifest-path util/io/Cargo.toml --no-default-features + - sccache -s cargo-check 2 3: stage: test <<: *docker-cache-status script: - time cargo check --target $CARGO_TARGET --locked --manifest-path util/io/Cargo.toml --features "mio" + - sccache -s cargo-audit: stage: test + <<: *docker-cache-status script: - cargo audit - tags: - - linux-docker + - sccache -s validate-chainspecs: stage: test <<: *docker-cache-status script: - ./scripts/gitlab/validate-chainspecs.sh + - sccache -s test-cpp: stage: build <<: *docker-cache-status script: - ./scripts/gitlab/test-cpp.sh + - sccache -s test-linux: stage: build <<: *docker-cache-status script: - ./scripts/gitlab/test-linux.sh + - sccache -s + +build-android: + stage: build + image: parity/rust-android:gitlab-ci + variables: + CARGO_TARGET: armv7-linux-androideabi + script: + - scripts/gitlab/build-linux.sh + tags: + - linux-docker + <<: *collect_artifacts build-linux: &build-linux stage: build @@ -91,6 +112,7 @@ build-linux: &build-linux <<: *docker-cache-status script: - scripts/gitlab/build-linux.sh + - sccache -s <<: *collect_artifacts build-linux-i386: @@ -138,7 +160,7 @@ build-windows: publish-docker: stage: publish only: *releaseable_branches - cache: {} + cache: {} dependencies: - build-linux tags: @@ -152,7 +174,7 @@ publish-snap: &publish-snap image: snapcore/snapcraft variables: BUILD_ARCH: amd64 - cache: {} + cache: {} dependencies: - build-linux tags: @@ -227,19 +249,9 @@ publish-docs: - tags except: - nightly - cache: {} + cache: {} script: - scripts/gitlab/publish-docs.sh tags: - linux-docker -build-android: - stage: build - image: parity/rust-android:gitlab-ci - variables: - CARGO_TARGET: armv7-linux-androideabi - script: - - scripts/gitlab/build-linux.sh - tags: - - linux-docker - <<: *collect_artifacts From effead9ba5c544ea982223802812d6871e9c4bec Mon Sep 17 00:00:00 2001 From: "Denis S. Soldatov aka General-Beck" Date: Tue, 19 Mar 2019 13:39:44 +0300 Subject: [PATCH 18/27] fix win&mac build (#10486) add CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" --- .gitlab-ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index cab10b56a92..217c49126fd 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -138,6 +138,7 @@ build-darwin: only: *releaseable_branches variables: CARGO_TARGET: x86_64-apple-darwin + CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" CC: gcc CXX: g++ script: @@ -151,6 +152,7 @@ build-windows: only: *releaseable_branches variables: CARGO_TARGET: x86_64-pc-windows-msvc + CARGO_HOME: "${CI_PROJECT_DIR}/.cargo" script: - sh scripts/gitlab/build-windows.sh tags: From 78a534633d754c95225312646184eff83e4cb78b Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Tue, 19 Mar 2019 16:37:24 +0100 Subject: [PATCH 19/27] fix(rpc): lint `unused_extern_crates` + fix warns (#10489) --- Cargo.lock | 2 -- rpc/Cargo.toml | 4 +--- rpc/src/lib.rs | 15 +++++++-------- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b6c0b3ef61f..36c723bbd81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2658,7 +2658,6 @@ dependencies = [ "jsonrpc-pubsub 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-ws-server 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "keccak-hash 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "kvdb-memorydb 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "macros 0.1.0", "multihash 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2683,7 +2682,6 @@ dependencies = [ "tokio-timer 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "transaction-pool 1.13.3 (registry+https://github.com/rust-lang/crates.io-index)", "transient-hashmap 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "trie-db 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "vm 0.1.0", ] diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index c6c59dc15a4..aea96f663a6 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -38,7 +38,6 @@ common-types = { path = "../ethcore/types" } ethash = { path = "../ethash" } ethcore = { path = "../ethcore", features = ["test-helpers"] } ethcore-accounts = { path = "../accounts", optional = true } -ethcore-io = { path = "../util/io" } ethcore-light = { path = "../ethcore/light" } ethcore-logger = { path = "../parity/logger" } ethcore-miner = { path = "../miner" } @@ -59,7 +58,6 @@ keccak-hash = "0.1.2" parity-runtime = { path = "../util/runtime" } parity-updater = { path = "../updater" } parity-version = { path = "../util/version" } -trie-db = "0.11.0" rlp = { version = "0.3.0", features = ["ethereum"] } stats = { path = "../util/stats" } vm = { path = "../ethcore/vm" } @@ -67,9 +65,9 @@ vm = { path = "../ethcore/vm" } [dev-dependencies] ethcore = { path = "../ethcore", features = ["test-helpers"] } ethcore-accounts = { path = "../accounts" } +ethcore-io = { path = "../util/io" } ethcore-network = { path = "../util/network" } fake-fetch = { path = "../util/fake-fetch" } -kvdb-memorydb = "0.1" macros = { path = "../util/macros" } pretty_assertions = "0.1" transaction-pool = "1.13" diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 4a90fbe6939..cafd7a8e440 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -16,7 +16,7 @@ //! Parity RPC. -#![warn(missing_docs)] +#![warn(missing_docs, unused_extern_crates)] #[macro_use] extern crate futures; @@ -32,7 +32,6 @@ extern crate rustc_hex; extern crate semver; extern crate serde; extern crate serde_json; -extern crate tiny_keccak; extern crate tokio_timer; extern crate transient_hashmap; @@ -48,7 +47,6 @@ extern crate ethcore; extern crate fastmap; extern crate parity_bytes as bytes; extern crate parity_crypto as crypto; -extern crate ethcore_io as io; extern crate ethcore_light as light; extern crate ethcore_logger; extern crate ethcore_miner as miner; @@ -63,15 +61,18 @@ extern crate keccak_hash as hash; extern crate parity_runtime; extern crate parity_updater as updater; extern crate parity_version as version; -extern crate trie_db as trie; extern crate eip_712; extern crate rlp; extern crate stats; +extern crate tempdir; extern crate vm; #[cfg(any(test, feature = "ethcore-accounts"))] extern crate ethcore_accounts as accounts; +#[cfg(any(test, feature = "ethcore-accounts"))] +extern crate tiny_keccak; + #[macro_use] extern crate log; #[macro_use] @@ -90,13 +91,11 @@ extern crate pretty_assertions; #[macro_use] extern crate macros; -#[cfg(test)] -extern crate kvdb_memorydb; - #[cfg(test)] extern crate fake_fetch; -extern crate tempdir; +#[cfg(test)] +extern crate ethcore_io as io; pub extern crate jsonrpc_ws_server as ws; From 037fd1b309d7769e8eb9f5d8dc54978c158c4fdb Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Tue, 19 Mar 2019 23:17:05 +0100 Subject: [PATCH 20/27] fix(extract `timestamp_checked_add` as lib) (#10383) * fix(extract `timestamp_checked_add` as lib) * fix(whisper types): remove unused `EmptyTopics` * fix(time-lib): feature-flag to use time-lib or std This commit adds conditional compilation checks that falls back to `our time-lib` when `time_checked_add` is not available in the standard library Note, `time_checked_add` covers both `checked_add` and `checked_sub` * fix(grumble): use cfg_attr to define rustc feature --- Cargo.lock | 6 +++ Cargo.toml | 3 +- ethcore/Cargo.toml | 1 + ethcore/src/engines/authority_round/mod.rs | 17 ++++++-- ethcore/src/lib.rs | 4 ++ ethcore/src/verification/verification.rs | 38 +++++----------- util/time-utils/Cargo.toml | 9 ++++ util/time-utils/src/lib.rs | 50 ++++++++++++++++++++++ whisper/Cargo.toml | 1 + whisper/src/lib.rs | 5 +++ whisper/src/message.rs | 25 ++++++----- whisper/src/net/mod.rs | 9 ++-- 12 files changed, 123 insertions(+), 45 deletions(-) create mode 100644 util/time-utils/Cargo.toml create mode 100644 util/time-utils/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 36c723bbd81..5902aa786cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -752,6 +752,7 @@ dependencies = [ "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", "stats 0.1.0", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", + "time-utils 0.1.0", "trace-time 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "trie-db 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "trie-standardmap 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2817,6 +2818,7 @@ dependencies = [ "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "time-utils 0.1.0", "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3772,6 +3774,10 @@ dependencies = [ "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "time-utils" +version = "0.1.0" + [[package]] name = "timer" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index ee4440dd010..a783175607f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,7 +138,8 @@ members = [ "util/triehash-ethereum", "util/keccak-hasher", "util/patricia-trie-ethereum", - "util/fastmap" + "util/fastmap", + "util/time-utils" ] [patch.crates-io] diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 2d26ba03814..3b8d60af8e9 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -63,6 +63,7 @@ serde = "1.0" serde_derive = "1.0" stats = { path = "../util/stats" } tempdir = {version="0.3", optional = true} +time-utils = { path = "../util/time-utils" } trace-time = "0.1" triehash-ethereum = { version = "0.2", path = "../util/triehash-ethereum" } unexpected = { path = "../util/unexpected" } diff --git a/ethcore/src/engines/authority_round/mod.rs b/ethcore/src/engines/authority_round/mod.rs index 65ea2f77989..36f25144f73 100644 --- a/ethcore/src/engines/authority_round/mod.rs +++ b/ethcore/src/engines/authority_round/mod.rs @@ -47,6 +47,9 @@ use types::header::{Header, ExtendedHeader}; use types::ancestry_action::AncestryAction; use unexpected::{Mismatch, OutOfBounds}; +#[cfg(not(time_checked_add))] +use time_utils::CheckedSystemTime; + mod finality; /// `AuthorityRound` params. @@ -574,8 +577,15 @@ fn verify_timestamp(step: &Step, header_step: u64) -> Result<(), BlockError> { // NOTE This error might be returned only in early stage of verification (Stage 1). // Returning it further won't recover the sync process. trace!(target: "engine", "verify_timestamp: block too early"); - let oob = oob.map(|n| SystemTime::now() + Duration::from_secs(n)); - Err(BlockError::TemporarilyInvalid(oob).into()) + + let now = SystemTime::now(); + let found = now.checked_add(Duration::from_secs(oob.found)).ok_or(BlockError::TimestampOverflow)?; + let max = oob.max.and_then(|m| now.checked_add(Duration::from_secs(m))); + let min = oob.min.and_then(|m| now.checked_add(Duration::from_secs(m))); + + let new_oob = OutOfBounds { min, max, found }; + + Err(BlockError::TemporarilyInvalid(new_oob).into()) }, Ok(_) => Ok(()), } @@ -611,6 +621,7 @@ fn combine_proofs(signal_number: BlockNumber, set_proof: &[u8], finality_proof: stream.out() } + fn destructure_proofs(combined: &[u8]) -> Result<(BlockNumber, &[u8], &[u8]), Error> { let rlp = Rlp::new(combined); Ok(( @@ -626,7 +637,7 @@ trait AsMillis { impl AsMillis for Duration { fn as_millis(&self) -> u64 { - self.as_secs()*1_000 + (self.subsec_nanos()/1_000_000) as u64 + self.as_secs() * 1_000 + (self.subsec_nanos() / 1_000_000) as u64 } } diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 17b33025a1c..eee076b32ea 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -15,6 +15,7 @@ // along with Parity Ethereum. If not, see . #![warn(missing_docs, unused_extern_crates)] +#![cfg_attr(feature = "time_checked_add", feature(time_checked_add))] //! Ethcore library //! @@ -148,6 +149,9 @@ extern crate fetch; #[cfg(all(test, feature = "price-info"))] extern crate parity_runtime; +#[cfg(not(time_checked_add))] +extern crate time_utils; + pub mod block; pub mod builtin; pub mod client; diff --git a/ethcore/src/verification/verification.rs b/ethcore/src/verification/verification.rs index 8a11f0ef45b..36a847f64af 100644 --- a/ethcore/src/verification/verification.rs +++ b/ethcore/src/verification/verification.rs @@ -40,24 +40,8 @@ use types::{BlockNumber, header::Header}; use types::transaction::SignedTransaction; use verification::queue::kind::blocks::Unverified; - -/// Returns `Ok` when the result less or equal to `i32::max_value` to prevent `SystemTime` to panic because -/// it is platform specific, may be i32 or i64. -/// -/// `Err Result { - let d1 = sys.duration_since(UNIX_EPOCH).map_err(|_| BlockError::TimestampOverflow)?; - let total_time = d1.checked_add(d2).ok_or(BlockError::TimestampOverflow)?; - - if total_time.as_secs() <= i32::max_value() as u64 { - Ok(sys + d2) - } else { - Err(BlockError::TimestampOverflow) - } -} +#[cfg(not(time_checked_add))] +use time_utils::CheckedSystemTime; /// Preprocessed block data gathered in `verify_block_unordered` call pub struct PreverifiedBlock { @@ -323,9 +307,11 @@ pub fn verify_header_params(header: &Header, engine: &EthEngine, is_full: bool, if is_full { const ACCEPTABLE_DRIFT: Duration = Duration::from_secs(15); + // this will resist overflow until `year 2037` let max_time = SystemTime::now() + ACCEPTABLE_DRIFT; let invalid_threshold = max_time + ACCEPTABLE_DRIFT * 9; - let timestamp = timestamp_checked_add(UNIX_EPOCH, Duration::from_secs(header.timestamp()))?; + let timestamp = UNIX_EPOCH.checked_add(Duration::from_secs(header.timestamp())) + .ok_or(BlockError::TimestampOverflow)?; if timestamp > invalid_threshold { return Err(From::from(BlockError::InvalidTimestamp(OutOfBounds { max: Some(max_time), min: None, found: timestamp }))) @@ -347,8 +333,11 @@ fn verify_parent(header: &Header, parent: &Header, engine: &EthEngine) -> Result let gas_limit_divisor = engine.params().gas_limit_bound_divisor; if !engine.is_timestamp_valid(header.timestamp(), parent.timestamp()) { - let min = timestamp_checked_add(SystemTime::now(), Duration::from_secs(parent.timestamp().saturating_add(1)))?; - let found = timestamp_checked_add(SystemTime::now(), Duration::from_secs(header.timestamp()))?; + let now = SystemTime::now(); + let min = now.checked_add(Duration::from_secs(parent.timestamp().saturating_add(1))) + .ok_or(BlockError::TimestampOverflow)?; + let found = now.checked_add(Duration::from_secs(header.timestamp())) + .ok_or(BlockError::TimestampOverflow)?; return Err(From::from(BlockError::InvalidTimestamp(OutOfBounds { max: None, min: Some(min), found }))) } if header.number() != parent.number() + 1 { @@ -835,11 +824,4 @@ mod tests { check_fail(unordered_test(&create_test_block_with_data(&header, &bad_transactions, &[]), &engine), TooManyTransactions(keypair.address())); unordered_test(&create_test_block_with_data(&header, &good_transactions, &[]), &engine).unwrap(); } - - #[test] - fn checked_add_systime_dur() { - assert!(timestamp_checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 + 1, 0)).is_err()); - assert!(timestamp_checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64, 0)).is_ok()); - assert!(timestamp_checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 - 1, 1_000_000_000)).is_ok()); - } } diff --git a/util/time-utils/Cargo.toml b/util/time-utils/Cargo.toml new file mode 100644 index 00000000000..38e7dd02c68 --- /dev/null +++ b/util/time-utils/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "time-utils" +version = "0.1.0" +authors = ["Parity Technologies "] +description = "Time utilities for checked arithmetic" +license = "GPL3" +edition = "2018" + +[dependencies] diff --git a/util/time-utils/src/lib.rs b/util/time-utils/src/lib.rs new file mode 100644 index 00000000000..ff9f159cfad --- /dev/null +++ b/util/time-utils/src/lib.rs @@ -0,0 +1,50 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// Temporary trait for `checked operations` on SystemTime until these are available in standard library +pub trait CheckedSystemTime { + /// Returns `Some` when the result less or equal to `i32::max_value` to prevent `SystemTime` to panic because + /// it is platform specific, possible representations are i32, i64, u64 and Duration. `None` otherwise + fn checked_add(self, _d: Duration) -> Option; + /// Returns `Some` when the result is successful and `None` when it is not + fn checked_sub(self, _d: Duration) -> Option; +} + +impl CheckedSystemTime for SystemTime { + fn checked_add(self, dur: Duration) -> Option { + let this_dur = self.duration_since(UNIX_EPOCH).ok()?; + let total_time = this_dur.checked_add(dur)?; + + if total_time.as_secs() <= i32::max_value() as u64 { + Some(self + dur) + } else { + None + } + } + + fn checked_sub(self, dur: Duration) -> Option { + let this_dur = self.duration_since(UNIX_EPOCH).ok()?; + let total_time = this_dur.checked_sub(dur)?; + + if total_time.as_secs() <= i32::max_value() as u64 { + Some(self - dur) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + use super::CheckedSystemTime; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 + 1, 0)).is_none()); + assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64, 0)).is_some()); + assert!(CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::new(i32::max_value() as u64 - 1, 1_000_000_000)).is_some()); + + assert!(CheckedSystemTime::checked_sub(UNIX_EPOCH, Duration::from_secs(120)).is_none()); + assert!(CheckedSystemTime::checked_sub(SystemTime::now(), Duration::from_secs(1000)).is_some()); + } +} diff --git a/whisper/Cargo.toml b/whisper/Cargo.toml index 5c3548a50c8..97aa8f23ac3 100644 --- a/whisper/Cargo.toml +++ b/whisper/Cargo.toml @@ -24,6 +24,7 @@ serde_json = "1.0" slab = "0.3" smallvec = "0.6" tiny-keccak = "1.4" +time-utils = { path = "../util/time-utils" } jsonrpc-core = "10.0.1" jsonrpc-derive = "10.0.2" diff --git a/whisper/src/lib.rs b/whisper/src/lib.rs index 0e79946d9a5..cdc88780d4d 100644 --- a/whisper/src/lib.rs +++ b/whisper/src/lib.rs @@ -17,6 +17,8 @@ //! Whisper P2P messaging system as a DevP2P subprotocol, with RPC and Rust //! interface. +#![cfg_attr(feature = "time_checked_add", feature(time_checked_add))] + extern crate byteorder; extern crate parity_crypto as crypto; extern crate ethcore_network as network; @@ -46,6 +48,9 @@ extern crate log; #[macro_use] extern crate serde_derive; +#[cfg(not(time_checked_add))] +extern crate time_utils; + #[cfg(test)] extern crate serde_json; diff --git a/whisper/src/message.rs b/whisper/src/message.rs index f8e8565a8eb..0fc686e52a8 100644 --- a/whisper/src/message.rs +++ b/whisper/src/message.rs @@ -24,6 +24,9 @@ use rlp::{self, DecoderError, RlpStream, Rlp}; use smallvec::SmallVec; use tiny_keccak::{keccak256, Keccak}; +#[cfg(not(time_checked_add))] +use time_utils::CheckedSystemTime; + /// Work-factor proved. Takes 3 parameters: size of message, time to live, /// and hash. /// @@ -117,6 +120,7 @@ pub enum Error { EmptyTopics, LivesTooLong, IssuedInFuture, + TimestampOverflow, ZeroTTL, } @@ -133,6 +137,7 @@ impl fmt::Display for Error { Error::LivesTooLong => write!(f, "Message claims to be issued before the unix epoch."), Error::IssuedInFuture => write!(f, "Message issued in future."), Error::ZeroTTL => write!(f, "Message live for zero time."), + Error::TimestampOverflow => write!(f, "Timestamp overflow"), Error::EmptyTopics => write!(f, "Message has no topics."), } } @@ -226,10 +231,6 @@ impl rlp::Decodable for Envelope { } } -/// Error indicating no topics. -#[derive(Debug, Copy, Clone)] -pub struct EmptyTopics; - /// Message creation parameters. /// Pass this to `Message::create` to make a message. pub struct CreateParams { @@ -255,11 +256,11 @@ pub struct Message { impl Message { /// Create a message from creation parameters. /// Panics if TTL is 0. - pub fn create(params: CreateParams) -> Result { + pub fn create(params: CreateParams) -> Result { use byteorder::{BigEndian, ByteOrder}; use rand::{Rng, SeedableRng, XorShiftRng}; - if params.topics.is_empty() { return Err(EmptyTopics) } + if params.topics.is_empty() { return Err(Error::EmptyTopics) } let mut rng = { let mut thread_rng = ::rand::thread_rng(); @@ -270,7 +271,8 @@ impl Message { assert!(params.ttl > 0); let expiry = { - let after_mining = SystemTime::now() + Duration::from_millis(params.work); + let after_mining = SystemTime::now().checked_sub(Duration::from_millis(params.work)) + .ok_or(Error::TimestampOverflow)?; let since_epoch = after_mining.duration_since(time::UNIX_EPOCH) .expect("time after now is after unix epoch; qed"); @@ -357,7 +359,10 @@ impl Message { (envelope.expiry - envelope.ttl).saturating_sub(LEEWAY_SECONDS) ); - if time::UNIX_EPOCH + issue_time_adjusted > now { + let issue_time_adjusted = time::UNIX_EPOCH.checked_add(issue_time_adjusted) + .ok_or(Error::TimestampOverflow)?; + + if issue_time_adjusted > now { return Err(Error::IssuedInFuture); } @@ -400,8 +405,8 @@ impl Message { } /// Get the expiry time. - pub fn expiry(&self) -> SystemTime { - time::UNIX_EPOCH + Duration::from_secs(self.envelope.expiry) + pub fn expiry(&self) -> Option { + time::UNIX_EPOCH.checked_add(Duration::from_secs(self.envelope.expiry)) } /// Get the topics. diff --git a/whisper/src/net/mod.rs b/whisper/src/net/mod.rs index 64431d14263..d263f6cfbd9 100644 --- a/whisper/src/net/mod.rs +++ b/whisper/src/net/mod.rs @@ -223,7 +223,10 @@ impl Messages { } } - let expiry = message.expiry(); + let expiry = match message.expiry() { + Some(time) => time, + _ => return false, + }; self.cumulative_size += message.encoded_size(); @@ -232,8 +235,8 @@ impl Messages { let sorted_entry = SortedEntry { slab_id: id, - work_proved: work_proved, - expiry: expiry, + work_proved, + expiry, }; match self.sorted.binary_search(&sorted_entry) { From 9519493e32ba98ac655381c786dffdf9ea0e33d7 Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Wed, 20 Mar 2019 16:01:38 +0100 Subject: [PATCH 21/27] fix(time-utils): add missing license (#10497) --- util/time-utils/src/lib.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/util/time-utils/src/lib.rs b/util/time-utils/src/lib.rs index ff9f159cfad..0bfc3bb9822 100644 --- a/util/time-utils/src/lib.rs +++ b/util/time-utils/src/lib.rs @@ -1,9 +1,25 @@ +// Copyright 2015-2019 Parity Technologies (UK) Ltd. +// This file is part of Parity Ethereum. + +// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see . + use std::time::{Duration, SystemTime, UNIX_EPOCH}; -/// Temporary trait for `checked operations` on SystemTime until these are available in standard library +/// Temporary trait for `checked operations` on SystemTime until these are available in the standard library pub trait CheckedSystemTime { /// Returns `Some` when the result less or equal to `i32::max_value` to prevent `SystemTime` to panic because - /// it is platform specific, possible representations are i32, i64, u64 and Duration. `None` otherwise + /// it is platform specific, possible representations are i32, i64, u64 or Duration. `None` otherwise fn checked_add(self, _d: Duration) -> Option; /// Returns `Some` when the result is successful and `None` when it is not fn checked_sub(self, _d: Duration) -> Option; From b700ff3501facd214324b1adf70994df868d0506 Mon Sep 17 00:00:00 2001 From: Guillaume Ballet Date: Thu, 21 Mar 2019 15:45:02 +0100 Subject: [PATCH 22/27] whisper/cli: add p2p port and ip parameters (#10057) * whisper/cli: add p2p port and ip parameters This is so that those params don't change randomly and are in sync with the URL that is displayed. * feedback: Result instead of panic Co-Authored-By: gballet * feedback: Map error in port conversion Co-Authored-By: gballet * whisper/cli: User can specify enode private key So that the enode doesn't change at every run. * whipser/cli: finish integrating review feedback. * Accomodate error API change * Update rustc-hex version in whisper/cli/Cargo.toml Co-Authored-By: gballet * Update README with new whisper cli options * Fix typo in error message Co-Authored-By: gballet * Fix Cargo.lock and build issue after lib version upgrade * Fix another typo Co-Authored-By: gballet --- Cargo.lock | 2 ++ whisper/README.md | 7 +++-- whisper/cli/Cargo.toml | 2 ++ whisper/cli/src/main.rs | 59 +++++++++++++++++++++++++++++++++++++---- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5902aa786cd..811bb6cbc71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4369,12 +4369,14 @@ dependencies = [ "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)", "ethcore-network 1.12.0", "ethcore-network-devp2p 1.12.0", + "ethkey 0.3.0", "jsonrpc-core 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-http-server 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-pubsub 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "panic_hook 0.1.0", "parity-whisper 0.1.0", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/whisper/README.md b/whisper/README.md index dc449568aa7..b64c0244f96 100644 --- a/whisper/README.md +++ b/whisper/README.md @@ -14,8 +14,11 @@ Usage: Options: --whisper-pool-size SIZE Specify Whisper pool size [default: 10]. - -p, --port PORT Specify which RPC port to use [default: 8545]. - -a, --address ADDRESS Specify which address to use [default: 127.0.0.1]. + -p, --port PORT Specify which P2P port to use [default: random]. + -a, --address ADDRESS Specify which P2P address to use [default: 127.0.0.1]. + -s, --secret KEYFILE Specify which file contains the key to generate the enode. + -P, --rpc-port PORT Specify which RPC port to use [default: 8545]. + -A, --rpc-address ADDRESS Specify which RPC address to use [default: 127.0.0.1]. -l, --log LEVEL Specify the logging level. Must conform to the same format as RUST_LOG [default: Error]. -h, --help Display this message and exit. ``` diff --git a/whisper/cli/Cargo.toml b/whisper/cli/Cargo.toml index 4d123c09ab7..5ed38e47d71 100644 --- a/whisper/cli/Cargo.toml +++ b/whisper/cli/Cargo.toml @@ -18,6 +18,8 @@ panic_hook = { path = "../../util/panic-hook" } parity-whisper = { path = "../" } serde = "1.0" serde_derive = "1.0" +ethkey = { path = "../../accounts/ethkey" } +rustc-hex = "2.0" [[bin]] name = "whisper" diff --git a/whisper/cli/src/main.rs b/whisper/cli/src/main.rs index 9ef2304b478..41d9e80e42d 100644 --- a/whisper/cli/src/main.rs +++ b/whisper/cli/src/main.rs @@ -33,6 +33,8 @@ extern crate serde; extern crate jsonrpc_core; extern crate jsonrpc_pubsub; extern crate jsonrpc_http_server; +extern crate ethkey; +extern crate rustc_hex; #[macro_use] extern crate log as rlog; @@ -45,6 +47,10 @@ use std::{fmt, io, process, env, sync::Arc}; use jsonrpc_core::{Metadata, MetaIoHandler}; use jsonrpc_pubsub::{PubSubMetadata, Session}; use jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation}; +use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr}; +use std::str::FromStr; +use ethkey::Secret; +use rustc_hex::FromHex; const POOL_UNIT: usize = 1024 * 1024; const USAGE: &'static str = r#" @@ -57,8 +63,11 @@ Usage: Options: --whisper-pool-size SIZE Specify Whisper pool size [default: 10]. - -p, --port PORT Specify which RPC port to use [default: 8545]. - -a, --address ADDRESS Specify which address to use [default: 127.0.0.1]. + -p, --port PORT Specify which P2P port to use [default: random]. + -a, --address ADDRESS Specify which P2P address to use [default: 127.0.0.1]. + -s, --secret KEYFILE Specify which file contains the key to generate the enode. + -P, --rpc-port PORT Specify which RPC port to use [default: 8545]. + -A, --rpc-address ADDRESS Specify which RPC address to use [default: 127.0.0.1]. -l, --log LEVEL Specify the logging level. Must conform to the same format as RUST_LOG [default: Error]. -h, --help Display this message and exit. "#; @@ -79,7 +88,10 @@ struct Args { flag_whisper_pool_size: usize, flag_port: String, flag_address: String, + flag_rpc_port: String, + flag_rpc_address: String, flag_log: String, + flag_secret: String, } struct WhisperPoolHandle { @@ -131,6 +143,8 @@ enum Error { JsonRpc(jsonrpc_core::Error), Network(net::Error), SockAddr(std::net::AddrParseError), + FromHex(rustc_hex::FromHexError), + ParseInt(std::num::ParseIntError), } impl From for Error { @@ -163,6 +177,18 @@ impl From for Error { } } +impl From for Error { + fn from(err: rustc_hex::FromHexError) -> Self { + Error::FromHex(err) + } +} + +impl From for Error { + fn from(err: std::num::ParseIntError) -> Self { + Error::ParseInt(err) + } +} + impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { @@ -171,6 +197,8 @@ impl fmt::Display for Error { Error::Io(ref e) => write!(f, "{}", e), Error::JsonRpc(ref e) => write!(f, "{:?}", e), Error::Network(ref e) => write!(f, "{}", e), + Error::ParseInt(ref e) => write!(f, "Invalid port: {}", e), + Error::FromHex(ref e) => write!(f, "Error deciphering key: {}", e), } } } @@ -196,7 +224,7 @@ fn execute(command: I) -> Result<(), Error> where I: IntoIterator, // Parse arguments let args: Args = Docopt::new(USAGE).and_then(|d| d.argv(command).deserialize())?; let pool_size = args.flag_whisper_pool_size * POOL_UNIT; - let url = format!("{}:{}", args.flag_address, args.flag_port); + let rpc_url = format!("{}:{}", args.flag_rpc_address, args.flag_rpc_port); initialize_logger(args.flag_log); info!(target: "whisper-cli", "start"); @@ -207,8 +235,29 @@ fn execute(command: I) -> Result<(), Error> where I: IntoIterator, // Whisper protocol network handler let whisper_network_handler = Arc::new(whisper::net::Network::new(pool_size, manager.clone())); + let network_config = { + let mut cfg = net::NetworkConfiguration::new(); + let port = match args.flag_port.as_str() { + "random" => 0 as u16, + port => port.parse::()?, + + }; + let addr = Ipv4Addr::from_str(&args.flag_address[..])?; + cfg.listen_address = Some(SocketAddr::V4(SocketAddrV4::new(addr, port))); + cfg.use_secret = match args.flag_secret.as_str() { + "" => None, + fname => { + let key_text = std::fs::read_to_string(fname)?; + let key : Vec = FromHex::from_hex(key_text.as_str())?; + Secret::from_slice(key.as_slice()) + } + }; + cfg.nat_enabled = false; + cfg + }; + // Create network service - let network = devp2p::NetworkService::new(net::NetworkConfiguration::new_local(), None)?; + let network = devp2p::NetworkService::new(network_config, None)?; // Start network service network.start().map_err(|(err, _)| err)?; @@ -233,7 +282,7 @@ fn execute(command: I) -> Result<(), Error> where I: IntoIterator, let server = jsonrpc_http_server::ServerBuilder::new(io) .cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null])) - .start_http(&url.parse()?)?; + .start_http(&rpc_url.parse()?)?; server.wait(); From 375a8daeb4693baa9f853255d94640ff4297f572 Mon Sep 17 00:00:00 2001 From: Hernando Castano Date: Thu, 21 Mar 2019 17:37:13 +0100 Subject: [PATCH 23/27] Add additional request tests (#10503) --- ethcore/light/src/types/request/batch.rs | 74 ++++++++++++++++++++++++ ethcore/light/src/types/request/mod.rs | 4 +- 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/ethcore/light/src/types/request/batch.rs b/ethcore/light/src/types/request/batch.rs index 6dc75c24976..f99b49d2b27 100644 --- a/ethcore/light/src/types/request/batch.rs +++ b/ethcore/light/src/types/request/batch.rs @@ -255,4 +255,78 @@ mod tests { hash: Field::BackReference(0, 0), })).unwrap(); } + + #[test] + fn batch_tx_index_backreference() { + let mut builder = Builder::default(); + builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { + num: 100.into(), // header proof puts hash at output 0. + })).unwrap(); + builder.push(Request::TransactionIndex(IncompleteTransactionIndexRequest { + hash: Field::BackReference(0, 0), + })).unwrap(); + + let mut batch = builder.build(); + batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(42.into()))); + + assert!(batch.next_complete().is_some()); + batch.answered += 1; + assert!(batch.next_complete().is_some()); + } + + #[test] + #[should_panic] + fn batch_tx_index_backreference_wrong_output() { + let mut builder = Builder::default(); + builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { + num: 100.into(), // header proof puts hash at output 0. + })).unwrap(); + builder.push(Request::TransactionIndex(IncompleteTransactionIndexRequest { + hash: Field::BackReference(0, 0), + })).unwrap(); + + let mut batch = builder.build(); + batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Number(42))); + + batch.next_complete(); + batch.answered += 1; + batch.next_complete(); + } + + #[test] + fn batch_receipts_backreference() { + let mut builder = Builder::default(); + builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { + num: 100.into(), // header proof puts hash at output 0. + })).unwrap(); + builder.push(Request::Receipts(IncompleteReceiptsRequest { + hash: Field::BackReference(0, 0), + })).unwrap(); + + let mut batch = builder.build(); + batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Hash(42.into()))); + + assert!(batch.next_complete().is_some()); + batch.answered += 1; + assert!(batch.next_complete().is_some()); + } + + #[test] + #[should_panic] + fn batch_receipts_backreference_wrong_output() { + let mut builder = Builder::default(); + builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { + num: 100.into(), // header proof puts hash at output 0. + })).unwrap(); + builder.push(Request::Receipts(IncompleteReceiptsRequest { + hash: Field::BackReference(0, 0), + })).unwrap(); + + let mut batch = builder.build(); + batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Number(42))); + + batch.next_complete(); + batch.answered += 1; + batch.next_complete(); + } } diff --git a/ethcore/light/src/types/request/mod.rs b/ethcore/light/src/types/request/mod.rs index d43aa726369..cacfbcbe508 100644 --- a/ethcore/light/src/types/request/mod.rs +++ b/ethcore/light/src/types/request/mod.rs @@ -907,7 +907,7 @@ pub mod transaction_index { fn fill(&mut self, oracle: F) where F: Fn(usize, usize) -> Result { if let Field::BackReference(req, idx) = self.hash { self.hash = match oracle(req, idx) { - Ok(Output::Number(hash)) => Field::Scalar(hash.into()), + Ok(Output::Hash(hash)) => Field::Scalar(hash.into()), _ => Field::BackReference(req, idx), } } @@ -982,7 +982,7 @@ pub mod block_receipts { fn fill(&mut self, oracle: F) where F: Fn(usize, usize) -> Result { if let Field::BackReference(req, idx) = self.hash { self.hash = match oracle(req, idx) { - Ok(Output::Number(hash)) => Field::Scalar(hash.into()), + Ok(Output::Hash(hash)) => Field::Scalar(hash.into()), _ => Field::BackReference(req, idx), } } From f2c34f7ca2e5893044bb5891c50b5f730dbe9a86 Mon Sep 17 00:00:00 2001 From: "Denis S. Soldatov aka General-Beck" Date: Fri, 22 Mar 2019 13:46:57 +0300 Subject: [PATCH 24/27] fix Sha3/keccak256 hash calculation for binaries (#10509) https://github.com/paritytech/parity-ethereum/issues/10495 --- scripts/gitlab/build-linux.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/gitlab/build-linux.sh b/scripts/gitlab/build-linux.sh index 9b2b1232804..f0697080cb8 100755 --- a/scripts/gitlab/build-linux.sh +++ b/scripts/gitlab/build-linux.sh @@ -47,5 +47,10 @@ echo "_____ Calculating checksums _____" for binary in $(ls) do rhash --sha256 $binary -o $binary.sha256 #do we still need this hash (SHA2)? - rhash --sha3-256 $binary -o $binary.sha3 + if [[ $CARGO_TARGET == *"x86_64"* ]]; + then + ./parity tools hash $binary > $binary.sha3 + else + echo "> ${binary} cannot be hashed with cross-compiled binary (keccak256)" + fi done From 17042e9c32005ded509dd821868acbd8d16cc475 Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Fri, 22 Mar 2019 12:01:11 +0100 Subject: [PATCH 25/27] fix(rpc): fix a bunch of clippy lints (#10493) * fix(rpc): fix a bunch of clippy lints * fix(rpc clippy): remove unused ignored lints * fix(clippy): fix all redundant_field_names This commit fixes all uses of `redundant_field_names` and removes the ignored lint `redundant_field_names` * fix(brain unwrap): replace with expect --- parity/rpc_apis.rs | 4 +- rpc/src/authcodes.rs | 12 +- rpc/src/http_common.rs | 2 +- rpc/src/lib.rs | 27 ++- rpc/src/tests/helpers.rs | 6 +- rpc/src/tests/http_client.rs | 22 +-- rpc/src/tests/ws.rs | 2 +- rpc/src/v1/extractors.rs | 14 +- rpc/src/v1/helpers/deprecated.rs | 2 +- rpc/src/v1/helpers/dispatch/light.rs | 8 +- rpc/src/v1/helpers/dispatch/mod.rs | 8 +- rpc/src/v1/helpers/external_signer/mod.rs | 2 +- rpc/src/v1/helpers/external_signer/oneshot.rs | 2 +- .../helpers/external_signer/signing_queue.rs | 4 +- rpc/src/v1/helpers/fake_sign.rs | 10 +- rpc/src/v1/helpers/ipfs.rs | 2 +- rpc/src/v1/helpers/light_fetch.rs | 56 +++---- rpc/src/v1/helpers/signature.rs | 2 +- rpc/src/v1/helpers/subscription_manager.rs | 2 +- rpc/src/v1/helpers/work.rs | 17 +- rpc/src/v1/impls/debug.rs | 11 +- rpc/src/v1/impls/eth.rs | 158 +++++++++--------- rpc/src/v1/impls/eth_filter.rs | 23 ++- rpc/src/v1/impls/eth_pubsub.rs | 22 +-- rpc/src/v1/impls/light/eth.rs | 108 ++++++------ rpc/src/v1/impls/light/net.rs | 2 +- rpc/src/v1/impls/light/parity.rs | 54 +++--- rpc/src/v1/impls/light/parity_set.rs | 6 +- rpc/src/v1/impls/parity.rs | 37 ++-- rpc/src/v1/impls/parity_set.rs | 14 +- rpc/src/v1/impls/private.rs | 27 +-- rpc/src/v1/impls/pubsub.rs | 2 +- rpc/src/v1/impls/rpc.rs | 4 +- rpc/src/v1/impls/signer.rs | 17 +- rpc/src/v1/impls/signing.rs | 15 +- rpc/src/v1/impls/signing_unsafe.rs | 6 +- rpc/src/v1/impls/traces.rs | 20 +-- rpc/src/v1/impls/web3.rs | 8 +- rpc/src/v1/informant.rs | 12 +- rpc/src/v1/tests/mocked/web3.rs | 6 +- rpc/src/v1/types/block.rs | 24 +-- rpc/src/v1/types/block_number.rs | 2 +- rpc/src/v1/types/confirmations.rs | 10 +- rpc/src/v1/types/consensus_status.rs | 2 +- rpc/src/v1/types/filter.rs | 13 +- rpc/src/v1/types/log.rs | 8 +- rpc/src/v1/types/private_receipt.rs | 6 +- rpc/src/v1/types/pubsub.rs | 8 +- rpc/src/v1/types/receipt.rs | 26 +-- rpc/src/v1/types/sync.rs | 4 +- rpc/src/v1/types/trace.rs | 48 +++--- rpc/src/v1/types/transaction.rs | 40 ++--- rpc/src/v1/types/transaction_request.rs | 16 +- 53 files changed, 472 insertions(+), 491 deletions(-) diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index 9287f62720b..288f85ab422 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -283,7 +283,7 @@ impl FullDependencies { handler.extend_with(DebugClient::new(self.client.clone()).to_delegate()); } Api::Web3 => { - handler.extend_with(Web3Client::new().to_delegate()); + handler.extend_with(Web3Client::default().to_delegate()); } Api::Net => { handler.extend_with(NetClient::new(&self.sync).to_delegate()); @@ -529,7 +529,7 @@ impl LightDependencies { warn!(target: "rpc", "Debug API is not available in light client mode.") } Api::Web3 => { - handler.extend_with(Web3Client::new().to_delegate()); + handler.extend_with(Web3Client::default().to_delegate()); } Api::Net => { handler.extend_with(light::NetClient::new(self.sync.clone()).to_delegate()); diff --git a/rpc/src/authcodes.rs b/rpc/src/authcodes.rs index 976ce1a3fb9..b348dfd729d 100644 --- a/rpc/src/authcodes.rs +++ b/rpc/src/authcodes.rs @@ -51,7 +51,7 @@ const TIME_THRESHOLD: u64 = 7; /// minimal length of hash const TOKEN_LENGTH: usize = 16; /// Separator between fields in serialized tokens file. -const SEPARATOR: &'static str = ";"; +const SEPARATOR: &str = ";"; /// Number of seconds to keep unused tokens. const UNUSED_TOKEN_TIMEOUT: u64 = 3600 * 24; // a day @@ -115,7 +115,7 @@ impl AuthCodes { }) .collect(); Ok(AuthCodes { - codes: codes, + codes, now: time_provider, }) } @@ -128,7 +128,7 @@ impl AuthCodes { pub fn to_file(&self, file: &Path) -> io::Result<()> { let mut file = fs::File::create(file)?; let content = self.codes.iter().map(|code| { - let mut data = vec![code.code.clone(), encode_time(code.created_at.clone())]; + let mut data = vec![code.code.clone(), encode_time(code.created_at)]; if let Some(used_at) = code.last_used_at { data.push(encode_time(used_at)); } @@ -141,11 +141,11 @@ impl AuthCodes { pub fn new(codes: Vec, now: T) -> Self { AuthCodes { codes: codes.into_iter().map(|code| Code { - code: code, + code, created_at: time::Duration::from_secs(now.now()), last_used_at: None, }).collect(), - now: now, + now, } } @@ -183,7 +183,7 @@ impl AuthCodes { .join("-"); trace!(target: "signer", "New authentication token generated."); self.codes.push(Code { - code: code, + code, created_at: time::Duration::from_secs(self.now.now()), last_used_at: None, }); diff --git a/rpc/src/http_common.rs b/rpc/src/http_common.rs index 517bbbf7608..99bd392f356 100644 --- a/rpc/src/http_common.rs +++ b/rpc/src/http_common.rs @@ -44,7 +44,7 @@ impl http::MetaExtractor for MetaExtractor where { fn read_metadata(&self, req: &hyper::Request) -> M { let as_string = |header: Option<&hyper::header::HeaderValue>| { - header.and_then(|val| val.to_str().ok().map(|s| s.to_owned())) + header.and_then(|val| val.to_str().ok().map(ToOwned::to_owned)) }; let origin = as_string(req.headers().get("origin")); diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index cafd7a8e440..a537cb29424 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -17,6 +17,25 @@ //! Parity RPC. #![warn(missing_docs, unused_extern_crates)] +#![cfg_attr(feature = "cargo-clippy", warn(clippy::all, clippy::pedantic))] +#![cfg_attr( + feature = "cargo-clippy", + allow( + // things are often more readable this way + clippy::cast_lossless, + clippy::module_name_repetitions, + clippy::single_match_else, + clippy::type_complexity, + clippy::use_self, + // not practical + clippy::match_bool, + clippy::needless_pass_by_value, + clippy::similar_names, + // don't require markdown syntax for docs + clippy::doc_markdown, + ), + warn(clippy::indexing_slicing) +)] #[macro_use] extern crate futures; @@ -145,8 +164,8 @@ pub fn start_http( Ok(http::ServerBuilder::with_meta_extractor(handler, extractor) .keep_alive(keep_alive) .threads(threads) - .cors(cors_domains.into()) - .allowed_hosts(allowed_hosts.into()) + .cors(cors_domains) + .allowed_hosts(allowed_hosts) .health_api(("/api/health", "parity_nodeStatus")) .cors_allow_headers(AccessControlAllowHeaders::Any) .max_request_body_size(max_payload * 1024 * 1024) @@ -176,8 +195,8 @@ pub fn start_http_with_middleware( Ok(http::ServerBuilder::with_meta_extractor(handler, extractor) .keep_alive(keep_alive) .threads(threads) - .cors(cors_domains.into()) - .allowed_hosts(allowed_hosts.into()) + .cors(cors_domains) + .allowed_hosts(allowed_hosts) .cors_allow_headers(AccessControlAllowHeaders::Any) .max_request_body_size(max_payload * 1024 * 1024) .request_middleware(middleware) diff --git a/rpc/src/tests/helpers.rs b/rpc/src/tests/helpers.rs index fe04906d4a9..301d77e91ce 100644 --- a/rpc/src/tests/helpers.rs +++ b/rpc/src/tests/helpers.rs @@ -39,7 +39,7 @@ impl Server { Server { server: f(remote), - event_loop: event_loop, + event_loop, } } } @@ -60,8 +60,8 @@ pub struct GuardedAuthCodes { pub path: PathBuf, } -impl GuardedAuthCodes { - pub fn new() -> Self { +impl Default for GuardedAuthCodes { + fn default() -> Self { let tempdir = TempDir::new("").unwrap(); let path = tempdir.path().join("file"); diff --git a/rpc/src/tests/http_client.rs b/rpc/src/tests/http_client.rs index 7720f4254be..0588c791e77 100644 --- a/rpc/src/tests/http_client.rs +++ b/rpc/src/tests/http_client.rs @@ -30,7 +30,7 @@ pub struct Response { impl Response { pub fn assert_header(&self, header: &str, value: &str) { let header = format!("{}: {}", header, value); - assert!(self.headers.iter().find(|h| *h == &header).is_some(), "Couldn't find header {} in {:?}", header, &self.headers) + assert!(self.headers.iter().any(|h| h == &header), "Couldn't find header {} in {:?}", header, &self.headers) } pub fn assert_status(&self, status: &str) { @@ -98,35 +98,35 @@ pub fn request(address: &SocketAddr, request: &str) -> Response { let mut lines = response.lines(); let status = lines.next().expect("Expected a response").to_owned(); let headers_raw = read_block(&mut lines, false); - let headers = headers_raw.split('\n').map(|v| v.to_owned()).collect(); + let headers = headers_raw.split('\n').map(ToOwned::to_owned).collect(); let body = read_block(&mut lines, true); Response { - status: status, - headers: headers, - headers_raw: headers_raw, - body: body, + status, + headers, + headers_raw, + body, } } /// Check if all required security headers are present pub fn assert_security_headers_present(headers: &[String], port: Option) { - if let None = port { + if port.is_none() { assert!( - headers.iter().find(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN").is_some(), + headers.iter().any(|header| header.as_str() == "X-Frame-Options: SAMEORIGIN") "X-Frame-Options: SAMEORIGIN missing: {:?}", headers ); } assert!( - headers.iter().find(|header| header.as_str() == "X-XSS-Protection: 1; mode=block").is_some(), + headers.iter().any(|header| header.as_str() == "X-XSS-Protection: 1; mode=block") "X-XSS-Protection missing: {:?}", headers ); assert!( - headers.iter().find(|header| header.as_str() == "X-Content-Type-Options: nosniff").is_some(), + headers.iter().any(|header| header.as_str() == "X-Content-Type-Options: nosniff") "X-Content-Type-Options missing: {:?}", headers ); assert!( - headers.iter().find(|header| header.starts_with("Content-Security-Policy: ")).is_some(), + headers.iter().any(|header| header.starts_with("Content-Security-Policy: ")) "Content-Security-Policy missing: {:?}", headers ) } diff --git a/rpc/src/tests/ws.rs b/rpc/src/tests/ws.rs index 7bb0b00894b..3b607888205 100644 --- a/rpc/src/tests/ws.rs +++ b/rpc/src/tests/ws.rs @@ -29,7 +29,7 @@ use tests::http_client; pub fn serve() -> (Server, usize, GuardedAuthCodes) { let address = "127.0.0.1:0".parse().unwrap(); let io = MetaIoHandler::default(); - let authcodes = GuardedAuthCodes::new(); + let authcodes = GuardedAuthCodes::default(); let stats = Arc::new(informant::RpcStats::default()); let res = Server::new(|_| ::start_ws( diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index 2620125e0dc..d3384c2c1d1 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -41,8 +41,8 @@ impl HttpMetaExtractor for RpcExtractor { Metadata { origin: Origin::Rpc( format!("{} / {}", - origin.unwrap_or("unknown origin".to_string()), - user_agent.unwrap_or("unknown agent".to_string())) + origin.unwrap_or_else(|| "unknown origin".to_string()), + user_agent.unwrap_or_else(|| "unknown agent".to_string())) ), session: None, } @@ -67,7 +67,7 @@ impl WsExtractor { /// Creates new `WsExtractor` with given authcodes path. pub fn new(path: Option<&Path>) -> Self { WsExtractor { - authcodes_path: path.map(|p| p.to_owned()), + authcodes_path: path.map(ToOwned::to_owned), } } } @@ -80,7 +80,7 @@ impl ws::MetaExtractor for WsExtractor { Some(ref path) => { let authorization = req.protocols.get(0).and_then(|p| auth_token_hash(&path, p, true)); match authorization { - Some(id) => Origin::Signer { session: id.into() }, + Some(id) => Origin::Signer { session: id }, None => Origin::Ws { session: id.into() }, } }, @@ -186,7 +186,7 @@ impl WsStats { /// Creates new WS usage tracker. pub fn new(stats: Arc) -> Self { WsStats { - stats: stats, + stats, } } } @@ -210,7 +210,7 @@ impl> WsDispatcher { /// Create new `WsDispatcher` with given full handler. pub fn new(full_handler: core::MetaIoHandler) -> Self { WsDispatcher { - full_handler: full_handler, + full_handler, } } } @@ -229,7 +229,7 @@ impl> core::Middleware for WsDispatcher< X: core::futures::Future, Error=()> + Send + 'static, { let use_full = match &meta.origin { - &Origin::Signer { .. } => true, + Origin::Signer { .. } => true, _ => false, }; diff --git a/rpc/src/v1/helpers/deprecated.rs b/rpc/src/v1/helpers/deprecated.rs index eb754c01ac1..49e9d8b0742 100644 --- a/rpc/src/v1/helpers/deprecated.rs +++ b/rpc/src/v1/helpers/deprecated.rs @@ -66,7 +66,7 @@ impl Instant> DeprecationNotice { pub fn print<'a, T: Into>>(&self, method: MethodName, details: T) { let now = (self.now)(); match self.next_warning_at.read().get(method) { - Some(next) if next > &now => return, + Some(next) if *next > now => return, _ => {}, } diff --git a/rpc/src/v1/helpers/dispatch/light.rs b/rpc/src/v1/helpers/dispatch/light.rs index 2913e52c85c..59c3af5232f 100644 --- a/rpc/src/v1/helpers/dispatch/light.rs +++ b/rpc/src/v1/helpers/dispatch/light.rs @@ -147,19 +147,19 @@ where const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]); let gas_limit = self.client.best_block_header().gas_limit(); - let request_gas_price = request.gas_price.clone(); + let request_gas_price = request.gas_price; let from = request.from.unwrap_or(default_sender); let with_gas_price = move |gas_price| { let request = request; FilledTransactionRequest { - from: from.clone(), + from, used_default_from: request.from.is_none(), to: request.to, nonce: request.nonce, - gas_price: gas_price, + gas_price, gas: request.gas.unwrap_or_else(|| gas_limit / 3), - value: request.value.unwrap_or_else(|| 0.into()), + value: request.value.unwrap_or_default(), data: request.data.unwrap_or_else(Vec::new), condition: request.condition, } diff --git a/rpc/src/v1/helpers/dispatch/mod.rs b/rpc/src/v1/helpers/dispatch/mod.rs index 8877209723d..3f247f0c6c0 100644 --- a/rpc/src/v1/helpers/dispatch/mod.rs +++ b/rpc/src/v1/helpers/dispatch/mod.rs @@ -294,7 +294,7 @@ pub fn execute( Box::new( dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| { - WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token)) + WithToken::from((ConfirmationResponse::SendTransaction(hash), token)) }) ) }, @@ -368,13 +368,13 @@ pub fn from_rpc(payload: RpcConfirmationPayload, default_account: Address, di .map(ConfirmationPayload::SignTransaction)) }, RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => { - Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into()))) + Box::new(future::ok(ConfirmationPayload::Decrypt(address, msg.into()))) }, RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => { - Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into()))) + Box::new(future::ok(ConfirmationPayload::EthSignMessage(address, data.into()))) }, RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => { - Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into()))) + Box::new(future::ok(ConfirmationPayload::SignMessage(address, data))) }, } } diff --git a/rpc/src/v1/helpers/external_signer/mod.rs b/rpc/src/v1/helpers/external_signer/mod.rs index 49bbaafe596..0797929cbdf 100644 --- a/rpc/src/v1/helpers/external_signer/mod.rs +++ b/rpc/src/v1/helpers/external_signer/mod.rs @@ -40,7 +40,7 @@ impl SignerService { SignerService { queue: Arc::new(ConfirmationsQueue::default()), generate_new_token: Box::new(new_token), - is_enabled: is_enabled, + is_enabled, } } diff --git a/rpc/src/v1/helpers/external_signer/oneshot.rs b/rpc/src/v1/helpers/external_signer/oneshot.rs index 623691d3998..eac3dca7f81 100644 --- a/rpc/src/v1/helpers/external_signer/oneshot.rs +++ b/rpc/src/v1/helpers/external_signer/oneshot.rs @@ -28,7 +28,7 @@ pub struct Sender { impl Sender { pub fn send(self, data: Res) { let res = self.sender.send(data); - if let Err(_) = res { + if res.is_err() { debug!(target: "rpc", "Responding to a no longer active request."); } } diff --git a/rpc/src/v1/helpers/external_signer/signing_queue.rs b/rpc/src/v1/helpers/external_signer/signing_queue.rs index 9bbc778ece1..00a459a869a 100644 --- a/rpc/src/v1/helpers/external_signer/signing_queue.rs +++ b/rpc/src/v1/helpers/external_signer/signing_queue.rs @@ -121,7 +121,7 @@ impl ConfirmationsQueue { )); // notify confirmation receiver about resolution - let result = result.ok_or(errors::request_rejected()); + let result = result.ok_or_else(errors::request_rejected); sender.sender.send(result); Some(sender.request) @@ -150,7 +150,7 @@ impl SigningQueue for ConfirmationsQueue { // Increment id let id = { let mut last_id = self.id.lock(); - *last_id = *last_id + U256::from(1); + *last_id += U256::from(1); *last_id }; // Add request to queue diff --git a/rpc/src/v1/helpers/fake_sign.rs b/rpc/src/v1/helpers/fake_sign.rs index 76d37aab2fb..9f9b7c8ed68 100644 --- a/rpc/src/v1/helpers/fake_sign.rs +++ b/rpc/src/v1/helpers/fake_sign.rs @@ -24,16 +24,16 @@ pub fn sign_call(request: CallRequest) -> Result { let max_gas = U256::from(50_000_000); let gas = match request.gas { Some(gas) => gas, - None => max_gas * 10u32, + None => max_gas * 10_u32, }; - let from = request.from.unwrap_or(0.into()); + let from = request.from.unwrap_or_default(); Ok(Transaction { - nonce: request.nonce.unwrap_or_else(|| 0.into()), + nonce: request.nonce.unwrap_or_default(), action: request.to.map_or(Action::Create, Action::Call), gas, - gas_price: request.gas_price.unwrap_or_else(|| 0.into()), - value: request.value.unwrap_or(0.into()), + gas_price: request.gas_price.unwrap_or_default(), + value: request.value.unwrap_or_default(), data: request.data.unwrap_or_default(), }.fake_sign(from)) } diff --git a/rpc/src/v1/helpers/ipfs.rs b/rpc/src/v1/helpers/ipfs.rs index 928362cf89f..93110dbf34d 100644 --- a/rpc/src/v1/helpers/ipfs.rs +++ b/rpc/src/v1/helpers/ipfs.rs @@ -28,5 +28,5 @@ pub fn cid(content: Bytes) -> Result { let hash = digest::sha256(&content.0); let mh = multihash::encode(multihash::Hash::SHA2256, &*hash).map_err(errors::encoding)?; let cid = Cid::new(Codec::DagProtobuf, Version::V0, &mh); - Ok(cid.to_string().into()) + Ok(cid.to_string()) } diff --git a/rpc/src/v1/helpers/light_fetch.rs b/rpc/src/v1/helpers/light_fetch.rs index 3ac17c2fd8d..3d19e3fa868 100644 --- a/rpc/src/v1/helpers/light_fetch.rs +++ b/rpc/src/v1/helpers/light_fetch.rs @@ -121,7 +121,7 @@ pub fn extract_transaction_at_index(block: encoded::Block, index: usize) -> Opti cached_sender, } }) - .map(|tx| Transaction::from_localized(tx)) + .map(Transaction::from_localized) } // extract the header indicated by the given `HeaderRef` from the given responses. @@ -159,7 +159,7 @@ where let idx = reqs.len(); let hash_ref = Field::back_ref(idx, 0); reqs.push(req.into()); - reqs.push(request::HeaderByHash(hash_ref.clone()).into()); + reqs.push(request::HeaderByHash(hash_ref).into()); Ok(HeaderRef::Unresolved(idx + 1, hash_ref)) } @@ -197,7 +197,7 @@ where Err(e) => return Either::A(future::err(e)), }; - reqs.push(request::Account { header: header_ref.clone(), address: address }.into()); + reqs.push(request::Account { header: header_ref.clone(), address }.into()); let account_idx = reqs.len() - 1; reqs.push(request::Code { header: header_ref, code_hash: Field::back_ref(account_idx, 0) }.into()); @@ -216,7 +216,7 @@ where Err(e) => return Either::A(future::err(e)), }; - reqs.push(request::Account { header: header_ref, address: address }.into()); + reqs.push(request::Account { header: header_ref, address }.into()); Either::B(self.send_requests(reqs, |mut res|match res.pop() { Some(OnDemandResponse::Account(acc)) => acc, @@ -246,7 +246,7 @@ where } }; - let from = req.from.unwrap_or_else(|| Address::zero()); + let from = req.from.unwrap_or_default(); let nonce_fut = match req.nonce { Some(nonce) => Either::A(future::ok(Some(nonce))), None => Either::B(self.account(from, id).map(|acc| acc.map(|a| a.nonce))), @@ -370,10 +370,10 @@ where for (transaction_log_index, log) in receipt.logs.into_iter().enumerate() { if filter.matches(&log) { matches.insert((num, block_index), Log { - address: log.address.into(), + address: log.address, topics: log.topics.into_iter().map(Into::into).collect(), data: log.data.into(), - block_hash: Some(hash.into()), + block_hash: Some(hash), block_number: Some(num.into()), // No way to easily retrieve transaction hash, so let's just skip it. transaction_hash: None, @@ -410,8 +410,8 @@ where let mut blocks = BTreeMap::new(); for log in result.iter() { let block_hash = log.block_hash.as_ref().expect("Previously initialized with value; qed"); - blocks.entry(block_hash.clone()).or_insert_with(|| { - fetcher_block.block(BlockId::Hash(block_hash.clone().into())) + blocks.entry(*block_hash).or_insert_with(|| { + fetcher_block.block(BlockId::Hash(*block_hash)) }); } // future get blocks (unordered it) @@ -419,12 +419,12 @@ where let transactions_per_block: BTreeMap<_, _> = blocks.iter() .map(|block| (block.hash(), block.transactions())).collect(); for log in result.iter_mut() { - let log_index: U256 = log.transaction_index.expect("Previously initialized with value; qed").into(); - let block_hash = log.block_hash.clone().expect("Previously initialized with value; qed").into(); + let log_index = log.transaction_index.expect("Previously initialized with value; qed"); + let block_hash = log.block_hash.expect("Previously initialized with value; qed"); let tx_hash = transactions_per_block.get(&block_hash) // transaction index is from an enumerate call in log common so not need to check value .and_then(|txs| txs.get(log_index.as_usize())) - .map(|tr| tr.hash().into()); + .map(types::transaction::UnverifiedTransaction::hash); log.transaction_hash = tx_hash; } result @@ -442,7 +442,7 @@ where Box::new(future::loop_fn(params, move |(sync, on_demand)| { let maybe_future = sync.with_context(|ctx| { - let req = request::TransactionIndex(tx_hash.clone().into()); + let req = request::TransactionIndex(tx_hash.into()); on_demand.request(ctx, req) }); @@ -468,7 +468,7 @@ where let index = index.index as usize; let transaction = extract_transaction_at_index(blk, index); - if transaction.as_ref().map_or(true, |tx| tx.hash != tx_hash.into()) { + if transaction.as_ref().map_or(true, |tx| tx.hash != tx_hash) { // index is actively wrong: indicated block has // fewer transactions than necessary or the transaction // at that index had a different hash. @@ -522,7 +522,7 @@ where ) -> impl Future, Error = Error> { let fetch_hashes = [from_block, to_block].iter() .filter_map(|block_id| match block_id { - BlockId::Hash(hash) => Some(hash.clone()), + BlockId::Hash(hash) => Some(*hash), _ => None, }) .collect::>(); @@ -533,14 +533,14 @@ where self.headers_by_hash(&fetch_hashes[..]).and_then(move |mut header_map| { let (from_block_num, to_block_num) = { let block_number = |id| match id { - &BlockId::Earliest => 0, - &BlockId::Latest => best_number, - &BlockId::Hash(ref h) => - header_map.get(h).map(|hdr| hdr.number()) + BlockId::Earliest => 0, + BlockId::Latest => best_number, + BlockId::Hash(ref h) => + header_map.get(h).map(types::encoded::Header::number) .expect("from_block and to_block headers are fetched by hash; this closure is only called on from_block and to_block; qed"), - &BlockId::Number(x) => x, + BlockId::Number(x) => x, }; - (block_number(&from_block), block_number(&to_block)) + (block_number(from_block), block_number(to_block)) }; if to_block_num < from_block_num { @@ -557,7 +557,7 @@ where let headers_fut = fetcher.headers_range(from_block_num, to_block_num, to_header_hint); Either::B(headers_fut.map(move |headers| { // Validate from_block if it's a hash - let last_hash = headers.last().map(|hdr| hdr.hash()); + let last_hash = headers.last().map(types::encoded::Header::hash); match (last_hash, from_block) { (Some(h1), BlockId::Hash(h2)) if h1 != h2 => Vec::new(), _ => headers, @@ -578,15 +578,13 @@ where } self.send_requests(reqs, move |res| { - let headers = refs.drain() - .map(|(hash, header_ref)| { + refs.into_iter().map(|(hash, header_ref)| { let hdr = extract_header(&res, header_ref) .expect("these responses correspond to requests that header_ref belongs to; \ qed"); (hash, hdr) - }) - .collect(); - headers + }) + .collect() }) } @@ -678,7 +676,7 @@ where { fn clone(&self) -> Self { Self { - from: self.from.clone(), + from: self.from, tx: self.tx.clone(), hdr: self.hdr.clone(), env_info: self.env_info.clone(), @@ -719,7 +717,7 @@ where required, got); if required <= params.hdr.gas_limit() { params.tx.gas = required; - return Ok(future::Loop::Continue(params)) + Ok(future::Loop::Continue(params)) } else { warn!(target: "light_fetch", "Required gas is bigger than block header's gas dropping the request"); diff --git a/rpc/src/v1/helpers/signature.rs b/rpc/src/v1/helpers/signature.rs index 32827ea1e11..b191a3737e8 100644 --- a/rpc/src/v1/helpers/signature.rs +++ b/rpc/src/v1/helpers/signature.rs @@ -45,7 +45,7 @@ pub fn verify_signature( let v = if v >= 35 { (v - 1) % 2 } else { v }; - let signature = Signature::from_rsv(&r.into(), &s.into(), v as u8); + let signature = Signature::from_rsv(&r, &s, v as u8); let public_key = recover(&signature, &hash).map_err(errors::encryption)?; let address = public_to_address(&public_key); Ok(RecoveredAccount { address, public_key, is_valid_for_current_chain }) diff --git a/rpc/src/v1/helpers/subscription_manager.rs b/rpc/src/v1/helpers/subscription_manager.rs index 4f50cad4235..d83beb397f0 100644 --- a/rpc/src/v1/helpers/subscription_manager.rs +++ b/rpc/src/v1/helpers/subscription_manager.rs @@ -52,7 +52,7 @@ impl> GenericPollManager { pub fn new(rpc: MetaIoHandler) -> Self { GenericPollManager { subscribers: Default::default(), - rpc: rpc, + rpc, } } diff --git a/rpc/src/v1/helpers/work.rs b/rpc/src/v1/helpers/work.rs index 661b4cab8b8..b52cb70c5f0 100644 --- a/rpc/src/v1/helpers/work.rs +++ b/rpc/src/v1/helpers/work.rs @@ -29,15 +29,10 @@ pub fn submit_work_detail(client: &Arc, // TODO [ToDr] Should disallow submissions in case of PoA? trace!(target: "miner", "submit_work_detail: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash); let seal = vec![rlp::encode(&mix_hash), rlp::encode(&nonce)]; - let import = miner.submit_seal(pow_hash, seal) - .and_then(|block| client.import_sealed_block(block)); - match import { - Ok(hash) => { - Ok(hash.into()) - }, - Err(err) => { - warn!(target: "miner", "Cannot submit work - {:?}.", err); - Err(errors::cannot_submit_work(err)) - }, - } + miner.submit_seal(pow_hash, seal) + .and_then(|block| client.import_sealed_block(block)) + .map_err(|e| { + warn!(target: "miner", "Cannot submit work - {:?}.", e); + errors::cannot_submit_work(e) + }) } diff --git a/rpc/src/v1/impls/debug.rs b/rpc/src/v1/impls/debug.rs index abec9b1f87c..e46dd628d1e 100644 --- a/rpc/src/v1/impls/debug.rs +++ b/rpc/src/v1/impls/debug.rs @@ -19,6 +19,7 @@ use std::sync::Arc; use ethcore::client::BlockChainClient; +use types::header::Header; use types::transaction::LocalizedTransaction; use jsonrpc_core::Result; @@ -50,7 +51,7 @@ impl Debug for DebugClient { let hash = block.header.hash(); RichBlock { inner: Block { - hash: Some(hash.into()), + hash: Some(hash), size: Some(block.bytes.len().into()), parent_hash: cast(block.header.parent_hash()), uncles_hash: cast(block.header.uncles_hash()), @@ -65,14 +66,14 @@ impl Debug for DebugClient { timestamp: block.header.timestamp().into(), difficulty: cast(block.header.difficulty()), total_difficulty: None, - seal_fields: block.header.seal().into_iter().cloned().map(Into::into).collect(), - uncles: block.uncles.into_iter().map(|u| u.hash().into()).collect(), + seal_fields: block.header.seal().iter().cloned().map(Into::into).collect(), + uncles: block.uncles.iter().map(Header::hash).collect(), transactions: BlockTransactions::Full(block.transactions .into_iter() .enumerate() .map(|(transaction_index, signed)| Transaction::from_localized(LocalizedTransaction { - block_number: number.into(), - block_hash: hash.into(), + block_number: number, + block_hash: hash, transaction_index, signed, cached_sender: None, diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 31b8be10c29..1b5fdf447f9 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -197,7 +197,7 @@ impl EthClient EthClient None, - false => Some(view.hash().into()), + false => Some(view.hash()), }, size: Some(block.rlp().as_raw().len().into()), - parent_hash: view.parent_hash().into(), - uncles_hash: view.uncles_hash().into(), - author: view.author().into(), - miner: view.author().into(), - state_root: view.state_root().into(), - transactions_root: view.transactions_root().into(), - receipts_root: view.receipts_root().into(), + parent_hash: view.parent_hash(), + uncles_hash: view.uncles_hash(), + author: view.author(), + miner: view.author(), + state_root: view.state_root(), + transactions_root: view.transactions_root(), + receipts_root: view.receipts_root(), number: match is_pending { true => None, false => Some(view.number().into()), }, - gas_used: view.gas_used().into(), - gas_limit: view.gas_limit().into(), + gas_used: view.gas_used(), + gas_limit: view.gas_limit(), logs_bloom: match is_pending { true => None, - false => Some(view.log_bloom().into()), + false => Some(view.log_bloom()), }, timestamp: view.timestamp().into(), - difficulty: view.difficulty().into(), - total_difficulty: Some(total_difficulty.into()), + difficulty: view.difficulty(), + total_difficulty: Some(total_difficulty), seal_fields: view.seal().into_iter().map(Into::into).collect(), - uncles: block.uncle_hashes().into_iter().map(Into::into).collect(), + uncles: block.uncle_hashes(), transactions: match include_txs { - true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(|t| Transaction::from_localized(t)).collect()), - false => BlockTransactions::Hashes(block.transaction_hashes().into_iter().map(Into::into).collect()), + true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(Transaction::from_localized).collect()), + false => BlockTransactions::Hashes(block.transaction_hashes()), }, extra_data: Bytes::new(view.extra_data()), }, @@ -334,7 +334,7 @@ impl EthClient EthClient { return Ok(None); } }; - let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(uncle.parent_hash().clone())) { + let parent_difficulty = match client.block_total_difficulty(BlockId::Hash(*uncle.parent_hash())) { Some(difficulty) => difficulty, None => { return Ok(None); } }; @@ -398,29 +398,28 @@ impl EthClient(miner: &M, best_block: EthBlockNumber, filter: &EthcoreFi .filter(|pair| filter.matches(&pair.1)) .map(|pair| { let mut log = Log::from(pair.1); - log.transaction_hash = Some(pair.0.into()); + log.transaction_hash = Some(pair.0); log }) .collect() @@ -518,8 +517,8 @@ impl Eth for EthClient< let info = SyncInfo { starting_block: status.start_block_number.into(), - current_block: current_block.into(), - highest_block: highest_block.into(), + current_block, + highest_block, warp_chunks_amount: warp_chunks_amount.map(|x| U256::from(x as u64)).map(Into::into), warp_chunks_processed: warp_chunks_processed.map(|x| U256::from(x as u64)).map(Into::into), }; @@ -535,10 +534,9 @@ impl Eth for EthClient< (self.accounts)() .first() .cloned() - .map(From::from) .ok_or_else(|| errors::account("No accounts were found", "")) } else { - Ok(H160::from(miner)) + Ok(miner) } } @@ -551,18 +549,18 @@ impl Eth for EthClient< } fn hashrate(&self) -> Result { - Ok(U256::from(self.external_miner.hashrate())) + Ok(self.external_miner.hashrate()) } fn gas_price(&self) -> Result { - Ok(U256::from(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile))) + Ok(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile)) } fn accounts(&self) -> Result> { self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS); let accounts = (self.accounts)(); - Ok(accounts.into_iter().map(Into::into).collect()) + Ok(accounts) } fn block_number(&self) -> Result { @@ -574,7 +572,7 @@ impl Eth for EthClient< try_bf!(check_known(&*self.client, num.clone())); let res = match self.client.balance(&address, self.get_state(num)) { - Some(balance) => Ok(balance.into()), + Some(balance) => Ok(balance), None => Err(errors::state_pruned()), }; @@ -600,16 +598,16 @@ impl Eth for EthClient< try_bf!(check_known(&*self.client, num.clone())); let res = match self.client.prove_account(key1, id) { Some((proof, account)) => Ok(EthAccount { - address: address, - balance: account.balance.into(), - nonce: account.nonce.into(), - code_hash: account.code_hash.into(), - storage_hash: account.storage_root.into(), + address, + balance: account.balance, + nonce: account.nonce, + code_hash: account.code_hash, + storage_hash: account.storage_root, account_proof: proof.into_iter().map(Bytes::new).collect(), storage_proof: values.into_iter().filter_map(|storage_index| { - let key2: H256 = storage_index.into(); + let key2: H256 = storage_index; self.client.prove_storage(key1, keccak(key2), id) - .map(|(storage_proof,storage_value)| StorageProof { + .map(|(storage_proof, storage_value)| StorageProof { key: key2.into(), value: storage_value.into(), proof: storage_proof.into_iter().map(Bytes::new).collect() @@ -624,12 +622,11 @@ impl Eth for EthClient< } fn storage_at(&self, address: H160, position: U256, num: Option) -> BoxFuture { - let address: Address = address.into(); let num = num.unwrap_or_default(); try_bf!(check_known(&*self.client, num.clone())); let res = match self.client.storage_at(&address, &H256::from(position), self.get_state(num)) { - Some(s) => Ok(s.into()), + Some(s) => Ok(s), None => Err(errors::state_pruned()), }; @@ -637,11 +634,9 @@ impl Eth for EthClient< } fn transaction_count(&self, address: H160, num: Option) -> BoxFuture { - let address: Address = address.into(); - let res = match num.unwrap_or_default() { BlockNumber::Pending if self.options.pending_nonce_from_queue => { - Ok(self.miner.next_nonce(&*self.client, &address).into()) + Ok(self.miner.next_nonce(&*self.client, &address)) } BlockNumber::Pending => { let info = self.client.chain_info(); @@ -654,14 +649,14 @@ impl Eth for EthClient< }); match nonce { - Some(nonce) => Ok(nonce.into()), + Some(nonce) => Ok(nonce), None => Err(errors::database("latest nonce missing")) } }, number => { try_bf!(check_known(&*self.client, number.clone())); match self.client.nonce(&address, block_number_to_id(number)) { - Some(nonce) => Ok(nonce.into()), + Some(nonce) => Ok(nonce), None => Err(errors::state_pruned()), } } @@ -671,7 +666,7 @@ impl Eth for EthClient< } fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture> { - let trx_count = self.client.block(BlockId::Hash(hash.into())) + let trx_count = self.client.block(BlockId::Hash(hash)) .map(|block| block.transactions_count().into()); let result = Ok(trx_count) .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); @@ -696,7 +691,7 @@ impl Eth for EthClient< } fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture> { - let uncle_count = self.client.block(BlockId::Hash(hash.into())) + let uncle_count = self.client.block(BlockId::Hash(hash)) .map(|block| block.uncles_count().into()); let result = Ok(uncle_count) .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); @@ -734,7 +729,7 @@ impl Eth for EthClient< } fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture> { - let result = self.rich_block(BlockId::Hash(hash.into()).into(), include_txs) + let result = self.rich_block(BlockId::Hash(hash).into(), include_txs) .and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); Box::new(future::done(result)) } @@ -756,7 +751,7 @@ impl Eth for EthClient< } fn transaction_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture> { - let id = PendingTransactionId::Location(PendingOrBlock::Block(BlockId::Hash(hash.into())), index.value()); + let id = PendingTransactionId::Location(PendingOrBlock::Block(BlockId::Hash(hash)), index.value()); let result = self.transaction(id).and_then( errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); Box::new(future::done(result)) @@ -792,7 +787,7 @@ impl Eth for EthClient< fn uncle_by_block_hash_and_index(&self, hash: H256, index: Index) -> BoxFuture> { let result = self.uncle(PendingUncleId { - id: PendingOrBlock::Block(BlockId::Hash(hash.into())), + id: PendingOrBlock::Block(BlockId::Hash(hash)), position: index.value() }).and_then(errors::check_block_gap(&*self.client, self.options.allow_missing_blocks)); Box::new(future::done(result)) @@ -822,7 +817,7 @@ impl Eth for EthClient< } fn logs(&self, filter: Filter) -> BoxFuture> { - base_logs(&*self.client, &*self.miner, filter.into()) + base_logs(&*self.client, &*self.miner, filter) } fn work(&self, no_new_work_timeout: Option) -> Result { @@ -865,16 +860,16 @@ impl Eth for EthClient< Err(errors::no_new_work()) } else if self.options.send_block_number_in_get_work { Ok(Work { - pow_hash: pow_hash.into(), + pow_hash, seed_hash: seed_hash.into(), - target: target.into(), + target, number: Some(number), }) } else { Ok(Work { - pow_hash: pow_hash.into(), + pow_hash, seed_hash: seed_hash.into(), - target: target.into(), + target, number: None }) } @@ -888,7 +883,7 @@ impl Eth for EthClient< } fn submit_hashrate(&self, rate: U256, id: H256) -> Result { - self.external_miner.submit_hashrate(rate.into(), id.into()); + self.external_miner.submit_hashrate(rate, id); Ok(true) } @@ -919,8 +914,8 @@ impl Eth for EthClient< let (mut state, header) = if num == BlockNumber::Pending { let info = self.client.chain_info(); - let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or(errors::state_pruned())); - let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or(errors::state_pruned())); + let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or_else(errors::state_pruned)); + let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or_else(errors::state_pruned)); (state, header) } else { @@ -931,8 +926,8 @@ impl Eth for EthClient< BlockNumber::Pending => unreachable!(), // Already covered }; - let state = try_bf!(self.client.state_at(id).ok_or(errors::state_pruned())); - let header = try_bf!(self.client.block_header(id).ok_or(errors::state_pruned()).and_then(|h| h.decode().map_err(errors::decode))); + let state = try_bf!(self.client.state_at(id).ok_or_else(errors::state_pruned)); + let header = try_bf!(self.client.block_header(id).ok_or_else(errors::state_pruned).and_then(|h| h.decode().map_err(errors::decode))); (state, header) }; @@ -958,8 +953,10 @@ impl Eth for EthClient< let (state, header) = if num == BlockNumber::Pending { let info = self.client.chain_info(); - let state = try_bf!(self.miner.pending_state(info.best_block_number).ok_or(errors::state_pruned())); - let header = try_bf!(self.miner.pending_block_header(info.best_block_number).ok_or(errors::state_pruned())); + let state = try_bf!(self.miner.pending_state(info.best_block_number) + .ok_or_else(errors::state_pruned)); + let header = try_bf!(self.miner.pending_block_header(info.best_block_number) + .ok_or_else(errors::state_pruned)); (state, header) } else { @@ -970,14 +967,15 @@ impl Eth for EthClient< BlockNumber::Pending => unreachable!(), // Already covered }; - let state = try_bf!(self.client.state_at(id).ok_or(errors::state_pruned())); - let header = try_bf!(self.client.block_header(id).ok_or(errors::state_pruned()).and_then(|h| h.decode().map_err(errors::decode))); - + let state = try_bf!(self.client.state_at(id) + .ok_or_else(errors::state_pruned)); + let header = try_bf!(self.client.block_header(id) + .ok_or_else(errors::state_pruned) + .and_then(|h| h.decode().map_err(errors::decode))); (state, header) }; Box::new(future::done(self.client.estimate_gas(&signed, &state, &header) - .map(Into::into) .map_err(errors::call) )) } diff --git a/rpc/src/v1/impls/eth_filter.rs b/rpc/src/v1/impls/eth_filter.rs index f8d4d290221..c51c85fb629 100644 --- a/rpc/src/v1/impls/eth_filter.rs +++ b/rpc/src/v1/impls/eth_filter.rs @@ -68,8 +68,8 @@ impl EthFilterClient { /// Creates new Eth filter client. pub fn new(client: Arc, miner: Arc, poll_lifetime: u32) -> Self { EthFilterClient { - client: client, - miner: miner, + client, + miner, polls: Mutex::new(PollManager::new(poll_lifetime)), } } @@ -188,17 +188,14 @@ impl EthFilter for T { let mut hashes = Vec::new(); for n in (*last_block_number + 1)..=current_number { let block_number = BlockId::Number(n); - match self.block_hash(block_number) { - Some(hash) => { - *last_block_number = n; - hashes.push(H256::from(hash)); - // Only keep the most recent history - if recent_reported_hashes.len() >= PollFilter::MAX_BLOCK_HISTORY_SIZE { - recent_reported_hashes.pop_back(); - } - recent_reported_hashes.push_front((n, hash)); - }, - None => (), + if let Some(hash) = self.block_hash(block_number) { + *last_block_number = n; + hashes.push(hash); + // Only keep the most recent history + if recent_reported_hashes.len() >= PollFilter::MAX_BLOCK_HISTORY_SIZE { + recent_reported_hashes.pop_back(); + } + recent_reported_hashes.push_front((n, hash)); } } diff --git a/rpc/src/v1/impls/eth_pubsub.rs b/rpc/src/v1/impls/eth_pubsub.rs index b4baf5aa4d7..91f32827b15 100644 --- a/rpc/src/v1/impls/eth_pubsub.rs +++ b/rpc/src/v1/impls/eth_pubsub.rs @@ -134,10 +134,10 @@ impl ChainNotificationHandler { fn notify_heads(&self, headers: &[(encoded::Header, BTreeMap)]) { for subscriber in self.heads_subscribers.read().values() { for &(ref header, ref extra_info) in headers { - Self::notify(&self.executor, subscriber, pubsub::Result::Header(RichHeader { + Self::notify(&self.executor, subscriber, pubsub::Result::Header(Box::new(RichHeader { inner: header.into(), extra_info: extra_info.clone(), - })); + }))); } } } @@ -154,7 +154,7 @@ impl ChainNotificationHandler { .map(|&(hash, ref ex)| { let mut filter = filter.clone(); filter.from_block = BlockId::Hash(hash); - filter.to_block = filter.from_block.clone(); + filter.to_block = filter.from_block; logs(filter, ex).into_future() }) .collect::>() @@ -167,7 +167,7 @@ impl ChainNotificationHandler { let logs = logs.into_iter().flat_map(|log| log).collect(); for log in limit_logs(logs, limit) { - Self::notify(&executor, &subscriber, pubsub::Result::Log(log)) + Self::notify(&executor, &subscriber, pubsub::Result::Log(Box::new(log))) } }) .map_err(|e| warn!("Unable to fetch latest logs: {:?}", e)) @@ -179,7 +179,7 @@ impl ChainNotificationHandler { pub fn notify_new_transactions(&self, hashes: &[H256]) { for subscriber in self.transactions_subscribers.read().values() { for hash in hashes { - Self::notify(&self.executor, subscriber, pubsub::Result::TransactionHash((*hash).into())); + Self::notify(&self.executor, subscriber, pubsub::Result::TransactionHash(*hash)); } } } @@ -223,13 +223,13 @@ impl LightChainNotify for ChainNotificationHandler { impl ChainNotify for ChainNotificationHandler { fn new_blocks(&self, new_blocks: NewBlocks) { if self.heads_subscribers.read().is_empty() && self.logs_subscribers.read().is_empty() { return } - const EXTRA_INFO_PROOF: &'static str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed"; + const EXTRA_INFO_PROOF: &str = "Object exists in in blockchain (fetched earlier), extra_info is always available if object exists; qed"; let headers = new_blocks.route.route() .iter() .filter_map(|&(hash, ref typ)| { match typ { - &ChainRouteType::Retracted => None, - &ChainRouteType::Enacted => self.client.block_header(BlockId::Hash(hash)) + ChainRouteType::Retracted => None, + ChainRouteType::Enacted => self.client.block_header(BlockId::Hash(hash)) } }) .map(|header| { @@ -244,9 +244,9 @@ impl ChainNotify for ChainNotificationHandler { // We notify logs enacting and retracting as the order in route. self.notify_logs(new_blocks.route.route(), |filter, ex| { match ex { - &ChainRouteType::Enacted => + ChainRouteType::Enacted => Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).collect()), - &ChainRouteType::Retracted => + ChainRouteType::Retracted => Ok(self.client.logs(filter).unwrap_or_default().into_iter().map(Into::into).map(|mut log: Log| { log.log_type = "removed".into(); log.removed = true; @@ -267,7 +267,7 @@ impl EthPubSub for EthPubSubClient { kind: pubsub::Kind, params: Option, ) { - let error = match (kind, params.into()) { + let error = match (kind, params) { (pubsub::Kind::NewHeads, None) => { self.heads_subscribers.write().push(subscriber); return; diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index 909d4c24439..fa972c5d609 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -142,23 +142,23 @@ where let extra_info = engine.extra_info(&header); RichBlock { inner: Block { - hash: Some(header.hash().into()), + hash: Some(header.hash()), size: Some(block.rlp().as_raw().len().into()), - parent_hash: header.parent_hash().clone().into(), - uncles_hash: header.uncles_hash().clone().into(), - author: header.author().clone().into(), - miner: header.author().clone().into(), - state_root: header.state_root().clone().into(), - transactions_root: header.transactions_root().clone().into(), - receipts_root: header.receipts_root().clone().into(), + parent_hash: *header.parent_hash(), + uncles_hash: *header.uncles_hash(), + author: *header.author(), + miner: *header.author(), + state_root: *header.state_root(), + transactions_root: *header.transactions_root(), + receipts_root: *header.receipts_root(), number: Some(header.number().into()), - gas_used: header.gas_used().clone().into(), - gas_limit: header.gas_limit().clone().into(), - logs_bloom: Some(header.log_bloom().clone().into()), + gas_used: *header.gas_used(), + gas_limit: *header.gas_limit(), + logs_bloom: Some(*header.log_bloom()), timestamp: header.timestamp().into(), - difficulty: header.difficulty().clone().into(), + difficulty: *header.difficulty(), total_difficulty: score.map(Into::into), - seal_fields: header.seal().into_iter().cloned().map(Into::into).collect(), + seal_fields: header.seal().iter().cloned().map(Into::into).collect(), uncles: block.uncle_hashes().into_iter().map(Into::into).collect(), transactions: match include_txs { true => BlockTransactions::Full(block.view().localized_transactions().into_iter().map(Transaction::from_localized).collect()), @@ -166,7 +166,7 @@ where }, extra_data: Bytes::new(header.extra_data().clone()), }, - extra_info: extra_info + extra_info, } }; @@ -237,9 +237,9 @@ where .unwrap_or_else(|| current_block); Ok(RpcSyncStatus::Info(RpcSyncInfo { - starting_block: U256::from(self.sync.start_block()).into(), - current_block: current_block.into(), - highest_block: highest_block.into(), + starting_block: U256::from(self.sync.start_block()), + current_block, + highest_block, warp_chunks_amount: None, warp_chunks_processed: None, })) @@ -289,8 +289,8 @@ where } fn balance(&self, address: H160, num: Option) -> BoxFuture { - Box::new(self.fetcher().account(address.into(), num.unwrap_or_default().to_block_id()) - .map(|acc| acc.map_or(0.into(), |a| a.balance).into())) + Box::new(self.fetcher().account(address, num.unwrap_or_default().to_block_id()) + .map(|acc| acc.map_or(0.into(), |a| a.balance))) } fn storage_at(&self, _address: H160, _key: U256, _num: Option) -> BoxFuture { @@ -298,7 +298,7 @@ where } fn block_by_hash(&self, hash: H256, include_txs: bool) -> BoxFuture> { - Box::new(self.rich_block(BlockId::Hash(hash.into()), include_txs).map(Some)) + Box::new(self.rich_block(BlockId::Hash(hash), include_txs).map(Some)) } fn block_by_number(&self, num: BlockNumber, include_txs: bool) -> BoxFuture> { @@ -306,20 +306,20 @@ where } fn transaction_count(&self, address: H160, num: Option) -> BoxFuture { - Box::new(self.fetcher().account(address.into(), num.unwrap_or_default().to_block_id()) - .map(|acc| acc.map_or(0.into(), |a| a.nonce).into())) + Box::new(self.fetcher().account(address, num.unwrap_or_default().to_block_id()) + .map(|acc| acc.map_or(0.into(), |a| a.nonce))) } fn block_transaction_count_by_hash(&self, hash: H256) -> BoxFuture> { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); - Box::new(self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { + Box::new(self.fetcher().header(BlockId::Hash(hash)).and_then(move |hdr| { if hdr.transactions_root() == KECCAK_NULL_RLP { - Either::A(future::ok(Some(U256::from(0).into()))) + Either::A(future::ok(Some(U256::from(0)))) } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) .map(|x| x.expect(NO_INVALID_BACK_REFS)) - .map(|x| x.map(|b| Some(U256::from(b.transactions_count()).into()))) + .map(|x| x.map(|b| Some(U256::from(b.transactions_count())))) .map(|x| Either::B(x.map_err(errors::on_demand_error))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) } @@ -331,11 +331,11 @@ where Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| { if hdr.transactions_root() == KECCAK_NULL_RLP { - Either::A(future::ok(Some(U256::from(0).into()))) + Either::A(future::ok(Some(U256::from(0)))) } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) .map(|x| x.expect(NO_INVALID_BACK_REFS)) - .map(|x| x.map(|b| Some(U256::from(b.transactions_count()).into()))) + .map(|x| x.map(|b| Some(U256::from(b.transactions_count())))) .map(|x| Either::B(x.map_err(errors::on_demand_error))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) } @@ -345,13 +345,13 @@ where fn block_uncles_count_by_hash(&self, hash: H256) -> BoxFuture> { let (sync, on_demand) = (self.sync.clone(), self.on_demand.clone()); - Box::new(self.fetcher().header(BlockId::Hash(hash.into())).and_then(move |hdr| { + Box::new(self.fetcher().header(BlockId::Hash(hash)).and_then(move |hdr| { if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { - Either::A(future::ok(Some(U256::from(0).into()))) + Either::A(future::ok(Some(U256::from(0)))) } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) .map(|x| x.expect(NO_INVALID_BACK_REFS)) - .map(|x| x.map(|b| Some(U256::from(b.uncles_count()).into()))) + .map(|x| x.map(|b| Some(U256::from(b.uncles_count())))) .map(|x| Either::B(x.map_err(errors::on_demand_error))) .unwrap_or_else(|| Either::A(future::err(errors::network_disabled()))) } @@ -363,11 +363,11 @@ where Box::new(self.fetcher().header(num.to_block_id()).and_then(move |hdr| { if hdr.uncles_hash() == KECCAK_EMPTY_LIST_RLP { - Either::B(future::ok(Some(U256::from(0).into()))) + Either::B(future::ok(Some(U256::from(0)))) } else { sync.with_context(|ctx| on_demand.request(ctx, request::Body(hdr.into()))) .map(|x| x.expect(NO_INVALID_BACK_REFS)) - .map(|x| x.map(|b| Some(U256::from(b.uncles_count()).into()))) + .map(|x| x.map(|b| Some(U256::from(b.uncles_count())))) .map(|x| Either::A(x.map_err(errors::on_demand_error))) .unwrap_or_else(|| Either::B(future::err(errors::network_disabled()))) } @@ -375,7 +375,7 @@ where } fn code_at(&self, address: H160, num: Option) -> BoxFuture { - Box::new(self.fetcher().code(address.into(), num.unwrap_or_default().to_block_id()).map(Into::into)) + Box::new(self.fetcher().code(address, num.unwrap_or_default().to_block_id()).map(Into::into)) } fn send_raw_transaction(&self, raw: Bytes) -> Result { @@ -414,15 +414,13 @@ where // TODO: binary chop for more accurate estimates. Box::new(self.fetcher().proved_read_only_execution(req, num).and_then(|res| { match res { - Ok(exec) => Ok((exec.refunded + exec.gas_used).into()), + Ok(exec) => Ok(exec.refunded + exec.gas_used), Err(e) => Err(errors::execution(e)), } })) } fn transaction_by_hash(&self, hash: H256) -> BoxFuture> { - let hash = hash.into(); - { let tx_queue = self.transaction_queue.read(); if let Some(tx) = tx_queue.get(&hash) { @@ -436,7 +434,7 @@ where } fn transaction_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture> { - Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| { + Box::new(self.fetcher().block(BlockId::Hash(hash)).map(move |block| { light_fetch::extract_transaction_at_index(block, idx.value()) })) } @@ -449,14 +447,14 @@ where fn transaction_receipt(&self, hash: H256) -> BoxFuture> { let fetcher = self.fetcher(); - Box::new(fetcher.transaction_by_hash(hash.into()).and_then(move |tx| { + Box::new(fetcher.transaction_by_hash(hash).and_then(move |tx| { // the block hash included in the transaction object here has // already been checked for canonicality and whether it contains // the transaction. match tx { - Some((tx, index)) => match tx.block_hash.clone() { + Some((tx, index)) => match tx.block_hash { Some(block_hash) => { - let extract_receipt = fetcher.receipts(BlockId::Hash(block_hash.clone().into())) + let extract_receipt = fetcher.receipts(BlockId::Hash(block_hash)) .and_then(move |mut receipts| future::ok(receipts.swap_remove(index))) .map(Receipt::from) .map(move |mut receipt| { @@ -479,7 +477,7 @@ where fn uncle_by_block_hash_and_index(&self, hash: H256, idx: Index) -> BoxFuture> { let client = self.client.clone(); - Box::new(self.fetcher().block(BlockId::Hash(hash.into())).map(move |block| { + Box::new(self.fetcher().block(BlockId::Hash(hash)).map(move |block| { extract_uncle_at_index(block, idx, client) })) } @@ -576,27 +574,27 @@ fn extract_uncle_at_index(block: encoded::Block, index: Ind let extra_info = client.engine().extra_info(&uncle); Some(RichBlock { inner: Block { - hash: Some(uncle.hash().into()), + hash: Some(uncle.hash()), size: None, - parent_hash: uncle.parent_hash().clone().into(), - uncles_hash: uncle.uncles_hash().clone().into(), - author: uncle.author().clone().into(), - miner: uncle.author().clone().into(), - state_root: uncle.state_root().clone().into(), - transactions_root: uncle.transactions_root().clone().into(), + parent_hash: *uncle.parent_hash(), + uncles_hash: *uncle.uncles_hash(), + author: *uncle.author(), + miner: *uncle.author(), + state_root: *uncle.state_root(), + transactions_root: *uncle.transactions_root(), number: Some(uncle.number().into()), - gas_used: uncle.gas_used().clone().into(), - gas_limit: uncle.gas_limit().clone().into(), - logs_bloom: Some(uncle.log_bloom().clone().into()), + gas_used: *uncle.gas_used(), + gas_limit: *uncle.gas_limit(), + logs_bloom: Some(*uncle.log_bloom()), timestamp: uncle.timestamp().into(), - difficulty: uncle.difficulty().clone().into(), + difficulty: *uncle.difficulty(), total_difficulty: None, - receipts_root: uncle.receipts_root().clone().into(), + receipts_root: *uncle.receipts_root(), extra_data: uncle.extra_data().clone().into(), - seal_fields: uncle.seal().into_iter().cloned().map(Into::into).collect(), + seal_fields: uncle.seal().iter().cloned().map(Into::into).collect(), uncles: vec![], transactions: BlockTransactions::Hashes(vec![]), }, - extra_info: extra_info, + extra_info, }) } diff --git a/rpc/src/v1/impls/light/net.rs b/rpc/src/v1/impls/light/net.rs index 3f73e010b93..a9ab012e5ad 100644 --- a/rpc/src/v1/impls/light/net.rs +++ b/rpc/src/v1/impls/light/net.rs @@ -29,7 +29,7 @@ impl NetClient where S: LightSyncProvider { /// Creates new NetClient. pub fn new(sync: Arc) -> Self { NetClient { - sync: sync, + sync, } } } diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index 24dba420e4a..b6e378f6804 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -140,7 +140,7 @@ where active: peer_numbers.active, connected: peer_numbers.connected, max: peer_numbers.max as u32, - peers: peers, + peers, }) } @@ -157,7 +157,7 @@ where if reg == Default::default() { Ok(None) } else { - Ok(Some(reg.into())) + Ok(Some(reg)) } } @@ -191,7 +191,7 @@ where } fn phrase_to_address(&self, phrase: String) -> Result { - Ok(Brain::new(phrase).generate().unwrap().address().into()) + Ok(Brain::new(phrase).generate().expect("Brain::generate always returns Ok; qed").address()) } fn list_accounts(&self, _: u64, _: Option, _: Option) -> Result>> { @@ -203,7 +203,7 @@ where } fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result { - ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0) + ecies::encrypt(&key, &DEFAULT_MAC, &phrase.0) .map_err(errors::encryption) .map(Into::into) } @@ -215,7 +215,7 @@ where txq.ready_transactions(chain_info.best_block_number, chain_info.best_block_timestamp) .into_iter() .take(limit.unwrap_or_else(usize::max_value)) - .map(|tx| Transaction::from_pending(tx)) + .map(Transaction::from_pending) .collect::>() ) } @@ -223,7 +223,7 @@ where fn all_transactions(&self) -> Result> { Ok( light_all_transactions(&self.light_dispatch) - .map(|tx| Transaction::from_pending(tx)) + .map(Transaction::from_pending) .collect() ) } @@ -231,7 +231,7 @@ where fn all_transaction_hashes(&self) -> Result> { Ok( light_all_transactions(&self.light_dispatch) - .map(|tx| tx.transaction.hash().into()) + .map(|tx| tx.transaction.hash()) .collect() ) } @@ -242,7 +242,7 @@ where Ok( txq.future_transactions(chain_info.best_block_number, chain_info.best_block_timestamp) .into_iter() - .map(|tx| Transaction::from_pending(tx)) + .map(Transaction::from_pending) .collect::>() ) } @@ -250,7 +250,7 @@ where fn pending_transactions_stats(&self) -> Result> { let stats = self.light_dispatch.sync.transactions_stats(); Ok(stats.into_iter() - .map(|(hash, stats)| (hash.into(), stats.into())) + .map(|(hash, stats)| (hash, stats.into())) .collect() ) } @@ -262,11 +262,11 @@ where let txq = self.light_dispatch.transaction_queue.read(); for pending in txq.ready_transactions(best_num, best_tm) { - map.insert(pending.hash().into(), LocalTransactionStatus::Pending); + map.insert(pending.hash(), LocalTransactionStatus::Pending); } for future in txq.future_transactions(best_num, best_tm) { - map.insert(future.hash().into(), LocalTransactionStatus::Future); + map.insert(future.hash(), LocalTransactionStatus::Future); } // TODO: other types? @@ -276,11 +276,11 @@ where fn ws_url(&self) -> Result { helpers::to_url(&self.ws_address) - .ok_or_else(|| errors::ws_disabled()) + .ok_or_else(errors::ws_disabled) } fn next_nonce(&self, address: H160) -> BoxFuture { - Box::new(self.light_dispatch.next_nonce(address.into()).map(Into::into)) + Box::new(self.light_dispatch.next_nonce(address)) } fn mode(&self) -> Result { @@ -314,7 +314,7 @@ where .and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last)))); Ok(ChainStatus { - block_gap: gap.map(|(x, y)| (x.into(), y.into())), + block_gap: gap, }) } @@ -336,25 +336,25 @@ where let extra_info = engine.extra_info(&header); Ok(RichHeader { inner: Header { - hash: Some(header.hash().into()), + hash: Some(header.hash()), size: Some(encoded.rlp().as_raw().len().into()), - parent_hash: header.parent_hash().clone().into(), - uncles_hash: header.uncles_hash().clone().into(), - author: header.author().clone().into(), - miner: header.author().clone().into(), - state_root: header.state_root().clone().into(), - transactions_root: header.transactions_root().clone().into(), - receipts_root: header.receipts_root().clone().into(), + parent_hash: *header.parent_hash(), + uncles_hash: *header.uncles_hash(), + author: *header.author(), + miner: *header.author(), + state_root: *header.state_root(), + transactions_root: *header.transactions_root(), + receipts_root: *header.receipts_root(), number: Some(header.number().into()), - gas_used: header.gas_used().clone().into(), - gas_limit: header.gas_limit().clone().into(), - logs_bloom: header.log_bloom().clone().into(), + gas_used: *header.gas_used(), + gas_limit: *header.gas_limit(), + logs_bloom: *header.log_bloom(), timestamp: header.timestamp().into(), - difficulty: header.difficulty().clone().into(), + difficulty: *header.difficulty(), seal_fields: header.seal().iter().cloned().map(Into::into).collect(), extra_data: Bytes::new(header.extra_data().clone()), }, - extra_info: extra_info, + extra_info, }) }; let id = number.unwrap_or_default().to_block_id(); diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index f129f86b3c9..68fc212b2fb 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -43,9 +43,9 @@ impl ParitySetClient { /// Creates new `ParitySetClient` with given `Fetch`. pub fn new(client: Arc, net: Arc, fetch: F) -> Self { ParitySetClient { - client: client, - net: net, - fetch: fetch, + client, + net, + fetch, } } } diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index d985f33f625..27a70379586 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -109,7 +109,7 @@ impl Parity for ParityClient where } fn min_gas_price(&self) -> Result { - Ok(self.miner.queue_status().options.minimal_gas_price.into()) + Ok(self.miner.queue_status().options.minimal_gas_price) } fn extra_data(&self) -> Result { @@ -117,11 +117,11 @@ impl Parity for ParityClient where } fn gas_floor_target(&self) -> Result { - Ok(U256::from(self.miner.authoring_params().gas_range_target.0)) + Ok(self.miner.authoring_params().gas_range_target.0) } fn gas_ceil_target(&self) -> Result { - Ok(U256::from(self.miner.authoring_params().gas_range_target.1)) + Ok(self.miner.authoring_params().gas_range_target.1) } fn dev_logs(&self) -> Result> { @@ -152,7 +152,7 @@ impl Parity for ParityClient where active: sync_status.num_active_peers, connected: sync_status.num_peers, max: sync_status.current_max_peers(*num_peers_range.start(), *num_peers_range.end()), - peers: peers + peers, }) } @@ -170,7 +170,6 @@ impl Parity for ParityClient where .additional_params() .get("registrar") .and_then(|s| Address::from_str(s).ok()) - .map(|s| H160::from(s)) ) } @@ -207,7 +206,7 @@ impl Parity for ParityClient where } fn phrase_to_address(&self, phrase: String) -> Result { - Ok(Brain::new(phrase).generate().unwrap().address().into()) + Ok(Brain::new(phrase).generate().expect("Brain::generate always returns Ok; qed").address()) } fn list_accounts(&self, count: u64, after: Option, block_number: Option) -> Result>> { @@ -236,12 +235,12 @@ impl Parity for ParityClient where }; Ok(self.client - .list_storage(number, &address.into(), after.map(Into::into).as_ref(), count) + .list_storage(number, &address, after.map(Into::into).as_ref(), count) .map(|a| a.into_iter().map(Into::into).collect())) } fn encrypt_message(&self, key: H512, phrase: Bytes) -> Result { - ecies::encrypt(&key.into(), &DEFAULT_MAC, &phrase.0) + ecies::encrypt(&key, &DEFAULT_MAC, &phrase.0) .map_err(errors::encryption) .map(Into::into) } @@ -271,13 +270,7 @@ impl Parity for ParityClient where } fn all_transaction_hashes(&self) -> Result> { - let all_transaction_hashes = self.miner.queued_transaction_hashes(); - - Ok(all_transaction_hashes - .into_iter() - .map(|hash| hash.into()) - .collect() - ) + Ok(self.miner.queued_transaction_hashes()) } fn future_transactions(&self) -> Result> { @@ -287,7 +280,7 @@ impl Parity for ParityClient where fn pending_transactions_stats(&self) -> Result> { let stats = self.sync.transactions_stats(); Ok(stats.into_iter() - .map(|(hash, stats)| (hash.into(), stats.into())) + .map(|(hash, stats)| (hash, stats.into())) .collect() ) } @@ -296,7 +289,7 @@ impl Parity for ParityClient where let transactions = self.miner.local_transactions(); Ok(transactions .into_iter() - .map(|(hash, status)| (hash.into(), LocalTransactionStatus::from(status))) + .map(|(hash, status)| (hash, LocalTransactionStatus::from(status))) .collect() ) } @@ -307,9 +300,7 @@ impl Parity for ParityClient where } fn next_nonce(&self, address: H160) -> BoxFuture { - let address: Address = address.into(); - - Box::new(future::ok(self.miner.next_nonce(&*self.client, &address).into())) + Box::new(future::ok(self.miner.next_nonce(&*self.client, &address))) } fn mode(&self) -> Result { @@ -339,7 +330,7 @@ impl Parity for ParityClient where .and_then(|first| chain_info.first_block_number.map(|last| (first, U256::from(last)))); Ok(ChainStatus { - block_gap: gap.map(|(x, y)| (x.into(), y.into())), + block_gap: gap, }) } @@ -370,7 +361,7 @@ impl Parity for ParityClient where BlockNumber::Pending => unreachable!(), // Already covered }; - let header = try_bf!(self.client.block_header(id.clone()).ok_or_else(errors::unknown_block)); + let header = try_bf!(self.client.block_header(id).ok_or_else(errors::unknown_block)); let info = self.client.block_extra_info(id).expect(EXTRA_INFO_PROOF); (header, Some(info)) @@ -467,7 +458,7 @@ impl Parity for ParityClient where fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture> { use v1::impls::eth::base_logs; // only specific impl for lightclient - base_logs(&*self.client, &*self.miner, filter.into()) + base_logs(&*self.client, &*self.miner, filter) } fn verify_signature(&self, is_prefixed: bool, message: Bytes, r: H256, s: H256, v: U64) -> Result { diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index 16ef8d54327..b7cef6c6b8c 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -119,7 +119,7 @@ impl ParitySet for ParitySetClient where { fn set_min_gas_price(&self, gas_price: U256) -> Result { - match self.miner.set_minimal_gas_price(gas_price.into()) { + match self.miner.set_minimal_gas_price(gas_price) { Ok(success) => Ok(success), Err(e) => Err(errors::unsupported(e, None)), } @@ -136,15 +136,15 @@ impl ParitySet for ParitySetClient where } fn set_gas_floor_target(&self, target: U256) -> Result { - let mut range = self.miner.authoring_params().gas_range_target.clone(); - range.0 = target.into(); + let mut range = self.miner.authoring_params().gas_range_target; + range.0 = target; self.miner.set_gas_range_target(range); Ok(true) } fn set_gas_ceil_target(&self, target: U256) -> Result { - let mut range = self.miner.authoring_params().gas_range_target.clone(); - range.1 = target.into(); + let mut range = self.miner.authoring_params().gas_range_target; + range.1 = target; self.miner.set_gas_range_target(range); Ok(true) } @@ -155,7 +155,7 @@ impl ParitySet for ParitySetClient where } fn set_author(&self, address: H160) -> Result { - self.miner.set_author(miner::Author::External(address.into())); + self.miner.set_author(miner::Author::External(address)); Ok(true) } @@ -236,8 +236,6 @@ impl ParitySet for ParitySetClient where } fn remove_transaction(&self, hash: H256) -> Result> { - let hash = hash.into(); - Ok(self.miner.remove_transaction(&hash) .map(|t| Transaction::from_pending(t.pending().clone())) ) diff --git a/rpc/src/v1/impls/private.rs b/rpc/src/v1/impls/private.rs index f1cf991240b..c3be3f91506 100644 --- a/rpc/src/v1/impls/private.rs +++ b/rpc/src/v1/impls/private.rs @@ -60,7 +60,7 @@ impl Private for PrivateClient { .map_err(errors::rlp) .and_then(|tx| SignedTransaction::new(tx).map_err(errors::transaction))?; let client = self.unwrap_manager()?; - let receipt = client.create_private_transaction(signed_transaction).map_err(|e| errors::private_message(e))?; + let receipt = client.create_private_transaction(signed_transaction).map_err(errors::private_message)?; Ok(receipt.into()) } @@ -76,16 +76,17 @@ impl Private for PrivateClient { num => block_number_to_id(num) }; - let (transaction, contract_address) = client.public_creation_transaction(id, &signed_transaction, addresses.as_slice(), gas_price.into()) - .map_err(|e| errors::private_message(e))?; + let (transaction, contract_address) = client + .public_creation_transaction(id, &signed_transaction, addresses.as_slice(), gas_price) + .map_err(errors::private_message)?; let tx_hash = transaction.hash(None); let request = TransactionRequest { - from: Some(signed_transaction.sender().into()), + from: Some(signed_transaction.sender()), to: None, - nonce: Some(transaction.nonce.into()), - gas_price: Some(transaction.gas_price.into()), - gas: Some(transaction.gas.into()), - value: Some(transaction.value.into()), + nonce: Some(transaction.nonce), + gas_price: Some(transaction.gas_price), + gas: Some(transaction.gas), + value: Some(transaction.value), data: Some(transaction.data.into()), condition: None, }; @@ -93,8 +94,8 @@ impl Private for PrivateClient { Ok(PrivateTransactionReceiptAndTransaction { transaction: request, receipt: PrivateTransactionReceipt { - transaction_hash: tx_hash.into(), - contract_address: contract_address.into(), + transaction_hash: tx_hash, + contract_address, status_code: 0, } }) @@ -109,13 +110,13 @@ impl Private for PrivateClient { let request = CallRequest::into(request); let signed = fake_sign::sign_call(request)?; let client = self.unwrap_manager()?; - let executed_result = client.private_call(id, &signed).map_err(|e| errors::private_message(e))?; + let executed_result = client.private_call(id, &signed).map_err(errors::private_message)?; Ok(executed_result.output.into()) } fn private_contract_key(&self, contract_address: H160) -> Result { let client = self.unwrap_manager()?; - let key = client.contract_key_id(&contract_address.into()).map_err(|e| errors::private_message(e))?; - Ok(key.into()) + let key = client.contract_key_id(&contract_address).map_err(errors::private_message)?; + Ok(key) } } diff --git a/rpc/src/v1/impls/pubsub.rs b/rpc/src/v1/impls/pubsub.rs index 9650fd2d079..1575aacdd67 100644 --- a/rpc/src/v1/impls/pubsub.rs +++ b/rpc/src/v1/impls/pubsub.rs @@ -81,7 +81,7 @@ impl> PubSub for PubSubClient { type Metadata = Metadata; fn parity_subscribe(&self, mut meta: Metadata, subscriber: Subscriber, method: String, params: Option) { - let params = params.unwrap_or(core::Params::Array(vec![])); + let params = params.unwrap_or_else(|| core::Params::Array(vec![])); // Make sure to get rid of PubSub session otherwise it will never be dropped. meta.session = None; diff --git a/rpc/src/v1/impls/rpc.rs b/rpc/src/v1/impls/rpc.rs index f218c5ade6e..0c2afd57caf 100644 --- a/rpc/src/v1/impls/rpc.rs +++ b/rpc/src/v1/impls/rpc.rs @@ -32,8 +32,8 @@ impl RpcClient { let valid_apis = vec!["web3", "eth", "net", "personal", "rpc"]; RpcClient { - modules: modules, - valid_apis: valid_apis.into_iter().map(|x| x.to_owned()).collect(), + modules, + valid_apis: valid_apis.into_iter().map(ToOwned::to_owned).collect(), } } } diff --git a/rpc/src/v1/impls/signer.rs b/rpc/src/v1/impls/signer.rs index c4f4d357668..4edac1144a4 100644 --- a/rpc/src/v1/impls/signer.rs +++ b/rpc/src/v1/impls/signer.rs @@ -85,7 +85,6 @@ impl SignerClient { T: IntoFuture, Error=Error>, T::Future: Send + 'static { - let id = id.into(); let dispatcher = self.dispatcher.clone(); let signer = self.signer.clone(); @@ -94,15 +93,15 @@ impl SignerClient { // Modify payload if let ConfirmationPayload::SendTransaction(ref mut request) = payload { if let Some(sender) = modification.sender { - request.from = sender.into(); + request.from = sender; // Altering sender should always reset the nonce. request.nonce = None; } if let Some(gas_price) = modification.gas_price { - request.gas_price = gas_price.into(); + request.gas_price = gas_price; } if let Some(gas) = modification.gas { - request.gas = gas.into(); + request.gas = gas; } if let Some(ref condition) = modification.condition { request.condition = condition.clone().map(Into::into); @@ -177,7 +176,7 @@ impl Signer for SignerClient { Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| { dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into())) - }).map(|v| v.into_value())) + }).map(dispatch::WithToken::into_value)) } fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String) @@ -191,7 +190,7 @@ impl Signer for SignerClient { WithToken::No(_) => Err(errors::internal("Unexpected response without token.", "")), WithToken::Yes(response, token) => Ok(ConfirmationResponseWithToken { result: response, - token: token, + token, }), })) } @@ -199,8 +198,6 @@ impl Signer for SignerClient { fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result { self.deprecation_notice.print("signer_confirmRequestRaw", deprecated::msgs::ACCOUNTS); - let id = id.into(); - self.signer.take(&id).map(|sender| { let payload = sender.request.payload.clone(); let result = match payload { @@ -251,7 +248,7 @@ impl Signer for SignerClient { fn reject_request(&self, id: U256) -> Result { self.deprecation_notice.print("signer_rejectRequest", deprecated::msgs::ACCOUNTS); - let res = self.signer.take(&id.into()).map(|sender| self.signer.request_rejected(sender)); + let res = self.signer.take(&id).map(|sender| self.signer.request_rejected(sender)); Ok(res.is_some()) } @@ -259,7 +256,7 @@ impl Signer for SignerClient { self.deprecation_notice.print("signer_generateAuthorizationToken", deprecated::msgs::ACCOUNTS); self.signer.generate_token() - .map_err(|e| errors::token(e)) + .map_err(errors::token) } fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber>) { diff --git a/rpc/src/v1/impls/signing.rs b/rpc/src/v1/impls/signing.rs index 12f8909563c..38ca6d59c9c 100644 --- a/rpc/src/v1/impls/signing.rs +++ b/rpc/src/v1/impls/signing.rs @@ -75,7 +75,7 @@ fn schedule(executor: Executor, future: RpcConfirmationReceiver) { { let mut confirmations = confirmations.lock(); - confirmations.insert(id.clone(), None); + confirmations.insert(id, None); } let future = future.then(move |result| { @@ -122,7 +122,7 @@ impl SigningQueueClient { let sender = payload.sender(); if accounts.is_unlocked(&sender) { Either::A(dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Nothing) - .map(|v| v.into_value()) + .map(dispatch::WithToken::into_value) .map(DispatchResult::Value)) } else { Either::B(future::done( @@ -149,13 +149,13 @@ impl ParitySigning for SigningQueueClient { let confirmations = self.confirmations.clone(); Box::new(self.dispatch( - RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), + RpcConfirmationPayload::EthSignMessage((address, data).into()), meta.origin ).map(move |result| match result { DispatchResult::Value(v) => RpcEither::Or(v), DispatchResult::Future(id, future) => { schedule(executor, confirmations, id, future); - RpcEither::Either(id.into()) + RpcEither::Either(id) }, })) } @@ -170,14 +170,13 @@ impl ParitySigning for SigningQueueClient { DispatchResult::Value(v) => RpcEither::Or(v), DispatchResult::Future(id, future) => { schedule(executor, confirmations, id, future); - RpcEither::Either(id.into()) + RpcEither::Either(id) }, })) } fn check_request(&self, id: U256) -> Result> { self.deprecation_notice.print("parity_checkRequest", deprecated::msgs::ACCOUNTS); - let id: U256 = id.into(); match self.confirmations.lock().get(&id) { None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there Some(&None) => Ok(None), // No confirmation yet, request is known, confirmation is pending @@ -188,7 +187,7 @@ impl ParitySigning for SigningQueueClient { fn decrypt_message(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture { self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS); let res = self.dispatch( - RpcConfirmationPayload::Decrypt((address.clone(), data).into()), + RpcConfirmationPayload::Decrypt((address, data).into()), meta.origin, ); @@ -208,7 +207,7 @@ impl EthSigning for SigningQueueClient { fn sign(&self, meta: Metadata, address: H160, data: RpcBytes) -> BoxFuture { self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS); let res = self.dispatch( - RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), + RpcConfirmationPayload::EthSignMessage((address, data).into()), meta.origin, ); diff --git a/rpc/src/v1/impls/signing_unsafe.rs b/rpc/src/v1/impls/signing_unsafe.rs index 72a3a6fbf18..f08a9ffbe6e 100644 --- a/rpc/src/v1/impls/signing_unsafe.rs +++ b/rpc/src/v1/impls/signing_unsafe.rs @@ -60,7 +60,7 @@ impl SigningUnsafeClient { .and_then(move |payload| { dispatch::execute(dis, &accounts, payload, dispatch::SignWith::Nothing) }) - .map(|v| v.into_value())) + .map(dispatch::WithToken::into_value)) } } @@ -70,7 +70,7 @@ impl EthSigning for SigningUnsafeClient fn sign(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture { self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS); - Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), address.into()) + Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address, data).into()), address) .then(|res| match res { Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature), Err(e) => Err(e), @@ -111,7 +111,7 @@ impl ParitySigning for SigningUnsafeClient { fn decrypt_message(&self, _: Metadata, address: H160, data: RpcBytes) -> BoxFuture { self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS); - Box::new(self.handle(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into()) + Box::new(self.handle(RpcConfirmationPayload::Decrypt((address, data).into()), address) .then(|res| match res { Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data), Err(e) => Err(e), diff --git a/rpc/src/v1/impls/traces.rs b/rpc/src/v1/impls/traces.rs index d7428aad27b..a6301eda539 100644 --- a/rpc/src/v1/impls/traces.rs +++ b/rpc/src/v1/impls/traces.rs @@ -74,13 +74,13 @@ impl Traces for TracesClient where } fn transaction_traces(&self, transaction_hash: H256) -> Result>> { - Ok(self.client.transaction_traces(TransactionId::Hash(transaction_hash.into())) + Ok(self.client.transaction_traces(TransactionId::Hash(transaction_hash)) .map(|traces| traces.into_iter().map(LocalizedTrace::from).collect())) } fn trace(&self, transaction_hash: H256, address: Vec) -> Result> { let id = TraceId { - transaction: TransactionId::Hash(transaction_hash.into()), + transaction: TransactionId::Hash(transaction_hash), address: address.into_iter().map(|i| i.value()).collect() }; @@ -102,8 +102,8 @@ impl Traces for TracesClient where BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), }; - let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; - let header = self.client.block_header(id).ok_or(errors::state_pruned())?; + let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?; + let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?; self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?) .map(TraceResults::from) @@ -129,8 +129,8 @@ impl Traces for TracesClient where BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), }; - let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; - let header = self.client.block_header(id).ok_or(errors::state_pruned())?; + let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?; + let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?; self.client.call_many(&requests, &mut state, &header.decode().map_err(errors::decode)?) .map(|results| results.into_iter().map(TraceResults::from).collect()) @@ -151,8 +151,8 @@ impl Traces for TracesClient where BlockNumber::Pending => return Err(errors::invalid_params("`BlockNumber::Pending` is not supported", ())), }; - let mut state = self.client.state_at(id).ok_or(errors::state_pruned())?; - let header = self.client.block_header(id).ok_or(errors::state_pruned())?; + let mut state = self.client.state_at(id).ok_or_else(errors::state_pruned)?; + let header = self.client.block_header(id).ok_or_else(errors::state_pruned)?; self.client.call(&signed, to_call_analytics(flags), &mut state, &header.decode().map_err(errors::decode)?) .map(TraceResults::from) @@ -160,7 +160,7 @@ impl Traces for TracesClient where } fn replay_transaction(&self, transaction_hash: H256, flags: TraceOptions) -> Result { - self.client.replay(TransactionId::Hash(transaction_hash.into()), to_call_analytics(flags)) + self.client.replay(TransactionId::Hash(transaction_hash), to_call_analytics(flags)) .map(TraceResults::from) .map_err(errors::call) } @@ -175,7 +175,7 @@ impl Traces for TracesClient where }; self.client.replay_block_transactions(id, to_call_analytics(flags)) - .map(|results| results.into_iter().map(TraceResultsWithTransactionHash::from).collect()) + .map(|results| results.map(TraceResultsWithTransactionHash::from).collect()) .map_err(errors::call) } } diff --git a/rpc/src/v1/impls/web3.rs b/rpc/src/v1/impls/web3.rs index e7bf9dd49fe..5ffda51b66c 100644 --- a/rpc/src/v1/impls/web3.rs +++ b/rpc/src/v1/impls/web3.rs @@ -23,19 +23,15 @@ use v1::traits::Web3; use v1::types::Bytes; /// Web3 rpc implementation. +#[derive(Default)] pub struct Web3Client; -impl Web3Client { - /// Creates new Web3Client. - pub fn new() -> Self { Web3Client } -} - impl Web3 for Web3Client { fn client_version(&self) -> Result { Ok(version().to_owned().replacen("/", "//", 1)) } fn sha3(&self, data: Bytes) -> Result { - Ok(keccak(&data.0).into()) + Ok(keccak(&data.0)) } } diff --git a/rpc/src/v1/informant.rs b/rpc/src/v1/informant.rs index 9455fa9ebbc..945378390b3 100644 --- a/rpc/src/v1/informant.rs +++ b/rpc/src/v1/informant.rs @@ -135,7 +135,7 @@ impl StatsCalculator { #[derive(Default, Debug)] pub struct RpcStats { requests: RwLock, - roundtrips: RwLock>, + roundtrips: RwLock>, active_sessions: AtomicUsize, } @@ -157,7 +157,7 @@ impl RpcStats { } /// Add roundtrip time (microseconds) - pub fn add_roundtrip(&self, microseconds: u32) { + pub fn add_roundtrip(&self, microseconds: u128) { self.roundtrips.write().add(microseconds) } @@ -172,7 +172,7 @@ impl RpcStats { } /// Returns approximated roundtrip in microseconds - pub fn approximated_roundtrip(&self) -> u32 { + pub fn approximated_roundtrip(&self) -> u128 { self.roundtrips.read().approximated_median() } } @@ -197,10 +197,6 @@ impl Middleware { notifier, } } - - fn as_micro(dur: time::Duration) -> u32 { - (dur.as_secs() * 1_000_000) as u32 + dur.subsec_nanos() / 1_000 - } } impl core::Middleware for Middleware { @@ -223,7 +219,7 @@ impl core::Middleware for Middleware< let stats = self.stats.clone(); let future = process(request, meta).map(move |res| { - let time = Self::as_micro(start.elapsed()); + let time = start.elapsed().as_micros(); if time > 10_000 { debug!(target: "rpc", "[{:?}] Took {}ms", id, time / 1_000); } diff --git a/rpc/src/v1/tests/mocked/web3.rs b/rpc/src/v1/tests/mocked/web3.rs index 79bcfe01dba..5590d5d2832 100644 --- a/rpc/src/v1/tests/mocked/web3.rs +++ b/rpc/src/v1/tests/mocked/web3.rs @@ -20,7 +20,7 @@ use v1::{Web3, Web3Client}; #[test] fn rpc_web3_version() { - let web3 = Web3Client::new().to_delegate(); + let web3 = Web3Client::default().to_delegate(); let mut io = IoHandler::new(); io.extend_with(web3); @@ -34,7 +34,7 @@ fn rpc_web3_version() { #[test] fn rpc_web3_sha3() { - let web3 = Web3Client::new().to_delegate(); + let web3 = Web3Client::default().to_delegate(); let mut io = IoHandler::new(); io.extend_with(web3); @@ -46,7 +46,7 @@ fn rpc_web3_sha3() { #[test] fn rpc_web3_sha3_wiki() { - let web3 = Web3Client::new().to_delegate(); + let web3 = Web3Client::default().to_delegate(); let mut io = IoHandler::new(); io.extend_with(web3); diff --git a/rpc/src/v1/types/block.rs b/rpc/src/v1/types/block.rs index 6e23647a0ec..61f4402af09 100644 --- a/rpc/src/v1/types/block.rs +++ b/rpc/src/v1/types/block.rs @@ -139,21 +139,21 @@ impl From for Header { impl<'a> From<&'a EthHeader> for Header { fn from(h: &'a EthHeader) -> Self { Header { - hash: Some(h.hash().into()), + hash: Some(h.hash()), size: Some(h.rlp().as_raw().len().into()), - parent_hash: h.parent_hash().into(), - uncles_hash: h.uncles_hash().into(), - author: h.author().into(), - miner: h.author().into(), - state_root: h.state_root().into(), - transactions_root: h.transactions_root().into(), - receipts_root: h.receipts_root().into(), + parent_hash: h.parent_hash(), + uncles_hash: h.uncles_hash(), + author: h.author(), + miner: h.author(), + state_root: h.state_root(), + transactions_root: h.transactions_root(), + receipts_root: h.receipts_root(), number: Some(h.number().into()), - gas_used: h.gas_used().into(), - gas_limit: h.gas_limit().into(), - logs_bloom: h.log_bloom().into(), + gas_used: h.gas_used(), + gas_limit: h.gas_limit(), + logs_bloom: h.log_bloom(), timestamp: h.timestamp().into(), - difficulty: h.difficulty().into(), + difficulty: h.difficulty(), extra_data: h.extra_data().into(), seal_fields: h.view().decode_seal() .expect("Client/Miner returns only valid headers. We only serialize headers from Client/Miner; qed") diff --git a/rpc/src/v1/types/block_number.rs b/rpc/src/v1/types/block_number.rs index 64b100d5aa7..7e19f2d3d9a 100644 --- a/rpc/src/v1/types/block_number.rs +++ b/rpc/src/v1/types/block_number.rs @@ -107,7 +107,7 @@ impl<'a> Visitor<'a> for BlockNumberVisitor { _ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16).map(BlockNumber::Num).map_err(|e| { Error::custom(format!("Invalid block number: {}", e)) }), - _ => Err(Error::custom(format!("Invalid block number: missing 0x prefix"))), + _ => Err(Error::custom("Invalid block number: missing 0x prefix".to_string())), } } diff --git a/rpc/src/v1/types/confirmations.rs b/rpc/src/v1/types/confirmations.rs index 1534fbcea19..dedd0ba2539 100644 --- a/rpc/src/v1/types/confirmations.rs +++ b/rpc/src/v1/types/confirmations.rs @@ -41,7 +41,7 @@ pub struct ConfirmationRequest { impl From for ConfirmationRequest { fn from(c: helpers::ConfirmationRequest) -> Self { ConfirmationRequest { - id: c.id.into(), + id: c.id, payload: c.payload.into(), origin: c.origin, } @@ -214,15 +214,15 @@ impl From for ConfirmationPayload { helpers::ConfirmationPayload::SendTransaction(t) => ConfirmationPayload::SendTransaction(t.into()), helpers::ConfirmationPayload::SignTransaction(t) => ConfirmationPayload::SignTransaction(t.into()), helpers::ConfirmationPayload::EthSignMessage(address, data) => ConfirmationPayload::EthSignMessage(EthSignRequest { - address: address.into(), + address, data: data.into(), }), helpers::ConfirmationPayload::SignMessage(address, data) => ConfirmationPayload::EIP191SignMessage(EIP191SignRequest { - address: address.into(), - data: data.into(), + address, + data, }), helpers::ConfirmationPayload::Decrypt(address, msg) => ConfirmationPayload::Decrypt(DecryptRequest { - address: address.into(), + address, msg: msg.into(), }), } diff --git a/rpc/src/v1/types/consensus_status.rs b/rpc/src/v1/types/consensus_status.rs index a5a5c9de8b3..da2aa26a1d8 100644 --- a/rpc/src/v1/types/consensus_status.rs +++ b/rpc/src/v1/types/consensus_status.rs @@ -109,7 +109,7 @@ impl Into for updater::VersionInfo { VersionInfo { track: self.track.into(), version: self.version.into(), - hash: self.hash.into(), + hash: self.hash, } } } diff --git a/rpc/src/v1/types/filter.rs b/rpc/src/v1/types/filter.rs index c6708da5765..ec9f541797c 100644 --- a/rpc/src/v1/types/filter.rs +++ b/rpc/src/v1/types/filter.rs @@ -88,10 +88,7 @@ impl Filter { }; let (from_block, to_block) = match self.block_hash { - Some(hash) => { - let hash = hash.into(); - (BlockId::Hash(hash), BlockId::Hash(hash)) - }, + Some(hash) => (BlockId::Hash(hash), BlockId::Hash(hash)), None => (self.from_block.map_or_else(|| BlockId::Latest, &num_to_id), self.to_block.map_or_else(|| BlockId::Latest, &num_to_id)), @@ -101,14 +98,14 @@ impl Filter { from_block, to_block, address: self.address.and_then(|address| match address { VariadicValue::Null => None, - VariadicValue::Single(a) => Some(vec![a.into()]), - VariadicValue::Multiple(a) => Some(a.into_iter().map(Into::into).collect()) + VariadicValue::Single(a) => Some(vec![a]), + VariadicValue::Multiple(a) => Some(a) }), topics: { let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic { VariadicValue::Null => None, - VariadicValue::Single(t) => Some(vec![t.into()]), - VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()) + VariadicValue::Single(t) => Some(vec![t]), + VariadicValue::Multiple(t) => Some(t) }).collect()).into_iter(); vec![ diff --git a/rpc/src/v1/types/log.rs b/rpc/src/v1/types/log.rs index 3dcc8fb2988..57b2cdd5dcd 100644 --- a/rpc/src/v1/types/log.rs +++ b/rpc/src/v1/types/log.rs @@ -51,12 +51,12 @@ pub struct Log { impl From for Log { fn from(e: LocalizedLogEntry) -> Log { Log { - address: e.entry.address.into(), + address: e.entry.address, topics: e.entry.topics.into_iter().map(Into::into).collect(), data: e.entry.data.into(), - block_hash: Some(e.block_hash.into()), + block_hash: Some(e.block_hash), block_number: Some(e.block_number.into()), - transaction_hash: Some(e.transaction_hash.into()), + transaction_hash: Some(e.transaction_hash), transaction_index: Some(e.transaction_index.into()), log_index: Some(e.log_index.into()), transaction_log_index: Some(e.transaction_log_index.into()), @@ -69,7 +69,7 @@ impl From for Log { impl From for Log { fn from(e: LogEntry) -> Log { Log { - address: e.address.into(), + address: e.address, topics: e.topics.into_iter().map(Into::into).collect(), data: e.data.into(), block_hash: None, diff --git a/rpc/src/v1/types/private_receipt.rs b/rpc/src/v1/types/private_receipt.rs index fd0eae067fb..68e9e716f99 100644 --- a/rpc/src/v1/types/private_receipt.rs +++ b/rpc/src/v1/types/private_receipt.rs @@ -34,9 +34,9 @@ pub struct PrivateTransactionReceipt { impl From for PrivateTransactionReceipt { fn from(r: EthPrivateReceipt) -> Self { PrivateTransactionReceipt { - transaction_hash: r.hash.into(), - contract_address: r.contract_address.into(), - status_code: r.status_code.into(), + transaction_hash: r.hash, + contract_address: r.contract_address, + status_code: r.status_code, } } } diff --git a/rpc/src/v1/types/pubsub.rs b/rpc/src/v1/types/pubsub.rs index c526a2b372e..1586b115c38 100644 --- a/rpc/src/v1/types/pubsub.rs +++ b/rpc/src/v1/types/pubsub.rs @@ -26,9 +26,9 @@ use v1::types::{RichHeader, Filter, Log}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Result { /// New block header. - Header(RichHeader), + Header(Box), /// Log - Log(Log), + Log(Box), /// Transaction hash TransactionHash(H256), } @@ -144,7 +144,7 @@ mod tests { #[test] fn should_serialize_header() { - let header = Result::Header(RichHeader { + let header = Result::Header(Box::new(RichHeader { extra_info: Default::default(), inner: Header { hash: Some(Default::default()), @@ -165,7 +165,7 @@ mod tests { seal_fields: vec![Default::default(), Default::default()], size: Some(69.into()), }, - }); + })); let expected = r#"{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x0","extraData":"0x","gasLimit":"0x0","gasUsed":"0x0","hash":"0x0000000000000000000000000000000000000000000000000000000000000000","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","sealFields":["0x","0x"],"sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","size":"0x45","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x0","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000"}"#; assert_eq!(serde_json::to_string(&header).unwrap(), expected); } diff --git a/rpc/src/v1/types/receipt.rs b/rpc/src/v1/types/receipt.rs index f440c8f4864..f492ca98c52 100644 --- a/rpc/src/v1/types/receipt.rs +++ b/rpc/src/v1/types/receipt.rs @@ -56,7 +56,7 @@ impl Receipt { fn outcome_to_state_root(outcome: TransactionOutcome) -> Option { match outcome { TransactionOutcome::Unknown | TransactionOutcome::StatusCode(_) => None, - TransactionOutcome::StateRoot(root) => Some(root.into()), + TransactionOutcome::StateRoot(root) => Some(root), } } @@ -72,18 +72,18 @@ impl From for Receipt { fn from(r: LocalizedReceipt) -> Self { Receipt { to: r.to.map(Into::into), - from: Some(r.from.into()), - transaction_hash: Some(r.transaction_hash.into()), + from: Some(r.from), + transaction_hash: Some(r.transaction_hash), transaction_index: Some(r.transaction_index.into()), - block_hash: Some(r.block_hash.into()), + block_hash: Some(r.block_hash), block_number: Some(r.block_number.into()), - cumulative_gas_used: r.cumulative_gas_used.into(), - gas_used: Some(r.gas_used.into()), + cumulative_gas_used: r.cumulative_gas_used, + gas_used: Some(r.gas_used), contract_address: r.contract_address.map(Into::into), logs: r.logs.into_iter().map(Into::into).collect(), status_code: Self::outcome_to_status_code(&r.outcome), state_root: Self::outcome_to_state_root(r.outcome), - logs_bloom: r.log_bloom.into(), + logs_bloom: r.log_bloom, } } } @@ -93,17 +93,17 @@ impl From for Receipt { Receipt { from: None, to: None, - transaction_hash: Some(r.transaction_hash.into()), + transaction_hash: Some(r.transaction_hash), transaction_index: Some(r.transaction_index.into()), block_hash: None, block_number: None, - cumulative_gas_used: r.cumulative_gas_used.into(), - gas_used: Some(r.gas_used.into()), + cumulative_gas_used: r.cumulative_gas_used, + gas_used: Some(r.gas_used), contract_address: r.contract_address.map(Into::into), logs: r.logs.into_iter().map(Into::into).collect(), status_code: Self::outcome_to_status_code(&r.outcome), state_root: Self::outcome_to_state_root(r.outcome), - logs_bloom: r.log_bloom.into(), + logs_bloom: r.log_bloom, } } } @@ -117,13 +117,13 @@ impl From for Receipt { transaction_index: None, block_hash: None, block_number: None, - cumulative_gas_used: r.gas_used.into(), + cumulative_gas_used: r.gas_used, gas_used: None, contract_address: None, logs: r.logs.into_iter().map(Into::into).collect(), status_code: Self::outcome_to_status_code(&r.outcome), state_root: Self::outcome_to_state_root(r.outcome), - logs_bloom: r.log_bloom.into(), + logs_bloom: r.log_bloom, } } } diff --git a/rpc/src/v1/types/sync.rs b/rpc/src/v1/types/sync.rs index 10094742c0a..901611fea2b 100644 --- a/rpc/src/v1/types/sync.rs +++ b/rpc/src/v1/types/sync.rs @@ -120,7 +120,7 @@ impl From for PipProtocolInfo { fn from(info: sync::PipProtocolInfo) -> Self { PipProtocolInfo { version: info.version, - difficulty: info.difficulty.into(), + difficulty: info.difficulty, head: format!("{:x}", info.head), } } @@ -179,7 +179,7 @@ impl From for TransactionStats { first_seen: s.first_seen, propagated_to: s.propagated_to .into_iter() - .map(|(id, count)| (id.into(), count)) + .map(|(id, count)| (id, count)) .collect(), } } diff --git a/rpc/src/v1/types/trace.rs b/rpc/src/v1/types/trace.rs index 715ffe62c58..58a5ee59622 100644 --- a/rpc/src/v1/types/trace.rs +++ b/rpc/src/v1/types/trace.rs @@ -58,8 +58,8 @@ pub struct StorageDiff { impl From for StorageDiff { fn from(c: et::StorageDiff) -> Self { StorageDiff { - key: c.location.into(), - val: c.value.into(), + key: c.location, + val: c.value, } } } @@ -190,7 +190,7 @@ impl From for AccountDiff { balance: c.balance.into(), nonce: c.nonce.into(), code: c.code.into(), - storage: c.storage.into_iter().map(|(k, v)| (k.into(), v.into())).collect(), + storage: c.storage.into_iter().map(|(k, v)| (k, v.into())).collect(), } } } @@ -208,7 +208,7 @@ impl Serialize for StateDiff { impl From for StateDiff { fn from(c: state_diff::StateDiff) -> Self { - StateDiff(c.raw.into_iter().map(|(k, v)| (k.into(), v.into())).collect()) + StateDiff(c.raw.into_iter().map(|(k, v)| (k, v.into())).collect()) } } @@ -228,9 +228,9 @@ pub struct Create { impl From for Create { fn from(c: trace::Create) -> Self { Create { - from: c.from.into(), - value: c.value.into(), - gas: c.gas.into(), + from: c.from, + value: c.value, + gas: c.gas, init: Bytes::new(c.init), } } @@ -285,10 +285,10 @@ pub struct Call { impl From for Call { fn from(c: trace::Call) -> Self { Call { - from: c.from.into(), - to: c.to.into(), - value: c.value.into(), - gas: c.gas.into(), + from: c.from, + to: c.to, + value: c.value, + gas: c.gas, input: c.input.into(), call_type: c.call_type.into(), } @@ -335,8 +335,8 @@ pub struct Reward { impl From for Reward { fn from(r: trace::Reward) -> Self { Reward { - author: r.author.into(), - value: r.value.into(), + author: r.author, + value: r.value, reward_type: r.reward_type.into(), } } @@ -357,9 +357,9 @@ pub struct Suicide { impl From for Suicide { fn from(s: trace::Suicide) -> Self { Suicide { - address: s.address.into(), - refund_address: s.refund_address.into(), - balance: s.balance.into(), + address: s.address, + refund_address: s.refund_address, + balance: s.balance, } } } @@ -401,7 +401,7 @@ pub struct CallResult { impl From for CallResult { fn from(c: trace::CallResult) -> Self { CallResult { - gas_used: c.gas_used.into(), + gas_used: c.gas_used, output: c.output.into(), } } @@ -422,9 +422,9 @@ pub struct CreateResult { impl From for CreateResult { fn from(c: trace::CreateResult) -> Self { CreateResult { - gas_used: c.gas_used.into(), + gas_used: c.gas_used, code: c.code.into(), - address: c.address.into(), + address: c.address, } } } @@ -526,11 +526,11 @@ impl From for LocalizedTrace { action: t.action.into(), result: t.result.into(), trace_address: t.trace_address.into_iter().map(Into::into).collect(), - subtraces: t.subtraces.into(), + subtraces: t.subtraces, transaction_position: t.transaction_number.map(Into::into), transaction_hash: t.transaction_hash.map(Into::into), - block_number: t.block_number.into(), - block_hash: t.block_hash.into(), + block_number: t.block_number, + block_hash: t.block_hash, } } } @@ -591,7 +591,7 @@ impl From for Trace { fn from(t: FlatTrace) -> Self { Trace { trace_address: t.trace_address.into_iter().map(Into::into).collect(), - subtraces: t.subtraces.into(), + subtraces: t.subtraces, action: t.action.into(), result: t.result.into(), } @@ -646,7 +646,7 @@ impl From<(H256, Executed)> for TraceResultsWithTransactionHash { trace: t.1.trace.into_iter().map(Into::into).collect(), vm_trace: t.1.vm_trace.map(Into::into), state_diff: t.1.state_diff.map(Into::into), - transaction_hash: t.0.into(), + transaction_hash: t.0, } } } diff --git a/rpc/src/v1/types/transaction.rs b/rpc/src/v1/types/transaction.rs index 72b591a89f7..931e0386696 100644 --- a/rpc/src/v1/types/transaction.rs +++ b/rpc/src/v1/types/transaction.rs @@ -177,22 +177,22 @@ impl Transaction { let signature = t.signature(); let scheme = CreateContractAddress::FromSenderAndNonce; Transaction { - hash: t.hash().into(), - nonce: t.nonce.into(), - block_hash: Some(t.block_hash.clone().into()), + hash: t.hash(), + nonce: t.nonce, + block_hash: Some(t.block_hash), block_number: Some(t.block_number.into()), transaction_index: Some(t.transaction_index.into()), - from: t.sender().into(), + from: t.sender(), to: match t.action { Action::Create => None, - Action::Call(ref address) => Some(address.clone().into()) + Action::Call(ref address) => Some(*address) }, - value: t.value.into(), - gas_price: t.gas_price.into(), - gas: t.gas.into(), + value: t.value, + gas_price: t.gas_price, + gas: t.gas, input: Bytes::new(t.data.clone()), creates: match t.action { - Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0.into()), + Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0), Action::Call(_) => None, }, raw: ::rlp::encode(&t.signed).into(), @@ -211,22 +211,22 @@ impl Transaction { let signature = t.signature(); let scheme = CreateContractAddress::FromSenderAndNonce; Transaction { - hash: t.hash().into(), - nonce: t.nonce.into(), + hash: t.hash(), + nonce: t.nonce, block_hash: None, block_number: None, transaction_index: None, - from: t.sender().into(), + from: t.sender(), to: match t.action { Action::Create => None, - Action::Call(ref address) => Some(address.clone().into()) + Action::Call(ref address) => Some(*address) }, - value: t.value.into(), - gas_price: t.gas_price.into(), - gas: t.gas.into(), + value: t.value, + gas_price: t.gas_price, + gas: t.gas, input: Bytes::new(t.data.clone()), creates: match t.action { - Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0.into()), + Action::Create => Some(contract_address(scheme, &t.sender(), &t.nonce, &t.data).0), Action::Call(_) => None, }, raw: ::rlp::encode(&t).into(), @@ -243,7 +243,7 @@ impl Transaction { /// Convert `PendingTransaction` into RPC Transaction. pub fn from_pending(t: PendingTransaction) -> Transaction { let mut r = Transaction::from_signed(t.transaction); - r.condition = t.condition.map(|b| b.into()); + r.condition = r.condition.map(Into::into); r } } @@ -265,8 +265,8 @@ impl LocalTransactionStatus { Canceled(tx) => LocalTransactionStatus::Canceled(convert(tx)), Replaced { old, new } => LocalTransactionStatus::Replaced( convert(old), - new.signed().gas_price.into(), - new.signed().hash().into(), + new.signed().gas_price, + new.signed().hash(), ), } } diff --git a/rpc/src/v1/types/transaction_request.rs b/rpc/src/v1/types/transaction_request.rs index a4698cafa76..944ee111484 100644 --- a/rpc/src/v1/types/transaction_request.rs +++ b/rpc/src/v1/types/transaction_request.rs @@ -63,7 +63,7 @@ pub fn format_ether(i: U256) -> String { impl fmt::Display for TransactionRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let eth = self.value.unwrap_or(U256::from(0)); + let eth = self.value.unwrap_or_default(); match self.to { Some(ref to) => write!( f, @@ -106,14 +106,14 @@ impl From for TransactionRequest { impl From for TransactionRequest { fn from(r: helpers::FilledTransactionRequest) -> Self { TransactionRequest { - from: Some(r.from.into()), - to: r.to.map(Into::into), - gas_price: Some(r.gas_price.into()), - gas: Some(r.gas.into()), - value: Some(r.value.into()), + from: Some(r.from), + to: r.to, + gas_price: Some(r.gas_price), + gas: Some(r.gas), + value: Some(r.value), data: Some(r.data.into()), - nonce: r.nonce.map(Into::into), - condition: r.condition.map(Into::into), + nonce: r.nonce, + condition: r.condition, } } } From 023e511f83ed30726a72c99807c2ef225afdab0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?So=C4=8Dik?= <47772477+soc1c@users.noreply.github.com> Date: Fri, 22 Mar 2019 15:59:20 +0100 Subject: [PATCH 26/27] docs: add changelogs for 2.3.{6,7,8} and 2.4.{1,2,3} (#10494) * docs: add changelogs for 2.3.{6,7} and 2.4.{1,2} * docs: add changelogs for 2.4.3 beta and 2.3.8 stable * Update docs/CHANGELOG-2.3.md Co-Authored-By: soc1c <47772477+soc1c@users.noreply.github.com> * Update docs/CHANGELOG-2.3.md Co-Authored-By: soc1c <47772477+soc1c@users.noreply.github.com> * docs: remove empty lines --- CHANGELOG.md | 36 +++++++++++++++++++++++++++++++++++- docs/CHANGELOG-2.3.md | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef1c68399d..b986da688cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,37 @@ +## Parity-Ethereum [v2.4.3](https://github.com/paritytech/parity-ethereum/releases/tag/v2.4.3) (2019-03-22) + +Parity-Ethereum 2.4.3-beta is a bugfix release that improves performance and stability. This patch release contains a critical bug fix where serving light clients previously led to client crashes. Upgrading is highly recommended. + +The full list of included changes: +- 2.4.3 beta backports ([#10508](https://github.com/paritytech/parity-ethereum/pull/10508)) + - Version: bump beta + - Add additional request tests ([#10503](https://github.com/paritytech/parity-ethereum/pull/10503)) + +## Parity-Ethereum [v2.4.2](https://github.com/paritytech/parity-ethereum/releases/tag/v2.4.2) (2019-03-20) + +Parity-Ethereum 2.4.2-beta is a bugfix release that improves performance and stability. + +The full list of included changes: +- 2.4.2 beta backports ([#10488](https://github.com/paritytech/parity-ethereum/pull/10488)) + - Version: bump beta + - Сaching through docker volume ([#10477](https://github.com/paritytech/parity-ethereum/pull/10477)) + - fix win&mac build ([#10486](https://github.com/paritytech/parity-ethereum/pull/10486)) + - fix(extract `timestamp_checked_add` as lib) ([#10383](https://github.com/paritytech/parity-ethereum/pull/10383)) + +## Parity-Ethereum [v2.4.1](https://github.com/paritytech/parity-ethereum/releases/tag/v2.4.1) (2019-03-19) + +Parity-Ethereum 2.4.1-beta is a bugfix release that improves performance and stability. + +The full list of included changes: +- 2.4.1 beta backports ([#10471](https://github.com/paritytech/parity-ethereum/pull/10471)) + - Version: bump beta + - Implement parity_versionInfo & parity_setChain on LC; fix parity_setChain ([#10312](https://github.com/paritytech/parity-ethereum/pull/10312)) + - CI publish to aws ([#10446](https://github.com/paritytech/parity-ethereum/pull/10446)) + - CI aws git checkout ([#10451](https://github.com/paritytech/parity-ethereum/pull/10451)) + - Revert "CI aws git checkout ([#10451](https://github.com/paritytech/parity-ethereum/pull/10451))" ([#10456](https://github.com/paritytech/parity-ethereum/pull/10456)) + - Tests parallelized ([#10452](https://github.com/paritytech/parity-ethereum/pull/10452)) + - Ensure static validator set changes are recognized ([#10467](https://github.com/paritytech/parity-ethereum/pull/10467)) + ## Parity-Ethereum [v2.4.0](https://github.com/paritytech/parity-ethereum/releases/tag/v2.4.0) (2019-02-25) Parity-Ethereum 2.4.0-beta is our trifortnightly minor version release coming with a lot of new features as well as bugfixes and performance improvements. @@ -6,7 +40,7 @@ Notable changes: - Account management is now deprecated ([#10213](https://github.com/paritytech/parity-ethereum/pull/10213)) - Local accounts can now be specified via CLI ([#9960](https://github.com/paritytech/parity-ethereum/pull/9960)) - Chains can now be reset to a particular block via CLI ([#9782](https://github.com/paritytech/parity-ethereum/pull/9782)) -- Ethash now additionally implements ProgPoW ([#9762](https://github.com/paritytech/parity-ethereum/pull/9762)) +- Ethash now additionally implements ProgPoW ([#9762](https://github.com/paritytech/parity-ethereum/pull/9762)) - The `eip1283DisableTransition` flag was added to revert EIP-1283 ([#10214](https://github.com/paritytech/parity-ethereum/pull/10214)) The full list of included changes: diff --git a/docs/CHANGELOG-2.3.md b/docs/CHANGELOG-2.3.md index f7e75d4427a..34286baf1b8 100644 --- a/docs/CHANGELOG-2.3.md +++ b/docs/CHANGELOG-2.3.md @@ -1,3 +1,36 @@ +## Parity-Ethereum [v2.3.8](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.8) (2019-03-22) + +Parity-Ethereum 2.3.8-stable is a bugfix release that improves performance and stability. This patch release contains a critical bug fix where serving light clients previously led to client crashes. Upgrading is highly recommended. + +The full list of included changes: +- 2.3.8 stable backports ([#10507](https://github.com/paritytech/parity-ethereum/pull/10507)) + - Version: bump stable + - Add additional request tests ([#10503](https://github.com/paritytech/parity-ethereum/pull/10503)) + +## Parity-Ethereum [v2.3.7](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.7) (2019-03-20) + +Parity-Ethereum 2.3.7-stable is a bugfix release that improves performance and stability. + +The full list of included changes: +- 2.3.7 stable backports ([#10487](https://github.com/paritytech/parity-ethereum/pull/10487)) + - Version: bump stable + - Сaching through docker volume ([#10477](https://github.com/paritytech/parity-ethereum/pull/10477)) + - fix win&mac build ([#10486](https://github.com/paritytech/parity-ethereum/pull/10486)) + - fix(extract `timestamp_checked_add` as lib) ([#10383](https://github.com/paritytech/parity-ethereum/pull/10383)) + +## Parity-Ethereum [v2.3.6](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.6) (2019-03-19) + +Parity-Ethereum 2.3.6-stable is a bugfix release that improves performance and stability. + +The full list of included changes: +- 2.3.6 stable backports ([#10470](https://github.com/paritytech/parity-ethereum/pull/10470)) + - Version: bump stable + - CI publish to aws ([#10446](https://github.com/paritytech/parity-ethereum/pull/10446)) + - Ensure static validator set changes are recognized ([#10467](https://github.com/paritytech/parity-ethereum/pull/10467)) + - CI aws git checkout ([#10451](https://github.com/paritytech/parity-ethereum/pull/10451)) + - Revert "CI aws git checkout ([#10451](https://github.com/paritytech/parity-ethereum/pull/10451))" ([#10456](https://github.com/paritytech/parity-ethereum/pull/10456)) + - Tests parallelized ([#10452](https://github.com/paritytech/parity-ethereum/pull/10452)) + ## Parity-Ethereum [v2.3.5](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.5) (2019-02-25) Parity-Ethereum 2.3.5-stable is a bugfix release that improves performance and stability. @@ -18,7 +51,7 @@ The full list of included changes: - Snap: reenable i386, arm64, armhf architecture publishing ([#10386](https://github.com/paritytech/parity-ethereum/pull/10386)) - Tx pool: always accept local transactions ([#10375](https://github.com/paritytech/parity-ethereum/pull/10375)) - Fix to_pod storage trie value decoding ([#10368)](https://github.com/paritytech/parity-ethereum/pull/10368)) -- Version: mark 2.3.5 as stable +- Version: mark 2.3.5 as stable ## Parity-Ethereum [v2.3.4](https://github.com/paritytech/parity-ethereum/releases/tag/v2.3.4) (2019-02-21) From 6cf3ba7efd8a366b440c7675df1c0576c8cd4762 Mon Sep 17 00:00:00 2001 From: Hernando Castano Date: Mon, 25 Mar 2019 10:42:33 +0100 Subject: [PATCH 27/27] Add a more realistic Batch test (#10511) * Remove unrealistic tests * Add test that more closely resembles real usage --- ethcore/light/src/types/request/batch.rs | 35 +++++++----------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/ethcore/light/src/types/request/batch.rs b/ethcore/light/src/types/request/batch.rs index f99b49d2b27..63641b5daa8 100644 --- a/ethcore/light/src/types/request/batch.rs +++ b/ethcore/light/src/types/request/batch.rs @@ -275,8 +275,7 @@ mod tests { } #[test] - #[should_panic] - fn batch_tx_index_backreference_wrong_output() { + fn batch_tx_index_backreference_public_api() { let mut builder = Builder::default(); builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { num: 100.into(), // header proof puts hash at output 0. @@ -286,11 +285,16 @@ mod tests { })).unwrap(); let mut batch = builder.build(); - batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Number(42))); - batch.next_complete(); - batch.answered += 1; - batch.next_complete(); + assert!(batch.next_complete().is_some()); + let hdr_proof_res = header_proof::Response { + proof: vec![], + hash: 12.into(), + td: 21.into(), + }; + batch.supply_response_unchecked(&hdr_proof_res); + + assert!(batch.next_complete().is_some()); } #[test] @@ -310,23 +314,4 @@ mod tests { batch.answered += 1; assert!(batch.next_complete().is_some()); } - - #[test] - #[should_panic] - fn batch_receipts_backreference_wrong_output() { - let mut builder = Builder::default(); - builder.push(Request::HeaderProof(IncompleteHeaderProofRequest { - num: 100.into(), // header proof puts hash at output 0. - })).unwrap(); - builder.push(Request::Receipts(IncompleteReceiptsRequest { - hash: Field::BackReference(0, 0), - })).unwrap(); - - let mut batch = builder.build(); - batch.requests[1].fill(|_req_idx, _out_idx| Ok(Output::Number(42))); - - batch.next_complete(); - batch.answered += 1; - batch.next_complete(); - } }