1use 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
28const MAX_RESPONSE_SIZE: usize = 20 * 1024 * 1024;
30
31pub struct Voting {
33 pub keys: Box<dyn VotingKeys + Send>,
34 pub data_directory: PathBuf,
35}
36
37pub struct View<'a> {
39 pub now: u64,
41 pub finalized: FinalizedBlockHeader,
43 pub chain_height: u64,
45 pub voters: &'a dyn Fn(u32) -> Option<VotingSet>,
47 pub hashes: &'a dyn Fn(u64, u64) -> Vec<Hash256>,
49}
50
51#[derive(Debug, Default)]
53pub struct Ticked {
54 pub notices: Vec<String>,
56 pub outgoing: Vec<Vec<u8>>,
58 pub proof: Option<(u32, Vec<u8>)>,
60}
61
62pub struct Observer {
64 settings: Settings,
65 parameters: ProofParameters,
66 aggregator: MultiRoundAggregator,
67 orchestrator: Orchestrator,
68 voting: Option<Voting>,
69 started_at: u64,
71 observed: Option<FinalizedBlockHeader>,
73 compared: Option<FinalizationRound>,
75 rejected: usize,
77}
78
79impl Observer {
80 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 pub fn is_voting(&self) -> bool {
115 self.voting.is_some()
116 }
117
118 pub fn round(&self) -> FinalizationRound {
120 self.orchestrator.status().round
121 }
122
123 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(observer.round(), round(3, 3));
494 assert!(tick(&mut observer, 1, &finalized).is_empty());
496 assert!(tick(&mut observer, 2, &header(round(3, 9), 18)).is_empty());
497
498 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 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 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 assert!(observer.add(everyone(round(3, 2), 10, 14)).is_empty());
555 tick(&mut observer, 0, &finalized);
557 assert_eq!(observer.add(everyone(round(3, 2), 10, 14)).len(), 6);
558 }
559}