From f9a8cc3eb61a96b47bbe8507ab4b4a1322cd2e04 Mon Sep 17 00:00:00 2001 From: SeongChan Lee Date: Tue, 7 May 2019 11:21:48 +0900 Subject: [PATCH 1/4] Remove unused is_epoch_begin `is_epoch_begin` flag which is determined by the result of `epoch_tranistion` call doesn't make any differences whether it is true or false since `on_new_block`, `on_epoch_begin` does nothing on it. So it is safe to remove. We can even remove reading `epoch_transition`. --- core/src/block.rs | 8 +++----- core/src/client/client.rs | 2 -- core/src/client/importer.rs | 3 +-- core/src/client/test_client.rs | 2 +- core/src/consensus/cuckoo/mod.rs | 2 +- core/src/consensus/mod.rs | 2 +- core/src/consensus/simple_poa/mod.rs | 2 +- core/src/consensus/solo/mod.rs | 2 +- core/src/consensus/tendermint/engine.rs | 3 +-- core/src/consensus/tendermint/mod.rs | 2 +- core/src/consensus/tendermint/worker.rs | 15 +++------------ core/src/consensus/validator_set/mod.rs | 11 ----------- core/src/miner/sealing_queue.rs | 2 +- 13 files changed, 15 insertions(+), 41 deletions(-) diff --git a/core/src/block.rs b/core/src/block.rs index 74ae825f26..552dbc249f 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -131,7 +131,6 @@ impl<'x> OpenBlock<'x> { parent: &Header, author: Address, extra_data: Bytes, - is_epoch_begin: bool, ) -> Result { let number = parent.number() + 1; let state = TopLevelState::from_existing(db, *parent.state_root()).map_err(StateError::from)?; @@ -150,7 +149,7 @@ impl<'x> OpenBlock<'x> { engine.machine().populate_from_parent(&mut r.block.header, parent); engine.populate_from_parent(&mut r.block.header, parent); - engine.on_new_block(&mut r.block, is_epoch_begin)?; + engine.on_new_block(&mut r.block)?; Ok(r) } @@ -442,9 +441,8 @@ pub fn enact( client: &C, db: StateDB, parent: &Header, - is_epoch_begin: bool, ) -> Result { - let mut b = OpenBlock::try_new(engine, db, parent, Address::default(), vec![], is_epoch_begin)?; + let mut b = OpenBlock::try_new(engine, db, parent, Address::default(), vec![])?; b.populate_from(header); b.push_transactions(transactions, client, parent.number(), parent.timestamp())?; @@ -464,7 +462,7 @@ mod tests { let scheme = Scheme::new_test(); let genesis_header = scheme.genesis_header(); let db = scheme.ensure_genesis_state(get_temp_state_db()).unwrap(); - let b = OpenBlock::try_new(&*scheme.engine, db, &genesis_header, Address::default(), vec![], false).unwrap(); + let b = OpenBlock::try_new(&*scheme.engine, db, &genesis_header, Address::default(), vec![]).unwrap(); let parent_transactions_root = *genesis_header.transactions_root(); let b = b.close_and_lock(parent_transactions_root).unwrap(); let _ = b.seal(&*scheme.engine, vec![]); diff --git a/core/src/client/client.rs b/core/src/client/client.rs index 16c4bb0706..0e1dad8284 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -821,14 +821,12 @@ impl BlockProducer for Client { let parent_hash = self.block_hash(&parent_block_id).expect("parent exist always"); let parent_header = chain.block_header(&parent_hash).expect("parent exist always"); - let is_epoch_begin = chain.epoch_transition(parent_header.number(), parent_hash).is_some(); OpenBlock::try_new( engine, self.state_db.read().clone(&parent_header.state_root()), &parent_header, author, extra_data, - is_epoch_begin, ).expect("OpenBlock::new only fails if parent state root invalid; state root of best block's header is never invalid; qed") } } diff --git a/core/src/client/importer.rs b/core/src/client/importer.rs index a18dfbff1e..5bde212db0 100644 --- a/core/src/client/importer.rs +++ b/core/src/client/importer.rs @@ -304,8 +304,7 @@ impl Importer { // Enact Verified Block let db = client.state_db().read().clone(&parent.state_root()); - let is_epoch_begin = chain.epoch_transition(parent.number(), *header.parent_hash()).is_some(); - let enact_result = enact(&block.header, &block.transactions, engine, client, db, &parent, is_epoch_begin); + let enact_result = enact(&block.header, &block.transactions, engine, client, db, &parent); let locked_block = enact_result.map_err(|e| { cwarn!(CLIENT, "Block import failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e); })?; diff --git a/core/src/client/test_client.rs b/core/src/client/test_client.rs index 79cbe554a1..2a0ace5f41 100644 --- a/core/src/client/test_client.rs +++ b/core/src/client/test_client.rs @@ -313,7 +313,7 @@ impl BlockProducer for TestBlockChainClient { let genesis_header = self.scheme.genesis_header(); let db = get_temp_state_db(); - let mut open_block = OpenBlock::try_new(engine, db, &genesis_header, author, extra_data, false) + let mut open_block = OpenBlock::try_new(engine, db, &genesis_header, author, extra_data) .expect("Opening block for tests will not fail."); // TODO [todr] Override timestamp for predictability (set_timestamp_now kind of sucks) open_block.set_timestamp(*self.latest_block_timestamp.read()); diff --git a/core/src/consensus/cuckoo/mod.rs b/core/src/consensus/cuckoo/mod.rs index decdd401b5..d06b3adb71 100644 --- a/core/src/consensus/cuckoo/mod.rs +++ b/core/src/consensus/cuckoo/mod.rs @@ -251,7 +251,7 @@ mod tests { let engine = &*scheme.engine; let db = scheme.ensure_genesis_state(get_temp_state_db()).unwrap(); let header = Header::default(); - let block = OpenBlock::try_new(engine, db, &header, Default::default(), vec![], false).unwrap(); + let block = OpenBlock::try_new(engine, db, &header, Default::default(), vec![]).unwrap(); let mut executed_block = block.block().clone(); assert!(engine.on_close_block(&mut executed_block).is_ok()); diff --git a/core/src/consensus/mod.rs b/core/src/consensus/mod.rs index 0462afeb15..5ef89fc362 100644 --- a/core/src/consensus/mod.rs +++ b/core/src/consensus/mod.rs @@ -222,7 +222,7 @@ pub trait ConsensusEngine: Sync + Send { fn stop(&self) {} /// Block transformation functions, before the transactions. - fn on_new_block(&self, _block: &mut ExecutedBlock, _epoch_begin: bool) -> Result<(), Error> { + fn on_new_block(&self, _block: &mut ExecutedBlock) -> Result<(), Error> { Ok(()) } diff --git a/core/src/consensus/simple_poa/mod.rs b/core/src/consensus/simple_poa/mod.rs index 30802ad4d7..8c4e43d76b 100644 --- a/core/src/consensus/simple_poa/mod.rs +++ b/core/src/consensus/simple_poa/mod.rs @@ -181,7 +181,7 @@ mod tests { let engine = &*scheme.engine; let db = scheme.ensure_genesis_state(get_temp_state_db()).unwrap(); let genesis_header = scheme.genesis_header(); - let b = OpenBlock::try_new(engine, db, &genesis_header, Default::default(), vec![], false).unwrap(); + let b = OpenBlock::try_new(engine, db, &genesis_header, Default::default(), vec![]).unwrap(); let parent_transactions_root = *genesis_header.transactions_root(); let b = b.close_and_lock(parent_transactions_root).unwrap(); if let Some(seal) = engine.generate_seal(b.block(), &genesis_header).seal_fields() { diff --git a/core/src/consensus/solo/mod.rs b/core/src/consensus/solo/mod.rs index aed8b6aabf..89db756142 100644 --- a/core/src/consensus/solo/mod.rs +++ b/core/src/consensus/solo/mod.rs @@ -133,7 +133,7 @@ mod tests { let engine = &*scheme.engine; let db = scheme.ensure_genesis_state(get_temp_state_db()).unwrap(); let genesis_header = scheme.genesis_header(); - let b = OpenBlock::try_new(engine, db, &genesis_header, Default::default(), vec![], false).unwrap(); + let b = OpenBlock::try_new(engine, db, &genesis_header, Default::default(), vec![]).unwrap(); let parent_transactions_root = *genesis_header.transactions_root(); let b = b.close_and_lock(parent_transactions_root).unwrap(); if let Some(seal) = engine.generate_seal(b.block(), &genesis_header).seal_fields() { diff --git a/core/src/consensus/tendermint/engine.rs b/core/src/consensus/tendermint/engine.rs index 653a12e609..2e86785bd8 100644 --- a/core/src/consensus/tendermint/engine.rs +++ b/core/src/consensus/tendermint/engine.rs @@ -143,12 +143,11 @@ impl ConsensusEngine for Tendermint { fn stop(&self) {} - fn on_new_block(&self, block: &mut ExecutedBlock, epoch_begin: bool) -> Result<(), Error> { + fn on_new_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { let (result, receiver) = crossbeam::bounded(1); self.inner .send(worker::Event::OnNewBlock { header: Box::from(block.header().clone()), - epoch_begin, result, }) .unwrap(); diff --git a/core/src/consensus/tendermint/mod.rs b/core/src/consensus/tendermint/mod.rs index a344d4cb9c..12d87e99ad 100644 --- a/core/src/consensus/tendermint/mod.rs +++ b/core/src/consensus/tendermint/mod.rs @@ -150,7 +150,7 @@ mod tests { let db = get_temp_state_db(); let db = scheme.ensure_genesis_state(db).unwrap(); let genesis_header = scheme.genesis_header(); - let b = OpenBlock::try_new(scheme.engine.as_ref(), db, &genesis_header, proposer, vec![], false).unwrap(); + let b = OpenBlock::try_new(scheme.engine.as_ref(), db, &genesis_header, proposer, vec![]).unwrap(); let b = b.close(*genesis_header.transactions_root()).unwrap(); if let Some(seal) = scheme.engine.generate_seal(b.block(), &genesis_header).seal_fields() { (b, seal) diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index 3493fda37c..2568e9077e 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -119,7 +119,6 @@ pub enum Event { OnTimeout(usize), OnNewBlock { header: Box
, - epoch_begin: bool, result: crossbeam::Sender>, }, HandleMessages { @@ -269,10 +268,9 @@ impl Worker { } Ok(Event::OnNewBlock { header, - epoch_begin, result, }) => { - result.send(inner.on_new_block(&header, epoch_begin)).unwrap(); + result.send(inner.on_new_block(&header)).unwrap(); } Ok(Event::HandleMessages { messages, @@ -1256,15 +1254,8 @@ impl Worker { nonce < self.timeout_token_nonce } - fn on_new_block(&self, header: &Header, epoch_begin: bool) -> Result<(), Error> { - if !epoch_begin { - return Ok(()) - } - - // genesis is never a new block, but might as well check. - let first = header.number() == 0; - - self.validators.on_epoch_begin(first, header) + fn on_new_block(&self, _header: &Header) -> Result<(), Error> { + Ok(()) } fn handle_message(&mut self, rlp: &[u8], is_restoring: bool) -> Result<(), EngineError> { diff --git a/core/src/consensus/validator_set/mod.rs b/core/src/consensus/validator_set/mod.rs index 1cc040a715..623baf8024 100644 --- a/core/src/consensus/validator_set/mod.rs +++ b/core/src/consensus/validator_set/mod.rs @@ -22,8 +22,6 @@ use primitives::{Bytes, H256}; use self::validator_list::ValidatorList; use crate::client::EngineClient; -use crate::error::Error; -use crate::header::Header; pub mod null_validator; pub mod validator_list; @@ -57,15 +55,6 @@ pub trait ValidatorSet: Send + Sync { /// Returns the current number of validators. fn count(&self, parent: &H256) -> usize; - /// Signalling that a new epoch has begun. - /// - /// The caller provided here may not generate proofs. - /// - /// `first` is true if this is the first block in the set. - fn on_epoch_begin(&self, _first: bool, _header: &Header) -> Result<(), Error> { - Ok(()) - } - /// Notifies about malicious behaviour. fn report_malicious(&self, _validator: &Address, _set_block: BlockNumber, _block: BlockNumber, _proof: Bytes) {} /// Notifies about benign misbehaviour. diff --git a/core/src/miner/sealing_queue.rs b/core/src/miner/sealing_queue.rs index 3137a08853..d488c64cc4 100644 --- a/core/src/miner/sealing_queue.rs +++ b/core/src/miner/sealing_queue.rs @@ -85,7 +85,7 @@ mod tests { let scheme = Scheme::new_test(); let genesis_header = scheme.genesis_header(); let db = scheme.ensure_genesis_state(get_temp_state_db()).unwrap(); - let b = OpenBlock::try_new(&*scheme.engine, db, &genesis_header, address, vec![], false).unwrap(); + let b = OpenBlock::try_new(&*scheme.engine, db, &genesis_header, address, vec![]).unwrap(); let parent_transactions_root = *genesis_header.transactions_root(); b.close(parent_transactions_root).unwrap() } From c5bdd55bf95a0a23bea2b6ede29924703f63b4c8 Mon Sep 17 00:00:00 2001 From: SeongChan Lee Date: Tue, 7 May 2019 11:24:25 +0900 Subject: [PATCH 2/4] Remove unused on_new_block `on_new_block` does nothing after removing `on_epoch_begin` --- core/src/block.rs | 2 -- core/src/consensus/mod.rs | 5 ----- core/src/consensus/tendermint/engine.rs | 11 ----------- core/src/consensus/tendermint/worker.rs | 14 -------------- 4 files changed, 32 deletions(-) diff --git a/core/src/block.rs b/core/src/block.rs index 552dbc249f..789082227b 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -149,8 +149,6 @@ impl<'x> OpenBlock<'x> { engine.machine().populate_from_parent(&mut r.block.header, parent); engine.populate_from_parent(&mut r.block.header, parent); - engine.on_new_block(&mut r.block)?; - Ok(r) } diff --git a/core/src/consensus/mod.rs b/core/src/consensus/mod.rs index 5ef89fc362..522c473dad 100644 --- a/core/src/consensus/mod.rs +++ b/core/src/consensus/mod.rs @@ -221,11 +221,6 @@ pub trait ConsensusEngine: Sync + Send { /// Stops any services that the may hold the Engine and makes it safe to drop. fn stop(&self) {} - /// Block transformation functions, before the transactions. - fn on_new_block(&self, _block: &mut ExecutedBlock) -> Result<(), Error> { - Ok(()) - } - /// Block transformation functions, after the transactions. fn on_close_block(&self, _block: &mut ExecutedBlock) -> Result<(), Error> { Ok(()) diff --git a/core/src/consensus/tendermint/engine.rs b/core/src/consensus/tendermint/engine.rs index 2e86785bd8..2d20dcd509 100644 --- a/core/src/consensus/tendermint/engine.rs +++ b/core/src/consensus/tendermint/engine.rs @@ -143,17 +143,6 @@ impl ConsensusEngine for Tendermint { fn stop(&self) {} - fn on_new_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { - let (result, receiver) = crossbeam::bounded(1); - self.inner - .send(worker::Event::OnNewBlock { - header: Box::from(block.header().clone()), - result, - }) - .unwrap(); - receiver.recv().unwrap() - } - fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { let author = *block.header().author(); let (total_fee, min_fee) = { diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index 2568e9077e..bf0e898328 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -117,10 +117,6 @@ pub enum Event { result: crossbeam::Sender, }, OnTimeout(usize), - OnNewBlock { - header: Box
, - result: crossbeam::Sender>, - }, HandleMessages { messages: Vec>, result: crossbeam::Sender>, @@ -266,12 +262,6 @@ impl Worker { Ok(Event::OnTimeout(token)) => { inner.on_timeout(token); } - Ok(Event::OnNewBlock { - header, - result, - }) => { - result.send(inner.on_new_block(&header)).unwrap(); - } Ok(Event::HandleMessages { messages, result, @@ -1254,10 +1244,6 @@ impl Worker { nonce < self.timeout_token_nonce } - fn on_new_block(&self, _header: &Header) -> Result<(), Error> { - Ok(()) - } - fn handle_message(&mut self, rlp: &[u8], is_restoring: bool) -> Result<(), EngineError> { fn fmt_err(x: T) -> EngineError { EngineError::MalformedMessage(format!("{:?}", x)) From c44c56af2ef8087ac527648e21aa56767b2e1da5 Mon Sep 17 00:00:00 2001 From: SeongChan Lee Date: Tue, 7 May 2019 12:01:54 +0900 Subject: [PATCH 3/4] Remove unused epoch_transition `epoch_transition` is not used anymore after removing `on_epoch_begin` --- core/src/blockchain/blockchain.rs | 125 +----------------------------- 1 file changed, 1 insertion(+), 124 deletions(-) diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index 360ddbf3d0..c96b3ed8d1 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -14,7 +14,6 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use std::mem; use std::sync::Arc; use ctypes::BlockNumber; @@ -25,7 +24,7 @@ use rlp::RlpStream; use super::block_info::BestBlockChanged; use super::body_db::{BodyDB, BodyProvider}; -use super::extras::{BlockDetails, EpochTransitions, TransactionAddress, EPOCH_KEY_PREFIX}; +use super::extras::{BlockDetails, EpochTransitions, TransactionAddress}; use super::headerchain::{HeaderChain, HeaderProvider}; use super::invoice_db::{InvoiceDB, InvoiceProvider}; use super::route::{tree_route, ImportRoute}; @@ -362,128 +361,6 @@ impl BlockChain { batch.write(db::COL_EXTRA, &epoch_num, &transitions); } } - - /// Iterate over all epoch transitions. - /// This will only return transitions within the canonical chain. - #[allow(dead_code)] - pub fn epoch_transitions(&self) -> EpochTransitionIter { - let iter = self.db.iter_from_prefix(db::COL_EXTRA, &EPOCH_KEY_PREFIX[..]); - EpochTransitionIter { - chain: self, - prefix_iter: iter, - } - } - - /// Get a specific epoch transition by block number and provided block hash. - pub fn epoch_transition(&self, block_num: u64, block_hash: H256) -> Option { - ctrace!(BLOCKCHAIN, "Loading epoch transition at block {}, {}", block_num, block_hash); - - self.db.read(db::COL_EXTRA, &block_num).and_then(|transitions: EpochTransitions| { - transitions.candidates.into_iter().find(|c| c.block_hash == block_hash) - }) - } - - /// Get the transition to the epoch the given parent hash is part of - /// or transitions to. - /// This will give the epoch that any children of this parent belong to. - /// - /// The block corresponding the the parent hash must be stored already. - #[allow(dead_code)] - pub fn epoch_transition_for(&self, parent_hash: H256) -> Option { - // slow path: loop back block by block - #[allow(clippy::identity_conversion)] - // This is a false alarm. https://github.com/rust-lang/rust-clippy/issues/3944 - for hash in self.ancestry_iter(parent_hash)? { - let details = self.block_details(&hash)?; - - // look for transition in database. - if let Some(transition) = self.epoch_transition(details.number, hash) { - return Some(transition) - } - - // canonical hash -> fast breakout: - // get the last epoch transition up to this block. - // - // if `block_hash` is canonical it will only return transitions up to - // the parent. - if self.block_hash(details.number)? == hash { - return self.epoch_transitions().map(|(_, t)| t).take_while(|t| t.block_number <= details.number).last() - } - } - - // should never happen as the loop will encounter genesis before concluding. - None - } - - /// Iterator that lists `first` and then all of `first`'s ancestors, by hash. - #[allow(dead_code)] - pub fn ancestry_iter(&self, first: H256) -> Option { - if self.is_known(&first) { - Some(AncestryIter { - current: first, - chain: self, - }) - } else { - None - } - } -} - -/// An iterator which walks the blockchain towards the genesis. -#[derive(Clone)] -pub struct AncestryIter<'a> { - current: H256, - chain: &'a BlockChain, -} - -impl<'a> Iterator for AncestryIter<'a> { - type Item = H256; - fn next(&mut self) -> Option { - if self.current.is_zero() { - None - } else { - self.chain.block_details(&self.current).map(|details| mem::replace(&mut self.current, details.parent)) - } - } -} - -type TransitionIterInternal<'a> = Box, Box<[u8]>)> + 'a>; -/// An iterator which walks all epoch transitions. -/// Returns epoch transitions. -#[allow(dead_code)] -pub struct EpochTransitionIter<'a> { - chain: &'a BlockChain, - prefix_iter: TransitionIterInternal<'a>, -} - -impl<'a> Iterator for EpochTransitionIter<'a> { - type Item = (u64, EpochTransition); - - fn next(&mut self) -> Option { - loop { - // some epochs never occurred on the main chain. - let (key, val) = self.prefix_iter.next()?; - - // iterator may continue beyond values beginning with this - // prefix. - if !key.starts_with(&EPOCH_KEY_PREFIX[..]) { - return None - } - - let transitions: EpochTransitions = ::rlp::decode(&val[..]); - - // if there are multiple candidates, at most one will be on the - // canon chain. - for transition in transitions.candidates.into_iter() { - let is_in_canon_chain = - self.chain.block_hash(transition.block_number).map_or(false, |hash| hash == transition.block_hash); - - if is_in_canon_chain { - return Some((transitions.number, transition)) - } - } - } - } } /// Interface for querying blocks by hash and by number. From fcace7157c36efbbfb2538a7a8e099005d3f9405 Mon Sep 17 00:00:00 2001 From: SeongChan Lee Date: Tue, 7 May 2019 12:30:29 +0900 Subject: [PATCH 4/4] Remove unused insert_epoch_transition Inserted `EpochTransition` is not read anymore and inserting it does not change state. So removing it doesn't introduce breaking change unless reusing the key index. --- core/src/blockchain/blockchain.rs | 29 +------------- core/src/blockchain/extras.rs | 47 +--------------------- core/src/client/importer.rs | 31 +-------------- core/src/consensus/epoch.rs | 52 ------------------------- core/src/consensus/mod.rs | 15 ------- core/src/consensus/simple_poa/mod.rs | 9 ----- core/src/consensus/tendermint/engine.rs | 17 -------- 7 files changed, 5 insertions(+), 195 deletions(-) delete mode 100644 core/src/consensus/epoch.rs diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index c96b3ed8d1..abec2d35d9 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -24,14 +24,13 @@ use rlp::RlpStream; use super::block_info::BestBlockChanged; use super::body_db::{BodyDB, BodyProvider}; -use super::extras::{BlockDetails, EpochTransitions, TransactionAddress}; +use super::extras::{BlockDetails, TransactionAddress}; use super::headerchain::{HeaderChain, HeaderProvider}; use super::invoice_db::{InvoiceDB, InvoiceProvider}; use super::route::{tree_route, ImportRoute}; use crate::blockchain_info::BlockChainInfo; -use crate::consensus::epoch::Transition as EpochTransition; use crate::consensus::CodeChainEngine; -use crate::db::{self, Readable, Writable}; +use crate::db; use crate::encoded; use crate::invoice::Invoice; use crate::transaction::LocalizedTransaction; @@ -53,8 +52,6 @@ pub struct BlockChain { body_db: BodyDB, invoice_db: InvoiceDB, - db: Arc, - pending_best_block_hash: RwLock>, pending_best_proposal_block_hash: RwLock>, } @@ -96,8 +93,6 @@ impl BlockChain { body_db: BodyDB::new(&genesis_block, db.clone()), invoice_db: InvoiceDB::new(db.clone()), - db, - pending_best_block_hash: RwLock::new(None), pending_best_proposal_block_hash: RwLock::new(None), } @@ -341,26 +336,6 @@ impl BlockChain { pub fn best_proposal_header(&self) -> encoded::Header { self.headerchain.best_proposal_header() } - - /// Insert an epoch transition. Provide an epoch number being transitioned to - /// and epoch transition object. - /// - /// The block the transition occurred at should have already been inserted into the chain. - pub fn insert_epoch_transition(&self, batch: &mut DBTransaction, epoch_num: u64, transition: EpochTransition) { - let mut transitions = match self.db.read(db::COL_EXTRA, &epoch_num) { - Some(existing) => existing, - None => EpochTransitions { - number: epoch_num, - candidates: Vec::with_capacity(1), - }, - }; - - // ensure we don't write any duplicates. - if transitions.candidates.iter().find(|c| c.block_hash == transition.block_hash).is_none() { - transitions.candidates.push(transition); - batch.write(db::COL_EXTRA, &epoch_num, &transitions); - } - } } /// Interface for querying blocks by hash and by number. diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index 8daa900eb0..7ef5aea063 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -14,14 +14,11 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use std::io::Write; -use std::ops::{self, Add, AddAssign, Deref, Sub, SubAssign}; +use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; use ctypes::BlockNumber; -use kvdb::PREFIX_LEN as DB_PREFIX_LEN; use primitives::{H256, H264, U256}; -use crate::consensus::epoch::Transition as EpochTransition; use crate::db::Key; use crate::types::TransactionId; @@ -36,8 +33,7 @@ enum ExtrasIndex { ParcelAddress = 2, /// Transaction address index TransactionAddress = 3, - /// Epoch transition data index. - EpochTransitions = 4, + // (Reserved) = 4, // (Reserved) = 5, } @@ -97,38 +93,6 @@ impl Key for H256 { } } -/// length of epoch keys. -const EPOCH_KEY_LEN: usize = DB_PREFIX_LEN + 16; - -/// epoch key prefix. -/// used to iterate over all epoch transitions in order from genesis. -pub const EPOCH_KEY_PREFIX: &[u8; DB_PREFIX_LEN] = - &[ExtrasIndex::EpochTransitions as u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - -pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]); - -impl ops::Deref for EpochTransitionsKey { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - &self.0[..] - } -} - -impl Key for u64 { - type Target = EpochTransitionsKey; - - fn key(&self) -> Self::Target { - let mut arr = [0u8; EPOCH_KEY_LEN]; - arr[..DB_PREFIX_LEN].copy_from_slice(&EPOCH_KEY_PREFIX[..]); - - write!(&mut arr[DB_PREFIX_LEN..], "{:016x}", self) - .expect("format arg is valid; no more than 16 chars will be written; qed"); - - EpochTransitionsKey(arr) - } -} - /// Familial details concerning a block #[derive(Debug, Clone, RlpEncodable, RlpDecodable)] pub struct BlockDetails { @@ -161,13 +125,6 @@ pub struct TransactionAddresses { addresses: Vec, } -/// Candidate transitions to an epoch with specific number. -#[derive(Clone, RlpEncodable, RlpDecodable)] -pub struct EpochTransitions { - pub number: u64, - pub candidates: Vec, -} - impl TransactionAddresses { pub fn new(address: TransactionAddress) -> Self { Self { diff --git a/core/src/client/importer.rs b/core/src/client/importer.rs index 5bde212db0..e562022f24 100644 --- a/core/src/client/importer.rs +++ b/core/src/client/importer.rs @@ -27,8 +27,7 @@ use rlp::Encodable; use super::{BlockChainTrait, Client, ClientConfig}; use crate::block::{enact, IsBlock, LockedBlock}; -use crate::blockchain::{BlockChain, BodyProvider, HeaderProvider, ImportRoute}; -use crate::consensus::epoch::Transition as EpochTransition; +use crate::blockchain::{BodyProvider, HeaderProvider, ImportRoute}; use crate::consensus::CodeChainEngine; use crate::encoded; use crate::error::Error; @@ -207,8 +206,6 @@ impl Importer { client.db().write_buffered(batch); chain.commit(); - self.check_epoch_end(block.header(), &chain, client); - if hash == chain.best_block_hash() { let mut state_db = client.state_db().write(); let state = block.state(); @@ -218,27 +215,6 @@ impl Importer { route } - // check for ending of epoch and write transition if it occurs. - fn check_epoch_end(&self, header: &Header, chain: &BlockChain, client: &Client) { - let is_epoch_end = self.engine.is_epoch_end(header, &(|hash| chain.block_header(&hash))); - - if let Some(proof) = is_epoch_end { - cdebug!(CLIENT, "Epoch transition at block {}", header.hash()); - - let mut batch = DBTransaction::new(); - chain.insert_epoch_transition(&mut batch, header.number(), EpochTransition { - block_hash: header.hash(), - block_number: header.number(), - proof, - }); - - // always write the batch directly since epoch transition proofs are - // fetched from a DB iterator and DB iterators are only available on - // flushed data. - client.db().write(batch).expect("DB flush failed"); - } - } - fn check_and_close_block(&self, block: &PreverifiedBlock, client: &Client) -> Result { let engine = &*self.engine; let header = &block.header; @@ -424,15 +400,10 @@ impl Importer { let chain = client.block_chain(); let mut batch = DBTransaction::new(); - // FIXME: Check if this line is still necessary. - // self.check_epoch_end_signal(header, &chain, &mut batch); let route = chain.insert_header(&mut batch, &HeaderView::new(&header.rlp_bytes()), self.engine.borrow()); client.db().write_buffered(batch); chain.commit(); - // FIXME: Check if this line is still necessary. - // self.check_epoch_end(&header, &chain, client); - route } } diff --git a/core/src/consensus/epoch.rs b/core/src/consensus/epoch.rs deleted file mode 100644 index f891df20e8..0000000000 --- a/core/src/consensus/epoch.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018 Kodebox, Inc. -// This file is part of CodeChain. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program 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 Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . - -use primitives::H256; -use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp}; - -/// A full epoch transition. -#[derive(Debug, Clone)] -pub struct Transition { - /// Block hash at which the transition occurred. - pub block_hash: H256, - /// Block number at which the transition occurred. - pub block_number: u64, - /// "transition/epoch" proof from the engine combined with a finality proof. - pub proof: Vec, -} - -impl Encodable for Transition { - fn rlp_append(&self, s: &mut RlpStream) { - s.begin_list(3).append(&self.block_hash).append(&self.block_number).append(&self.proof); - } -} - -impl Decodable for Transition { - fn decode(rlp: &UntrustedRlp) -> Result { - let item_count = rlp.item_count()?; - if item_count != 3 { - return Err(DecoderError::RlpInvalidLength { - expected: 3, - got: item_count, - }) - } - Ok(Transition { - block_hash: rlp.val_at(0)?, - block_number: rlp.val_at(1)?, - proof: rlp.val_at(2)?, - }) - } -} diff --git a/core/src/consensus/mod.rs b/core/src/consensus/mod.rs index 522c473dad..35137db88b 100644 --- a/core/src/consensus/mod.rs +++ b/core/src/consensus/mod.rs @@ -16,7 +16,6 @@ mod blake_pow; mod cuckoo; -pub mod epoch; mod null_engine; mod signer; mod simple_poa; @@ -200,17 +199,6 @@ pub trait ConsensusEngine: Sync + Send { Ok(()) } - /// Whether a block is the end of an epoch. - /// - /// This either means that an immediate transition occurs or a block signalling transition - /// has reached finality. The `Headers` given are not guaranteed to return any blocks - /// from any epoch other than the current. - /// - /// Return optional transition proof. - fn is_epoch_end(&self, _chain_head: &Header, _chain: &Headers
) -> Option> { - None - } - /// 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 Header, _parent: &Header) {} @@ -283,9 +271,6 @@ pub trait ConsensusEngine: Sync + Send { } } -/// Type alias for a function we can get headers by hash through. -pub type Headers<'a, H> = Fn(H256) -> Option + 'a; - /// Voting errors. #[derive(Debug)] pub enum EngineError { diff --git a/core/src/consensus/simple_poa/mod.rs b/core/src/consensus/simple_poa/mod.rs index 8c4e43d76b..8b3a5d5550 100644 --- a/core/src/consensus/simple_poa/mod.rs +++ b/core/src/consensus/simple_poa/mod.rs @@ -117,15 +117,6 @@ impl ConsensusEngine for SimplePoA { verify_external(header, &*self.validators) } - fn is_epoch_end(&self, chain_head: &Header, _chain: &super::Headers
) -> Option> { - let first = chain_head.number() == 0; - if first { - Some(Vec::new()) - } else { - None - } - } - fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { let author = *block.header().author(); let total_reward = self.block_reward(block.header().number()) diff --git a/core/src/consensus/tendermint/engine.rs b/core/src/consensus/tendermint/engine.rs index 2d20dcd509..df7592c0b6 100644 --- a/core/src/consensus/tendermint/engine.rs +++ b/core/src/consensus/tendermint/engine.rs @@ -22,7 +22,6 @@ use ckey::Address; use cnetwork::NetworkService; use crossbeam_channel as crossbeam; use cstate::ActionHandler; -use ctypes::BlockNumber; use primitives::H256; use super::super::stake; @@ -114,16 +113,6 @@ impl ConsensusEngine for Tendermint { receiver.recv().unwrap() } - fn is_epoch_end(&self, chain_head: &Header, _chain: &super::super::Headers
) -> Option> { - let first = chain_head.number() == 0; - if first { - let change = combine_proofs(chain_head.number(), &[], &[]); - return Some(change) - } - - None - } - fn populate_from_parent(&self, header: &mut Header, _parent: &Header) { let (result, receiver) = crossbeam::bounded(1); self.inner @@ -249,9 +238,3 @@ impl ConsensusEngine for Tendermint { &self.action_handlers } } - -fn combine_proofs(signal_number: BlockNumber, set_proof: &[u8], finality_proof: &[u8]) -> Vec { - let mut stream = ::rlp::RlpStream::new_list(3); - stream.append(&signal_number).append(&set_proof).append(&finality_proof); - stream.out() -}