simplify parity machine (#10469)

* simplify ethcore machine by removing redundant traits

* further ethereum machine simplifications

* removed obsolete todo
This commit is contained in:
Marek Kotewicz 2019-03-13 11:36:13 +01:00 committed by GitHub
parent 595dac6c3f
commit a16bad4175
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 109 additions and 224 deletions

9
Cargo.lock generated
View File

@ -306,7 +306,6 @@ dependencies = [
"heapsize 0.4.2 (git+https://github.com/cheme/heapsize.git?branch=ec-macfix)", "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)", "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-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 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rlp_derive 0.1.0", "rlp_derive 0.1.0",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
@ -739,7 +738,6 @@ dependencies = [
"num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "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-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-crypto 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"parity-machine 0.1.0",
"parity-runtime 0.1.0", "parity-runtime 0.1.0",
"parity-snappy 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "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)", "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)", "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]] [[package]]
name = "parity-path" name = "parity-path"
version = "0.1.1" version = "0.1.1"

View File

@ -50,7 +50,6 @@ num = { version = "0.1", default-features = false, features = ["bigint"] }
num_cpus = "1.2" num_cpus = "1.2"
parity-bytes = "0.1" parity-bytes = "0.1"
parity-crypto = "0.3.0" parity-crypto = "0.3.0"
parity-machine = { path = "../machine" }
parity-snappy = "0.1" parity-snappy = "0.1"
parking_lot = "0.7" parking_lot = "0.7"
trie-db = "0.11.0" trie-db = "0.11.0"

View File

@ -195,26 +195,6 @@ impl IsBlock for ExecutedBlock {
fn block(&self) -> &ExecutedBlock { self } 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> { impl<'x> OpenBlock<'x> {
/// Create a new `OpenBlock` ready for transaction pushing. /// Create a new `OpenBlock` ready for transaction pushing.
pub fn new<'a>( pub fn new<'a>(

View File

@ -24,11 +24,12 @@ use ethereum_types::{H160, Address, U256};
use std::sync::Arc; use std::sync::Arc;
use hash::keccak; use hash::keccak;
use error::Error; use error::Error;
use machine::WithRewards; use machine::Machine;
use parity_machine::Machine;
use trace; use trace;
use types::BlockNumber; use types::BlockNumber;
use super::{SystemOrCodeCall, SystemOrCodeCallKind}; use super::{SystemOrCodeCall, SystemOrCodeCallKind};
use trace::{Tracer, ExecutiveTracer, Tracing};
use block::ExecutedBlock;
use_contract!(block_reward_contract, "res/contracts/block_reward.json"); 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. /// Applies the given block rewards, i.e. adds the given balance to each beneficiary' address.
/// If tracing is enabled the operations are recorded. /// If tracing is enabled the operations are recorded.
pub fn apply_block_rewards<M: Machine + WithRewards>( pub fn apply_block_rewards<M: Machine>(
rewards: &[(Address, RewardKind, U256)], rewards: &[(Address, RewardKind, U256)],
block: &mut M::LiveBlock, block: &mut ExecutedBlock,
machine: &M, machine: &M,
) -> Result<(), M::Error> { ) -> Result<(), M::Error> {
for &(ref author, _, ref block_reward) in rewards { for &(ref author, _, ref block_reward) in rewards {
machine.add_balance(block, author, block_reward)?; machine.add_balance(block, author, block_reward)?;
} }
let rewards: Vec<_> = rewards.into_iter().map(|&(a, k, r)| (a, k.into(), r)).collect(); if let Tracing::Enabled(ref mut traces) = *block.traces_mut() {
machine.note_rewards(block, &rewards) 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)] #[cfg(test)]

View File

@ -15,8 +15,9 @@
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>. // along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use engines::{Engine, Seal}; use engines::{Engine, Seal};
use parity_machine::{Machine, Transactions}; use machine::Machine;
use types::header::ExtendedHeader; use types::header::{Header, ExtendedHeader};
use block::ExecutedBlock;
/// `InstantSeal` params. /// `InstantSeal` params.
#[derive(Default, Debug, PartialEq)] #[derive(Default, Debug, PartialEq)]
@ -49,7 +50,7 @@ impl<M> InstantSeal<M> {
} }
} }
impl<M: Machine> Engine<M> for InstantSeal<M> where M::LiveBlock: Transactions { impl<M: Machine> Engine<M> for InstantSeal<M> {
fn name(&self) -> &str { fn name(&self) -> &str {
"InstantSeal" "InstantSeal"
} }
@ -58,11 +59,15 @@ impl<M: Machine> Engine<M> for InstantSeal<M> where M::LiveBlock: Transactions {
fn seals_internally(&self) -> Option<bool> { Some(true) } fn seals_internally(&self) -> Option<bool> { Some(true) }
fn generate_seal(&self, block: &M::LiveBlock, _parent: &M::Header) -> Seal { fn generate_seal(&self, block: &ExecutedBlock, _parent: &Header) -> Seal {
if block.transactions().is_empty() { Seal::None } else { Seal::Regular(Vec::new()) } 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(()) Ok(())
} }

View File

@ -27,14 +27,13 @@ pub mod signer;
pub use self::authority_round::AuthorityRound; pub use self::authority_round::AuthorityRound;
pub use self::basic_authority::BasicAuthority; pub use self::basic_authority::BasicAuthority;
pub use self::epoch::{EpochVerifier, Transition as EpochTransition};
pub use self::instant_seal::{InstantSeal, InstantSealParams}; pub use self::instant_seal::{InstantSeal, InstantSealParams};
pub use self::null_engine::NullEngine; pub use self::null_engine::NullEngine;
pub use self::signer::EngineSigner; pub use self::signer::EngineSigner;
// TODO [ToDr] Remove re-export (#10130) // TODO [ToDr] Remove re-export (#10130)
pub use types::engines::ForkChoice; 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::sync::{Weak, Arc};
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
@ -50,11 +49,13 @@ use spec::CommonParams;
use types::transaction::{self, UnverifiedTransaction, SignedTransaction}; use types::transaction::{self, UnverifiedTransaction, SignedTransaction};
use ethkey::{Signature}; use ethkey::{Signature};
use parity_machine::{Machine, LocalizedMachine as Localized}; use machine::{Machine, LocalizedMachine as Localized};
use ethereum_types::{H256, U256, Address}; use ethereum_types::{H256, U256, Address};
use unexpected::{Mismatch, OutOfBounds}; use unexpected::{Mismatch, OutOfBounds};
use bytes::Bytes; use bytes::Bytes;
use types::ancestry_action::AncestryAction; use types::ancestry_action::AncestryAction;
use block::ExecutedBlock;
use machine;
/// Default EIP-210 contract code. /// Default EIP-210 contract code.
/// As defined in https://github.com/ethereum/EIPs/pull/210 /// As defined in https://github.com/ethereum/EIPs/pull/210
@ -235,10 +236,10 @@ pub trait Engine<M: Machine>: Sync + Send {
fn machine(&self) -> &M; fn machine(&self) -> &M;
/// The number of additional header fields required for this engine. /// 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`. /// Additional engine-specific information for the user/developer concerning `header`.
fn extra_info(&self, _header: &M::Header) -> BTreeMap<String, String> { BTreeMap::new() } fn extra_info(&self, _header: &Header) -> BTreeMap<String, String> { BTreeMap::new() }
/// Maximum number of uncles a block is allowed to declare. /// Maximum number of uncles a block is allowed to declare.
fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 } fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 0 }
@ -253,7 +254,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// `epoch_begin` set to true if this block kicks off an epoch. /// `epoch_begin` set to true if this block kicks off an epoch.
fn on_new_block( fn on_new_block(
&self, &self,
_block: &mut M::LiveBlock, _block: &mut ExecutedBlock,
_epoch_begin: bool, _epoch_begin: bool,
_ancestry: &mut Iterator<Item = ExtendedHeader>, _ancestry: &mut Iterator<Item = ExtendedHeader>,
) -> Result<(), M::Error> { ) -> Result<(), M::Error> {
@ -261,7 +262,7 @@ pub trait Engine<M: Machine>: Sync + Send {
} }
/// Block transformation functions, after the transactions. /// 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(()) Ok(())
} }
@ -279,7 +280,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// ///
/// It is fine to require access to state or a full client for this function, since /// It is fine to require access to state or a full client for this function, since
/// light clients do not generate seals. /// 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. /// Verify a locally-generated seal of a header.
/// ///
@ -291,25 +292,25 @@ pub trait Engine<M: Machine>: Sync + Send {
/// ///
/// It is fine to require access to state or a full client for this function, since /// It is fine to require access to state or a full client for this function, since
/// light clients do not generate seals. /// 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. /// 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. /// 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. /// 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. /// 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. /// 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. /// Phase 4 verification. Verify block header against potentially external data.
/// Should only be called when `register_client` has been called previously. /// 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. /// Genesis epoch data.
fn genesis_epoch_data<'a>(&self, _header: &M::Header, _state: &<M as Localized<'a>>::StateContext) -> Result<Vec<u8>, String> { Ok(Vec::new()) } fn genesis_epoch_data<'a>(&self, _header: &Header, _state: &<M as Localized<'a>>::StateContext) -> Result<Vec<u8>, String> { Ok(Vec::new()) }
/// Whether an epoch change is signalled at the given header but will require finality. /// 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 /// If a change can be enacted immediately then return `No` from this function but
@ -320,7 +321,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Return `Yes` or `No` when the answer is definitively known. /// Return `Yes` or `No` when the answer is definitively known.
/// ///
/// Should not interact with state. /// Should not interact with state.
fn signals_epoch_end<'a>(&self, _header: &M::Header, _aux: <M as Localized<'a>>::AuxiliaryData) fn signals_epoch_end<'a>(&self, _header: &Header, _aux: <M as Localized<'a>>::AuxiliaryData)
-> EpochChange<M> -> EpochChange<M>
{ {
EpochChange::No EpochChange::No
@ -336,9 +337,9 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Return optional transition proof. /// Return optional transition proof.
fn is_epoch_end( fn is_epoch_end(
&self, &self,
_chain_head: &M::Header, _chain_head: &Header,
_finalized: &[H256], _finalized: &[H256],
_chain: &Headers<M::Header>, _chain: &Headers<Header>,
_transition_store: &PendingTransitionStore, _transition_store: &PendingTransitionStore,
) -> Option<Vec<u8>> { ) -> Option<Vec<u8>> {
None None
@ -355,8 +356,8 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Return optional transition proof. /// Return optional transition proof.
fn is_epoch_end_light( fn is_epoch_end_light(
&self, &self,
_chain_head: &M::Header, _chain_head: &Header,
_chain: &Headers<M::Header>, _chain: &Headers<Header>,
_transition_store: &PendingTransitionStore, _transition_store: &PendingTransitionStore,
) -> Option<Vec<u8>> { ) -> Option<Vec<u8>> {
None None
@ -364,13 +365,13 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Create an epoch verifier from validation proof and a flag indicating /// Create an epoch verifier from validation proof and a flag indicating
/// whether finality is required. /// whether finality is required.
fn epoch_verifier<'a>(&self, _header: &M::Header, _proof: &'a [u8]) -> ConstructedVerifier<'a, M> { fn epoch_verifier<'a>(&self, _header: &Header, _proof: &'a [u8]) -> ConstructedVerifier<'a, M> {
ConstructedVerifier::Trusted(Box::new(self::epoch::NoOp)) ConstructedVerifier::Trusted(Box::new(NoOp))
} }
/// Populate a header's fields based on its parent's header. /// Populate a header's fields based on its parent's header.
/// Usually implements the chain scoring rule based on weight. /// 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; /// Handle any potential consensus messages;
/// updating consensus state and potentially issuing a new one. /// updating consensus state and potentially issuing a new one.
@ -378,7 +379,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Find out if the block is a proposal block and should not be inserted into the DB. /// 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. /// 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. /// Register a component which signs consensus messages.
fn set_signer(&self, _signer: Box<EngineSigner>) {} fn set_signer(&self, _signer: Box<EngineSigner>) {}
@ -421,7 +422,7 @@ pub trait Engine<M: Machine>: Sync + Send {
/// Gather all ancestry actions. Called at the last stage when a block is committed. The Engine must guarantee that /// Gather all ancestry actions. Called at the last stage when a block is committed. The Engine must guarantee that
/// the ancestry exists. /// the ancestry exists.
fn ancestry_actions(&self, _header: &M::Header, _ancestry: &mut Iterator<Item = ExtendedHeader>) -> Vec<AncestryAction> { fn ancestry_actions(&self, _header: &Header, _ancestry: &mut Iterator<Item = ExtendedHeader>) -> Vec<AncestryAction> {
Vec::new() Vec::new()
} }
@ -523,3 +524,29 @@ pub trait EthEngine: Engine<::machine::EthereumMachine> {
// convenience wrappers for existing functions. // convenience wrappers for existing functions.
impl<T> EthEngine for T where T: Engine<::machine::EthereumMachine> { } impl<T> EthEngine for T where T: Engine<::machine::EthereumMachine> { }
/// Verifier for all blocks within an epoch with self-contained state.
pub trait EpochVerifier<M: machine::Machine>: 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<Vec<H256>> {
None
}
}
/// Special "no-op" verifier for stateless, epoch-less engines.
pub struct NoOp;
impl<M: machine::Machine> EpochVerifier<M> for NoOp {
fn verify_light(&self, _header: &Header) -> Result<(), M::Error> { Ok(()) }
}

View File

@ -17,10 +17,10 @@
use engines::Engine; use engines::Engine;
use engines::block_reward::{self, RewardKind}; use engines::block_reward::{self, RewardKind};
use ethereum_types::U256; use ethereum_types::U256;
use machine::WithRewards; use machine::Machine;
use parity_machine::{Machine, Header, LiveBlock};
use types::BlockNumber; use types::BlockNumber;
use types::header::ExtendedHeader; use types::header::{Header, ExtendedHeader};
use block::ExecutedBlock;
/// Params for a null engine. /// Params for a null engine.
#[derive(Clone, Default)] #[derive(Clone, Default)]
@ -59,23 +59,23 @@ impl<M: Default> Default for NullEngine<M> {
} }
} }
impl<M: Machine + WithRewards> Engine<M> for NullEngine<M> { impl<M: Machine> Engine<M> for NullEngine<M> {
fn name(&self) -> &str { fn name(&self) -> &str {
"NullEngine" "NullEngine"
} }
fn machine(&self) -> &M { &self.machine } 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; use std::ops::Shr;
let author = *LiveBlock::header(&*block).author(); let author = *block.header.author();
let number = LiveBlock::header(&*block).number(); let number = block.header.number();
let reward = self.params.block_reward; let reward = self.params.block_reward;
if reward == U256::zero() { return Ok(()) } if reward == U256::zero() { return Ok(()) }
let n_uncles = LiveBlock::uncles(&*block).len(); let n_uncles = block.uncles.len();
let mut rewards = Vec::new(); let mut rewards = Vec::new();
@ -84,7 +84,7 @@ impl<M: Machine + WithRewards> Engine<M> for NullEngine<M> {
rewards.push((author, RewardKind::Author, result_block_reward)); rewards.push((author, RewardKind::Author, result_block_reward));
// bestow uncle rewards. // bestow uncle rewards.
for u in LiveBlock::uncles(&*block) { for u in &block.uncles {
let uncle_author = u.author(); let uncle_author = u.author();
let result_uncle_reward = (reward * U256::from(8 + u.number() - number)).shr(3); 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)); rewards.push((*uncle_author, RewardKind::uncle(number, u.number()), result_uncle_reward));
@ -95,7 +95,7 @@ impl<M: Machine + WithRewards> Engine<M> for NullEngine<M> {
fn maximum_uncle_count(&self, _block: BlockNumber) -> usize { 2 } 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(()) Ok(())
} }

View File

@ -241,17 +241,16 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
/// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current). /// 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> { fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> {
use std::ops::Shr; use std::ops::Shr;
use parity_machine::LiveBlock;
let author = *LiveBlock::header(&*block).author(); let author = *block.header.author();
let number = LiveBlock::header(&*block).number(); let number = block.header.number();
let rewards = match self.ethash_params.block_reward_contract { let rewards = match self.ethash_params.block_reward_contract {
Some(ref c) if number >= self.ethash_params.block_reward_contract_transition => { Some(ref c) if number >= self.ethash_params.block_reward_contract_transition => {
let mut beneficiaries = Vec::new(); let mut beneficiaries = Vec::new();
beneficiaries.push((author, RewardKind::Author)); beneficiaries.push((author, RewardKind::Author));
for u in LiveBlock::uncles(&*block) { for u in &block.uncles {
let uncle_author = u.author(); let uncle_author = u.author();
beneficiaries.push((*uncle_author, RewardKind::uncle(number, u.number()))); beneficiaries.push((*uncle_author, RewardKind::uncle(number, u.number())));
} }
@ -274,7 +273,8 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
let eras_rounds = self.ethash_params.ecip1017_era_rounds; let eras_rounds = self.ethash_params.ecip1017_era_rounds;
let (eras, reward) = ecip1017_eras_block_reward(eras_rounds, reward, number); 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. // Bestow block rewards.
let mut result_block_reward = reward + reward.shr(5) * U256::from(n_uncles); let mut result_block_reward = reward + reward.shr(5) * U256::from(n_uncles);
@ -282,7 +282,7 @@ impl Engine<EthereumMachine> for Arc<Ethash> {
rewards.push((author, RewardKind::Author, result_block_reward)); rewards.push((author, RewardKind::Author, result_block_reward));
// Bestow uncle rewards. // Bestow uncle rewards.
for u in LiveBlock::uncles(&*block) { for u in &block.uncles {
let uncle_author = u.author(); let uncle_author = u.author();
let result_uncle_reward = if eras == 0 { let result_uncle_reward = if eras == 0 {
(reward * U256::from(8 + u.number() - number)).shr(3) (reward * U256::from(8 + u.number() - number)).shr(3)

View File

@ -89,7 +89,6 @@ extern crate num;
extern crate num_cpus; extern crate num_cpus;
extern crate parity_bytes as bytes; extern crate parity_bytes as bytes;
extern crate parity_crypto; extern crate parity_crypto;
extern crate parity_machine;
extern crate parity_snappy as snappy; extern crate parity_snappy as snappy;
extern crate parking_lot; extern crate parking_lot;
extern crate trie_db as trie; extern crate trie_db as trie;

View File

@ -36,7 +36,7 @@ use error::Error;
use executive::Executive; use executive::Executive;
use spec::CommonParams; use spec::CommonParams;
use state::{CleanupMode, Substate}; use state::{CleanupMode, Substate};
use trace::{NoopTracer, NoopVMTracer, Tracer, ExecutiveTracer, RewardType, Tracing}; use trace::{NoopTracer, NoopVMTracer};
use tx_filter::TransactionFilter; use tx_filter::TransactionFilter;
/// Parity tries to round block.gas_limit to multiple of this constant /// Parity tries to round block.gas_limit to multiple of this constant
@ -428,10 +428,7 @@ pub enum AuxiliaryRequest {
Both, Both,
} }
impl ::parity_machine::Machine for EthereumMachine { impl super::Machine for EthereumMachine {
type Header = Header;
type LiveBlock = ExecutedBlock;
type EngineClient = ::client::EngineClient; type EngineClient = ::client::EngineClient;
type AuxiliaryRequest = AuxiliaryRequest; type AuxiliaryRequest = AuxiliaryRequest;
type AncestryAction = ::types::ancestry_action::AncestryAction; 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 StateContext = Call<'a>;
type AuxiliaryData = AuxiliaryData<'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: // Try to round gas_limit a bit so that:
// 1) it will still be in desired range // 1) it will still be in desired range
// 2) it will be a nearest (with tendency to increase) multiple of PARITY_GAS_LIMIT_DETERMINANT // 2) it will be a nearest (with tendency to increase) multiple of PARITY_GAS_LIMIT_DETERMINANT

View File

@ -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::*;

View File

@ -17,59 +17,11 @@
//! Generalization of a state machine for a consensus engine. //! Generalization of a state machine for a consensus engine.
//! This will define traits for the header, block, and state of a blockchain. //! This will define traits for the header, block, and state of a blockchain.
extern crate ethereum_types; use ethereum_types::{U256, Address};
use block::ExecutedBlock;
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<u8>];
/// 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];
}
/// Generalization of types surrounding blockchain-suitable state machines. /// Generalization of types surrounding blockchain-suitable state machines.
pub trait Machine: for<'a> LocalizedMachine<'a> { pub trait Machine: for<'a> LocalizedMachine<'a> {
/// The block header type.
type Header: Header;
/// The live block type.
type LiveBlock: LiveBlock<Header=Self::Header>;
/// A handle to a blockchain client for this machine. /// A handle to a blockchain client for this machine.
type EngineClient: ?Sized; type EngineClient: ?Sized;
/// A description of needed auxiliary data. /// 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. /// Get the balance, in base units, associated with an account.
/// Extracts data from the live block. /// Extracts data from the live block.
fn balance(&self, live: &Self::LiveBlock, address: &Address) -> Result<U256, Self::Error>; fn balance(&self, live: &ExecutedBlock, address: &Address) -> Result<U256, Self::Error>;
/// Increment the balance of an account in the state of the live block. /// 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. /// Machine-related types localized to a specific lifetime.

View File

@ -135,7 +135,7 @@ impl Create {
} }
/// Reward type. /// Reward type.
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone, Copy)]
pub enum RewardType { pub enum RewardType {
/// Block /// Block
Block, Block,

View File

@ -11,7 +11,6 @@ ethkey = { path = "../../accounts/ethkey" }
heapsize = "0.4" heapsize = "0.4"
keccak-hash = "0.1" keccak-hash = "0.1"
parity-bytes = "0.1" parity-bytes = "0.1"
parity-machine = { path = "../../machine" }
rlp = { version = "0.3.0", features = ["ethereum"] } rlp = { version = "0.3.0", features = ["ethereum"] }
rlp_derive = { path = "../../util/rlp-derive" } rlp_derive = { path = "../../util/rlp-derive" }
unexpected = { path = "../../util/unexpected" } unexpected = { path = "../../util/unexpected" }

View File

@ -71,28 +71,3 @@ impl Decodable for PendingTransition {
} }
} }
/// Verifier for all blocks within an epoch with self-contained state.
pub trait EpochVerifier<M: ::parity_machine::Machine>: 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<Vec<H256>> {
None
}
}
/// Special "no-op" verifier for stateless, epoch-less engines.
pub struct NoOp;
impl<M: ::parity_machine::Machine> EpochVerifier<M> for NoOp {
fn verify_light(&self, _header: &M::Header) -> Result<(), M::Error> { Ok(()) }
}

View File

@ -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<u8>] { 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<u8>] { self.header.seal() }
fn author(&self) -> &Address { self.header.author() }
fn number(&self) -> BlockNumber { self.header.number() }
}
impl ExtendedHeader { impl ExtendedHeader {
/// Returns combined difficulty of all ancestors together with the difficulty of this header. /// Returns combined difficulty of all ancestors together with the difficulty of this header.
pub fn total_score(&self) -> U256 { pub fn total_score(&self) -> U256 {

View File

@ -39,7 +39,6 @@ extern crate ethkey;
extern crate heapsize; extern crate heapsize;
extern crate keccak_hash as hash; extern crate keccak_hash as hash;
extern crate parity_bytes as bytes; extern crate parity_bytes as bytes;
extern crate parity_machine;
extern crate rlp; extern crate rlp;
extern crate unexpected; extern crate unexpected;

View File

@ -1,8 +0,0 @@
[package]
name = "parity-machine"
version = "0.1.0"
description = "Generalization of a state machine for consensus engines"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
ethereum-types = "0.4"