Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions core/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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());
Expand Down
15 changes: 8 additions & 7 deletions core/src/blockchain/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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!(
Expand Down Expand Up @@ -326,13 +333,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,
Expand Down
6 changes: 3 additions & 3 deletions core/src/blockchain/extras.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -93,10 +93,10 @@ impl Key<TransactionAddresses> 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,
}
Expand Down
23 changes: 13 additions & 10 deletions core/src/blockchain/headerchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl HeaderChain {

let details = BlockDetails {
number: genesis.number(),
total_score: genesis.score(),
view: genesis.view(),
parent: genesis.parent_hash(),
};

Expand Down Expand Up @@ -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(),
});

Expand Down Expand Up @@ -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<BlockHash, BlockDetails> {
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,
};

Expand All @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 0 additions & 7 deletions core/src/blockchain_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,10 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

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.
Expand Down
12 changes: 2 additions & 10 deletions core/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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 + self.importer.block_queue.total_score();
chain_info
self.block_chain().chain_info()
}

fn genesis_accounts(&self) -> Vec<PlatformAddress> {
Expand Down Expand Up @@ -673,12 +671,6 @@ impl BlockChainClient for Client {
}
}

fn block_total_score(&self, id: &BlockId) -> Option<U256> {
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<BlockHash> {
let chain = self.block_chain();
Self::block_hash(&chain, id)
Expand Down
5 changes: 1 addition & 4 deletions core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<U256>;

/// Get block hash.
fn block_hash(&self, id: &BlockId) -> Option<BlockHash>;

Expand Down
18 changes: 1 addition & 17 deletions core/src/client/test_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -80,8 +80,6 @@ pub struct TestBlockChainClient {
pub last_hash: RwLock<BlockHash>,
/// Extra data do set for each block
pub extra_data: Bytes,
/// Score.
pub score: RwLock<U256>,
/// Balances.
pub balances: RwLock<HashMap<Address, u64>>,
/// Seqs.
Expand Down Expand Up @@ -136,15 +134,13 @@ 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()),
numbers: RwLock::new(HashMap::new()),
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()),
Expand Down Expand Up @@ -199,7 +195,6 @@ impl TestBlockChainClient {
/// Add a block to test client with designated author.
pub fn add_block_with_author(&self, author: Option<Address>, 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());
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -574,10 +562,6 @@ impl BlockChainClient for TestBlockChainClient {
}
}

fn block_total_score(&self, _id: &BlockId) -> Option<U256> {
Some(U256::zero())
}

fn block_hash(&self, id: &BlockId) -> Option<BlockHash> {
Self::block_hash(self, id)
}
Expand Down
6 changes: 0 additions & 6 deletions core/src/codechain_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 0 additions & 12 deletions core/src/consensus/tendermint/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
34 changes: 1 addition & 33 deletions core/src/consensus/tendermint/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -120,10 +120,6 @@ pub enum Event {
header: Box<Header>,
result: crossbeam::Sender<Result<(), Error>>,
},
CalculateScore {
block_number: Height,
result: crossbeam::Sender<U256>,
},
OnTimeout(usize),
HandleMessages {
messages: Vec<Vec<u8>>,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -1193,19 +1183,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(())
}

Expand Down Expand Up @@ -1271,10 +1248,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 {
Expand Down Expand Up @@ -2245,11 +2218,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<T> {
Expand Down
Loading