-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathproposal_keeper.rs
210 lines (184 loc) · 6.57 KB
/
proposal_keeper.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
//! For storing proposals.
use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
use derive_where::derive_where;
use thiserror::Error;
use malachitebft_core_types::{Context, Proposal, Round, SignedProposal, Validity};
/// Errors can that be yielded when recording a proposal.
#[derive_where(Debug)]
#[derive(Error)]
pub enum RecordProposalError<Ctx>
where
Ctx: Context,
{
/// Attempted to record a conflicting proposal.
#[error("Conflicting proposal: existing: {existing}, conflicting: {conflicting}")]
ConflictingProposal {
/// The proposal already recorded for the same value.
existing: SignedProposal<Ctx>,
/// The conflicting proposal, from the same validator.
conflicting: SignedProposal<Ctx>,
},
/// Attempted to record a conflicting proposal from a different validator.
#[error("Invalid conflicting proposal: existing: {existing}, conflicting: {conflicting}")]
InvalidConflictingProposal {
/// The proposal already recorded for the same value.
existing: SignedProposal<Ctx>,
/// The conflicting proposal, from a different validator.
conflicting: SignedProposal<Ctx>,
},
}
#[derive_where(Clone, Debug, PartialEq, Eq, Default)]
struct PerRound<Ctx>
where
Ctx: Context,
{
/// The proposal received in a given round (proposal.round) if any.
proposal: Option<(SignedProposal<Ctx>, Validity)>,
}
impl<Ctx> PerRound<Ctx>
where
Ctx: Context,
{
/// Add a proposal to the round, checking for conflicts.
pub fn add(
&mut self,
proposal: SignedProposal<Ctx>,
validity: Validity,
) -> Result<(), RecordProposalError<Ctx>> {
if let Some((existing, _)) = self.get_proposal() {
if existing.value() != proposal.value() {
if existing.validator_address() != proposal.validator_address() {
// This is not a valid equivocating proposal, since the two proposers are different
// We should never reach this point, since the consensus algorithm should prevent this.
return Err(RecordProposalError::InvalidConflictingProposal {
existing: existing.clone(),
conflicting: proposal,
});
}
// This is an equivocating proposal
return Err(RecordProposalError::ConflictingProposal {
existing: existing.clone(),
conflicting: proposal,
});
}
}
// Add the proposal
self.proposal = Some((proposal, validity));
Ok(())
}
/// Return the proposal received from the given validator.
pub fn get_proposal(&self) -> Option<&(SignedProposal<Ctx>, Validity)> {
self.proposal.as_ref()
}
}
/// Keeps track of proposals.
#[derive_where(Clone, Debug, Default)]
pub struct ProposalKeeper<Ctx>
where
Ctx: Context,
{
/// The proposal for each round.
per_round: BTreeMap<Round, PerRound<Ctx>>,
/// Evidence of equivocation.
evidence: EvidenceMap<Ctx>,
}
impl<Ctx> ProposalKeeper<Ctx>
where
Ctx: Context,
{
/// Create a new `ProposalKeeper` instance
pub fn new() -> Self {
Self::default()
}
/// Return the proposal and validity for the round.
pub fn get_proposal_and_validity_for_round(
&self,
round: Round,
) -> Option<&(SignedProposal<Ctx>, Validity)> {
self.per_round
.get(&round)
.and_then(|round_info| round_info.proposal.as_ref())
}
/// Return the evidence of equivocation.
pub fn evidence(&self) -> &EvidenceMap<Ctx> {
&self.evidence
}
/// Store a proposal, checking for conflicts and storing evidence of equivocation if necessary.
///
/// # Precondition
/// - The given proposal must have been proposed by the expected proposer at the proposal's height and round.
pub fn store_proposal(&mut self, proposal: SignedProposal<Ctx>, validity: Validity) {
let per_round = self.per_round.entry(proposal.round()).or_default();
match per_round.add(proposal, validity) {
Ok(()) => (),
Err(RecordProposalError::ConflictingProposal {
existing,
conflicting,
}) => {
// This is an equivocating proposal
self.evidence.add(existing, conflicting);
}
Err(RecordProposalError::InvalidConflictingProposal {
existing,
conflicting,
}) => {
// This is not a valid equivocating proposal, since the two proposers are different
// We should never reach this point, since the consensus algorithm should prevent this.
unreachable!(
"Conflicting proposals from different validators: existing: {}, conflicting: {}",
existing.validator_address(), conflicting.validator_address()
);
}
}
}
}
/// Keeps track of evidence of equivocation.
#[derive_where(Clone, Debug, Default)]
pub struct EvidenceMap<Ctx>
where
Ctx: Context,
{
#[allow(clippy::type_complexity)]
map: BTreeMap<Ctx::Address, Vec<(SignedProposal<Ctx>, SignedProposal<Ctx>)>>,
}
impl<Ctx> EvidenceMap<Ctx>
where
Ctx: Context,
{
/// Create a new `EvidenceMap` instance.
pub fn new() -> Self {
Self::default()
}
/// Return whether or not there is any evidence of equivocation.
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Return the evidence of equivocation for a given address, if any.
pub fn get(
&self,
address: &Ctx::Address,
) -> Option<&Vec<(SignedProposal<Ctx>, SignedProposal<Ctx>)>> {
self.map.get(address)
}
/// Add evidence of equivocating proposals, ie. two proposals submitted by the same validator,
/// but with different values but for the same height and round.
///
/// # Precondition
/// - Panics if the two conflicting proposals were not proposed by the same validator.
pub(crate) fn add(&mut self, existing: SignedProposal<Ctx>, conflicting: SignedProposal<Ctx>) {
assert_eq!(
existing.validator_address(),
conflicting.validator_address()
);
if let Some(evidence) = self.map.get_mut(conflicting.validator_address()) {
evidence.push((existing, conflicting));
} else {
self.map.insert(
conflicting.validator_address().clone(),
vec![(existing, conflicting)],
);
}
}
}