Skip to main content

heika_node/
finalization.rs

1//! ファイナライズの投票(`finalization`)。`observe` なら見るだけ、`votingKeys` があれば投票もする。
2//!
3//! 投票するピア(Voting のロール)から投票のメッセージを引いて集計器に入れ、段取り役でラウンドを進める。鍵があれば
4//! prevote と precommit を作り、投票状況をディスクに書いてから、集計器に足して投票するピアに配る。鍵がなければ
5//! 何も作らずに進む。集まったメッセージで確定したら、その証明を組み、ピアから届いた証明(中核の確かめた確定)と
6//! 同じラウンドになったところで比べる。どちらもログに出すだけで、中核の確定には使わない。
7//!
8//! 集計を始めるのは、始めたときの中核の確定のラウンドから。投票するときは、前に書いた投票状況があればそこから
9//! 進める。エポックは、中核の確定がエポックの最後のブロックに届き、手元も同じブロックを持っていたら進める
10//! (catapult の投票ノードと同じ)。
11
12use std::collections::BTreeSet;
13use std::path::PathBuf;
14use std::sync::Arc;
15
16use heika_block::finalization::aggregator::{MultiRoundAggregator, MultiRoundError};
17use heika_block::finalization::message::FinalizationMessage;
18use heika_block::finalization::proof::{MessageError, ProofParameters, VotingSet, verify_proof};
19use heika_block::finalization::{FinalizationRound, FinalizedBlockHeader};
20use heika_core::hash::Hash256;
21use heika_finalization::Settings;
22use heika_finalization::epoch::{EpochStatus, epoch_status, finalize};
23use heika_finalization::orchestrator::{NoVotes, Orchestrator, VotingStatus};
24use heika_finalization::signer::{Signer, VotingKeys};
25
26use crate::voting::write_status;
27
28/// 引かれたときに返すメッセージの大きさの上限。catapult の `messageSynchronizationMaxResponseSize` の既定(20MB)
29const MAX_RESPONSE_SIZE: usize = 20 * 1024 * 1024;
30
31/// 投票するときの鍵と、投票状況を書くデータのフォルダー
32pub struct Voting {
33    pub keys: Box<dyn VotingKeys + Send>,
34    pub data_directory: PathBuf,
35}
36
37/// 進めるときに渡す、チェーンの様子
38pub struct View<'a> {
39    /// ネットワークの時刻(ミリ秒)
40    pub now: u64,
41    /// 中核の確定
42    pub finalized: FinalizedBlockHeader,
43    /// 手元のチェーンの先端の高さ
44    pub chain_height: u64,
45    /// エポックの投票者
46    pub voters: &'a dyn Fn(u32) -> Option<VotingSet>,
47    /// 手元のチェーンの、高さ `from` から `count` 個のブロックのハッシュ(あるだけ)
48    pub hashes: &'a dyn Fn(u64, u64) -> Vec<Hash256>,
49}
50
51/// 進めた結果
52#[derive(Debug, Default)]
53pub struct Ticked {
54    /// ログに出すこと
55    pub notices: Vec<String>,
56    /// 自分が作ったメッセージ(投票するピアに配る)
57    pub outgoing: Vec<Vec<u8>>,
58    /// 投票を数えて組み、確かめが通った証明(エポックと証明)。中核に渡して確定を進める
59    pub proof: Option<(u32, Vec<u8>)>,
60}
61
62/// 投票を数える(鍵があれば投票もする)
63pub struct Observer {
64    settings: Settings,
65    parameters: ProofParameters,
66    aggregator: MultiRoundAggregator,
67    orchestrator: Orchestrator,
68    voting: Option<Voting>,
69    /// 始めたときの中核の確定の高さ
70    started_at: u64,
71    /// 自分で数えて確定した、いちばん新しいもの
72    observed: Option<FinalizedBlockHeader>,
73    /// 届いた証明と比べ終えたラウンド
74    compared: Option<FinalizationRound>,
75    /// 足せなかったメッセージの数(ログを間引くため、まとめて出す)
76    rejected: usize,
77}
78
79impl Observer {
80    /// 中核の確定 `finalized` から始める。投票するなら `voting` と、前に書いた投票状況 `status`
81    pub fn new(
82        finalized: &FinalizedBlockHeader,
83        parameters: ProofParameters,
84        settings: Settings,
85        voting: Option<Voting>,
86        status: Option<VotingStatus>,
87    ) -> Self {
88        let next = FinalizationRound {
89            epoch: finalized.round.epoch,
90            point: finalized.round.point + 1,
91        };
92        Self {
93            settings,
94            parameters,
95            aggregator: MultiRoundAggregator::new(
96                parameters,
97                MAX_RESPONSE_SIZE,
98                finalized.round,
99                (finalized.height, finalized.hash),
100            ),
101            orchestrator: Orchestrator::new(
102                status.unwrap_or(VotingStatus::at(next)),
103                settings.step_duration,
104            ),
105            voting,
106            started_at: finalized.height,
107            observed: None,
108            compared: None,
109            rejected: 0,
110        }
111    }
112
113    /// 投票するか(鍵を持っているか)
114    pub fn is_voting(&self) -> bool {
115        self.voting.is_some()
116    }
117
118    /// 段取り役のいるラウンド
119    pub fn round(&self) -> FinalizationRound {
120        self.orchestrator.status().round
121    }
122
123    /// ピアに頼むもの。集めている範囲(最小、最大のラウンド)と、持っているメッセージの短いハッシュ
124    pub fn request(&self) -> (FinalizationRound, FinalizationRound, Vec<u32>) {
125        (
126            self.aggregator.min_round(),
127            self.aggregator.max_round(),
128            self.aggregator.short_hashes(),
129        )
130    }
131
132    /// ピアに引かれたときに返すもの。ラウンド `min` から `max` までのうち、短いハッシュが `known` にないもの
133    pub fn unknown_to(
134        &self,
135        min: FinalizationRound,
136        max: FinalizationRound,
137        known: &BTreeSet<u32>,
138    ) -> Vec<u8> {
139        self.aggregator
140            .unknown_messages(min, max, known)
141            .into_iter()
142            .flat_map(FinalizationMessage::to_bytes)
143            .collect()
144    }
145
146    /// ピアから届いたメッセージを足し、新しく足せたもの(ほかの投票するピアに配る)を返す。範囲の外のもの、
147    /// 同じものの重複は、足せなかったとは数えずに捨てる
148    pub fn add(&mut self, messages: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
149        let mut added = Vec::new();
150        for bytes in messages {
151            let Ok(message) = FinalizationMessage::from_bytes(&bytes) else {
152                self.rejected += 1;
153                continue;
154            };
155            match self.aggregator.add(message) {
156                Ok(_) => added.push(bytes),
157                Err(MultiRoundError::Round | MultiRoundError::Message(MessageError::Redundant)) => {
158                }
159                Err(_) => self.rejected += 1,
160            }
161        }
162        added
163    }
164
165    /// 進める
166    pub fn tick(&mut self, view: &View, hash_at: impl FnOnce(u64) -> Option<Hash256>) -> Ticked {
167        let mut ticked = Ticked::default();
168        if self.rejected > 0 {
169            ticked.notices.push(format!(
170                "投票のメッセージ {} 件を足せませんでした",
171                std::mem::take(&mut self.rejected)
172            ));
173        }
174        let finalized = &view.finalized;
175        match epoch_status(
176            self.round().epoch,
177            finalized,
178            self.settings.voting_set_grouping,
179            hash_at,
180        ) {
181            EpochStatus::Wait => return ticked,
182            EpochStatus::Advance(epoch) => self.orchestrator.set_epoch(epoch),
183            EpochStatus::Continue => {}
184        }
185        let round = self.round();
186        for epoch in self.aggregator.min_round().epoch..=round.epoch {
187            if !self.aggregator.has_voting_set(epoch)
188                && let Some(set) = (view.voters)(epoch)
189            {
190                self.aggregator.set_voting_set(epoch, Arc::new(set));
191            }
192        }
193        if round > self.aggregator.max_round() {
194            self.aggregator.set_max_round(round);
195        }
196        self.poll(view, &mut ticked);
197
198        // 自分の前の確定(まだなければ、始めたときの中核の確定)から進んだら確定する。catapult と同じく、組んだ
199        // 証明は中核に渡してしまう(`Ticked::proof`)。中核が受け入れたかによらず、自分の確定と比べる
200        let previous = self
201            .observed
202            .map_or(self.started_at, |observed| observed.height);
203        if let Some(done) = finalize(&mut self.aggregator, previous) {
204            let header = done.header;
205            let verified = (view.voters)(header.round.epoch)
206                .map(|set| verify_proof(&done.proof, header.round.epoch, &set, &self.parameters));
207            ticked.notices.push(format!(
208                "投票を数えて、エポック {} のポイント {} で、高さ {} を確定しました(証明 {} バイト{})",
209                header.round.epoch,
210                header.round.point,
211                header.height,
212                done.proof.len(),
213                match verified {
214                    Some(Ok(_)) => "、確かめました",
215                    Some(Err(_)) => "、確かめられません",
216                    None => "",
217                }
218            ));
219            if matches!(verified, Some(Ok(_))) {
220                ticked.proof = Some((header.round.epoch, done.proof));
221            }
222            self.observed = Some(header);
223        }
224
225        // 届いた証明が同じラウンドになったら比べる
226        if let Some(observed) = self.observed
227            && finalized.round == observed.round
228            && self.compared != Some(observed.round)
229        {
230            self.compared = Some(observed.round);
231            if (finalized.height, finalized.hash) == (observed.height, observed.hash) {
232                ticked.notices.push(format!(
233                    "エポック {} のポイント {} の確定は、届いた証明と一致しました",
234                    observed.round.epoch, observed.round.point
235                ));
236            } else {
237                ticked.notices.push(format!(
238                    "エポック {} のポイント {} の確定が、届いた証明と違います(数えたのは高さ {}、証明は高さ {})",
239                    observed.round.epoch, observed.round.point, observed.height, finalized.height
240                ));
241            }
242        }
243        ticked
244    }
245
246    /// 段取り役を進める。投票するなら、作ったメッセージを、投票状況を書いてから集計器に足して配る
247    fn poll(&mut self, view: &View, ticked: &mut Ticked) {
248        let Some(voting) = self.voting.as_mut() else {
249            self.orchestrator
250                .poll(view.now, &self.aggregator, &mut NoVotes, &|_| false);
251            return;
252        };
253        let before = self.orchestrator.status();
254        // prevote は、中核の確定と自分の確定の新しいほうのブロックから
255        let finalized = match self.observed {
256            Some(observed) if observed.round > view.finalized.round => observed,
257            _ => view.finalized,
258        };
259        let mut signer = Signer {
260            keys: voting.keys.as_mut(),
261            settings: self.settings,
262            finalized,
263            chain_height: view.chain_height,
264            hashes: view.hashes,
265        };
266        let eligible = |message: &FinalizationMessage| {
267            (view.voters)(message.round.epoch)
268                .is_some_and(|set| set.voters.contains_key(&message.root_key()))
269        };
270        let sent = self
271            .orchestrator
272            .poll(view.now, &self.aggregator, &mut signer, &eligible);
273        let status = self.orchestrator.status();
274        if status != before
275            && let Err(error) = write_status(&voting.data_directory, &status)
276        {
277            // 書けなかったら配らない。起き直したときに、同じ段階をもう一度出しかねない
278            ticked
279                .notices
280                .push(format!("投票状況を書けないので、投票を配りません: {error}"));
281            return;
282        }
283        for message in sent {
284            let (round, stage) = (
285                message.round,
286                if message.is_prevote {
287                    "prevote"
288                } else {
289                    "precommit"
290                },
291            );
292            ticked.notices.push(format!(
293                "エポック {} のポイント {} の {stage} を出しました(高さ {} から {})",
294                round.epoch,
295                round.point,
296                message.height,
297                message.last_height()
298            ));
299            let bytes = message.to_bytes();
300            if let Err(error) = self.aggregator.add(message) {
301                ticked
302                    .notices
303                    .push(format!("自分の {stage} を足せませんでした: {error:?}"));
304            }
305            ticked.outgoing.push(bytes);
306        }
307    }
308
309    /// 持っているメッセージの数
310    pub fn messages(&self) -> usize {
311        self.aggregator.short_hashes().len()
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use heika_core::key::{PrivateKey, PublicKey};
318
319    use super::*;
320
321    /// エポックは 10 ブロック。エポック 3 は高さ 20 で終わる
322    const PARAMETERS: ProofParameters = ProofParameters {
323        voting_set_grouping: 10,
324        size: 10_000,
325        threshold: 6_700,
326        max_hashes_per_point: 256,
327    };
328    const SETTINGS: Settings = Settings {
329        step_duration: 1000,
330        prevote_blocks_multiple: 4,
331        max_hashes_per_point: 256,
332        voting_set_grouping: 10,
333    };
334
335    fn round(epoch: u32, point: u32) -> FinalizationRound {
336        FinalizationRound { epoch, point }
337    }
338
339    fn block_hash(height: u64) -> Hash256 {
340        let mut hash = [0; 32];
341        hash[..8].copy_from_slice(&height.to_le_bytes());
342        Hash256(hash)
343    }
344
345    fn header(round: FinalizationRound, height: u64) -> FinalizedBlockHeader {
346        FinalizedBlockHeader {
347            round,
348            height,
349            hash: block_hash(height),
350        }
351    }
352
353    fn keys(seed: u8) -> (PrivateKey, PrivateKey) {
354        (
355            PrivateKey::from_bytes(&[seed; 32]),
356            PrivateKey::from_bytes(&[seed ^ 0x80; 32]),
357        )
358    }
359
360    /// 重み 40、30、30 の投票者 1、2、3。閾値は 67
361    fn voters(_epoch: u32) -> Option<VotingSet> {
362        Some(VotingSet {
363            voters: [1, 2, 3]
364                .into_iter()
365                .zip([40, 30, 30])
366                .map(|(seed, weight)| (PublicKey::from_private_key(&keys(seed).0).0, weight))
367                .collect(),
368        })
369    }
370
371    /// 投票者 `seed` が署名した、catapult の形のメッセージ。高さ `from` から `through` までのハッシュ
372    fn vote(seed: u8, at: FinalizationRound, is_prevote: bool, from: u64, through: u64) -> Vec<u8> {
373        let (root, bottom) = keys(seed);
374        let bottom_public = PublicKey::from_private_key(&bottom).0;
375        let mut signed = Vec::new();
376        signed.extend_from_slice(&1u32.to_le_bytes());
377        signed.extend_from_slice(&((through - from + 1) as u32).to_le_bytes());
378        signed.extend_from_slice(&at.epoch.to_le_bytes());
379        signed.extend_from_slice(&((at.point << 1) | u32::from(!is_prevote)).to_le_bytes());
380        signed.extend_from_slice(&from.to_le_bytes());
381        for height in from..=through {
382            signed.extend_from_slice(&block_hash(height).0);
383        }
384        let mut bytes = Vec::new();
385        bytes.extend_from_slice(&((200 + signed.len()) as u32).to_le_bytes());
386        bytes.extend_from_slice(&0u32.to_le_bytes());
387        bytes.extend_from_slice(&PublicKey::from_private_key(&root).0);
388        let epoch = u64::from(at.epoch).to_le_bytes();
389        bytes.extend_from_slice(&root.sign(&[&bottom_public, &epoch]).0);
390        bytes.extend_from_slice(&bottom_public);
391        bytes.extend_from_slice(&bottom.sign(&[&signed]).0);
392        bytes.extend_from_slice(&signed);
393        bytes
394    }
395
396    /// 全員が、高さ `from` から `through` に prevote し、`through` に precommit する
397    fn everyone(at: FinalizationRound, from: u64, through: u64) -> Vec<Vec<u8>> {
398        (1..=3)
399            .flat_map(|seed| {
400                [
401                    vote(seed, at, true, from, through),
402                    vote(seed, at, false, through, through),
403                ]
404            })
405            .collect()
406    }
407
408    fn local(height: u64) -> Option<Hash256> {
409        Some(block_hash(height))
410    }
411
412    fn hashes(from: u64, count: u64) -> Vec<Hash256> {
413        (from..from + count).map(block_hash).collect()
414    }
415
416    /// 先端が高さ 30 のチェーンで進め、ログに出すことを返す
417    fn tick(observer: &mut Observer, now: u64, finalized: &FinalizedBlockHeader) -> Vec<String> {
418        observer.tick(&view(now, finalized), local).notices
419    }
420
421    fn view<'a>(now: u64, finalized: &FinalizedBlockHeader) -> View<'a> {
422        View {
423            now,
424            finalized: *finalized,
425            chain_height: 30,
426            voters: &voters,
427            hashes: &hashes,
428        }
429    }
430
431    /// 手元のチェーンにまだブロックがないとして進める
432    fn tick_without_blocks(
433        observer: &mut Observer,
434        now: u64,
435        finalized: &FinalizedBlockHeader,
436    ) -> Vec<String> {
437        observer.tick(&view(now, finalized), |_| None).notices
438    }
439
440    /// エポック 3 のポイント 1 で高さ 10 が確定したところから見始め、1回進めて、ポイント 2 まで集めるようにしたもの
441    fn started() -> (Observer, FinalizedBlockHeader) {
442        let finalized = header(round(3, 1), 10);
443        let mut observer = Observer::new(&finalized, PARAMETERS, SETTINGS, None, None);
444        assert_eq!(observer.round(), round(3, 2));
445        assert!(tick(&mut observer, 0, &finalized).is_empty());
446        (observer, finalized)
447    }
448
449    #[test]
450    fn asks_for_the_rounds_it_collects() {
451        let (mut observer, _) = started();
452        let (min, max, known) = observer.request();
453        assert_eq!((min, max), (round(3, 1), round(3, 2)));
454        assert!(known.is_empty());
455        let messages = everyone(round(3, 2), 10, 14);
456        assert_eq!(observer.add(messages.clone()).len(), 6);
457        assert_eq!(observer.messages(), 6);
458        assert_eq!(observer.request().2.len(), 6);
459        // 同じものはもう足さないが、足せなかったとも言わない
460        assert!(observer.add(messages).is_empty());
461        let (_, finalized) = started();
462        assert!(
463            tick(&mut observer, 0, &finalized)
464                .iter()
465                .all(|notice| !notice.contains("足せません"))
466        );
467    }
468
469    #[test]
470    fn reports_messages_it_could_not_add() {
471        let (mut observer, finalized) = started();
472        // 読めないもの、投票者でない鍵、集めていないラウンド(数えない)
473        let messages = vec![
474            vec![0; 10],
475            vote(9, round(3, 2), true, 10, 14),
476            vote(1, round(3, 5), true, 10, 14),
477        ];
478        assert!(observer.add(messages).is_empty());
479        let notices = tick(&mut observer, 0, &finalized);
480        assert_eq!(notices, ["投票のメッセージ 2 件を足せませんでした"]);
481        assert!(tick(&mut observer, 0, &finalized).is_empty());
482    }
483
484    #[test]
485    fn finalizes_each_height_once_and_compares_with_the_arriving_proof() {
486        let (mut observer, finalized) = started();
487        observer.add(everyone(round(3, 2), 10, 14));
488        let notices = tick(&mut observer, 0, &finalized);
489        assert_eq!(notices.len(), 1);
490        assert!(notices[0].contains("ポイント 2 で、高さ 14 を確定しました"));
491        assert!(notices[0].contains("確かめました"));
492        // 結果がもう変わらないので、次のポイントに進む
493        assert_eq!(observer.round(), round(3, 3));
494        // 同じ高さはもう確定しない。中核の確定が先に進んでいても
495        assert!(tick(&mut observer, 1, &finalized).is_empty());
496        assert!(tick(&mut observer, 2, &header(round(3, 9), 18)).is_empty());
497
498        // 届いた証明が同じラウンドになったら、1回だけ比べる
499        let arrived = header(round(3, 2), 14);
500        assert_eq!(
501            tick(&mut observer, 3, &arrived),
502            ["エポック 3 のポイント 2 の確定は、届いた証明と一致しました"]
503        );
504        assert!(tick(&mut observer, 4, &arrived).is_empty());
505    }
506
507    #[test]
508    fn says_when_the_arriving_proof_differs() {
509        let (mut observer, finalized) = started();
510        observer.add(everyone(round(3, 2), 10, 14));
511        tick(&mut observer, 0, &finalized);
512        let mut arrived = header(round(3, 2), 13);
513        arrived.hash = block_hash(13);
514        assert_eq!(
515            tick(&mut observer, 1, &arrived),
516            [
517                "エポック 3 のポイント 2 の確定が、届いた証明と違います(数えたのは高さ 14、証明は高さ 13)"
518            ]
519        );
520    }
521
522    #[test]
523    fn moves_to_the_next_epoch_only_when_the_local_chain_has_its_last_block() {
524        let (mut observer, _) = started();
525        // エポック 3 の最後の高さ 20 が確定した
526        let closed = header(round(3, 7), 20);
527        assert!(tick_without_blocks(&mut observer, 0, &closed).is_empty());
528        assert_eq!(observer.round(), round(3, 2));
529        assert!(tick(&mut observer, 0, &closed).is_empty());
530        assert_eq!(observer.round(), round(4, 1));
531        assert_eq!(observer.request().1, round(4, 1));
532
533        // 新しいエポックの票も数える
534        observer.add(everyone(round(4, 1), 20, 24));
535        let notices = tick(&mut observer, 1, &closed);
536        assert!(notices[0].contains("エポック 4 のポイント 1 で、高さ 24 を確定しました"));
537    }
538
539    #[test]
540    fn waits_without_voters() {
541        let finalized = header(round(3, 1), 10);
542        let mut observer = Observer::new(&finalized, PARAMETERS, SETTINGS, None, None);
543        observer.tick(
544            &View {
545                now: 0,
546                finalized,
547                chain_height: 30,
548                voters: &|_| None,
549                hashes: &hashes,
550            },
551            local,
552        );
553        // 投票者を知らないエポックのメッセージは足せない
554        assert!(observer.add(everyone(round(3, 2), 10, 14)).is_empty());
555        // あとで投票者がわかれば数える
556        tick(&mut observer, 0, &finalized);
557        assert_eq!(observer.add(everyone(round(3, 2), 10, 14)).len(), 6);
558    }
559}