Skip to main content

heika_block/finalization/
proof.rs

1//! ファイナライズの証明を確かめる。catapult の `chain::VerifyFinalizationProof` と同じ手順。
2//!
3//! 証明(`FinalizationProof`)は、見出しのあとに、メッセージの組が並ぶ。組は同じ段階(prevote か precommit)、
4//! 同じ高さから始まる同じハッシュの並びに、投票者ごとの署名を並べたもの。組と署名から1つずつメッセージを組み直し、
5//! 集計器(`RoundMessageAggregator`)に足していく。
6//!
7//! - 1つでも足せないメッセージがあれば、証明全体を捨てる。同じ投票者が同じ段階に2つ出す(二重投票でも、同じものの重複でも)
8//!   ことも、足せないうちに入る
9//! - 全部足せたら、prevote と precommit の重みがどちらも閾値を超えたいちばん高いブロックが、見出しの言うものと
10//!   同じかを見る
11//!
12//! 投票者とその重みは、証明の外から渡す。エポック E の投票者は、E − 1 の最後の高さの状態で決まる。
13
14use 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/// 証明を確かめるのに要る、ネットワークの設定(config-network.properties の `[chain]` と `[finalization]`)
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct ProofParameters {
30    /// `votingSetGrouping`。エポックの長さ(ブロック)
31    pub voting_set_grouping: u64,
32    /// `size`。閾値は、重みの合計 × `threshold` / `size`
33    pub size: u64,
34    /// `threshold`
35    pub threshold: u64,
36    /// `maxHashesPerPoint`。1つのメッセージに入れられるハッシュの数
37    pub max_hashes_per_point: u64,
38}
39
40impl ProofParameters {
41    /// エポック `epoch` の最後の高さ。次のエポックの投票者は、この高さの状態で決まる。
42    /// catapult の `CalculateVotingSetEndHeight`
43    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/// エポックの投票者。投票の鍵(根の公開鍵)→ 重み
53#[derive(Clone, Default, Debug, PartialEq, Eq)]
54pub struct VotingSet {
55    pub voters: BTreeMap<[u8; 32], u64>,
56}
57
58impl VotingSet {
59    /// 重みの合計
60    pub fn total(&self) -> u64 {
61        self.voters.values().sum()
62    }
63
64    /// しまう形。投票者の数 u32 と、(鍵 `[32]`、重み u64)の並び
65    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/// 証明を確かめられなかった理由。catapult の `VerifyFinalizationProofResult` と `RoundMessageAggregatorAddResult` に近い
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ProofError {
99    /// 形が読めない
100    Malformed(String),
101    Version(u32),
102    Epoch {
103        expected: u32,
104        actual: u32,
105    },
106    /// `index` 番目のメッセージ(組の順、署名の順に数える)を足せなかった
107    Message {
108        index: usize,
109        reason: MessageError,
110    },
111    /// 閾値を超えた precommit がない
112    NoPrecommit,
113    /// 閾値を超えたいちばん高いブロックが、証明の言うものと違う
114    Mismatch {
115        height: u64,
116        hash: Hash256,
117    },
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum MessageError {
122    /// ハッシュの数が0か、多すぎる。prevote の範囲がエポックの外。precommit のハッシュが1つでない
123    InvalidHashes,
124    /// 最後のハッシュの高さが、投票者を決めた高さより前
125    InvalidHeight,
126    /// 同じ投票者が、同じ段階に違うメッセージを出している(二重投票)
127    Conflicting,
128    /// 同じ投票者が、同じ段階に同じメッセージを2回出している
129    Redundant,
130    /// 投票者ではない
131    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;
158/// `FinalizationMessageGroup` の見出し。大きさ、ハッシュの数、署名の数、段階、高さ
159const GROUP_HEADER_SIZE: usize = 4 + 4 + 4 + 4 + 8;
160
161/// 証明の見出し。大きさと版だけを確かめ、投票の署名と重みはまだ確かめない
162pub 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
177/// ファイナライズしたブロック `header` の証明を、メッセージ `messages` から組む。catapult の `CreateFinalizationProof`。
178///
179/// 段階、高さ、ハッシュが同じメッセージを1つの組にまとめ、署名を並べる。組は(大きさ、署名するところのバイト列)の順、
180/// 組の中の署名は渡された順。`header` のラウンドでないメッセージは入れない。組の大きさはいつも8の倍数なので、
181/// 組のあいだに詰め物は要らない
182pub fn build_proof<'a>(
183    header: &FinalizedBlockHeader,
184    messages: impl IntoIterator<Item = &'a FinalizationMessage>,
185) -> Vec<u8> {
186    // (大きさ、署名するところ)→(組の見本、署名の並び)
187    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
224/// 証明が、エポックの最後の高さ([`ProofParameters::voting_set_end_height`])を指しているか。
225/// エポックの途中のポイントの証明は、エポックが終わると最後のものに替わる
226pub 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
233/// エポック `epoch` の証明を、投票者 `voters` で確かめる。確かめられたら、ファイナライズされたブロック
234pub 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        // 最後でない組は8バイトの境界までそろえてある(catapult の `ContiguousEntityContainer`)
292        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    /// エポックは 10 ブロック。エポック 3 の prevote は高さ 10〜20
318    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    /// catapult と同じ形の証明を組む。最後でない組は8バイトの境界までそろえる
356    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    /// 重み 40、30、30 の3人。閾値は 67
400    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        // 40 + 30 = 70 で閾値の 67 を超える
435        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        // 30 + 30 = 60
459        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        // prevote は足りても、precommit が足りない
465        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        // 最初のメッセージの下の署名の最後のバイト
549        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        // エポック 3 の prevote は高さ 10〜20
566        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        // precommit のハッシュは1つ
577        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        // 投票者を決めた高さ(10)より前で終わる
587        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        // 別のラウンドのメッセージは入らない
657        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        // 組は2つ(prevote と precommit)、それぞれ3人の署名
665        assert_eq!(
666            proof.len(),
667            PROOF_HEADER_SIZE + 2 * GROUP_HEADER_SIZE + 7 * 32 + 6 * SIGNATURE_SIZE
668        );
669        // 渡す順を変えても同じ組になる
670        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}