Skip to content

Pay the block propose rewards at the end of the term #1559

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 30, 2019
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
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ kvdb = { path = "../util/kvdb" }
kvdb-rocksdb = { path = "../util/kvdb-rocksdb" }
kvdb-memorydb = { path = "../util/kvdb-memorydb" }
memorydb = { path = "../util/memorydb" }
num-rational = "0.2.1"
parking_lot = "0.6.0"
primitives = { git = "https://github.com/CodeChain-io/rust-codechain-primitives.git", version = "0.4" }
rand = "0.6.1"
Expand Down
12 changes: 11 additions & 1 deletion core/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ use ckey::{Address, PlatformAddress, Public};
use cmerkle::Result as TrieResult;
use cnetwork::NodeId;
use cstate::{
ActionHandler, AssetScheme, FindActionHandler, OwnedAsset, StateDB, StateResult, Text, TopLevelState, TopStateView,
ActionHandler, AssetScheme, FindActionHandler, Metadata, OwnedAsset, StateDB, StateResult, Text, TopLevelState,
TopStateView,
};
use ctimer::{TimeoutHandler, TimerApi, TimerScheduleError, TimerToken};
use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction};
Expand All @@ -45,6 +46,7 @@ use super::{
};
use crate::block::{ClosedBlock, IsBlock, OpenBlock, SealedBlock};
use crate::blockchain::{BlockChain, BlockProvider, BodyProvider, HeaderProvider, InvoiceProvider, TransactionAddress};
use crate::client::{ConsensusClient, MetadataInfo};
use crate::consensus::CodeChainEngine;
use crate::encoded;
use crate::error::{BlockImportError, Error, ImportError, SchemeError};
Expand Down Expand Up @@ -563,6 +565,8 @@ impl EngineClient for Client {
}
}

impl ConsensusClient for Client {}

impl BlockChainTrait for Client {
fn chain_info(&self) -> BlockChainInfo {
let mut chain_info = self.block_chain().chain_info();
Expand Down Expand Up @@ -777,6 +781,12 @@ impl BlockChainClient for Client {
}
}

impl MetadataInfo for Client {
fn metadata(&self, id: BlockId) -> Option<Metadata> {
self.state_at(id).and_then(|state| state.metadata().unwrap())
}
}

impl AccountData for Client {
fn seq(&self, address: &Address, id: BlockId) -> Option<u64> {
self.state_at(id).and_then(|s| s.seq(address).ok())
Expand Down
8 changes: 7 additions & 1 deletion core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use std::sync::Arc;
use ckey::{Address, PlatformAddress, Public};
use cmerkle::Result as TrieResult;
use cnetwork::NodeId;
use cstate::{AssetScheme, FindActionHandler, OwnedAsset, StateResult, Text, TopLevelState, TopStateView};
use cstate::{AssetScheme, FindActionHandler, Metadata, OwnedAsset, StateResult, Text, TopLevelState, TopStateView};
use ctypes::transaction::{AssetTransferInput, PartialHashing, ShardTransaction};
use ctypes::{BlockNumber, CommonParams, ShardId};
use cvm::ChainTimeInfo;
Expand Down Expand Up @@ -111,6 +111,12 @@ pub trait EngineClient: Sync + Send + BlockChainTrait + ImportBlock {
fn get_kvdb(&self) -> Arc<KeyValueDB>;
}

pub trait ConsensusClient: BlockChainTrait + EngineClient + MetadataInfo {}

pub trait MetadataInfo {
fn metadata(&self, id: BlockId) -> Option<Metadata>;
}

/// Provides methods to access account info
pub trait AccountData {
/// Attempt to get address seq at given block.
Expand Down
13 changes: 11 additions & 2 deletions core/src/client/test_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use std::sync::Arc;
use ckey::{public_to_address, Address, Generator, NetworkId, PlatformAddress, Public, Random};
use cmerkle::skewed_merkle_root;
use cnetwork::NodeId;
use cstate::{FindActionHandler, StateDB};
use cstate::{FindActionHandler, Metadata, StateDB};
use ctimer::{TimeoutHandler, TimerToken};
use ctypes::transaction::{Action, Transaction};
use ctypes::{BlockNumber, CommonParams, Header as BlockHeader};
Expand All @@ -55,7 +55,7 @@ use crate::block::{ClosedBlock, OpenBlock, SealedBlock};
use crate::blockchain_info::BlockChainInfo;
use crate::client::ImportResult;
use crate::client::{
AccountData, BlockChainClient, BlockChainTrait, BlockProducer, BlockStatus, EngineInfo, ImportBlock,
AccountData, BlockChainClient, BlockChainTrait, BlockProducer, BlockStatus, EngineInfo, ImportBlock, MetadataInfo,
MiningBlockChainClient, StateOrBlock,
};
use crate::db::{COL_STATE, NUM_COLUMNS};
Expand All @@ -65,6 +65,7 @@ use crate::miner::{Miner, MinerService, TransactionImportResult};
use crate::scheme::Scheme;
use crate::transaction::{LocalizedTransaction, PendingSignedTransactions, SignedTransaction};
use crate::types::{BlockId, TransactionId, VerificationQueueInfo as QueueInfo};
use client::ConsensusClient;

/// Test client.
pub struct TestBlockChainClient {
Expand Down Expand Up @@ -599,3 +600,11 @@ impl EngineInfo for TestBlockChainClient {
unimplemented!()
}
}

impl ConsensusClient for TestBlockChainClient {}

impl MetadataInfo for TestBlockChainClient {
fn metadata(&self, _id: BlockId) -> Option<Metadata> {
None
}
}
6 changes: 4 additions & 2 deletions core/src/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ use primitives::{Bytes, H256, U256};
use self::tendermint::types::{BitSet, View};
use crate::account_provider::AccountProvider;
use crate::block::{ExecutedBlock, SealedBlock};
use crate::client::EngineClient;
use crate::client::ConsensusClient;
use crate::codechain_machine::CodeChainMachine;
use crate::encoded;
use crate::error::Error;
Expand Down Expand Up @@ -222,7 +222,7 @@ pub trait ConsensusEngine: Sync + Send {
}

/// Add Client which can be used for sealing, potentially querying the state and sending messages.
fn register_client(&self, _client: Weak<EngineClient>) {}
fn register_client(&self, _client: Weak<ConsensusClient>) {}

/// Handle any potential consensus messages;
/// updating consensus state and potentially issuing a new one.
Expand Down Expand Up @@ -312,6 +312,7 @@ pub enum EngineError {
BadSealFieldSize(OutOfBounds<usize>),
/// Malformed consensus message.
MalformedMessage(String),
CannotOpenBlock,
}

impl fmt::Display for EngineError {
Expand Down Expand Up @@ -340,6 +341,7 @@ impl fmt::Display for EngineError {
UnexpectedMessage => "This Engine should not be fed messages.".into(),
BadSealFieldSize(oob) => format!("Seal field has an unexpected length: {}", oob),
MalformedMessage(msg) => format!("Received malformed consensus message: {}", msg),
CannotOpenBlock => "Cannot open a block".to_string(),
};

f.write_fmt(format_args!("Engine error ({})", msg))
Expand Down
4 changes: 2 additions & 2 deletions core/src/consensus/simple_poa/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use super::validator_set::ValidatorSet;
use super::{ConsensusEngine, EngineError, Seal};
use crate::account_provider::AccountProvider;
use crate::block::ExecutedBlock;
use crate::client::EngineClient;
use crate::client::ConsensusClient;
use crate::codechain_machine::CodeChainMachine;
use crate::consensus::EngineType;
use crate::error::{BlockError, Error};
Expand Down Expand Up @@ -125,7 +125,7 @@ impl ConsensusEngine for SimplePoA {
self.machine.add_balance(block, &author, total_reward)
}

fn register_client(&self, client: Weak<EngineClient>) {
fn register_client(&self, client: Weak<ConsensusClient>) {
self.validators.register_client(client);
}

Expand Down
15 changes: 12 additions & 3 deletions core/src/consensus/solo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,20 @@ impl ConsensusEngine for Solo<CodeChainMachine> {

assert!(total_reward >= total_min_fee, "{} >= {}", total_reward, total_min_fee);
let stakes = stake::get_stakes(block.state()).expect("Cannot get Stake status");
for (address, share) in stake::fee_distribute(total_min_fee, &stakes) {

let mut distributor = stake::fee_distribute(total_min_fee, &stakes);
for (address, share) in &mut distributor {
self.machine.add_balance(block, &address, share)?
}
let stakeholders_share = stake::stakeholders_share(total_min_fee, &stakes);
self.machine.add_balance(block, &author, total_reward - stakeholders_share)?;

let block_author_reward = total_reward - total_min_fee + distributor.remaining_fee();

let term_seconds = parent_common_params.term_seconds();
if term_seconds == 0 {
self.machine.add_balance(block, &author, block_author_reward)?;
return Ok(())
}
stake::add_intermediate_rewards(block.state_mut(), author, block_author_reward)?;
let (last_term_finished_block_num, current_term_id) = {
let header = block.header();
let term_id = header.timestamp() / term_seconds;
Expand All @@ -115,6 +119,11 @@ impl ConsensusEngine for Solo<CodeChainMachine> {
}
(header.number(), term_id)
};
stake::move_current_to_previous_intermediate_rewards(&mut block.state_mut())?;
let rewards = stake::drain_previous_rewards(&mut block.state_mut())?;
for (address, reward) in rewards {
self.machine.add_balance(block, &address, reward)?;
}
self.machine.change_term_id(block, last_term_finished_block_num, current_term_id)?;
Ok(())
}
Expand Down
Loading