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
use std::fmt::Debug;
use util::*;
use rlp::Encodable;
pub trait Message: Clone + PartialEq + Eq + Hash + Encodable + Debug {
type Round: Clone + PartialEq + Eq + Hash + Default + Debug + Ord;
fn signature(&self) -> H520;
fn block_hash(&self) -> Option<H256>;
fn round(&self) -> &Self::Round;
fn is_broadcastable(&self) -> bool;
}
#[derive(Debug)]
pub struct VoteCollector<M: Message> {
votes: RwLock<BTreeMap<M::Round, StepCollector<M>>>,
}
#[derive(Debug, Default)]
struct StepCollector<M: Message> {
voted: HashSet<Address>,
pub block_votes: HashMap<Option<H256>, HashMap<H520, Address>>,
messages: HashSet<M>,
}
impl <M: Message> StepCollector<M> {
fn insert<'a>(&mut self, message: M, address: &'a Address) -> Option<&'a Address> {
if self.messages.insert(message.clone()) {
if self.voted.insert(address.clone()) {
self
.block_votes
.entry(message.block_hash())
.or_insert_with(HashMap::new)
.insert(message.signature(), address.clone());
} else {
return Some(address);
}
}
None
}
fn count_block(&self, block_hash: &Option<H256>) -> usize {
self.block_votes.get(block_hash).map_or(0, HashMap::len)
}
fn count(&self) -> usize {
self.block_votes.values().map(HashMap::len).sum()
}
}
#[derive(Debug)]
pub struct SealSignatures {
pub proposal: H520,
pub votes: Vec<H520>,
}
impl PartialEq for SealSignatures {
fn eq(&self, other: &SealSignatures) -> bool {
self.proposal == other.proposal
&& self.votes.iter().collect::<HashSet<_>>() == other.votes.iter().collect::<HashSet<_>>()
}
}
impl Eq for SealSignatures {}
impl <M: Message + Default> Default for VoteCollector<M> {
fn default() -> Self {
let mut collector = BTreeMap::new();
collector.insert(Default::default(), Default::default());
VoteCollector { votes: RwLock::new(collector) }
}
}
impl <M: Message + Default + Encodable + Debug> VoteCollector<M> {
pub fn vote<'a>(&self, message: M, voter: &'a Address) -> Option<&'a Address> {
self
.votes
.write()
.entry(message.round().clone())
.or_insert_with(Default::default)
.insert(message, voter)
}
pub fn is_old_or_known(&self, message: &M) -> bool {
self
.votes
.read()
.get(&message.round())
.map_or(false, |c| {
let is_known = c.messages.contains(message);
if is_known { trace!(target: "poa", "Known message: {:?}.", message); }
is_known
})
|| {
let guard = self.votes.read();
let is_old = guard.keys().next().map_or(true, |oldest| message.round() <= oldest);
if is_old { trace!(target: "poa", "Old message {:?}.", message); }
is_old
}
}
pub fn throw_out_old(&self, vote_round: &M::Round) {
let mut guard = self.votes.write();
let new_collector = guard.split_off(vote_round);
*guard = new_collector;
}
pub fn seal_signatures(&self, proposal_round: M::Round, commit_round: M::Round, block_hash: &H256) -> Option<SealSignatures> {
let ref bh = Some(*block_hash);
let maybe_seal = {
let guard = self.votes.read();
guard
.get(&proposal_round)
.and_then(|c| c.block_votes.get(bh))
.and_then(|proposals| proposals.keys().next())
.map(|proposal| SealSignatures {
proposal: proposal.clone(),
votes: guard
.get(&commit_round)
.and_then(|c| c.block_votes.get(bh))
.map(|precommits| precommits.keys().cloned().collect())
.unwrap_or_else(Vec::new),
})
.and_then(|seal| if seal.votes.is_empty() { None } else { Some(seal) })
};
if maybe_seal.is_some() {
self.throw_out_old(&commit_round);
}
maybe_seal
}
pub fn count_aligned_votes(&self, message: &M) -> usize {
self
.votes
.read()
.get(&message.round())
.map_or(0, |m| m.count_block(&message.block_hash()))
}
pub fn count_round_votes(&self, vote_round: &M::Round) -> usize {
self.votes.read().get(vote_round).map_or(0, StepCollector::count)
}
pub fn get_up_to(&self, round: &M::Round) -> Vec<Bytes> {
let guard = self.votes.read();
guard
.iter()
.take_while(|&(r, _)| r <= round)
.map(|(_, c)| c.messages.iter().filter(|m| m.is_broadcastable()).map(|m| ::rlp::encode(m).to_vec()).collect::<Vec<_>>())
.fold(Vec::new(), |mut acc, mut messages| { acc.append(&mut messages); acc })
}
pub fn get(&self, message: &M) -> Option<Address> {
let guard = self.votes.read();
guard.get(&message.round()).and_then(|c| c.block_votes.get(&message.block_hash())).and_then(|origins| origins.get(&message.signature()).cloned())
}
#[cfg(test)]
pub fn len(&self) -> usize {
self.votes.read().len()
}
}
#[cfg(test)]
mod tests {
use util::*;
use rlp::*;
use super::*;
#[derive(Debug, PartialEq, Eq, Clone, Hash, Default)]
struct TestMessage {
step: TestStep,
block_hash: Option<H256>,
signature: H520,
}
type TestStep = u64;
impl Message for TestMessage {
type Round = TestStep;
fn signature(&self) -> H520 { self.signature }
fn block_hash(&self) -> Option<H256> { self.block_hash }
fn round(&self) -> &TestStep { &self.step }
fn is_broadcastable(&self) -> bool { true }
}
impl Encodable for TestMessage {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(3)
.append(&self.signature)
.append(&self.step)
.append(&self.block_hash.unwrap_or_else(H256::zero));
}
}
fn random_vote(collector: &VoteCollector<TestMessage>, signature: H520, step: TestStep, block_hash: Option<H256>) -> bool {
full_vote(collector, signature, step, block_hash, &H160::random()).is_none()
}
fn full_vote<'a>(collector: &VoteCollector<TestMessage>, signature: H520, step: TestStep, block_hash: Option<H256>, address: &'a Address) -> Option<&'a Address> {
collector.vote(TestMessage { signature: signature, step: step, block_hash: block_hash }, address)
}
#[test]
fn seal_retrieval() {
let collector = VoteCollector::default();
let bh = Some("1".sha3());
let mut signatures = Vec::new();
for _ in 0..5 {
signatures.push(H520::random());
}
let propose_round = 3;
let commit_round = 5;
random_vote(&collector, signatures[4].clone(), 1, bh.clone());
random_vote(&collector, signatures[0].clone(), propose_round.clone(), bh.clone());
random_vote(&collector, signatures[0].clone(), propose_round.clone(), Some("0".sha3()));
random_vote(&collector, signatures[3].clone(), commit_round.clone(), Some("0".sha3()));
random_vote(&collector, signatures[0].clone(), 6, bh.clone());
random_vote(&collector, signatures[0].clone(), 4, bh.clone());
random_vote(&collector, signatures[2].clone(), commit_round.clone(), bh.clone());
random_vote(&collector, signatures[2].clone(), commit_round.clone(), bh.clone());
random_vote(&collector, signatures[4].clone(), 6, bh.clone());
random_vote(&collector, signatures[1].clone(), commit_round.clone(), bh.clone());
random_vote(&collector, signatures[1].clone(), 7, bh.clone());
let seal = SealSignatures {
proposal: signatures[0],
votes: signatures[1..3].to_vec()
};
assert_eq!(seal, collector.seal_signatures(propose_round, commit_round, &bh.unwrap()).unwrap());
}
#[test]
fn count_votes() {
let collector = VoteCollector::default();
let round1 = 1;
let round3 = 3;
random_vote(&collector, H520::random(), round1, Some("0".sha3()));
random_vote(&collector, H520::random(), 0, Some("0".sha3()));
random_vote(&collector, H520::random(), round3, Some("0".sha3()));
random_vote(&collector, H520::random(), 2, Some("0".sha3()));
random_vote(&collector, H520::random(), round1, Some("1".sha3()));
let same_sig = H520::random();
random_vote(&collector, same_sig.clone(), round1, Some("1".sha3()));
random_vote(&collector, same_sig, round1, Some("1".sha3()));
random_vote(&collector, H520::random(), round3, Some("1".sha3()));
random_vote(&collector, H520::random(), round1, Some("0".sha3()));
random_vote(&collector, H520::random(), 4, Some("2".sha3()));
assert_eq!(collector.count_round_votes(&round1), 4);
assert_eq!(collector.count_round_votes(&round3), 2);
let message = TestMessage {
signature: H520::default(),
step: round1,
block_hash: Some("1".sha3())
};
assert_eq!(collector.count_aligned_votes(&message), 2);
}
#[test]
fn remove_old() {
let collector = VoteCollector::default();
let vote = |round, hash| {
random_vote(&collector, H520::random(), round, hash);
};
vote(6, Some("0".sha3()));
vote(3, Some("0".sha3()));
vote(7, Some("0".sha3()));
vote(8, Some("1".sha3()));
vote(1, Some("1".sha3()));
collector.throw_out_old(&7);
assert_eq!(collector.len(), 2);
}
#[test]
fn malicious_authority() {
let collector = VoteCollector::default();
let round = 3;
assert!(full_vote(&collector, H520::random(), round, Some("0".sha3()), &Address::default()).is_none());
full_vote(&collector, H520::random(), round, Some("1".sha3()), &Address::default()).unwrap();
assert_eq!(collector.count_round_votes(&round), 1);
}
}