1use alloc::borrow::ToOwned;
15use alloc::collections::BTreeMap;
16use alloc::string::String;
17use alloc::sync::Arc;
18use alloc::vec::Vec;
19use core::fmt;
20
21use heika_core::hash::Hash256;
22
23use super::FinalizedBlockHeader;
24use super::aggregator::RoundAggregator;
25use super::message::{FinalizationMessage, SIGNATURE_SIZE, u32_at};
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct ProofParameters {
30 pub voting_set_grouping: u64,
32 pub size: u64,
34 pub threshold: u64,
36 pub max_hashes_per_point: u64,
38}
39
40impl ProofParameters {
41 pub fn voting_set_end_height(&self, epoch: u32) -> u64 {
44 if epoch == 1 {
45 1
46 } else {
47 (u64::from(epoch) - 1) * self.voting_set_grouping
48 }
49 }
50}
51
52#[derive(Clone, Default, Debug, PartialEq, Eq)]
54pub struct VotingSet {
55 pub voters: BTreeMap<[u8; 32], u64>,
56}
57
58impl VotingSet {
59 pub fn total(&self) -> u64 {
61 self.voters.values().sum()
62 }
63
64 pub fn encode(&self) -> Vec<u8> {
66 let mut out = Vec::with_capacity(4 + self.voters.len() * 40);
67 out.extend_from_slice(&(self.voters.len() as u32).to_le_bytes());
68 for (key, weight) in &self.voters {
69 out.extend_from_slice(key);
70 out.extend_from_slice(&weight.to_le_bytes());
71 }
72 out
73 }
74
75 pub fn decode(bytes: &[u8]) -> Option<Self> {
76 let count = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?) as usize;
77 let rest = bytes.get(4..)?;
78 if rest.len() != count * 40 {
79 return None;
80 }
81 let voters = rest
82 .as_chunks::<40>()
83 .0
84 .iter()
85 .map(|chunk| {
86 (
87 chunk[..32].try_into().expect("32 bytes"),
88 u64::from_le_bytes(chunk[32..].try_into().expect("8 bytes")),
89 )
90 })
91 .collect();
92 Some(Self { voters })
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ProofError {
99 Malformed(String),
101 Version(u32),
102 Epoch {
103 expected: u32,
104 actual: u32,
105 },
106 Message {
108 index: usize,
109 reason: MessageError,
110 },
111 NoPrecommit,
113 Mismatch {
115 height: u64,
116 hash: Hash256,
117 },
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum MessageError {
122 InvalidHashes,
124 InvalidHeight,
126 Conflicting,
128 Redundant,
130 Voter,
132 Signature,
133}
134
135impl fmt::Display for ProofError {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 match self {
138 Self::Malformed(what) => write!(f, "証明の形が読めません: {what}"),
139 Self::Version(version) => write!(f, "知らない版の証明です({version})"),
140 Self::Epoch { expected, actual } => {
141 write!(f, "エポック {expected} の証明のはずが、{actual} です")
142 }
143 Self::Message { index, reason } => {
144 write!(f, "{index} 番目のメッセージを足せません: {reason:?}")
145 }
146 Self::NoPrecommit => write!(f, "閾値を超えた precommit がありません"),
147 Self::Mismatch { height, hash } => write!(
148 f,
149 "閾値を超えたいちばん高いブロックは、高さ {height} の {hash} で、証明の言うものと違います"
150 ),
151 }
152 }
153}
154
155impl core::error::Error for ProofError {}
156
157const PROOF_HEADER_SIZE: usize = 8 + FinalizedBlockHeader::SIZE;
158const GROUP_HEADER_SIZE: usize = 4 + 4 + 4 + 4 + 8;
160
161pub fn proof_header(proof: &[u8]) -> Result<FinalizedBlockHeader, ProofError> {
163 let malformed = |what: &str| ProofError::Malformed(what.to_owned());
164 if proof.len() < PROOF_HEADER_SIZE {
165 return Err(malformed("見出しより短い"));
166 }
167 if u32_at(proof, 0) as usize != proof.len() {
168 return Err(malformed("大きさが合わない"));
169 }
170 let version = u32_at(proof, 4);
171 if version != 1 {
172 return Err(ProofError::Version(version));
173 }
174 FinalizedBlockHeader::from_bytes(&proof[8..PROOF_HEADER_SIZE]).map_err(|_| malformed("見出し"))
175}
176
177pub fn build_proof<'a>(
183 header: &FinalizedBlockHeader,
184 messages: impl IntoIterator<Item = &'a FinalizationMessage>,
185) -> Vec<u8> {
186 type Group<'a> = (&'a FinalizationMessage, Vec<[u8; SIGNATURE_SIZE]>);
188 let mut groups: BTreeMap<(usize, Vec<u8>), Group> = BTreeMap::new();
189 for message in messages {
190 if message.round != header.round {
191 continue;
192 }
193 groups
194 .entry((message.size(), message.signed_part()))
195 .or_insert_with(|| (message, Vec::new()))
196 .1
197 .push(message.signature);
198 }
199 let mut body = Vec::new();
200 for (template, signatures) in groups.values() {
201 let size =
202 GROUP_HEADER_SIZE + template.hashes.len() * 32 + signatures.len() * SIGNATURE_SIZE;
203 body.extend_from_slice(&(size as u32).to_le_bytes());
204 body.extend_from_slice(&(template.hashes.len() as u32).to_le_bytes());
205 body.extend_from_slice(&(signatures.len() as u32).to_le_bytes());
206 body.extend_from_slice(&u32::from(!template.is_prevote).to_le_bytes());
207 body.extend_from_slice(&template.height.to_le_bytes());
208 for hash in &template.hashes {
209 body.extend_from_slice(&hash.0);
210 }
211 for signature in signatures {
212 body.extend_from_slice(signature);
213 }
214 }
215 let size = PROOF_HEADER_SIZE + body.len();
216 let mut proof = Vec::with_capacity(size);
217 proof.extend_from_slice(&(size as u32).to_le_bytes());
218 proof.extend_from_slice(&1u32.to_le_bytes());
219 proof.extend_from_slice(&header.to_bytes());
220 proof.extend_from_slice(&body);
221 proof
222}
223
224pub fn closes_epoch(header: &FinalizedBlockHeader, voting_set_grouping: u64) -> bool {
227 match u64::from(header.round.epoch) {
228 1 => header.height == 1,
229 epoch => header.height == (epoch - 1) * voting_set_grouping,
230 }
231}
232
233pub fn verify_proof(
235 proof: &[u8],
236 epoch: u32,
237 voters: &VotingSet,
238 parameters: &ProofParameters,
239) -> Result<FinalizedBlockHeader, ProofError> {
240 let malformed = |what: &str| ProofError::Malformed(what.to_owned());
241 let header = proof_header(proof)?;
242 if header.round.epoch != epoch {
243 return Err(ProofError::Epoch {
244 expected: epoch,
245 actual: header.round.epoch,
246 });
247 }
248
249 let mut aggregator = RoundAggregator::new(epoch, Arc::new(voters.clone()), *parameters);
250 let mut index = 0;
251 let mut offset = PROOF_HEADER_SIZE;
252 while offset < proof.len() {
253 let group = proof
254 .get(offset..)
255 .filter(|rest| rest.len() >= GROUP_HEADER_SIZE);
256 let group = group.ok_or_else(|| malformed("組の見出し"))?;
257 let group_size = u32_at(group, 0) as usize;
258 let hashes_count = u32_at(group, 4) as usize;
259 let signatures_count = u32_at(group, 8) as usize;
260 let stage = u32_at(group, 12);
261 let height = u64::from_le_bytes(group[16..24].try_into().expect("8 bytes"));
262 let real_size = GROUP_HEADER_SIZE + hashes_count * 32 + signatures_count * SIGNATURE_SIZE;
263 if group_size != real_size || group.len() < group_size {
264 return Err(malformed("組の大きさ"));
265 }
266 let is_prevote = match stage {
267 0 => true,
268 1 => false,
269 _ => return Err(malformed("組の段階")),
270 };
271 let hashes: Vec<Hash256> = group[GROUP_HEADER_SIZE..GROUP_HEADER_SIZE + hashes_count * 32]
272 .as_chunks::<32>()
273 .0
274 .iter()
275 .map(|hash| Hash256(*hash))
276 .collect();
277 let signatures = &group[GROUP_HEADER_SIZE + hashes_count * 32..group_size];
278 for signature in signatures.as_chunks::<SIGNATURE_SIZE>().0 {
279 let message = FinalizationMessage {
280 round: header.round,
281 is_prevote,
282 height,
283 hashes: hashes.clone(),
284 signature: *signature,
285 };
286 aggregator
287 .add(message)
288 .map_err(|reason| ProofError::Message { index, reason })?;
289 index += 1;
290 }
291 offset += group_size;
293 if offset < proof.len() {
294 offset = offset.next_multiple_of(8);
295 }
296 }
297
298 let (best_height, best_hash) = aggregator
299 .round()
300 .best_precommit()
301 .ok_or(ProofError::NoPrecommit)?;
302 if best_height != header.height || best_hash != header.hash {
303 return Err(ProofError::Mismatch {
304 height: best_height,
305 hash: best_hash,
306 });
307 }
308 Ok(header)
309}
310
311#[cfg(test)]
312mod tests {
313 use super::super::FinalizationRound;
314 use super::super::message::testing::{Voter, block_hash};
315 use super::*;
316
317 const PARAMETERS: ProofParameters = ProofParameters {
319 voting_set_grouping: 10,
320 size: 10_000,
321 threshold: 6_700,
322 max_hashes_per_point: 256,
323 };
324 const EPOCH: u32 = 3;
325 const ROUND: FinalizationRound = FinalizationRound {
326 epoch: EPOCH,
327 point: 2,
328 };
329
330 struct Group<'a> {
331 is_prevote: bool,
332 height: u64,
333 hashes: Vec<Hash256>,
334 voters: Vec<&'a Voter>,
335 }
336
337 fn prevote(height: u64, through: u64, voters: Vec<&Voter>) -> Group<'_> {
338 Group {
339 is_prevote: true,
340 height,
341 hashes: (height..=through).map(|at| block_hash(at, 0)).collect(),
342 voters,
343 }
344 }
345
346 fn precommit(height: u64, voters: Vec<&Voter>) -> Group<'_> {
347 Group {
348 is_prevote: false,
349 height,
350 hashes: vec![block_hash(height, 0)],
351 voters,
352 }
353 }
354
355 fn build(header: &FinalizedBlockHeader, groups: &[Group]) -> Vec<u8> {
357 let mut body = Vec::new();
358 for (index, group) in groups.iter().enumerate() {
359 let unsigned = FinalizationMessage {
360 round: header.round,
361 is_prevote: group.is_prevote,
362 height: group.height,
363 hashes: group.hashes.clone(),
364 signature: [0; SIGNATURE_SIZE],
365 };
366 let signed = unsigned.signed_part();
367 let hashes = &signed[24..];
368 let size = GROUP_HEADER_SIZE + hashes.len() + group.voters.len() * SIGNATURE_SIZE;
369 body.extend_from_slice(&(size as u32).to_le_bytes());
370 body.extend_from_slice(&(group.hashes.len() as u32).to_le_bytes());
371 body.extend_from_slice(&(group.voters.len() as u32).to_le_bytes());
372 body.extend_from_slice(&u32::from(!group.is_prevote).to_le_bytes());
373 body.extend_from_slice(&group.height.to_le_bytes());
374 body.extend_from_slice(hashes);
375 for voter in &group.voters {
376 body.extend_from_slice(&voter.sign(header.round, &signed));
377 }
378 if index + 1 < groups.len() {
379 body.resize(body.len().next_multiple_of(8), 0);
380 }
381 }
382 let size = PROOF_HEADER_SIZE + body.len();
383 let mut proof = Vec::with_capacity(size);
384 proof.extend_from_slice(&(size as u32).to_le_bytes());
385 proof.extend_from_slice(&1u32.to_le_bytes());
386 proof.extend_from_slice(&header.to_bytes());
387 proof.extend_from_slice(&body);
388 proof
389 }
390
391 fn header_at(height: u64) -> FinalizedBlockHeader {
392 FinalizedBlockHeader {
393 round: ROUND,
394 height,
395 hash: block_hash(height, 0),
396 }
397 }
398
399 fn voters() -> [Voter; 3] {
401 [Voter::new(1), Voter::new(2), Voter::new(3)]
402 }
403
404 fn voting_set(voters: &[Voter], weights: &[u64]) -> VotingSet {
405 VotingSet {
406 voters: voters
407 .iter()
408 .zip(weights)
409 .map(|(voter, weight)| (voter.key(), *weight))
410 .collect(),
411 }
412 }
413
414 fn verify(proof: &[u8], voters: &[Voter]) -> Result<FinalizedBlockHeader, ProofError> {
415 verify_proof(
416 proof,
417 EPOCH,
418 &voting_set(voters, &[40, 30, 30]),
419 &PARAMETERS,
420 )
421 }
422
423 #[test]
424 fn accepts_a_proof_with_enough_weight() {
425 let voters = voters();
426 let [a, b, c] = &voters;
427 let header = header_at(15);
428 let proof = build(
429 &header,
430 &[prevote(10, 15, vec![a, b, c]), precommit(15, vec![a, b, c])],
431 );
432 assert_eq!(verify(&proof, &voters), Ok(header));
433 assert_eq!(proof_header(&proof), Ok(header));
434 let proof = build(
436 &header,
437 &[prevote(10, 15, vec![a, b]), precommit(15, vec![a, b])],
438 );
439 assert_eq!(verify(&proof, &voters), Ok(header));
440 }
441
442 #[test]
443 fn counts_a_precommit_that_comes_before_its_prevote() {
444 let voters = voters();
445 let [a, b, c] = &voters;
446 let header = header_at(15);
447 let proof = build(
448 &header,
449 &[precommit(15, vec![a, b, c]), prevote(10, 15, vec![a, b, c])],
450 );
451 assert_eq!(verify(&proof, &voters), Ok(header));
452 }
453
454 #[test]
455 fn rejects_too_little_weight() {
456 let voters = voters();
457 let [a, b, c] = &voters;
458 let proof = build(
460 &header_at(15),
461 &[prevote(10, 15, vec![b, c]), precommit(15, vec![b, c])],
462 );
463 assert_eq!(verify(&proof, &voters), Err(ProofError::NoPrecommit));
464 let proof = build(
466 &header_at(15),
467 &[prevote(10, 15, vec![a, b, c]), precommit(15, vec![a])],
468 );
469 assert_eq!(verify(&proof, &voters), Err(ProofError::NoPrecommit));
470 }
471
472 #[test]
473 fn rejects_a_header_that_is_not_the_best_precommit() {
474 let voters = voters();
475 let [a, b, c] = &voters;
476 let proof = build(
477 &header_at(14),
478 &[prevote(10, 15, vec![a, b, c]), precommit(15, vec![a, b, c])],
479 );
480 assert_eq!(
481 verify(&proof, &voters),
482 Err(ProofError::Mismatch {
483 height: 15,
484 hash: block_hash(15, 0)
485 })
486 );
487 }
488
489 #[test]
490 fn rejects_double_and_repeated_votes() {
491 let voters = voters();
492 let [a, b, c] = &voters;
493 let header = header_at(15);
494 let mut forked = prevote(10, 15, vec![a]);
495 forked.hashes[5] = block_hash(15, 1);
496 let proof = build(
497 &header,
498 &[
499 prevote(10, 15, vec![a, b, c]),
500 forked,
501 precommit(15, vec![a, b, c]),
502 ],
503 );
504 assert_eq!(
505 verify(&proof, &voters),
506 Err(ProofError::Message {
507 index: 3,
508 reason: MessageError::Conflicting
509 })
510 );
511 let proof = build(
512 &header,
513 &[
514 prevote(10, 15, vec![a, b, c, a]),
515 precommit(15, vec![a, b, c]),
516 ],
517 );
518 assert_eq!(
519 verify(&proof, &voters),
520 Err(ProofError::Message {
521 index: 3,
522 reason: MessageError::Redundant
523 })
524 );
525 }
526
527 #[test]
528 fn rejects_strangers_and_broken_signatures() {
529 let voters = voters();
530 let [a, b, c] = &voters;
531 let stranger = Voter::new(9);
532 let header = header_at(15);
533 let proof = build(
534 &header,
535 &[prevote(10, 15, vec![a, &stranger]), precommit(15, vec![a])],
536 );
537 assert_eq!(
538 verify(&proof, &voters),
539 Err(ProofError::Message {
540 index: 1,
541 reason: MessageError::Voter
542 })
543 );
544 let mut proof = build(
545 &header,
546 &[prevote(10, 15, vec![a, b, c]), precommit(15, vec![a, b, c])],
547 );
548 let last = PROOF_HEADER_SIZE + GROUP_HEADER_SIZE + 6 * 32 + SIGNATURE_SIZE - 1;
550 proof[last] ^= 1;
551 assert_eq!(
552 verify(&proof, &voters),
553 Err(ProofError::Message {
554 index: 0,
555 reason: MessageError::Signature
556 })
557 );
558 }
559
560 #[test]
561 fn rejects_hashes_outside_the_epoch() {
562 let voters = voters();
563 let [a, ..] = &voters;
564 let header = header_at(15);
565 for group in [prevote(9, 15, vec![a]), prevote(15, 21, vec![a])] {
567 let proof = build(&header, &[group]);
568 assert_eq!(
569 verify(&proof, &voters),
570 Err(ProofError::Message {
571 index: 0,
572 reason: MessageError::InvalidHashes
573 })
574 );
575 }
576 let mut group = precommit(15, vec![a]);
578 group.hashes.push(block_hash(16, 0));
579 assert_eq!(
580 verify(&build(&header, &[group]), &voters),
581 Err(ProofError::Message {
582 index: 0,
583 reason: MessageError::InvalidHashes
584 })
585 );
586 let proof = build(&header, &[precommit(9, vec![a])]);
588 assert_eq!(
589 verify(&proof, &voters),
590 Err(ProofError::Message {
591 index: 0,
592 reason: MessageError::InvalidHeight
593 })
594 );
595 }
596
597 #[test]
598 fn rejects_malformed_proofs() {
599 let voters = voters();
600 let [a, b, c] = &voters;
601 let proof = build(
602 &header_at(15),
603 &[prevote(10, 15, vec![a, b, c]), precommit(15, vec![a, b, c])],
604 );
605 assert_eq!(
606 verify_proof(&proof, 4, &voting_set(&voters, &[40, 30, 30]), &PARAMETERS),
607 Err(ProofError::Epoch {
608 expected: 4,
609 actual: 3
610 })
611 );
612 let mut versioned = proof.clone();
613 versioned[4] = 2;
614 assert_eq!(verify(&versioned, &voters), Err(ProofError::Version(2)));
615 assert!(matches!(
616 verify(&proof[..proof.len() - 1], &voters),
617 Err(ProofError::Malformed(_))
618 ));
619 assert!(matches!(
620 proof_header(&proof[..10]),
621 Err(ProofError::Malformed(_))
622 ));
623 let mut staged = proof.clone();
624 staged[PROOF_HEADER_SIZE + 12] = 2;
625 assert!(matches!(
626 verify(&staged, &voters),
627 Err(ProofError::Malformed(_))
628 ));
629 }
630
631 #[test]
632 fn voting_sets_round_trip() {
633 let voters = voters();
634 let set = voting_set(&voters, &[40, 30, 30]);
635 assert_eq!(set.total(), 100);
636 assert_eq!(VotingSet::decode(&set.encode()), Some(set.clone()));
637 let encoded = set.encode();
638 assert_eq!(VotingSet::decode(&encoded[..encoded.len() - 1]), None);
639 }
640
641 #[test]
642 fn builds_proofs_that_verify() {
643 let voters = voters();
644 let header = header_at(15);
645 let mut messages = Vec::new();
646 for voter in &voters {
647 for (is_prevote, height, through) in [(true, 10, 15), (false, 15, 15)] {
648 messages.push(voter.message(
649 ROUND,
650 is_prevote,
651 height,
652 (height..=through).map(|at| block_hash(at, 0)).collect(),
653 ));
654 }
655 }
656 let other = FinalizationRound {
658 epoch: EPOCH,
659 point: 1,
660 };
661 messages.push(voters[0].message(other, true, 10, vec![block_hash(10, 0)]));
662 let proof = build_proof(&header, &messages);
663 assert_eq!(verify(&proof, &voters), Ok(header));
664 assert_eq!(
666 proof.len(),
667 PROOF_HEADER_SIZE + 2 * GROUP_HEADER_SIZE + 7 * 32 + 6 * SIGNATURE_SIZE
668 );
669 let mut reversed = messages.clone();
671 reversed.reverse();
672 assert_eq!(
673 verify(&build_proof(&header, &reversed), &voters),
674 Ok(header)
675 );
676 }
677
678 #[test]
679 fn knows_which_heights_close_an_epoch() {
680 assert_eq!(PARAMETERS.voting_set_end_height(1), 1);
681 assert_eq!(PARAMETERS.voting_set_end_height(3), 20);
682 let at = |epoch, height| FinalizedBlockHeader {
683 round: FinalizationRound { epoch, point: 1 },
684 height,
685 hash: Hash256([0; 32]),
686 };
687 assert!(closes_epoch(&at(1, 1), 10));
688 assert!(closes_epoch(&at(3, 20), 10));
689 assert!(!closes_epoch(&at(3, 15), 10));
690 }
691}