diff --git a/ethcore/src/engines/authority_round.rs b/ethcore/src/engines/authority_round.rs index c3f283265..22635425e 100644 --- a/ethcore/src/engines/authority_round.rs +++ b/ethcore/src/engines/authority_round.rs @@ -36,8 +36,9 @@ use io::{IoContext, IoHandler, TimerToken, IoService}; use env_info::EnvInfo; use builtin::Builtin; use client::{Client, EngineClient}; -use super::validator_set::{ValidatorSet, new_validator_set}; use state::CleanupMode; +use super::signer::EngineSigner; +use super::validator_set::{ValidatorSet, new_validator_set}; /// `AuthorityRound` params. #[derive(Debug, PartialEq)] @@ -78,8 +79,7 @@ pub struct AuthorityRound { step: AtomicUsize, proposed: AtomicBool, client: RwLock>>, - account_provider: Mutex>, - password: RwLock>, + signer: EngineSigner, validators: Box, } @@ -117,8 +117,7 @@ impl AuthorityRound { step: AtomicUsize::new(initial_step), proposed: AtomicBool::new(false), client: RwLock::new(None), - account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())), - password: RwLock::new(None), + signer: Default::default(), validators: new_validator_set(our_params.validators), }); // Do not initialize timeouts for tests. @@ -234,11 +233,10 @@ impl Engine for AuthorityRound { let header = block.header(); let step = self.step.load(AtomicOrdering::SeqCst); if self.is_step_proposer(step, header.author()) { - let ap = self.account_provider.lock(); - if let Ok(signature) = ap.sign(*header.author(), self.password.read().clone(), header.bare_hash()) { + if let Ok(signature) = self.signer.sign(header.bare_hash()) { trace!(target: "poa", "generate_seal: Issuing a block for step {}.", step); self.proposed.store(true, AtomicOrdering::SeqCst); - return Seal::Regular(vec![encode(&step).to_vec(), encode(&(&*signature as &[u8])).to_vec()]); + return Seal::Regular(vec![encode(&step).to_vec(), encode(&(&H520::from(signature) as &[u8])).to_vec()]); } else { warn!(target: "poa", "generate_seal: FAIL: Accounts secret key unavailable."); } @@ -330,9 +328,7 @@ impl Engine for AuthorityRound { } fn set_signer(&self, ap: Arc, address: Address, password: String) { - *self.account_provider.lock() = ap; - *self.password.write() = Some(password); - debug!(target: "poa", "Setting Engine signer to {}", address); + self.signer.set(ap, address, password); } } diff --git a/ethcore/src/engines/basic_authority.rs b/ethcore/src/engines/basic_authority.rs index fbee7c811..fdd2deb0b 100644 --- a/ethcore/src/engines/basic_authority.rs +++ b/ethcore/src/engines/basic_authority.rs @@ -30,6 +30,7 @@ use evm::Schedule; use ethjson; use header::Header; use client::Client; +use super::signer::EngineSigner; use super::validator_set::{ValidatorSet, new_validator_set}; /// `BasicAuthority` params. @@ -56,8 +57,7 @@ pub struct BasicAuthority { params: CommonParams, gas_limit_bound_divisor: U256, builtins: BTreeMap, - account_provider: Mutex>, - password: RwLock>, + signer: EngineSigner, validators: Box, } @@ -69,8 +69,7 @@ impl BasicAuthority { gas_limit_bound_divisor: our_params.gas_limit_bound_divisor, builtins: builtins, validators: new_validator_set(our_params.validators), - account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())), - password: RwLock::new(None), + signer: Default::default(), } } } @@ -110,14 +109,12 @@ impl Engine for BasicAuthority { /// Attempt to seal the block internally. fn generate_seal(&self, block: &ExecutedBlock) -> Seal { - let ref ap = *self.account_provider.lock(); let header = block.header(); let author = header.author(); if self.validators.contains(author) { - let message = header.bare_hash(); // account should be pernamently unlocked, otherwise sealing will fail - if let Ok(signature) = ap.sign(*author, self.password.read().clone(), message) { - return Seal::Regular(vec![::rlp::encode(&(&*signature as &[u8])).to_vec()]); + if let Ok(signature) = self.signer.sign(header.bare_hash()) { + return Seal::Regular(vec![::rlp::encode(&(&H520::from(signature) as &[u8])).to_vec()]); } else { trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable"); } @@ -171,9 +168,8 @@ impl Engine for BasicAuthority { self.validators.register_call_contract(client); } - fn set_signer(&self, ap: Arc, _address: Address, password: String) { - *self.password.write() = Some(password); - *self.account_provider.lock() = ap; + fn set_signer(&self, ap: Arc, address: Address, password: String) { + self.signer.set(ap, address, password); } } diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 86f51bf2b..42d5d3dca 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -22,6 +22,7 @@ mod basic_authority; mod authority_round; mod tendermint; mod validator_set; +mod signer; pub use self::null_engine::NullEngine; pub use self::instant_seal::InstantSeal; diff --git a/ethcore/src/engines/signer.rs b/ethcore/src/engines/signer.rs new file mode 100644 index 000000000..cdd57707e --- /dev/null +++ b/ethcore/src/engines/signer.rs @@ -0,0 +1,63 @@ +// Copyright 2015, 2016 Parity Technologies (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! A signer used by Engines which need to sign messages. + +use util::{Arc, Mutex, RwLock, H256, Address}; +use ethkey::Signature; +use account_provider::{self, AccountProvider}; + +/// Everything that an Engine needs to sign messages. +pub struct EngineSigner { + account_provider: Mutex>, + address: RwLock
, + password: RwLock>, +} + +impl Default for EngineSigner { + fn default() -> Self { + EngineSigner { + account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())), + address: Default::default(), + password: Default::default(), + } + } +} + +impl EngineSigner { + /// Set up the signer to sign with given address and password. + pub fn set(&self, ap: Arc, address: Address, password: String) { + *self.account_provider.lock() = ap; + *self.address.write() = address; + *self.password.write() = Some(password); + debug!(target: "poa", "Setting Engine signer to {}", address); + } + + /// Sign a consensus message hash. + pub fn sign(&self, hash: H256) -> Result { + self.account_provider.lock().sign(*self.address.read(), self.password.read().clone(), hash) + } + + /// Signing address. + pub fn address(&self) -> Address { + self.address.read().clone() + } + + /// Check if the given address is the signing address. + pub fn is_address(&self, address: &Address) -> bool { + *self.address.read() == *address + } +} diff --git a/ethcore/src/engines/tendermint/mod.rs b/ethcore/src/engines/tendermint/mod.rs index 661044ddb..ca8e7f0c4 100644 --- a/ethcore/src/engines/tendermint/mod.rs +++ b/ethcore/src/engines/tendermint/mod.rs @@ -46,6 +46,7 @@ use views::HeaderView; use evm::Schedule; use state::CleanupMode; use io::IoService; +use super::signer::EngineSigner; use super::validator_set::{ValidatorSet, new_validator_set}; use self::message::*; use self::transition::TransitionHandler; @@ -81,10 +82,6 @@ pub struct Tendermint { step_service: IoService, client: RwLock>>, block_reward: U256, - /// Address to be used as authority. - authority: RwLock
, - /// Password used for signing messages. - password: RwLock>, /// Blockchain height. height: AtomicUsize, /// Consensus round. @@ -94,7 +91,7 @@ pub struct Tendermint { /// Vote accumulator. votes: VoteCollector, /// Used to sign messages and proposals. - account_provider: Mutex>, + signer: EngineSigner, /// Message for the last PoLC. lock_change: RwLock>, /// Last lock round. @@ -116,13 +113,11 @@ impl Tendermint { client: RwLock::new(None), step_service: IoService::::start()?, block_reward: our_params.block_reward, - authority: RwLock::new(Address::default()), - password: RwLock::new(None), height: AtomicUsize::new(1), round: AtomicUsize::new(0), step: RwLock::new(Step::Propose), votes: VoteCollector::new(), - account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())), + signer: Default::default(), lock_change: RwLock::new(None), last_lock: AtomicUsize::new(0), proposal: RwLock::new(None), @@ -158,18 +153,17 @@ impl Tendermint { } fn generate_message(&self, block_hash: Option) -> Option { - let ref ap = *self.account_provider.lock(); let h = self.height.load(AtomicOrdering::SeqCst); let r = self.round.load(AtomicOrdering::SeqCst); let s = self.step.read(); let vote_info = message_info_rlp(&VoteStep::new(h, r, *s), block_hash); - let authority = self.authority.read(); - match ap.sign(*authority, self.password.read().clone(), vote_info.sha3()).map(Into::into) { + match self.signer.sign(vote_info.sha3()).map(Into::into) { Ok(signature) => { let message_rlp = message_full_rlp(&signature, &vote_info); let message = ConsensusMessage::new(signature, h, r, *s, block_hash); - self.votes.vote(message.clone(), &*authority); - debug!(target: "poa", "Generated {:?} as {}.", message, *authority); + let validator = self.signer.address(); + self.votes.vote(message.clone(), &validator); + debug!(target: "poa", "Generated {:?} as {}.", message, validator); self.handle_valid_message(&message); Some(message_rlp) @@ -240,7 +234,7 @@ impl Tendermint { let height = self.height.load(AtomicOrdering::SeqCst); if let Some(block_hash) = *self.proposal.read() { // Generate seal and remove old votes. - if self.is_proposer(&*self.authority.read()).is_ok() { + if self.is_signer_proposer() { if let Some(seal) = self.votes.seal_signatures(height, round, &block_hash) { trace!(target: "poa", "Collected seal: {:?}", seal); let seal = vec![ @@ -267,11 +261,16 @@ impl Tendermint { n > self.validators.count() * 2/3 } + /// Find the designated for the given round. + fn round_proposer(&self, height: Height, round: Round) -> Address { + let proposer_nonce = height + round; + trace!(target: "poa", "Proposer nonce: {}", proposer_nonce); + self.validators.get(proposer_nonce) + } + /// Check if address is a proposer for given round. fn is_round_proposer(&self, height: Height, round: Round, address: &Address) -> Result<(), EngineError> { - let proposer_nonce = height + round; - trace!(target: "poa", "is_proposer: Proposer nonce: {}", proposer_nonce); - let proposer = self.validators.get(proposer_nonce); + let proposer = self.round_proposer(height, round); if proposer == *address { Ok(()) } else { @@ -279,9 +278,10 @@ impl Tendermint { } } - /// Check if address is the current proposer. - fn is_proposer(&self, address: &Address) -> Result<(), EngineError> { - self.is_round_proposer(self.height.load(AtomicOrdering::SeqCst), self.round.load(AtomicOrdering::SeqCst), address) + /// Check if current signer is the current proposer. + fn is_signer_proposer(&self) -> bool { + let proposer = self.round_proposer(self.height.load(AtomicOrdering::SeqCst), self.round.load(AtomicOrdering::SeqCst)); + self.signer.is_address(&proposer) } fn is_height(&self, message: &ConsensusMessage) -> bool { @@ -416,11 +416,10 @@ impl Engine for Tendermint { /// Attempt to seal generate a proposal seal. fn generate_seal(&self, block: &ExecutedBlock) -> Seal { - let ref ap = *self.account_provider.lock(); let header = block.header(); let author = header.author(); // Only proposer can generate seal if None was generated. - if self.is_proposer(author).is_err() || self.proposal.read().is_some() { + if !self.is_signer_proposer() || self.proposal.read().is_some() { return Seal::None; } @@ -428,7 +427,7 @@ impl Engine for Tendermint { let round = self.round.load(AtomicOrdering::SeqCst); let bh = Some(header.bare_hash()); let vote_info = message_info_rlp(&VoteStep::new(height, round, Step::Propose), bh.clone()); - if let Ok(signature) = ap.sign(*author, self.password.read().clone(), vote_info.sha3()).map(H520::from) { + if let Ok(signature) = self.signer.sign(vote_info.sha3()).map(Into::into) { // Insert Propose vote. debug!(target: "poa", "Submitting proposal {} at height {} round {}.", header.bare_hash(), height, round); self.votes.vote(ConsensusMessage::new(signature, height, round, Step::Propose, bh), author); @@ -557,9 +556,7 @@ impl Engine for Tendermint { fn set_signer(&self, ap: Arc, address: Address, password: String) { { - *self.authority.write() = address; - *self.password.write() = Some(password); - *self.account_provider.lock() = ap; + self.signer.set(ap, address, password); } self.to_step(Step::Propose); }