Skip to content

Commit 558e867

Browse files
committed
Implement report_double_vote custom action
1 parent e039f3e commit 558e867

File tree

16 files changed

+221
-35
lines changed

16 files changed

+221
-35
lines changed

core/src/consensus/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ pub use self::solo::Solo;
3434
pub use self::tendermint::{Tendermint, TendermintParams, TimeGapParams};
3535
pub use self::validator_set::validator_list::RoundRobinValidator;
3636
pub use self::validator_set::ValidatorSet;
37+
pub use self::vote_collector::Message;
3738

3839
use std::fmt;
3940
use std::sync::{Arc, Weak};
@@ -273,6 +274,10 @@ pub trait ConsensusEngine: Sync + Send {
273274
self.action_handlers().iter().find(|handler| handler.handler_id() == id).map(AsRef::as_ref)
274275
}
275276

277+
fn get_validator_set(&self) -> Option<Arc<ValidatorSet>> {
278+
None
279+
}
280+
276281
fn possible_authors(&self, block_number: Option<u64>) -> Result<Option<Vec<Address>>, EngineError>;
277282
}
278283

@@ -353,6 +358,7 @@ pub trait CodeChainEngine: ConsensusEngine {
353358
&self,
354359
tx: &UnverifiedTransaction,
355360
common_params: &CommonParams,
361+
parent: &H256,
356362
) -> Result<(), Error> {
357363
if let Action::Custom {
358364
handler_id,
@@ -362,7 +368,8 @@ pub trait CodeChainEngine: ConsensusEngine {
362368
let handler = self
363369
.find_action_handler_for(*handler_id)
364370
.ok_or_else(|| SyntaxError::InvalidCustomAction(format!("{} is an invalid handler id", handler_id)))?;
365-
handler.verify(bytes, common_params)?;
371+
let validators = self.get_validator_set().map(|set| set.get_whole_publics(parent));
372+
handler.verify(bytes, common_params, validators)?;
366373
}
367374
self.machine().verify_transaction_with_params(tx, common_params)
368375
}

core/src/consensus/solo/mod.rs

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,18 @@ mod params;
1818

1919
use std::sync::Arc;
2020

21-
use ckey::Address;
21+
use ckey::{Address, SchnorrSignature};
2222
use cstate::{ActionHandler, HitHandler};
2323
use ctypes::{CommonParams, Header};
24+
use primitives::{Bytes, H256};
25+
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};
2426

2527
use self::params::SoloParams;
2628
use super::stake;
2729
use super::{ConsensusEngine, Seal};
2830
use crate::block::{ExecutedBlock, IsBlock};
2931
use crate::codechain_machine::CodeChainMachine;
30-
use crate::consensus::{EngineError, EngineType};
32+
use crate::consensus::{EngineError, EngineType, Message};
3133
use crate::error::Error;
3234

3335
/// A consensus engine which does not provide any consensus mechanism.
@@ -37,14 +39,57 @@ pub struct Solo {
3739
action_handlers: Vec<Arc<ActionHandler>>,
3840
}
3941

42+
#[derive(Debug, PartialEq, Eq, Clone, Hash, Default)]
43+
pub struct SoloMessage {}
44+
45+
impl Encodable for SoloMessage {
46+
fn rlp_append(&self, s: &mut RlpStream) {
47+
s.append_empty_data();
48+
}
49+
}
50+
51+
impl Decodable for SoloMessage {
52+
fn decode(_rlp: &UntrustedRlp) -> Result<Self, DecoderError> {
53+
Ok(SoloMessage {})
54+
}
55+
}
56+
57+
impl Message for SoloMessage {
58+
type Round = bool;
59+
60+
fn signature(&self) -> SchnorrSignature {
61+
SchnorrSignature::random()
62+
}
63+
64+
fn signer_index(&self) -> usize {
65+
Default::default()
66+
}
67+
68+
fn block_hash(&self) -> Option<H256> {
69+
None
70+
}
71+
72+
fn round(&self) -> &bool {
73+
&false
74+
}
75+
76+
fn is_broadcastable(&self) -> bool {
77+
false
78+
}
79+
80+
fn message_for_signature(&self) -> Bytes {
81+
Default::default()
82+
}
83+
}
84+
4085
impl Solo {
4186
/// Returns new instance of Solo over the given state machine.
4287
pub fn new(params: SoloParams, machine: CodeChainMachine) -> Self {
4388
let mut action_handlers: Vec<Arc<ActionHandler>> = Vec::new();
4489
if params.enable_hit_handler {
4590
action_handlers.push(Arc::new(HitHandler::new()));
4691
}
47-
action_handlers.push(Arc::new(stake::Stake::new(params.genesis_stakes.clone())));
92+
action_handlers.push(Arc::new(stake::Stake::<SoloMessage>::new(params.genesis_stakes.clone())));
4893

4994
Solo {
5095
params,

core/src/consensus/stake/actions.rs

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,24 @@
1414
// You should have received a copy of the GNU Affero General Public License
1515
// along with this program. If not, see <https://www.gnu.org/licenses/>.
1616

17-
use ccrypto::Blake;
18-
use ckey::{recover, Address, Signature};
17+
use ccrypto::{blake256, Blake};
18+
use ckey::{recover, verify_schnorr, Address, Public, Signature};
1919
use ctypes::errors::SyntaxError;
2020
use ctypes::CommonParams;
2121
use primitives::{Bytes, H256};
2222
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};
2323

24+
use consensus::vote_collector::Message;
25+
2426
const ACTION_TAG_TRANSFER_CCS: u8 = 1;
2527
const ACTION_TAG_DELEGATE_CCS: u8 = 2;
2628
const ACTION_TAG_REVOKE: u8 = 3;
2729
const ACTION_TAG_SELF_NOMINATE: u8 = 4;
30+
const ACTION_TAG_REPORT_DOUBLE_VOTE: u8 = 5;
2831
const ACTION_TAG_CHANGE_PARAMS: u8 = 0xFF;
2932

3033
#[derive(Debug, PartialEq)]
31-
pub enum Action {
34+
pub enum Action<M: Message> {
3235
TransferCCS {
3336
address: Address,
3437
quantity: u64,
@@ -50,10 +53,14 @@ pub enum Action {
5053
params: Box<CommonParams>,
5154
signatures: Vec<Signature>,
5255
},
56+
ReportDoubleVote {
57+
message1: M,
58+
message2: M,
59+
},
5360
}
5461

55-
impl Action {
56-
pub fn verify(&self, current_params: &CommonParams) -> Result<(), SyntaxError> {
62+
impl<M: Message> Action<M> {
63+
pub fn verify(&self, current_params: &CommonParams, signers: Option<Vec<Public>>) -> Result<(), SyntaxError> {
5764
match self {
5865
Action::TransferCCS {
5966
..
@@ -89,7 +96,7 @@ impl Action {
8996
)))
9097
}
9198
params.verify().map_err(SyntaxError::InvalidCustomAction)?;
92-
let action = Action::ChangeParams {
99+
let action = Action::<M>::ChangeParams {
93100
metadata_seq: *metadata_seq,
94101
params: params.clone(),
95102
signatures: vec![],
@@ -102,12 +109,42 @@ impl Action {
102109
})?;
103110
}
104111
}
112+
Action::ReportDoubleVote {
113+
message1,
114+
message2,
115+
} => {
116+
// what is the general verifying for general message?
117+
let message_for_signature = message1.message_for_signature();
118+
let message_hash = blake256(&message_for_signature);
119+
120+
let signature1 = message1.signature();
121+
let signature2 = message2.signature();
122+
123+
let signer_idx1 = message1.signer_index();
124+
let signer_idx2 = message2.signer_index();
125+
126+
let signers = signers.ok_or_else(|| {
127+
SyntaxError::InvalidCustomAction(String::from(
128+
"ReportDoubleVote Custom action is invalid for consensus engines without validators",
129+
))
130+
})?;
131+
let signer1 = signers
132+
.get(signer_idx1)
133+
.ok_or_else(|| SyntaxError::InvalidCustomAction(String::from("Invalid signer index")))?;
134+
let signer2 = signers
135+
.get(signer_idx2)
136+
.ok_or_else(|| SyntaxError::InvalidCustomAction(String::from("Invalid signer index")))?;
137+
138+
verify_schnorr(signer1, &signature1, &message_hash)
139+
.and(verify_schnorr(signer2, &signature2, &message_hash))
140+
.map_err(|err| SyntaxError::InvalidCustomAction(format!("{}", err)))?;
141+
}
105142
}
106143
Ok(())
107144
}
108145
}
109146

110-
impl Encodable for Action {
147+
impl<M: Message> Encodable for Action<M> {
111148
fn rlp_append(&self, s: &mut RlpStream) {
112149
match self {
113150
Action::TransferCCS {
@@ -147,11 +184,17 @@ impl Encodable for Action {
147184
s.append(signature);
148185
}
149186
}
187+
Action::ReportDoubleVote {
188+
message1,
189+
message2,
190+
} => {
191+
s.begin_list(3).append(&ACTION_TAG_REPORT_DOUBLE_VOTE).append(message1).append(message2);
192+
}
150193
};
151194
}
152195
}
153196

154-
impl Decodable for Action {
197+
impl<M: Message> Decodable for Action<M> {
155198
fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> {
156199
let tag = rlp.val_at(0)?;
157200
match tag {
@@ -224,6 +267,21 @@ impl Decodable for Action {
224267
signatures,
225268
})
226269
}
270+
ACTION_TAG_REPORT_DOUBLE_VOTE => {
271+
let item_count = rlp.item_count()?;
272+
if item_count != 3 {
273+
return Err(DecoderError::RlpIncorrectListLen {
274+
expected: 3,
275+
got: item_count,
276+
})
277+
}
278+
let message1 = rlp.val_at(1)?;
279+
let message2 = rlp.val_at(2)?;
280+
Ok(Action::ReportDoubleVote {
281+
message1,
282+
message2,
283+
})
284+
}
227285
_ => Err(DecoderError::Custom("Unexpected Tendermint Stake Action Type")),
228286
}
229287
}
@@ -247,7 +305,7 @@ mod tests {
247305
expected: 4,
248306
got: 3,
249307
}),
250-
UntrustedRlp::new(&rlp::encode(&action)).as_val::<Action>()
308+
UntrustedRlp::new(&rlp::encode(&action)).as_val::<Action>::<_>()
251309
);
252310
}
253311

0 commit comments

Comments
 (0)