Skip to content

Implement reportDoubleVote custom action #1640

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 5 commits into from
Jul 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
38 changes: 35 additions & 3 deletions core/src/client/test_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ use std::ops::Range;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder};
use std::sync::Arc;

use ckey::{public_to_address, Address, Generator, NetworkId, PlatformAddress, Public, Random};
use ckey::{public_to_address, Address, Generator, KeyPair, NetworkId, PlatformAddress, Private, Public, Random};
use cmerkle::skewed_merkle_root;
use cnetwork::NodeId;
use cstate::tests::helpers::empty_top_state;
use cstate::{FindActionHandler, StateDB, TopLevelState};
use ctimer::{TimeoutHandler, TimerToken};
use ctypes::transaction::{Action, Transaction};
Expand All @@ -58,6 +59,7 @@ use crate::client::{
AccountData, BlockChainClient, BlockChainTrait, BlockProducer, BlockStatus, EngineInfo, ImportBlock,
MiningBlockChainClient, StateInfo, StateOrBlock, TermInfo,
};
use crate::consensus::stake::{Validator, Validators};
use crate::consensus::EngineError;
use crate::db::{COL_STATE, NUM_COLUMNS};
use crate::encoded;
Expand Down Expand Up @@ -102,6 +104,10 @@ pub struct TestBlockChainClient {
pub history: RwLock<Option<u64>>,
/// Term ID
pub term_id: Option<u64>,
/// Fixed validator keys
pub validator_keys: RwLock<HashMap<Public, Private>>,
/// Fixed validators
pub validators: Validators,
}

impl Default for TestBlockChainClient {
Expand Down Expand Up @@ -153,7 +159,9 @@ impl TestBlockChainClient {
scheme,
latest_block_timestamp: RwLock::new(10_000_000),
history: RwLock::new(None),
term_id: None,
term_id: Some(1),
validator_keys: RwLock::new(HashMap::new()),
validators: Validators::from_vector_to_test(vec![]),
};

// insert genesis hash.
Expand Down Expand Up @@ -308,6 +316,26 @@ impl TestBlockChainClient {
pub fn set_history(&self, h: Option<u64>) {
*self.history.write() = h;
}

/// Set validators which can be brought from state.
pub fn set_random_validators(&mut self, count: usize) {
let mut pubkeys: Vec<Public> = vec![];
for _ in 0..count {
let random_priv_key = Private::from(H256::random());
let key_pair = KeyPair::from_private(random_priv_key).unwrap();
self.validator_keys.write().insert(*key_pair.public(), *key_pair.private());
pubkeys.push(*key_pair.public());
}
let fixed_validators: Validators = Validators::from_vector_to_test(
pubkeys.into_iter().map(|pubkey| Validator::new_for_test(0, 0, pubkey)).collect(),
);

self.validators = fixed_validators;
}

pub fn get_validators(&self) -> &Validators {
&self.validators
}
}

pub fn get_temp_state_db() -> StateDB {
Expand Down Expand Up @@ -627,6 +655,10 @@ impl TermInfo for TestBlockChainClient {

impl StateInfo for TestBlockChainClient {
fn state_at(&self, _id: BlockId) -> Option<TopLevelState> {
None
let statedb = StateDB::new_with_memorydb();
let mut top_state = empty_top_state(statedb);
let _ = self.validators.save_to_state(&mut top_state);

Some(top_state)
}
}
11 changes: 7 additions & 4 deletions core/src/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ mod null_engine;
mod signer;
mod simple_poa;
mod solo;
mod stake;
pub mod stake;
mod tendermint;
mod validator_set;
mod vote_collector;
Expand All @@ -31,9 +31,13 @@ pub use self::cuckoo::Cuckoo;
pub use self::null_engine::NullEngine;
pub use self::simple_poa::SimplePoA;
pub use self::solo::Solo;
pub use self::tendermint::{Tendermint, TendermintParams, TimeGapParams};
pub use self::tendermint::{
message_info_rlp, ConsensusMessage, Height, Step, Tendermint, TendermintParams, TimeGapParams, View, VoteOn,
VoteStep,
};
pub use self::validator_set::validator_list::RoundRobinValidator;
pub use self::validator_set::ValidatorSet;
pub use self::validator_set::{DynamicValidator, ValidatorSet};
pub use self::vote_collector::Message;

use std::fmt;
use std::sync::{Arc, Weak};
Expand All @@ -48,7 +52,6 @@ use ctypes::{CommonParams, Header};
use primitives::{Bytes, H256, U256};

use self::bit_set::BitSet;
use self::tendermint::types::View;
use crate::account_provider::AccountProvider;
use crate::block::{ExecutedBlock, SealedBlock};
use crate::client::ConsensusClient;
Expand Down
55 changes: 52 additions & 3 deletions core/src/consensus/solo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,18 @@ mod params;

use std::sync::Arc;

use ckey::Address;
use ckey::{Address, Error as KeyError, Public, SchnorrSignature};
use cstate::{ActionHandler, HitHandler};
use ctypes::{CommonParams, Header};
use primitives::H256;
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};

use self::params::SoloParams;
use super::stake;
use super::{ConsensusEngine, Seal};
use crate::block::{ExecutedBlock, IsBlock};
use crate::codechain_machine::CodeChainMachine;
use crate::consensus::{EngineError, EngineType};
use crate::consensus::{EngineError, EngineType, Message};
use crate::error::Error;

/// A consensus engine which does not provide any consensus mechanism.
Expand All @@ -37,14 +39,61 @@ pub struct Solo {
action_handlers: Vec<Arc<ActionHandler>>,
}

#[derive(Debug, PartialEq, Eq, Clone, Hash, Default)]
pub struct SoloMessage {}

impl Encodable for SoloMessage {
fn rlp_append(&self, s: &mut RlpStream) {
s.append_empty_data();
}
}

impl Decodable for SoloMessage {
fn decode(_rlp: &UntrustedRlp) -> Result<Self, DecoderError> {
Ok(SoloMessage {})
}
}

impl Message for SoloMessage {
type Round = bool;

fn signature(&self) -> SchnorrSignature {
SchnorrSignature::random()
}

fn signer_index(&self) -> usize {
Default::default()
}

fn block_hash(&self) -> Option<H256> {
None
}

fn round(&self) -> &bool {
&false
}

fn height(&self) -> u64 {
0
}

fn is_broadcastable(&self) -> bool {
false
}

fn verify(&self, _signer_public: &Public) -> Result<bool, KeyError> {
Ok(true)
}
}

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<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.clone())));
action_handlers.push(Arc::new(stake::Stake::<SoloMessage>::new(params.genesis_stakes.clone())));

Solo {
params,
Expand Down
13 changes: 13 additions & 0 deletions core/src/consensus/stake/action_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,15 @@ pub struct Validator {
}

impl Validator {
pub fn new_for_test(delegation: StakeQuantity, deposit: Deposit, pubkey: Public) -> Self {
Self {
weight: delegation,
delegation,
deposit,
pubkey,
}
}

fn new(delegation: StakeQuantity, deposit: Deposit, pubkey: Public) -> Self {
Self {
weight: delegation,
Expand All @@ -263,6 +272,10 @@ impl Validator {
#[derive(Debug)]
pub struct Validators(Vec<Validator>);
impl Validators {
pub fn from_vector_to_test(vec: Vec<Validator>) -> Self {
Validators(vec)
}

pub fn load_from_state(state: &TopLevelState) -> StateResult<Self> {
let key = &*VALIDATORS_KEY;
let validators = state.action_data(&key)?.map(|data| decode_list(&data)).unwrap_or_default();
Expand Down
Loading