-
Notifications
You must be signed in to change notification settings - Fork 39
/
state.rs
465 lines (440 loc) · 16.7 KB
/
state.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use super::*;
use eyre::eyre;
use serde::{Deserialize, Serialize};
use simperby_core::*;
use simperby_network::*;
use std::collections::{BTreeMap, BTreeSet};
use vetomint::{
BlockIdentifier, ConsensusEvent, ConsensusParams, ConsensusResponse, HeightInfo, Vetomint,
};
pub type Error = eyre::Error;
/// Consensus messages to propagate each other.
///
/// Note that all message are signed by DMS itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConsensusMessage {
Proposal {
round: ConsensusRound,
valid_round: Option<ConsensusRound>,
block_hash: Hash256,
},
NonNilPreVoted(ConsensusRound, Hash256),
NonNilPreCommitted(ConsensusRound, Hash256),
NilPreVoted(ConsensusRound),
NilPreCommitted(ConsensusRound),
}
impl ToHash256 for ConsensusMessage {
fn to_hash256(&self) -> Hash256 {
Hash256::hash(serde_spb::to_vec(self).unwrap())
}
}
impl DmsMessage for ConsensusMessage {
const DMS_TAG: &'static str = "consensus";
fn check(&self) -> Result<(), dms::Error> {
Ok(())
}
fn commit(
&self,
dms_key: &DmsKey,
private_key: &PrivateKey,
) -> Result<MessageCommitmentProof, simperby_core::CryptoError>
where
Self: Sized,
{
Ok(MessageCommitmentProof {
signature: match self {
ConsensusMessage::NonNilPreCommitted(round, block_hash) => Signature::sign(
FinalizationSignTarget {
block_hash: *block_hash,
round: *round,
}
.to_hash256(),
private_key,
)?,
_ => Signature::sign(
self.to_hash256().aggregate(&dms_key.to_hash256()),
private_key,
)?,
},
committer: private_key.public_key(),
})
}
fn verify_commitment(
&self,
proof: &MessageCommitmentProof,
dms_key: &DmsKey,
) -> Result<(), simperby_core::CryptoError> {
match self {
ConsensusMessage::NonNilPreCommitted(round, block_hash) => proof.signature.verify(
FinalizationSignTarget {
block_hash: *block_hash,
round: *round,
}
.to_hash256(),
&proof.committer,
),
_ => proof.signature.verify(
self.to_hash256().aggregate(&dms_key.to_hash256()),
&proof.committer,
),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct State {
/// The vetomint state machine.
vetomint: Vetomint,
/// The block header that this consensus is performing on.
block_header: BlockHeader,
/// An increasing counter for assigning block identifiers.
block_identifier_count: BlockIdentifier,
/// The list of the block hashes that have been verified.
verified_block_hashes: BTreeMap<Hash256, BlockIdentifier>,
/// The set of hashes of the block that are valid but vetoed by the user.
vetoed_block_hashes: BTreeSet<Hash256>,
/// The list of the events that are to be processed.
to_be_processed_events: Vec<(ConsensusEvent, Timestamp)>,
/// The set of messages that have been already updated to the Vetomint state machine.
updated_events: BTreeSet<ConsensusEvent>,
/// Messages by this node, which are to be broadcasted.
messages_to_broadcast: Vec<ConsensusMessage>,
/// Precommits collected so far, for each `(block, round)`.
precommits: BTreeMap<(Hash256, ConsensusRound), Vec<TypedSignature<FinalizationSignTarget>>>,
/// If `Some`, any operation on the consensus module will fail;
/// the user must run `new()` with the next height info.
finalized: Option<Finalization>,
}
impl State {
pub fn new(
block_header: &BlockHeader,
consensus_parameters: ConsensusParams,
round_zero_timestamp: Timestamp,
this_node_key: PrivateKey,
) -> Result<State, Error> {
let height_info = generate_height_info(
block_header,
consensus_parameters,
round_zero_timestamp,
this_node_key,
)?;
let state = State {
vetomint: Vetomint::new(height_info),
block_header: block_header.clone(),
block_identifier_count: 0,
to_be_processed_events: vec![(ConsensusEvent::Start, round_zero_timestamp)],
updated_events: BTreeSet::new(),
verified_block_hashes: BTreeMap::new(),
vetoed_block_hashes: BTreeSet::new(),
messages_to_broadcast: Vec::new(),
precommits: BTreeMap::new(),
finalized: None,
};
Ok(state)
}
pub fn check_finalized(&self) -> Option<Finalization> {
self.finalized.clone()
}
pub fn block_header(&self) -> &BlockHeader {
&self.block_header
}
pub fn register_verified_block_hash(&mut self, block_hash: Hash256) {
self.assert_not_finalized();
if self.verified_block_hashes.contains_key(&block_hash) {
return;
}
self.verified_block_hashes
.insert(block_hash, self.block_identifier_count);
self.block_identifier_count += 1;
}
pub fn set_proposal_candidate(
&mut self,
block_hash: Hash256,
timestamp: Timestamp,
) -> Result<(), Error> {
self.assert_not_finalized();
let block_index = self.get_block_index(&block_hash)?;
let consensus_event = ConsensusEvent::BlockCandidateUpdated {
proposal: block_index,
};
self.to_be_processed_events
.push((consensus_event, timestamp));
Ok(())
}
pub fn veto_block(&mut self, block_hash: Hash256) {
self.assert_not_finalized();
self.vetoed_block_hashes.insert(block_hash);
}
pub fn veto_round(&mut self, round: ConsensusRound, timestamp: Timestamp) {
self.assert_not_finalized();
let consensus_event = ConsensusEvent::SkipRound {
round: round as usize,
};
self.to_be_processed_events
.push((consensus_event, timestamp));
}
pub fn add_consensus_messages(
&mut self,
messages: Vec<(ConsensusMessage, PublicKey, Signature)>,
timestamp: Timestamp,
) {
self.assert_not_finalized();
for (message, author, signature) in messages {
if !self.is_consensus_message_acceptable(&message) {
continue;
}
let event = self.convert_consensus_message_to_event(
&message,
self.get_validator_index(&author)
.expect("dms signer must be one of the validators"),
);
if self.updated_events.contains(&event) {
continue;
}
self.to_be_processed_events.push((event, timestamp));
if let ConsensusMessage::NonNilPreCommitted(round, block_hash) = message {
self.precommits
.entry((block_hash, round))
.and_modify(|v| v.push(TypedSignature::new(signature.clone(), author.clone())))
.or_insert(vec![TypedSignature::new(signature, author)]);
}
}
}
pub fn progress(&mut self, timestamp: Timestamp) -> Vec<ProgressResult> {
self.assert_not_finalized();
let mut result = Vec::new();
self.to_be_processed_events
.push((ConsensusEvent::Timer, timestamp));
while let Some((event, timestamp)) = self.to_be_processed_events.pop() {
let responses = self.vetomint.progress(event.clone(), timestamp);
self.updated_events.insert(event);
for response in responses {
let (x, message) =
self.process_consensus_response_to_progress_result(response, timestamp);
result.push(x);
if let Some(message) = message {
self.messages_to_broadcast.push(message);
}
}
}
result
}
pub fn drain_messages_to_broadcast(&mut self) -> Vec<ConsensusMessage> {
self.assert_not_finalized();
std::mem::take(&mut self.messages_to_broadcast)
}
}
impl State {
fn assert_not_finalized(&self) {
if self.finalized.is_some() {
panic!("mutable operations on finalized state");
}
}
fn get_block_index(&self, block_hash: &Hash256) -> Result<usize, Error> {
self.verified_block_hashes
.get(block_hash)
.ok_or_else(|| eyre!("block not verified yet"))
.cloned()
}
fn get_validator_index(&self, public_key: &PublicKey) -> Result<usize, Error> {
self.block_header
.validator_set
.iter()
.position(|(x, _)| x == public_key)
.ok_or_else(|| eyre!("validator not found"))
}
/// Checks if the given message is assoicated with a verified block.
/// If not, it's not acceptable yet (though it could be turned out to be valid later).
fn is_consensus_message_acceptable(&self, message: &ConsensusMessage) -> bool {
match message {
ConsensusMessage::Proposal { block_hash, .. } => {
self.verified_block_hashes.contains_key(block_hash)
}
ConsensusMessage::NonNilPreVoted(_, block_hash) => {
self.verified_block_hashes.contains_key(block_hash)
}
ConsensusMessage::NonNilPreCommitted(_, block_hash) => {
self.verified_block_hashes.contains_key(block_hash)
}
_ => true,
}
}
fn process_consensus_response_to_progress_result(
&mut self,
response: ConsensusResponse,
timestamp: Timestamp,
) -> (ProgressResult, Option<ConsensusMessage>) {
fn get_block_hash(state: &State, index: BlockIdentifier) -> Hash256 {
*state
.verified_block_hashes
.iter()
.find(|(_, &v)| v == index)
.map(|(k, _)| k)
.expect("the block is not in verified_block_hashes")
}
match response {
ConsensusResponse::BroadcastProposal {
proposal,
valid_round,
round,
} => {
let block_hash = get_block_hash(self, proposal);
(
ProgressResult::Proposed(round as u64, block_hash, timestamp),
Some(ConsensusMessage::Proposal {
round: round as u64,
valid_round: valid_round.map(|r| r as u64),
block_hash,
}),
)
}
ConsensusResponse::BroadcastPrevote { proposal, round } => {
let (consensus_message, progress_result) = if let Some(block_index) = proposal {
let block_hash = get_block_hash(self, block_index);
(
ConsensusMessage::NonNilPreVoted(round as u64, block_hash),
ProgressResult::NonNilPreVoted(round as u64, block_hash, timestamp),
)
} else {
let message = ConsensusMessage::NilPreVoted(round as u64);
let result = ProgressResult::NilPreVoted(round as u64, timestamp);
(message, result)
};
(progress_result, Some(consensus_message))
}
ConsensusResponse::BroadcastPrecommit { proposal, round } => {
let (consensus_message, progress_result) = if let Some(block_index) = proposal {
let block_hash = get_block_hash(self, block_index);
(
ConsensusMessage::NonNilPreCommitted(round as u64, block_hash),
ProgressResult::NonNilPreCommitted(round as u64, block_hash, timestamp),
)
} else {
let message = ConsensusMessage::NilPreCommitted(round as u64);
let result = ProgressResult::NilPreCommitted(round as u64, timestamp);
(message, result)
};
(progress_result, Some(consensus_message))
}
ConsensusResponse::FinalizeBlock {
proposal, round, ..
} => {
let round = round as ConsensusRound;
let block_hash = get_block_hash(self, proposal);
let signatures = self
.precommits
.get(&(block_hash, round))
.cloned()
.expect("there must be valid precommits for the finalized block");
let finalization = Finalization {
block_hash,
timestamp,
proof: FinalizationProof { round, signatures },
};
self.finalized = Some(finalization.clone());
(ProgressResult::Finalized(finalization), None)
}
ConsensusResponse::ViolationReport {
violator,
misbehavior,
} => {
let pubkey = self
.block_header
.validator_set
.get(violator)
.expect("the violator must be in the validator set")
.0
.clone();
(
// TODO: add misbehavior handling
ProgressResult::ViolationReported(
pubkey,
format!("{misbehavior:?}"),
timestamp,
),
None,
)
}
}
}
fn convert_consensus_message_to_event(
&self,
consensus_message: &ConsensusMessage,
signer: usize,
) -> ConsensusEvent {
match consensus_message {
ConsensusMessage::Proposal {
round,
valid_round,
block_hash,
} => {
let valid_round = valid_round.map(|r| r as usize);
let index = self
.get_block_index(block_hash)
.expect("this must be already verified by the message filter");
ConsensusEvent::BlockProposalReceived {
proposal: index,
// Todo, Note: For now, all proposals are regarded as valid.
// See issue#201 (https://github.com/postech-dao/simperby/issues/201).
valid: true,
valid_round,
proposer: signer,
round: *round as usize,
favor: !self.vetoed_block_hashes.contains(block_hash),
}
}
ConsensusMessage::NonNilPreVoted(round, block_hash) => {
let index = self
.get_block_index(block_hash)
.expect("this must be already verified by the message filter");
ConsensusEvent::Prevote {
proposal: Some(index),
signer,
round: *round as usize,
}
}
ConsensusMessage::NonNilPreCommitted(round, block_hash) => {
let index = self
.get_block_index(block_hash)
.expect("this must be already verified by the message filter");
ConsensusEvent::Precommit {
proposal: Some(index),
signer,
round: *round as usize,
}
}
ConsensusMessage::NilPreVoted(round) => ConsensusEvent::Prevote {
proposal: None,
signer,
round: *round as usize,
},
ConsensusMessage::NilPreCommitted(round) => ConsensusEvent::Precommit {
proposal: None,
signer,
round: *round as usize,
},
}
}
}
fn generate_height_info(
header: &BlockHeader,
consensus_params: ConsensusParams,
round_zero_timestamp: Timestamp,
this_node_key: PrivateKey,
) -> Result<HeightInfo, Error> {
let this_node_index = header
.validator_set
.iter()
.position(|(pubkey, _)| *pubkey == this_node_key.public_key());
let info = HeightInfo {
validators: header
.validator_set
.iter()
.map(|(_, power)| *power)
.collect(),
this_node_index,
timestamp: round_zero_timestamp,
consensus_params,
initial_block_candidate: 0 as BlockIdentifier,
};
Ok(info)
}