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
1 change: 0 additions & 1 deletion core/res/solo.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"engine": {
"solo": {
"params": {
"hit": {},
"genesisStakes": {
"tccqxphelyu2n73ekpewrsyj0256wjhn2aqds9xrrrg": 70000,
"tccq9qvruafmf9vegjhkl0ruunkwp0d4lc8fgxknzh5": 20000,
Expand Down
15 changes: 4 additions & 11 deletions core/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::stake;
use crate::transaction::{UnverifiedTransaction, VerifiedTransaction};
use ccrypto::BLAKE_NULL_RLP;
use ckey::Address;
use cstate::{FindActionHandler, StateDB, StateError, StateWithCache, TopLevelState};
use cstate::{FindStakeHandler, StateDB, StateError, StateWithCache, TopLevelState};
use ctypes::errors::HistoryError;
use ctypes::header::{Header, Seal};
use ctypes::util::unexpected::Mismatch;
Expand Down Expand Up @@ -147,7 +147,7 @@ impl<'x> OpenBlock<'x> {
}

/// Push a transaction into the block.
pub fn push_transaction<C: FindActionHandler>(
pub fn push_transaction<C: FindStakeHandler>(
&mut self,
tx: VerifiedTransaction,
h: Option<TxHash>,
Expand Down Expand Up @@ -188,7 +188,7 @@ impl<'x> OpenBlock<'x> {
}

/// Push transactions onto the block.
pub fn push_transactions<C: FindActionHandler>(
pub fn push_transactions<C: FindStakeHandler>(
&mut self,
transactions: &[VerifiedTransaction],
client: &C,
Expand All @@ -215,13 +215,6 @@ impl<'x> OpenBlock<'x> {
warn!("Encountered error on closing the block: {}", e);
return Err(e)
}
let header = self.block.header().clone();
for handler in self.engine.action_handlers() {
handler.on_close_block(self.block.state_mut(), &header).map_err(|e| {
warn!("Encountered error in {}::on_close_block", handler.name());
e
})?;
}
let state_root = self.block.state.commit().map_err(|e| {
warn!("Encountered error on state commit: {}", e);
e
Expand Down Expand Up @@ -359,7 +352,7 @@ impl<'x> IsBlock for ClosedBlock {
}

/// Enact the block given by block header, transactions and uncles
pub fn enact<C: EngineInfo + FindActionHandler + TermInfo>(
pub fn enact<C: EngineInfo + FindStakeHandler + TermInfo>(
header: &Header,
transactions: &[VerifiedTransaction],
engine: &dyn CodeChainEngine,
Expand Down
8 changes: 4 additions & 4 deletions core/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use crate::MemPoolMinFees;
use cdb::{new_journaldb, Algorithm, AsHashDB};
use cio::IoChannel;
use ckey::{Address, NetworkId, PlatformAddress};
use cstate::{ActionHandler, FindActionHandler, StateDB, StateResult, TopLevelState, TopStateView};
use cstate::{FindStakeHandler, StakeHandler, StateDB, StateResult, TopLevelState, TopStateView};
use ctimer::{TimeoutHandler, TimerApi, TimerScheduleError, TimerToken};
use ctypes::header::Header;
use ctypes::transaction::ShardTransaction;
Expand Down Expand Up @@ -705,9 +705,9 @@ impl MiningBlockChainClient for Client {
}
}

impl FindActionHandler for Client {
fn find_action_handler_for(&self, id: u64) -> Option<&dyn ActionHandler> {
self.engine.find_action_handler_for(id)
impl FindStakeHandler for Client {
fn stake_handler(&self) -> Option<&dyn StakeHandler> {
self.engine.stake_handler()
}
}

Expand Down
4 changes: 2 additions & 2 deletions core/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use crate::transaction::{LocalizedTransaction, PendingVerifiedTransactions, Veri
use crate::types::{BlockId, BlockStatus, TransactionId, VerificationQueueInfo as BlockQueueInfo};
use cdb::DatabaseError;
use ckey::{Address, NetworkId, PlatformAddress};
use cstate::{FindActionHandler, StateResult, TopLevelState, TopStateView};
use cstate::{FindStakeHandler, StateResult, TopLevelState, TopStateView};
use ctypes::header::Header;
use ctypes::transaction::ShardTransaction;
use ctypes::{BlockHash, BlockNumber, CommonParams, ShardId, TxHash};
Expand Down Expand Up @@ -247,7 +247,7 @@ pub trait BlockProducer {
}

/// Extended client interface used for mining
pub trait MiningBlockChainClient: BlockChainClient + BlockProducer + FindActionHandler {
pub trait MiningBlockChainClient: BlockChainClient + BlockProducer + FindStakeHandler {
/// Returns malicious users who sent failing transactions.
fn get_malicious_users(&self) -> Vec<Address>;

Expand Down
4 changes: 2 additions & 2 deletions core/src/client/test_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use ckey::{
Generator, KeyPairTrait, NetworkId, PlatformAddress, Random,
};
use cstate::tests::helpers::empty_top_state_with_metadata;
use cstate::{FindActionHandler, StateDB, TopLevelState};
use cstate::{FindStakeHandler, StateDB, TopLevelState};
use ctimer::{TimeoutHandler, TimerToken};
use ctypes::header::Header;
use ctypes::transaction::{Action, Transaction};
Expand Down Expand Up @@ -578,7 +578,7 @@ impl TimeoutHandler for TestBlockChainClient {
fn on_timeout(&self, _token: TimerToken) {}
}

impl FindActionHandler for TestBlockChainClient {}
impl FindStakeHandler for TestBlockChainClient {}

impl super::EngineClient for TestBlockChainClient {
fn update_sealing(&self, parent_block: BlockId, allow_empty_block: bool) {
Expand Down
17 changes: 6 additions & 11 deletions core/src/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use crate::views::HeaderView;
use crate::Client;
use ckey::{Address, Signature};
use cnetwork::NetworkService;
use cstate::{ActionHandler, StateDB, StateResult};
use cstate::{StakeHandler, StateDB, StateResult};
use ctypes::errors::SyntaxError;
use ctypes::transaction::Action;
use ctypes::util::unexpected::{Mismatch, OutOfBounds};
Expand Down Expand Up @@ -233,12 +233,8 @@ pub trait ConsensusEngine: Sync + Send {
true
}

fn action_handlers(&self) -> &[Arc<dyn ActionHandler>] {
&[]
}

fn find_action_handler_for(&self, id: u64) -> Option<&dyn ActionHandler> {
self.action_handlers().iter().find(|handler| handler.handler_id() == id).map(AsRef::as_ref)
fn stake_handler(&self) -> Option<&dyn StakeHandler> {
None
}

fn possible_authors(&self, block_number: Option<u64>) -> Result<Option<Vec<Address>>, EngineError>;
Expand Down Expand Up @@ -327,13 +323,12 @@ pub trait CodeChainEngine: ConsensusEngine {
common_params: &CommonParams,
) -> Result<(), Error> {
if let Action::Custom {
handler_id,
bytes,
..
} = &tx.transaction().action
{
let handler = self
.find_action_handler_for(*handler_id)
.ok_or_else(|| SyntaxError::InvalidCustomAction(format!("{} is an invalid handler id", handler_id)))?;
let handler =
self.stake_handler().ok_or_else(|| SyntaxError::InvalidCustomAction("no valid handler".to_string()))?;
handler.verify(bytes, common_params)?;
}
self.machine().verify_transaction_with_params(tx, common_params)
Expand Down
30 changes: 16 additions & 14 deletions core/src/consensus/solo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,37 +26,33 @@ use crate::codechain_machine::CodeChainMachine;
use crate::consensus::{EngineError, EngineType};
use crate::error::Error;
use ckey::Address;
use cstate::{ActionHandler, HitHandler};
use cstate::{StakeHandler, StateDB, StateResult, StateWithCache, TopLevelState};
use ctypes::{BlockHash, Header};
use parking_lot::RwLock;
use primitives::H256;
use std::collections::HashMap;
use std::sync::{Arc, Weak};

/// A consensus engine which does not provide any consensus mechanism.
pub struct Solo {
client: RwLock<Option<Weak<dyn ConsensusClient>>>,
machine: CodeChainMachine,
action_handlers: Vec<Arc<dyn ActionHandler>>,
snapshot_notify_sender: Arc<RwLock<Option<NotifySender>>>,
genesis_stakes: HashMap<Address, u64>,
stake: stake::Stake,
}

impl Solo {
/// Returns new instance of Solo over the given state machine.
pub fn new(params: SoloParams, machine: CodeChainMachine) -> Self {
let mut action_handlers: Vec<Arc<dyn ActionHandler>> = Vec::new();
if params.enable_hit_handler {
action_handlers.push(Arc::new(HitHandler::new()));
}
action_handlers.push(Arc::new(stake::Stake::new(
params.genesis_stakes,
Default::default(),
Default::default(),
)));
let genesis_stakes = params.genesis_stakes;

Solo {
client: Default::default(),
machine,
action_handlers,
snapshot_notify_sender: Arc::new(RwLock::new(None)),
genesis_stakes,
stake: stake::Stake::default(),
}
}

Expand Down Expand Up @@ -130,13 +126,19 @@ impl ConsensusEngine for Solo {
}
}

fn action_handlers(&self) -> &[Arc<dyn ActionHandler>] {
&self.action_handlers
fn stake_handler(&self) -> Option<&dyn StakeHandler> {
Some(&self.stake)
}

fn possible_authors(&self, _block_number: Option<u64>) -> Result<Option<Vec<Address>>, EngineError> {
Ok(None)
}

fn initialize_genesis_state(&self, db: StateDB, root: H256) -> StateResult<(StateDB, H256)> {
let mut top_level = TopLevelState::from_existing(db, root)?;
stake::init(&mut top_level, self.genesis_stakes.clone(), Default::default(), Default::default())?;
Ok(top_level.commit_and_into_db()?)
}
}

#[cfg(test)]
Expand Down
3 changes: 0 additions & 3 deletions core/src/consensus/solo/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,13 @@ use std::collections::HashMap;
/// Params for a null engine.
#[derive(Clone, Default)]
pub struct SoloParams {
pub enable_hit_handler: bool,
pub genesis_stakes: HashMap<Address, u64>,
}

impl From<cjson::scheme::SoloParams> for SoloParams {
fn from(p: cjson::scheme::SoloParams) -> Self {
SoloParams {
enable_hit_handler: p.action_handlers.hit.is_some(),
genesis_stakes: p
.action_handlers
.genesis_stakes
.unwrap_or_default()
.into_iter()
Expand Down
24 changes: 9 additions & 15 deletions core/src/consensus/stake/action_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::CUSTOM_ACTION_HANDLER_ID;
use ckey::{public_to_address, Address, Ed25519Public as Public};
use cstate::{ActionData, ActionDataKeyBuilder, StateResult, TopLevelState, TopState, TopStateView};
use cstate::{ActionData, StakeKeyBuilder, StateResult, TopLevelState, TopState, TopStateView};
use ctypes::errors::RuntimeError;
use ctypes::{CompactValidatorEntry, CompactValidatorSet};
use primitives::{Bytes, H256};
Expand All @@ -29,25 +28,20 @@ use std::ops::Deref;
use std::vec;

pub fn get_account_key(address: &Address) -> H256 {
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 2).append(&"Account").append(address).into_key()
StakeKeyBuilder::new(2).append(&"Account").append(address).into_key()
}

lazy_static! {
pub static ref STAKEHOLDER_ADDRESSES_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"StakeholderAddresses").into_key();
pub static ref CANDIDATES_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"Candidates").into_key();
pub static ref JAIL_KEY: H256 = ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"Jail").into_key();
pub static ref BANNED_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"Banned").into_key();
pub static ref NEXT_VALIDATORS_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"Validators").into_key();
pub static ref CURRENT_VALIDATORS_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"CurrentValidators").into_key();
pub static ref STAKEHOLDER_ADDRESSES_KEY: H256 = StakeKeyBuilder::new(1).append(&"StakeholderAddresses").into_key();
pub static ref CANDIDATES_KEY: H256 = StakeKeyBuilder::new(1).append(&"Candidates").into_key();
pub static ref JAIL_KEY: H256 = StakeKeyBuilder::new(1).append(&"Jail").into_key();
pub static ref BANNED_KEY: H256 = StakeKeyBuilder::new(1).append(&"Banned").into_key();
pub static ref NEXT_VALIDATORS_KEY: H256 = StakeKeyBuilder::new(1).append(&"Validators").into_key();
pub static ref CURRENT_VALIDATORS_KEY: H256 = StakeKeyBuilder::new(1).append(&"CurrentValidators").into_key();
}

pub fn get_delegation_key(address: &Address) -> H256 {
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 2).append(&"Delegation").append(address).into_key()
StakeKeyBuilder::new(2).append(&"Delegation").append(address).into_key()
}

pub type StakeQuantity = u64;
Expand Down
Loading