From f87dea6242d752761688237854ca067f30a31f1f Mon Sep 17 00:00:00 2001 From: SeungMin Lee Date: Wed, 12 Feb 2020 15:13:52 +0900 Subject: [PATCH 1/4] Remove the logic related to the score in queue --- core/src/client/client.rs | 2 +- core/src/verification/queue/kind.rs | 25 +++---------------- core/src/verification/queue/mod.rs | 38 ++++++----------------------- 3 files changed, 12 insertions(+), 53 deletions(-) diff --git a/core/src/client/client.rs b/core/src/client/client.rs index b0afd768d0..58be32eac4 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -483,7 +483,7 @@ impl ConsensusClient for Client {} impl BlockChainTrait for Client { fn chain_info(&self) -> BlockChainInfo { let mut chain_info = self.block_chain().chain_info(); - chain_info.pending_total_score = chain_info.best_score + self.importer.block_queue.total_score(); + chain_info.pending_total_score = chain_info.best_score; chain_info } diff --git a/core/src/verification/queue/kind.rs b/core/src/verification/queue/kind.rs index 83bc117f19..f34761fe44 100644 --- a/core/src/verification/queue/kind.rs +++ b/core/src/verification/queue/kind.rs @@ -14,16 +14,13 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . -use ctypes::BlockHash; -use primitives::U256; -use rlp::*; - pub use self::blocks::Blocks; pub use self::headers::Headers; - use crate::consensus::CodeChainEngine; use crate::error::Error; use crate::service::ClientIoMessage; +use ctypes::BlockHash; +use rlp::*; /// Something which can produce a hash and a parent hash. pub trait BlockLike { @@ -32,9 +29,6 @@ pub trait BlockLike { /// Get the hash of this item's parent. fn parent_hash(&self) -> BlockHash; - - /// Get the score of this item. - fn score(&self) -> U256; } /// Memory usage in the verification queue @@ -86,7 +80,6 @@ pub trait Kind: 'static + Sized + Send + Sync { /// Verification for headers. pub mod headers { use ctypes::{BlockHash, Header}; - use primitives::U256; use super::super::super::verification::verify_header_basic; use super::{BlockLike, Kind}; @@ -103,10 +96,6 @@ pub mod headers { fn parent_hash(&self) -> BlockHash { *self.parent_hash() } - - fn score(&self) -> U256 { - *self.score() - } } /// A mode for verifying headers. @@ -149,7 +138,7 @@ pub mod headers { /// The blocks verification module. pub mod blocks { use ctypes::{BlockHash, Header}; - use primitives::{Bytes, U256}; + use primitives::Bytes; use super::super::super::verification::{ verify_block_basic, verify_block_seal, verify_header_with_engine, PreverifiedBlock, @@ -233,10 +222,6 @@ pub mod blocks { fn parent_hash(&self) -> BlockHash { *self.header.parent_hash() } - - fn score(&self) -> U256 { - *self.header.score() - } } impl BlockLike for PreverifiedBlock { @@ -247,10 +232,6 @@ pub mod blocks { fn parent_hash(&self) -> BlockHash { *self.header.parent_hash() } - - fn score(&self) -> U256 { - *self.header.score() - } } impl MemUsage for Unverified { diff --git a/core/src/verification/queue/mod.rs b/core/src/verification/queue/mod.rs index 487deeed2b..8458455d5f 100644 --- a/core/src/verification/queue/mod.rs +++ b/core/src/verification/queue/mod.rs @@ -24,9 +24,8 @@ use crate::types::{BlockStatus as Status, VerificationQueueInfo as QueueInfo}; use cio::IoChannel; use ctypes::BlockHash; use parking_lot::{Mutex, RwLock}; -use primitives::U256; use std::cmp; -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashSet, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; use std::sync::{Arc, Condvar as SCondvar, Mutex as SMutex}; use std::thread::{self, JoinHandle}; @@ -64,10 +63,9 @@ impl Default for Config { pub struct VerificationQueue { engine: Arc, verification: Arc>, - processing: RwLock>, // hash to score + processing: RwLock>, // hash to block number deleting: Arc, ready_signal: Arc, - total_score: RwLock, #[allow(dead_code)] empty: Arc, more_to_verify: Arc, @@ -178,10 +176,9 @@ impl VerificationQueue { Self { engine, verification, - processing: RwLock::new(HashMap::new()), + processing: RwLock::new(HashSet::new()), deleting, ready_signal, - total_score: RwLock::new(0.into()), empty, more_to_verify, verifier_handles, @@ -324,7 +321,7 @@ impl VerificationQueue { /// Check if the item is currently in the queue pub fn status(&self, hash: &BlockHash) -> Status { - if self.processing.read().contains_key(hash) { + if self.processing.read().contains(hash) { return Status::Queued } if self.verification.bad.lock().contains(hash) { @@ -337,7 +334,7 @@ impl VerificationQueue { pub fn import(&self, input: K::Input) -> Result { let h = input.hash(); { - if self.processing.read().contains_key(&h) { + if self.processing.read().contains(&h) { return Err(ImportError::AlreadyQueued.into()) } @@ -355,11 +352,7 @@ impl VerificationQueue { Ok(item) => { self.verification.sizes.unverified.fetch_add(item.mem_usage(), AtomicOrdering::SeqCst); - self.processing.write().insert(h, item.score()); - { - let mut ts = self.total_score.write(); - *ts += item.score(); - } + self.processing.write().insert(h); self.verification.unverified.lock().push_back(item); self.more_to_verify.notify_all(); @@ -404,10 +397,7 @@ impl VerificationQueue { } let mut processing = self.processing.write(); for hash in hashes { - if let Some(score) = processing.remove(hash) { - let mut td = self.total_score.write(); - *td -= score; - } + processing.remove(hash); } processing.shrink_to_fit(); processing.is_empty() @@ -426,10 +416,7 @@ impl VerificationQueue { bad.reserve(hashes.len()); for hash in hashes { bad.insert(*hash); - if let Some(score) = processing.remove(hash) { - let mut td = self.total_score.write(); - *td -= score; - } + processing.remove(hash); } let mut new_verified = VecDeque::new(); @@ -438,10 +425,6 @@ impl VerificationQueue { if bad.contains(&output.parent_hash()) { removed_size += output.mem_usage(); bad.insert(output.hash()); - if let Some(score) = processing.remove(&output.hash()) { - let mut td = self.total_score.write(); - *td -= score; - } } else { new_verified.push_back(output); } @@ -482,11 +465,6 @@ impl VerificationQueue { mem_used: unverified_bytes + verifying_bytes + verified_bytes, } } - - /// Get the total score of all the blocks in the queue. - pub fn total_score(&self) -> U256 { - *self.total_score.read() - } } impl Drop for VerificationQueue { From 7b175e238e3a30133be3e0d15e5e4ff75b6ecb87 Mon Sep 17 00:00:00 2001 From: SeungMin Lee Date: Wed, 12 Feb 2020 15:17:59 +0900 Subject: [PATCH 2/4] Remove the logic related to the score in client --- core/src/blockchain/blockchain.rs | 6 ------ core/src/blockchain_info.rs | 7 ------- core/src/client/client.rs | 12 ++---------- core/src/client/mod.rs | 5 +---- core/src/client/test_client.rs | 18 +----------------- core/src/consensus/tendermint/worker.rs | 12 ------------ core/src/error.rs | 10 +--------- 7 files changed, 5 insertions(+), 65 deletions(-) diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index 1478f3b3a8..a9d854402d 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -326,13 +326,7 @@ impl BlockChain { let best_block_detail = self.block_details(&best_block_hash).expect("Best block always exists"); let best_block_header = self.block_header_data(&best_block_hash).expect("Best block always exists"); - let best_proposal_block_detail = - self.block_details(&best_proposal_block_hash).expect("Best proposal block always exists"); - BlockChainInfo { - best_score: best_block_detail.total_score, - best_proposal_score: best_proposal_block_detail.total_score, - pending_total_score: best_block_detail.total_score, genesis_hash: self.genesis_hash(), best_block_hash: best_block_header.hash(), best_proposal_block_hash, diff --git a/core/src/blockchain_info.rs b/core/src/blockchain_info.rs index 065605543b..394a700c92 100644 --- a/core/src/blockchain_info.rs +++ b/core/src/blockchain_info.rs @@ -15,17 +15,10 @@ // along with this program. If not, see . use ctypes::{BlockHash, BlockNumber}; -use primitives::U256; /// Information about the blockchain gathered together. #[derive(Clone, Debug)] pub struct BlockChainInfo { - /// Score of the canonical chain. - pub best_score: U256, - /// The best score from proposal blocks. - pub best_proposal_score: U256, - /// Block queue score. - pub pending_total_score: U256, /// Genesis block hash. pub genesis_hash: BlockHash, /// Best blockchain block hash. diff --git a/core/src/client/client.rs b/core/src/client/client.rs index 58be32eac4..0602f8bdc8 100644 --- a/core/src/client/client.rs +++ b/core/src/client/client.rs @@ -44,7 +44,7 @@ use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker, TxHash}; use cvm::{decode, execute, ChainTimeInfo, ScriptResult, VMConfig}; use kvdb::{DBTransaction, KeyValueDB}; use parking_lot::{Mutex, RwLock, RwLockReadGuard}; -use primitives::{Bytes, H256, U256}; +use primitives::{Bytes, H256}; use rlp::Rlp; use std::ops::Range; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; @@ -482,9 +482,7 @@ impl ConsensusClient for Client {} impl BlockChainTrait for Client { fn chain_info(&self) -> BlockChainInfo { - let mut chain_info = self.block_chain().chain_info(); - chain_info.pending_total_score = chain_info.best_score; - chain_info + self.block_chain().chain_info() } fn genesis_accounts(&self) -> Vec { @@ -673,12 +671,6 @@ impl BlockChainClient for Client { } } - fn block_total_score(&self, id: &BlockId) -> Option { - let chain = self.block_chain(); - - Self::block_hash(&chain, id).and_then(|hash| chain.block_details(&hash)).map(|d| d.total_score) - } - fn block_hash(&self, id: &BlockId) -> Option { let chain = self.block_chain(); Self::block_hash(&chain, id) diff --git a/core/src/client/mod.rs b/core/src/client/mod.rs index 0e59b73c03..72f1b705ff 100644 --- a/core/src/client/mod.rs +++ b/core/src/client/mod.rs @@ -45,7 +45,7 @@ use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction}; use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, Tracker, TxHash}; use cvm::ChainTimeInfo; use kvdb::KeyValueDB; -use primitives::{Bytes, H256, U256}; +use primitives::{Bytes, H256}; use std::ops::Range; use std::sync::Arc; @@ -235,9 +235,6 @@ pub trait BlockChainClient: Sync + Send + AccountData + BlockChainTrait + Import /// Get block status by block header hash. fn block_status(&self, id: &BlockId) -> BlockStatus; - /// Get block total score. - fn block_total_score(&self, id: &BlockId) -> Option; - /// Get block hash. fn block_hash(&self, id: &BlockId) -> Option; diff --git a/core/src/client/test_client.rs b/core/src/client/test_client.rs index 247ce633c2..428290bb3e 100644 --- a/core/src/client/test_client.rs +++ b/core/src/client/test_client.rs @@ -60,7 +60,7 @@ use kvdb::KeyValueDB; use kvdb_memorydb; use merkle_trie::skewed_merkle_root; use parking_lot::RwLock; -use primitives::{Bytes, H256, U256}; +use primitives::{Bytes, H256}; use rlp::*; use std::collections::HashMap; use std::mem; @@ -80,8 +80,6 @@ pub struct TestBlockChainClient { pub last_hash: RwLock, /// Extra data do set for each block pub extra_data: Bytes, - /// Score. - pub score: RwLock, /// Balances. pub balances: RwLock>, /// Seqs. @@ -136,7 +134,6 @@ impl TestBlockChainClient { let genesis_block = scheme.genesis_block(); let genesis_header = scheme.genesis_header(); let genesis_hash = genesis_header.hash(); - let genesis_score = *genesis_header.score(); let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), @@ -144,7 +141,6 @@ impl TestBlockChainClient { genesis_hash, extra_data, last_hash: RwLock::new(genesis_hash), - score: RwLock::new(genesis_score), balances: RwLock::new(HashMap::new()), seqs: RwLock::new(HashMap::new()), storage: RwLock::new(HashMap::new()), @@ -199,7 +195,6 @@ impl TestBlockChainClient { /// Add a block to test client with designated author. pub fn add_block_with_author(&self, author: Option
, n: usize, transaction_length: usize) -> BlockHash { let mut header = BlockHeader::new(); - header.set_score(From::from(n)); header.set_parent_hash(*self.last_hash.read()); header.set_number(n as BlockNumber); header.set_extra_data(self.extra_data.clone()); @@ -401,9 +396,6 @@ impl BlockChainTrait for TestBlockChainClient { fn chain_info(&self) -> BlockChainInfo { let number = self.blocks.read().len() as BlockNumber - 1; BlockChainInfo { - best_score: *self.score.read(), - best_proposal_score: *self.score.read(), - pending_total_score: *self.score.read(), genesis_hash: self.genesis_hash, best_block_hash: *self.last_hash.read(), best_proposal_block_hash: *self.last_hash.read(), @@ -465,10 +457,6 @@ impl ImportBlock for TestBlockChainClient { } let len = self.numbers.read().len(); if number == len { - { - let mut score = self.score.write(); - *score += *header.score(); - } mem::replace(&mut *self.last_hash.write(), h); self.blocks.write().insert(h, b); self.numbers.write().insert(number, h); @@ -574,10 +562,6 @@ impl BlockChainClient for TestBlockChainClient { } } - fn block_total_score(&self, _id: &BlockId) -> Option { - Some(U256::zero()) - } - fn block_hash(&self, id: &BlockId) -> Option { Self::block_hash(self, id) } diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index 916962be0a..6fdf47e890 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -1193,18 +1193,6 @@ impl Worker { .into()) } - let height = header.number(); - let author_view = TendermintSealView::new(header.seal()).author_view().unwrap(); - let score = calculate_score(height, author_view); - - if *header.score() != score { - return Err(BlockError::InvalidScore(Mismatch { - expected: score, - found: *header.score(), - }) - .into()) - } - Ok(()) } diff --git a/core/src/error.rs b/core/src/error.rs index 468d4f2e39..c4d985d66a 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -24,7 +24,7 @@ use ctypes::errors::{HistoryError, RuntimeError, SyntaxError}; use ctypes::util::unexpected::{Mismatch, OutOfBounds}; use ctypes::{BlockHash, BlockNumber}; use merkle_trie::TrieError; -use primitives::{H256, U256}; +use primitives::H256; use rlp::DecoderError; use std::fmt; use std::io::Error as StdIoError; @@ -86,12 +86,6 @@ pub enum BlockError { InvalidTransactionsRoot(Mismatch), /// Next validator set hash header field is invalid. InvalidNextValidatorSetHash(Mismatch), - /// Score is out of range; this can be used as an looser error prior to getting a definitive - /// value for score. This error needs only provide bounds of which it is out. - ScoreOutOfBounds(OutOfBounds), - /// Score header field is invalid; this is a strong error used after getting a definitive - /// value for difficulty (which is provided). - InvalidScore(Mismatch), /// Proof-of-work aspect of seal is invalid. InvalidProofOfWork, /// Some low-level aspect of the seal is incorrect. @@ -142,8 +136,6 @@ impl fmt::Display for BlockError { InvalidStateRoot(mis) => format!("Invalid state root in header: {}", mis), InvalidTransactionsRoot(mis) => format!("Invalid transactions root in header: {}", mis), InvalidNextValidatorSetHash(mis) => format!("Invalid next validator set hash in header: {}", mis), - ScoreOutOfBounds(oob) => format!("Invalid block score: {}", oob), - InvalidScore(oob) => format!("Invalid block score: {}", oob), InvalidProofOfWork => "Invalid proof of work.".into(), InvalidSeal => "Block has invalid seal.".into(), InvalidTimestamp(oob) => format!("Invalid timestamp in header: {}", oob), From bf966af2e375783258eaca710e435cb88a93562d Mon Sep 17 00:00:00 2001 From: SeungMin Lee Date: Wed, 12 Feb 2020 16:12:58 +0900 Subject: [PATCH 3/4] Remove the logic related to the score in tendermint --- core/src/consensus/tendermint/engine.rs | 12 ------------ core/src/consensus/tendermint/worker.rs | 22 +--------------------- 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/core/src/consensus/tendermint/engine.rs b/core/src/consensus/tendermint/engine.rs index e5e14e465e..f2c166da1a 100644 --- a/core/src/consensus/tendermint/engine.rs +++ b/core/src/consensus/tendermint/engine.rs @@ -121,18 +121,6 @@ impl ConsensusEngine for Tendermint { receiver.recv().unwrap() } - fn populate_from_parent(&self, header: &mut Header, _parent: &Header) { - let (result, receiver) = crossbeam::bounded(1); - self.inner - .send(worker::Event::CalculateScore { - block_number: header.number(), - result, - }) - .unwrap(); - let score = receiver.recv().unwrap(); - header.set_score(score); - } - /// Equivalent to a timeout: to be used for tests. fn on_timeout(&self, token: usize) { self.inner.send(worker::Event::OnTimeout(token)).unwrap(); diff --git a/core/src/consensus/tendermint/worker.rs b/core/src/consensus/tendermint/worker.rs index 6fdf47e890..6cdb40ba7e 100644 --- a/core/src/consensus/tendermint/worker.rs +++ b/core/src/consensus/tendermint/worker.rs @@ -45,7 +45,7 @@ use crossbeam_channel as crossbeam; use ctypes::transaction::{Action, Transaction}; use ctypes::util::unexpected::Mismatch; use ctypes::{BlockHash, BlockNumber, Header}; -use primitives::{u256_from_u128, Bytes, U256}; +use primitives::Bytes; use rlp::{Encodable, Rlp}; use std::cell::Cell; use std::cmp::Ordering; @@ -120,10 +120,6 @@ pub enum Event { header: Box
, result: crossbeam::Sender>, }, - CalculateScore { - block_number: Height, - result: crossbeam::Sender, - }, OnTimeout(usize), HandleMessages { messages: Vec>, @@ -304,12 +300,6 @@ impl Worker { Ok(Event::VerifyBlockExternal{header, result, }) => { result.send(inner.verify_block_external(&*header)).unwrap(); } - Ok(Event::CalculateScore { - block_number, - result, - }) => { - result.send(inner.calculate_score(block_number)).unwrap(); - } Ok(Event::OnTimeout(token)) => { inner.on_timeout(token); } @@ -1192,7 +1182,6 @@ impl Worker { }) .into()) } - Ok(()) } @@ -1258,10 +1247,6 @@ impl Worker { Ok(()) } - fn calculate_score(&self, block_number: Height) -> U256 { - calculate_score(block_number, self.view) - } - fn on_timeout(&mut self, token: usize) { // Timeout from empty block generation if token == ENGINE_TIMEOUT_EMPTY_PROPOSAL { @@ -2231,11 +2216,6 @@ impl Worker { } } -fn calculate_score(height: Height, view: View) -> U256 { - let height = U256::from(height); - u256_from_u128(std::u128::MAX) * height - view -} - /// Sets internal trigger on deref_mut (taking mutable reference to internal value) /// trigger is reset on borrowing struct MutTrigger { From 3466ca8d595eae4507da57d948a5cf25c6484db1 Mon Sep 17 00:00:00 2001 From: SeungMin Lee Date: Wed, 12 Feb 2020 16:44:30 +0900 Subject: [PATCH 4/4] Remove the score except it of the Header and the Block --- core/src/block.rs | 2 -- core/src/blockchain/blockchain.rs | 9 ++++++++- core/src/blockchain/extras.rs | 6 +++--- core/src/blockchain/headerchain.rs | 23 +++++++++++++---------- core/src/codechain_machine.rs | 6 ------ core/src/encoded.rs | 12 +----------- core/src/scheme/genesis.rs | 5 +---- core/src/scheme/scheme.rs | 6 +----- core/src/tests/helpers.rs | 3 +-- core/src/views/header.rs | 10 ++++++++++ json/src/scheme/genesis.rs | 4 ---- json/src/scheme/scheme.rs | 1 - rpc/src/v1/types/block.rs | 2 +- types/src/header.rs | 15 +++++++++++---- 14 files changed, 50 insertions(+), 54 deletions(-) diff --git a/core/src/block.rs b/core/src/block.rs index 0bde4634a3..8c66d0d34b 100644 --- a/core/src/block.rs +++ b/core/src/block.rs @@ -143,7 +143,6 @@ impl<'x> OpenBlock<'x> { r.block.header.set_extra_data(extra_data); r.block.header.note_dirty(); - engine.machine().populate_from_parent(&mut r.block.header, parent); engine.populate_from_parent(&mut r.block.header, parent); Ok(r) @@ -208,7 +207,6 @@ impl<'x> OpenBlock<'x> { /// Populate self from a header. fn populate_from(&mut self, header: &Header) { - self.block.header.set_score(*header.score()); self.block.header.set_timestamp(header.timestamp()); self.block.header.set_author(*header.author()); self.block.header.set_extra_data(header.extra_data().clone()); diff --git a/core/src/blockchain/blockchain.rs b/core/src/blockchain/blockchain.rs index a9d854402d..4c33c0a07e 100644 --- a/core/src/blockchain/blockchain.rs +++ b/core/src/blockchain/blockchain.rs @@ -210,6 +210,13 @@ impl BlockChain { } } + /// Compare the number and the view of current block with these of best block + fn is_new_header_eligible_to_be_best(&self, new_header: &HeaderView<'_>) -> bool { + let details_of_best_block = self.best_proposal_block_detail(); + + (new_header.number(), details_of_best_block.view) > (details_of_best_block.number, new_header.view()) + } + /// Calculate how best block is changed fn best_block_changed(&self, new_block: &BlockView<'_>, engine: &dyn CodeChainEngine) -> BestBlockChanged { let new_header = new_block.header_view(); @@ -218,7 +225,7 @@ impl BlockChain { let grandparent_hash_of_new_block = parent_details_of_new_block.parent; let prev_best_hash = self.best_block_hash(); - if parent_details_of_new_block.total_score + new_header.score() > self.best_proposal_block_detail().total_score + if self.is_new_header_eligible_to_be_best(&new_header) && engine.can_change_canon_chain(parent_hash_of_new_block, grandparent_hash_of_new_block, prev_best_hash) { cinfo!( diff --git a/core/src/blockchain/extras.rs b/core/src/blockchain/extras.rs index 1ff9d3422b..d739c72cf5 100644 --- a/core/src/blockchain/extras.rs +++ b/core/src/blockchain/extras.rs @@ -17,7 +17,7 @@ use crate::db::Key; use crate::types::TransactionId; use ctypes::{BlockHash, BlockNumber, Tracker, TxHash}; -use primitives::{H256, H264, U256}; +use primitives::{H256, H264}; use std::ops::{Add, AddAssign, Deref, Sub, SubAssign}; /// Represents index of extra data in database @@ -93,10 +93,10 @@ impl Key for Tracker { /// Familial details concerning a block #[derive(Debug, Clone, RlpEncodable, RlpDecodable)] pub struct BlockDetails { + /// Block view + pub view: u64, /// Block number pub number: BlockNumber, - /// Total score of the block and all its parents - pub total_score: U256, /// Parent block hash pub parent: BlockHash, } diff --git a/core/src/blockchain/headerchain.rs b/core/src/blockchain/headerchain.rs index c091feb1ae..9787cf9d6a 100644 --- a/core/src/blockchain/headerchain.rs +++ b/core/src/blockchain/headerchain.rs @@ -72,7 +72,7 @@ impl HeaderChain { let details = BlockDetails { number: genesis.number(), - total_score: genesis.score(), + view: genesis.view(), parent: genesis.parent_hash(), }; @@ -134,7 +134,7 @@ impl HeaderChain { let mut new_details = HashMap::new(); new_details.insert(hash, BlockDetails { number: header.number(), - total_score: 0.into(), + view: header.view(), parent: header.parent_hash(), }); @@ -252,12 +252,11 @@ impl HeaderChain { /// Uses the given parent details or attempts to load them from the database. fn new_detail_entries(&self, header: &HeaderView<'_>) -> HashMap { let parent_hash = header.parent_hash(); - let parent_details = self.block_details(&parent_hash).expect("Invalid parent hash"); // create current block details. let details = BlockDetails { number: header.number(), - total_score: parent_details.total_score + header.score(), + view: header.view(), parent: parent_hash, }; @@ -267,14 +266,22 @@ impl HeaderChain { block_details } + /// Compare the number and the view of current block with these of best block + fn is_new_header_eligible_to_be_best(&self, new_header: &HeaderView<'_>) -> bool { + let best_proposal_block_hash = self.best_header_hash(); + let best_proposal_block_detail = + self.block_details(&best_proposal_block_hash).expect("Best proposal block always exists"); + + (new_header.number(), best_proposal_block_detail.view) > (best_proposal_block_detail.number, new_header.view()) + } + /// Calculate how best block is changed fn best_header_changed(&self, new_header: &HeaderView<'_>, engine: &dyn CodeChainEngine) -> BestHeaderChanged { let parent_hash_of_new_header = new_header.parent_hash(); let parent_details_of_new_header = self.block_details(&parent_hash_of_new_header).expect("Invalid parent hash"); let grandparent_hash_of_new_header = parent_details_of_new_header.parent; let prev_best_hash = self.best_header_hash(); - let is_new_best = parent_details_of_new_header.total_score + new_header.score() - > self.best_proposal_header_detail().total_score + let is_new_best = self.is_new_header_eligible_to_be_best(new_header) && engine.can_change_canon_chain(parent_hash_of_new_header, grandparent_hash_of_new_header, prev_best_hash); if is_new_best { @@ -364,10 +371,6 @@ impl HeaderChain { pub fn best_proposal_header(&self) -> encoded::Header { self.block_header_data(&self.best_proposal_header_hash()).expect("Highest header always exists") } - - pub fn best_proposal_header_detail(&self) -> BlockDetails { - self.block_details(&self.best_proposal_header_hash()).expect("Best Proposal header always exists") - } } /// Interface for querying blocks by hash and by number. diff --git a/core/src/codechain_machine.rs b/core/src/codechain_machine.rs index d2a2ed6d73..f9e0304264 100644 --- a/core/src/codechain_machine.rs +++ b/core/src/codechain_machine.rs @@ -78,12 +78,6 @@ impl CodeChainMachine { Ok(()) } - /// Populate a header's fields based on its parent's header. - /// Usually implements the chain scoring rule based on weight. - pub fn populate_from_parent(&self, header: &mut Header, parent: &Header) { - header.set_score(*parent.score()); - } - pub fn min_cost(params: &CommonParams, action: &Action) -> u64 { match action { Action::Pay { diff --git a/core/src/encoded.rs b/core/src/encoded.rs index 8ec2a0b4b8..76c44186d9 100644 --- a/core/src/encoded.rs +++ b/core/src/encoded.rs @@ -29,7 +29,7 @@ use crate::views; use ccrypto::blake256; use ckey::Address; use ctypes::{BlockHash, BlockNumber, Header as FullHeader, TxHash}; -use primitives::{H256, U256}; +use primitives::H256; use rlp::Rlp; /// Owning header view. @@ -99,11 +99,6 @@ impl Header { self.view().next_validator_set_hash() } - /// Score of this block - pub fn score(&self) -> U256 { - self.view().score() - } - /// Number of this block. pub fn number(&self) -> BlockNumber { self.view().number() @@ -258,11 +253,6 @@ impl Block { self.header_view().transactions_root() } - /// Score of this block - pub fn score(&self) -> U256 { - self.header_view().score() - } - /// Number of this block. pub fn number(&self) -> BlockNumber { self.header_view().number() diff --git a/core/src/scheme/genesis.rs b/core/src/scheme/genesis.rs index d90a3566e2..a0e60fe650 100644 --- a/core/src/scheme/genesis.rs +++ b/core/src/scheme/genesis.rs @@ -19,14 +19,12 @@ use ccrypto::BLAKE_NULL_RLP; use cjson; use ckey::{Address, PlatformAddress}; use ctypes::BlockHash; -use primitives::{Bytes, H256, U256}; +use primitives::{Bytes, H256}; /// Genesis components. pub struct Genesis { /// Seal. pub seal: Seal, - /// Score. - pub score: U256, /// Author. pub author: Address, /// Timestamp. @@ -47,7 +45,6 @@ impl From for Genesis { fn from(g: cjson::scheme::Genesis) -> Self { Genesis { seal: From::from(g.seal), - score: g.score.into(), author: g.author.map_or_else(Address::default, PlatformAddress::into_address), timestamp: g.timestamp.map_or(0, Into::into), parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into).into(), diff --git a/core/src/scheme/scheme.rs b/core/src/scheme/scheme.rs index 57f57ce3b6..1e74886d36 100644 --- a/core/src/scheme/scheme.rs +++ b/core/src/scheme/scheme.rs @@ -30,7 +30,7 @@ use ctypes::errors::SyntaxError; use ctypes::{BlockHash, CommonParams, Header, ShardId}; use merkle_trie::{TrieFactory, TrieMut}; use parking_lot::RwLock; -use primitives::{Bytes, H256, U256}; +use primitives::{Bytes, H256}; use rlp::{Encodable, Rlp, RlpStream}; use std::io::Read; use std::sync::Arc; @@ -52,8 +52,6 @@ pub struct Scheme { pub parent_hash: BlockHash, /// The genesis block's author field. pub author: Address, - /// The genesis block's score field. - pub score: U256, /// The genesis block's timestamp field. pub timestamp: u64, /// Transactions root of the genesis block. Should be BLAKE_NULL_RLP. @@ -267,7 +265,6 @@ impl Scheme { header.set_extra_data(blake256(&self.genesis_params().rlp_bytes()).to_vec()); header.set_state_root(self.state_root()); header.set_next_validator_set_hash(BLAKE_NULL_RLP /* This will be calculated from state after https://github.com/CodeChain-io/foundry/issues/142*/); - header.set_score(self.score); header.set_seal({ let r = Rlp::new(&self.seal_rlp); r.iter().map(|f| f.as_raw().to_vec()).collect() @@ -308,7 +305,6 @@ fn load_from(s: cjson::scheme::Scheme) -> Result { parent_hash: g.parent_hash, transactions_root: g.transactions_root, author: g.author, - score: g.score, timestamp: g.timestamp, extra_data: g.extra_data, seal_rlp, diff --git a/core/src/tests/helpers.rs b/core/src/tests/helpers.rs index 348f547bca..54d46331f3 100644 --- a/core/src/tests/helpers.rs +++ b/core/src/tests/helpers.rs @@ -18,7 +18,7 @@ use crate::scheme::Scheme; use crate::transaction::SignedTransaction; use cstate::StateDB; use ctypes::{BlockHash, Header}; -use primitives::{Bytes, U256}; +use primitives::Bytes; use rlp::{self, RlpStream}; pub fn create_test_block(header: &Header) -> Bytes { @@ -48,7 +48,6 @@ pub fn get_good_dummy_block() -> Bytes { pub fn get_good_dummy_block_hash() -> (BlockHash, Bytes) { let mut block_header = Header::new(); let test_scheme = Scheme::new_test(); - block_header.set_score(U256::from(0x20000)); block_header.set_timestamp(40); block_header.set_number(1); block_header.set_parent_hash(test_scheme.genesis_header().hash()); diff --git a/core/src/views/header.rs b/core/src/views/header.rs index 2f8ff4e774..a170651c22 100644 --- a/core/src/views/header.rs +++ b/core/src/views/header.rs @@ -112,4 +112,14 @@ impl<'a> HeaderView<'a> { let seal = self.seal(); seal.into_iter().map(|s| rlp::Rlp::new(&s).data().map(|x| x.to_vec())).collect() } + + /// Get view in the seal field of the header. + pub fn view(&self) -> u64 { + let seal = self.seal(); + if let Some(rlp_view) = seal.get(1) { + Rlp::new(rlp_view.as_slice()).as_val().unwrap() + } else { + 0 + } + } } diff --git a/json/src/scheme/genesis.rs b/json/src/scheme/genesis.rs index 35dd826a1e..a1da526169 100644 --- a/json/src/scheme/genesis.rs +++ b/json/src/scheme/genesis.rs @@ -26,8 +26,6 @@ use ckey::PlatformAddress; pub struct Genesis { /// Seal. pub seal: Seal, - /// Score. Difficulty in PoW. - pub score: Uint, /// Block author, defaults to 0. pub author: Option, /// Block timestamp, defaults to 0. @@ -61,7 +59,6 @@ mod tests { #[test] fn genesis_deserialization() { let s = r#"{ - "score": "0x400000000", "seal": { "tendermint": { "prev_view": "0x0", @@ -87,7 +84,6 @@ mod tests { H520(Core520::from("0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), ] }), - score: 0x0004_0000_0000u64.into(), author: Some(PlatformAddress::from_str("tccqyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqhhn9p3").unwrap()), timestamp: Some(0x07.into()), parent_hash: Some(H256(Core256::from("0x9000000000000000000000000000000000000000000000000000000000000000"))), diff --git a/json/src/scheme/scheme.rs b/json/src/scheme/scheme.rs index fb5fded4ea..c1869255ec 100644 --- a/json/src/scheme/scheme.rs +++ b/json/src/scheme/scheme.rs @@ -105,7 +105,6 @@ mod tests { ] } }, - "score": "0x20000", "author": "tccqyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqhhn9p3", "timestamp": "0x00", "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" diff --git a/rpc/src/v1/types/block.rs b/rpc/src/v1/types/block.rs index 24b2fc959a..b025198d06 100644 --- a/rpc/src/v1/types/block.rs +++ b/rpc/src/v1/types/block.rs @@ -65,7 +65,7 @@ impl Block { state_root: *block.header.state_root(), next_validator_set_hash: *block.header.next_validator_set_hash(), - score: *block.header.score(), + score: U256::default(), seal: block.header.seal().to_vec(), hash: block.header.hash(), diff --git a/types/src/header.rs b/types/src/header.rs index da0daa9f82..ed70379d51 100644 --- a/types/src/header.rs +++ b/types/src/header.rs @@ -143,15 +143,22 @@ impl Header { self.transactions_root() == &BLAKE_NULL_RLP } - /// Get the score field of the header. - pub fn score(&self) -> &U256 { - &self.score - } /// Get the seal field of the header. pub fn seal(&self) -> &[Bytes] { &self.seal } + /// Get view in the seal field of the header. + pub fn view(&self) -> u64 { + let seal = self.seal(); + if let Some(rlp_view) = seal.get(1) { + Rlp::new(rlp_view.as_slice()).as_val().unwrap() + } else { + 0 + } + } + + /// Set the number field of the header. pub fn set_parent_hash(&mut self, a: BlockHash) { self.parent_hash = a;