1use std::collections::{BTreeMap, VecDeque};
19use std::fmt;
20use std::sync::Arc;
21use std::time::{Duration, SystemTime};
22
23use heika_block::Block;
24use heika_block::finalization::proof::{VotingSet, closes_epoch, proof_header, verify_proof};
25use heika_block::finalization::{FinalizationRound, FinalizedBlockHeader};
26use heika_block::scoring::{BlockStatistic, block_score, difficulty};
27use heika_block::statement::BlockStatement;
28use heika_core::address::Address;
29use heika_core::hash::Hash256;
30use heika_core::key::{PrivateKey, PublicKey};
31use heika_core::network::NetworkParameters;
32use heika_core::vrf::GenerationHash;
33use heika_packet::ChainStatistics;
34use heika_state_transition::config::ChainConfig;
35use heika_state_transition::executor::source::StateSource;
36use heika_state_transition::executor::{Executor, Wanted};
37use heika_transaction::Transaction;
38
39use crate::ChainError;
40use crate::env::Env;
41use crate::event::{ChainEvent, PULL_BLOCKS, PULL_HASHES, PeerCommand, PeerId};
42use crate::produce;
43use crate::store::{BlockWrite, ChainStore, Prune};
44use crate::verify::{Tip, verify_link};
45
46mod accept;
47mod finality;
48mod harvest;
49mod partial;
50mod push;
51mod sync;
52
53#[derive(Clone, Copy, Debug)]
55pub struct Status {
56 pub height: u64,
58 pub score: u128,
60 pub finalized: FinalizedBlockHeader,
62}
63
64pub const CHECKPOINT_EPOCHS: u64 = 2;
67
68#[derive(Clone, Copy, Debug)]
71pub struct Keep {
72 pub state: u64,
73 pub trie: u64,
74 pub history: bool,
77}
78
79impl Keep {
80 pub fn plan(
86 keep: Option<Self>,
87 config: &ChainConfig,
88 parameters: &NetworkParameters,
89 finalized: u64,
90 floor: u64,
91 ) -> Prune {
92 let grouping = config.finalization.voting_set_grouping;
93 let bound = |epochs: u64| finalized.saturating_sub(epochs * grouping).min(floor);
94 Prune {
95 checkpoints_below: finalized.saturating_sub(CHECKPOINT_EPOCHS * grouping),
96 history: keep.map(|keep| (bound(keep.state), bound(keep.trie))),
97 blocks: keep.filter(|keep| keep.history).map(|keep| {
98 let through = bound(keep.state).saturating_sub(config.blocks_for_restart());
99 let epoch =
100 u32::try_from(parameters.finalization_epoch(through)).unwrap_or(u32::MAX);
101 (through, epoch)
102 }),
103 }
104 }
105}
106
107pub struct Loaded {
109 pub executor: Executor,
110 pub parent: Block,
112 pub statistics: VecDeque<BlockStatistic>,
114 pub tip: Tip,
115}
116
117pub async fn load_from<S: ChainStore + StateSource>(
121 store: &S,
122 config: ChainConfig,
123 parameters: &NetworkParameters,
124 partial: bool,
125) -> Result<Loaded, ChainError> {
126 let lifetime = config
127 .max_transaction_lifetime
128 .max(config.max_bonded_transaction_lifetime);
129 let mut executor = if partial {
130 let (meta, rows, nodes) = store.load_partial_state().await?;
131 let mut executor = Executor::restore_partial(
132 config,
133 parameters.identifier,
134 parameters.generation_hash_seed,
135 rows,
136 &meta,
137 )?;
138 executor.restore_trees(nodes)?;
139 executor.load_tree_roots(store)?;
140 executor
141 } else {
142 let (meta, rows, nodes) = store.load_state().await?;
143 let mut executor = Executor::restore(
144 config,
145 parameters.identifier,
146 parameters.generation_hash_seed,
147 rows,
148 &meta,
149 )?;
150 executor.restore_trees(nodes)?;
151 executor
152 };
153 let parent = block_at(store, executor.height()).await?;
154 if executor.state_hash() != parent.state_hash {
155 if partial {
157 return Err("しまった木の根が StateHash と合いません".into());
158 }
159 executor.rebuild_trees();
160 }
161 executor.forget_node_changes();
163 let (parent, statistics, tip) = context(store, &mut executor, parameters, lifetime).await?;
164 Ok(Loaded {
165 executor,
166 parent,
167 statistics,
168 tip,
169 })
170}
171
172async fn block_at<S: ChainStore>(store: &S, height: u64) -> Result<Block, ChainError> {
173 Ok(Block::from_bytes(
174 &store
175 .block(height)
176 .await?
177 .ok_or("実行した高さのブロックがありません")?,
178 )?)
179}
180
181async fn anchor_of<S: ChainStore>(store: &S, tip: u64) -> Result<FinalizedBlockHeader, ChainError> {
187 for epoch in (1..=store.proofs_tip().await?).rev() {
188 let Some(proof) = store.proof(epoch).await? else {
189 continue;
190 };
191 let header = proof_header(&proof)?;
192 if header.height > tip {
193 continue;
194 }
195 match store.block(header.height).await? {
196 Some(bytes) if Block::from_bytes(&bytes)?.hash() != header.hash => continue,
197 _ => return Ok(header),
198 }
199 }
200 Ok(FinalizedBlockHeader {
201 round: FinalizationRound { epoch: 1, point: 1 },
202 height: 1,
203 hash: block_at(store, 1).await?.hash(),
204 })
205}
206
207async fn context<S: ChainStore>(
210 store: &S,
211 executor: &mut Executor,
212 parameters: &NetworkParameters,
213 lifetime: u64,
214) -> Result<(Block, VecDeque<BlockStatistic>, Tip), ChainError> {
215 let height = executor.height();
216 let parent = block_at(store, height).await?;
217 let mut recent = Vec::new();
218 for height in (1..=height).rev() {
219 let block = block_at(store, height).await?;
220 if recent
221 .first()
222 .is_some_and(|last: &Block| block.timestamp + lifetime < last.timestamp)
223 {
224 break;
225 }
226 recent.push(block);
227 }
228 for block in recent.iter().rev() {
229 executor.remember_transactions(block)?;
230 }
231 let from = height
232 .saturating_sub(parameters.max_difficulty_blocks as u64 - 1)
233 .max(1);
234 let mut statistics = VecDeque::new();
235 for height in from..=height {
236 statistics.push_back(BlockStatistic::from(&block_at(store, height).await?));
237 }
238 let importance_height =
239 (height / parameters.importance_grouping * parameters.importance_grouping).max(1);
240 let tip = Tip {
241 height,
242 hash: parent.hash(),
243 importance_hash: block_at(store, importance_height).await?.hash(),
244 };
245 Ok((parent, statistics, tip))
246}
247
248struct Peer {
249 statistics: Option<ChainStatistics>,
250 pending: usize,
252}
253
254enum Sync {
255 Idle,
256 Extending {
258 peer: PeerId,
259 },
260 Comparing {
262 peer: PeerId,
263 from: u64,
264 },
265 Forking {
267 peer: PeerId,
268 common: u64,
269 blocks: Vec<(Block, Vec<u8>)>,
270 },
271}
272
273impl Sync {
274 fn peer(&self) -> Option<PeerId> {
275 match self {
276 Self::Idle => None,
277 Self::Extending { peer }
278 | Self::Comparing { peer, .. }
279 | Self::Forking { peer, .. } => Some(*peer),
280 }
281 }
282}
283
284#[derive(Clone, Copy, PartialEq, Eq, Debug)]
286pub enum Penalty {
287 None,
289 Failure,
291 Ban,
293}
294
295#[derive(Debug)]
297pub enum Action {
298 Command(PeerId, PeerCommand),
300 Disconnect { peer: PeerId, penalty: Penalty },
302 WakeAt(SystemTime),
304 RejectPush(PublicKey),
307 Notify(Notice),
309 Included(Vec<Hash256>),
311 Restored(Vec<Vec<u8>>),
314 Dropped(Hash256),
316}
317
318#[derive(Clone, Debug)]
320pub enum Notice {
321 Accepted {
323 height: u64,
324 transactions: usize,
325 hash: Hash256,
326 pushed: bool,
327 },
328 Switched {
330 common: u64,
331 old: Tip,
332 new: Tip,
333 peer: PeerId,
334 },
335 Finalized {
337 epoch: u32,
338 point: u32,
339 height: u64,
340 peer: Option<PeerId>,
342 checkpoints: usize,
343 rows: Option<u64>,
344 remaining: bool,
346 },
347 EarlierProof {
349 epoch: u32,
350 height: u64,
351 peer: PeerId,
352 partial: bool,
353 },
354 TooFarInFuture {
356 peer: PeerId,
357 height: u64,
358 ahead: u64,
359 },
360 Behind {
362 peer: PeerId,
363 finalized: u64,
364 tip: u64,
365 },
366 Produced {
368 height: u64,
369 hash: Hash256,
370 seconds: u64,
371 peers: usize,
372 },
373 PeerDropped { peer: PeerId, message: String },
375 Progress { message: String, warning: bool },
377}
378
379impl Notice {
380 pub fn is_warning(&self) -> bool {
382 match self {
383 Self::PeerDropped { .. } => true,
384 Self::Progress { warning, .. } => *warning,
385 _ => false,
386 }
387 }
388}
389
390impl fmt::Display for Notice {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 match self {
393 Self::Accepted {
394 height,
395 transactions,
396 hash,
397 pushed,
398 } => write!(
399 f,
400 "高さ {height} を受け入れました(トランザクション {transactions} 件、ハッシュ {hash}{})",
401 if *pushed {
402 "、押し付けで届いたもの"
403 } else {
404 ""
405 }
406 ),
407 Self::Produced {
408 height,
409 hash,
410 seconds,
411 peers,
412 } => write!(
413 f,
414 "高さ {height} のブロックを作りました(親から {seconds} 秒、ハッシュ {hash})。{peers} か所のピアに配ります"
415 ),
416 Self::Switched {
417 common,
418 old,
419 new,
420 peer,
421 } => write!(
422 f,
423 "枝を取り替えました: 分かれ目 {common}、深さ {}、元の先端 {}(高さ {})→ 新しい先端 {}(高さ {})、ピア {}",
424 old.height - common,
425 old.hash,
426 old.height,
427 new.hash,
428 new.height,
429 peer.0
430 ),
431 Self::Finalized {
432 epoch,
433 point,
434 height,
435 peer,
436 checkpoints,
437 rows,
438 remaining,
439 } => {
440 let from = match peer {
441 Some(peer) => format!("ピア {}", peer.0),
442 None => "自分で数えたもの".to_owned(),
443 };
444 write!(
445 f,
446 "エポック {epoch} ポイント {point} の証明を確かめました: 高さ {height} をファイナライズ({from}、消したチェックポイント {checkpoints}"
447 )?;
448 if let Some(rows) = rows {
449 write!(f, "、消した差分 {rows} 行")?;
450 }
451 if *remaining {
452 write!(f, "、残りは次の確定で消します")?;
453 }
454 write!(f, ")")
455 }
456 Self::EarlierProof {
457 epoch,
458 height,
459 peer,
460 partial,
461 } => write!(
462 f,
463 "{}エポック {epoch} の証明を確かめてしまいました(高さ {height}、ピア {})",
464 if *partial {
465 "途中のポイントのままだった"
466 } else {
467 "抜けていた"
468 },
469 peer.0
470 ),
471 Self::TooFarInFuture {
472 peer,
473 height,
474 ahead,
475 } => write!(
476 f,
477 "ピア {} の高さ {height} は、時刻が今より {ahead} ミリ秒先なので、今は使いません",
478 peer.0
479 ),
480 Self::Behind {
481 peer,
482 finalized,
483 tip,
484 } => write!(
485 f,
486 "ピア {} の言う確定(高さ {finalized})が、自分の先端(高さ {tip})より1エポック以上先にあります。追いつく段階に戻ります",
487 peer.0
488 ),
489 Self::PeerDropped { message, .. } | Self::Progress { message, .. } => {
490 f.write_str(message)
491 }
492 }
493 }
494}
495
496const PUSH_REPORT: Duration = Duration::from_secs(60);
498
499const HARVEST_HORIZON: u64 = 60 * 60 * 1000;
501const HARVEST_ANNOUNCE: u64 = 120;
503
504#[derive(Clone, Copy, PartialEq, Eq, Debug)]
506pub enum HarvestPlan {
507 NotPlanned,
510 NoHit,
512 Hit { height: u64, timestamp: SystemTime },
515}
516
517struct Planned {
519 parent: Hash256,
520 slot: Option<(u64, usize)>,
521 importance: u64,
523}
524
525#[derive(Clone, Copy, PartialEq, Debug)]
528pub struct HarvestOutlook {
529 pub parent: SystemTime,
531 pub importance: u64,
533 pub active_importance: f64,
535 pub per_block: f64,
537 pub block_seconds: f64,
539 pub next: Option<f64>,
541}
542
543struct HarvestParent {
545 block: Block,
546 recent: Vec<BlockStatistic>,
547 generation_hash: GenerationHash,
548 importance_hash: Hash256,
549}
550
551impl HarvestParent {
552 fn context(&self) -> produce::Parent<'_> {
553 produce::Parent {
554 block: &self.block,
555 generation_hash: self.generation_hash,
556 recent: &self.recent,
557 importance_hash: self.importance_hash,
558 }
559 }
560}
561
562#[derive(Default)]
564struct PushCounts {
565 since: Option<SystemTime>,
567 used: u64,
569 rejected: u64,
571 known: u64,
573 late_total: Duration,
575 late_count: u32,
576 syncing: u64,
578 unlinked: u64,
580 ahead: u64,
582 held: u64,
584 used_late: u64,
586 rejected_late: u64,
588 future: u64,
590 replaced: u64,
592 rival_worse: u64,
594 rival_rejected: u64,
596 rival_skipped: u64,
598}
599
600impl PushCounts {
601 fn total(&self) -> u64 {
602 self.used
603 + self.rejected
604 + self.known
605 + self.syncing
606 + self.unlinked
607 + self.ahead
608 + self.held
609 + self.future
610 + self.rivals()
611 }
612
613 fn rivals(&self) -> u64 {
615 self.replaced + self.rival_worse + self.rival_rejected + self.rival_skipped
616 }
617}
618
619impl fmt::Display for PushCounts {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 write!(
622 f,
623 "押し付けられたブロック {}: 使った {}、弾いた {}、もう持っていた {}",
624 self.total(),
625 self.used,
626 self.rejected,
627 self.known
628 )?;
629 if self.late_count > 0 {
630 write!(
631 f,
632 "(受け入れてから平均 {:.1} 秒あと)",
633 (self.late_total / self.late_count).as_secs_f64()
634 )?;
635 }
636 write!(
637 f,
638 "、時刻が来るまで持った {}(来て受け入れた {}、弾いた {})、もう持っていたので捨てた {}、同期の途中 {}、つながらない {}、先の高さ {}",
639 self.held,
640 self.used_late,
641 self.rejected_late,
642 self.future,
643 self.syncing,
644 self.unlinked,
645 self.ahead
646 )?;
647 if self.rivals() > 0 {
648 write!(
649 f,
650 "、先端と競う {}(差し替えた {}、スコアが高くない {}、弾いた {}、試さなかった {})",
651 self.rivals(),
652 self.replaced,
653 self.rival_worse,
654 self.rival_rejected,
655 self.rival_skipped
656 )?;
657 }
658 Ok(())
659 }
660}
661
662const MAX_RETRIES: usize = 8;
664const MAX_DROPS: usize = 16;
666#[derive(Debug)]
668struct Missed(Wanted);
669
670impl fmt::Display for Missed {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672 write!(f, "読んでいない状態が {} 個あります", self.0.len())
673 }
674}
675
676impl std::error::Error for Missed {}
677
678#[derive(Debug)]
681struct Invalid(ChainError);
682
683impl fmt::Display for Invalid {
684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
685 self.0.fmt(f)
686 }
687}
688
689impl std::error::Error for Invalid {}
690
691fn invalid(error: impl Into<ChainError>) -> ChainError {
692 Box::new(Invalid(error.into()))
693}
694
695enum Replaced {
697 Done,
699 Failed { message: String, penalty: Penalty },
701}
702
703fn is_invalid(error: &ChainError) -> bool {
704 error.downcast_ref::<Invalid>().is_some()
705}
706
707pub enum Outcome {
709 Stopped,
711 Behind { finalized: u64 },
713}
714
715pub struct Chain<'a, S: ChainStore + StateSource> {
717 store: &'a S,
718 env: &'a dyn Env,
719 config: ChainConfig,
720 parameters: &'static NetworkParameters,
721 executor: Executor,
722 parent: Block,
723 generation_hash: GenerationHash,
724 statistics: VecDeque<BlockStatistic>,
725 tip: Tip,
726 peers: BTreeMap<PeerId, Peer>,
727 sync: Sync,
728 finalized: FinalizedBlockHeader,
730 anchor: FinalizedBlockHeader,
733 proof_requested: finality::ProofRequest,
735 backfilled: u32,
737 keep: Option<Keep>,
739 pushes: PushCounts,
741 held: Option<(Block, Vec<u8>, Option<PublicKey>)>,
744 accepted_at: VecDeque<(u64, SystemTime)>,
746 harvesters: Arc<Vec<(PrivateKey, PrivateKey)>>,
748 planned: Option<Planned>,
750 harvest_warning: Option<String>,
752 pending: Option<Arc<dyn produce::Pending>>,
754 beneficiary: Option<Address>,
756 assemble: Option<Arc<dyn produce::Assemble>>,
758 actions: Vec<Action>,
760}
761
762impl<'a, S: ChainStore + StateSource> Chain<'a, S> {
763 pub async fn new(
765 store: &'a S,
766 env: &'a dyn Env,
767 config: ChainConfig,
768 parameters: &'static NetworkParameters,
769 partial: bool,
770 ) -> Result<Self, ChainError> {
771 let loaded = load_from(store, config.clone(), parameters, partial).await?;
772 let finalized = match store.proofs_tip().await? {
774 0 => FinalizedBlockHeader {
775 round: FinalizationRound { epoch: 1, point: 1 },
776 height: 1,
777 hash: block_at(store, 1).await?.hash(),
778 },
779 epoch => proof_header(
780 &store
781 .proof(epoch)
782 .await?
783 .ok_or("しまった証明がありません")?,
784 )?,
785 };
786 let anchor = anchor_of(store, loaded.tip.height).await?;
787 Ok(Self {
788 finalized,
789 anchor,
790 proof_requested: finality::ProofRequest::default(),
791 backfilled: 1,
792 store,
793 env,
794 config,
795 parameters,
796 generation_hash: loaded.parent.generation_hash(),
797 executor: loaded.executor,
798 parent: loaded.parent,
799 statistics: loaded.statistics,
800 tip: loaded.tip,
801 peers: BTreeMap::new(),
802 sync: Sync::Idle,
803 keep: None,
804 pushes: PushCounts::default(),
805 accepted_at: VecDeque::new(),
806 held: None,
807 harvesters: Arc::new(Vec::new()),
808 planned: None,
809 harvest_warning: None,
810 pending: None,
811 beneficiary: None,
812 assemble: None,
813 actions: Vec::new(),
814 })
815 }
816
817 pub fn set_harvesters(&mut self, keys: Arc<Vec<(PrivateKey, PrivateKey)>>) {
820 self.harvesters = keys;
821 self.planned = None;
822 }
823
824 pub fn set_pending(&mut self, pending: Arc<dyn produce::Pending>) {
827 self.pending = Some(pending);
828 }
829
830 pub fn set_beneficiary(&mut self, beneficiary: Option<Address>) {
833 self.beneficiary = beneficiary;
834 }
835
836 pub fn set_assemble(&mut self, assemble: Arc<dyn produce::Assemble>) {
838 self.assemble = Some(assemble);
839 }
840
841 pub fn set_keep(&mut self, keep: Keep) {
843 self.keep = Some(keep);
844 }
845
846 pub fn height(&self) -> u64 {
848 self.tip.height
849 }
850
851 pub fn tip(&self) -> Tip {
853 self.tip
854 }
855
856 pub fn harvest_plan(&self) -> HarvestPlan {
858 match &self.planned {
859 Some(planned) if planned.parent == self.tip.hash => match planned.slot {
860 Some((timestamp, _)) => HarvestPlan::Hit {
861 height: self.tip.height + 1,
862 timestamp: self.parameters.epoch() + Duration::from_millis(timestamp),
863 },
864 None => HarvestPlan::NoHit,
865 },
866 _ => HarvestPlan::NotPlanned,
867 }
868 }
869
870 pub fn harvest_outlook(&self) -> Option<HarvestOutlook> {
872 let planned = self
873 .planned
874 .as_ref()
875 .filter(|planned| planned.parent == self.tip.hash && planned.importance > 0)?;
876 let recent: Vec<BlockStatistic> = self.statistics.iter().copied().collect();
877 let estimated = crate::outlook::active_importance(&recent, self.parameters)?;
878 let importance = planned.importance;
879 let active = estimated.max(importance as f64);
881 let others = active - importance as f64;
882 let next = planned.slot.map(|(timestamp, _)| {
883 let elapsed = timestamp.saturating_sub(self.parent.timestamp) / 1000;
884 let difficulty = difficulty(&recent, self.parameters);
885 crate::outlook::win_chance(elapsed, difficulty, others, self.parameters)
886 });
887 Some(HarvestOutlook {
888 parent: self.parameters.epoch() + Duration::from_millis(self.parent.timestamp),
889 importance,
890 active_importance: active,
891 per_block: importance as f64 / active,
892 block_seconds: crate::outlook::average_block_seconds(&recent)?,
893 next,
894 })
895 }
896
897 pub fn status(&self) -> Status {
899 Status {
900 height: self.tip.height,
901 score: self.executor.score().unwrap_or(0),
902 finalized: self.finalized,
903 }
904 }
905
906 pub fn state_matches(&mut self) -> bool {
908 self.executor.state_hash() == self.parent.state_hash
909 }
910
911 pub async fn extend_offline(
913 &mut self,
914 block: &Block,
915 bytes: Vec<u8>,
916 ) -> Result<(), ChainError> {
917 self.accept(block, bytes, false).await
918 }
919
920 pub async fn switch_offline(
923 &mut self,
924 common: u64,
925 blocks: Vec<(Block, Vec<u8>)>,
926 ) -> Result<bool, ChainError> {
927 let before = self.tip.hash;
928 self.switch(PeerId(usize::MAX), common, blocks).await?;
929 self.actions
931 .retain(|action| matches!(action, Action::Notify(_)));
932 Ok(self.tip.hash != before)
933 }
934
935 pub fn anchor(&self) -> FinalizedBlockHeader {
937 self.anchor
938 }
939
940 pub async fn rewind_to(&mut self, common: u64) -> Result<(), ChainError> {
944 if common < self.anchor.height {
945 return Err(format!(
946 "高さ {common} は、自分の枝の上にある確定(高さ {})より下なので巻き戻せません",
947 self.anchor.height
948 )
949 .into());
950 }
951 let mut originals = Vec::new();
952 for height in common + 1..=self.tip.height {
953 originals.push(
954 self.store
955 .block(height)
956 .await?
957 .ok_or("外れる枝のブロックがありません")?,
958 );
959 }
960 let orphans = originals
961 .iter()
962 .map(|bytes| {
963 let block = Block::from_bytes(bytes)?;
964 Ok((block.height, block.hash().0, bytes.as_slice()))
965 })
966 .collect::<Result<Vec<_>, ChainError>>()?;
967 if !orphans.is_empty() {
968 self.rewind(common, &orphans).await?;
969 }
970 self.actions
971 .retain(|action| matches!(action, Action::Notify(_)));
972 Ok(())
973 }
974
975 pub fn add_peer(&mut self, id: PeerId) {
977 self.peers.insert(
978 id,
979 Peer {
980 statistics: None,
981 pending: 0,
982 },
983 );
984 }
985
986 pub fn take_actions(&mut self) -> Vec<Action> {
988 std::mem::take(&mut self.actions)
989 }
990
991 pub async fn handle(&mut self, event: ChainEvent) -> Result<Option<Outcome>, ChainError> {
993 let outcome = self.handle_event(event).await?;
994 if outcome.is_none() {
995 self.harvest().await?;
996 }
997 Ok(outcome)
998 }
999
1000 async fn handle_event(&mut self, event: ChainEvent) -> Result<Option<Outcome>, ChainError> {
1001 match event {
1002 ChainEvent::Tick => {
1003 self.report_pushes();
1004 self.accept_held().await?;
1005 let idle: Vec<PeerId> = self
1006 .peers
1007 .iter()
1008 .filter(|(_, peer)| peer.pending == 0)
1009 .map(|(id, _)| *id)
1010 .collect();
1011 for id in idle {
1012 self.command(id, PeerCommand::Statistics);
1013 self.command(id, PeerCommand::Finalized);
1014 }
1015 self.backfill_proofs().await?;
1016 }
1017 ChainEvent::Statistics { peer, statistics } => {
1018 self.answered(peer);
1019 if let Some(entry) = self.peers.get_mut(&peer) {
1020 entry.statistics = Some(statistics);
1021 }
1022 let grouping = self.config.finalization.voting_set_grouping;
1025 if matches!(self.sync, Sync::Idle)
1026 && statistics.finalized_height > self.tip.height + grouping
1027 {
1028 self.notify(Notice::Behind {
1029 peer,
1030 finalized: statistics.finalized_height,
1031 tip: self.tip.height,
1032 });
1033 return Ok(Some(Outcome::Behind {
1034 finalized: statistics.finalized_height,
1035 }));
1036 }
1037 self.start_sync();
1038 }
1039 ChainEvent::Blocks {
1040 peer,
1041 from,
1042 count,
1043 blocks,
1044 } => {
1045 self.answered(peer);
1046 self.on_blocks(peer, from, count, blocks).await?;
1047 }
1048 ChainEvent::Hashes {
1049 peer,
1050 from,
1051 count,
1052 hashes,
1053 } => {
1054 self.answered(peer);
1055 self.on_hashes(peer, from, count, &hashes).await?;
1056 }
1057 ChainEvent::Finalized { peer, header } => {
1058 self.answered(peer);
1059 self.on_finalized(peer, header).await;
1060 }
1061 ChainEvent::Proof { peer, epoch, proof } => {
1062 self.answered(peer);
1063 self.on_proof(peer, epoch, proof).await?;
1064 }
1065 ChainEvent::OwnProof { epoch, proof } => self.on_own_proof(epoch, proof).await?,
1066 ChainEvent::Failed {
1067 peer,
1068 error,
1069 malformed,
1070 } => {
1071 self.notify(Notice::PeerDropped {
1072 peer,
1073 message: format!("ピア {} を外します: {error}", peer.0),
1074 });
1075 let penalty = if malformed {
1076 Penalty::Ban
1077 } else {
1078 Penalty::None
1079 };
1080 self.forget_peer(peer, penalty);
1081 }
1082 ChainEvent::PeerAdded { peer } => {
1083 self.add_peer(peer);
1084 self.progress(format!(
1085 "ピア {} をつなぎました({} か所)",
1086 peer.0,
1087 self.peers.len()
1088 ));
1089 self.command(peer, PeerCommand::Statistics);
1090 self.command(peer, PeerCommand::Finalized);
1091 }
1092 ChainEvent::PeerLost { peer } => self.forget_peer(peer, Penalty::None),
1093 ChainEvent::Pushed { block, bytes, from } => {
1094 self.on_pushed(*block, bytes, from).await?;
1095 }
1096 ChainEvent::Wake => self.accept_held().await?,
1097 }
1098 Ok(None)
1099 }
1100
1101 fn answered(&mut self, id: PeerId) {
1103 if let Some(entry) = self.peers.get_mut(&id) {
1104 entry.pending = entry.pending.saturating_sub(1);
1105 }
1106 }
1107
1108 fn command(&mut self, id: PeerId, command: PeerCommand) {
1110 let Some(peer) = self.peers.get_mut(&id) else {
1111 return;
1112 };
1113 peer.pending += 1;
1114 self.actions.push(Action::Command(id, command));
1115 }
1116
1117 fn drop_peer(&mut self, id: PeerId, message: String) {
1119 self.notify(Notice::PeerDropped { peer: id, message });
1120 self.forget_peer(id, Penalty::Failure);
1121 }
1122
1123 fn forget_peer(&mut self, id: PeerId, penalty: Penalty) {
1125 if self.peers.remove(&id).is_some() {
1126 self.actions.push(Action::Disconnect { peer: id, penalty });
1127 if self.peers.is_empty() {
1128 self.notify(Notice::Progress {
1129 message: "つないでいるピアがなくなりました".to_owned(),
1130 warning: true,
1131 });
1132 }
1133 }
1134 if self.sync.peer() == Some(id) {
1135 self.sync = Sync::Idle;
1136 }
1137 self.proof_requested.forget(id);
1139 }
1140
1141 fn notify(&mut self, notice: Notice) {
1142 self.actions.push(Action::Notify(notice));
1143 }
1144
1145 fn progress(&mut self, message: String) {
1146 self.notify(Notice::Progress {
1147 message,
1148 warning: false,
1149 });
1150 }
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155 use super::*;
1156
1157 #[test]
1158 fn notices_read_like_the_old_log_lines() {
1159 let finalized = |rows| Notice::Finalized {
1160 epoch: 4082,
1161 point: 17,
1162 height: 5_876_316,
1163 peer: Some(PeerId(2)),
1164 checkpoints: 0,
1165 rows,
1166 remaining: false,
1167 };
1168 assert_eq!(
1169 finalized(Some(524)).to_string(),
1170 "エポック 4082 ポイント 17 の証明を確かめました: 高さ 5876316 をファイナライズ(ピア 2、消したチェックポイント 0、消した差分 524 行)"
1171 );
1172 assert_eq!(
1173 finalized(None).to_string(),
1174 "エポック 4082 ポイント 17 の証明を確かめました: 高さ 5876316 をファイナライズ(ピア 2、消したチェックポイント 0)"
1175 );
1176 let tip = |height, byte| Tip {
1177 height,
1178 hash: Hash256([byte; 32]),
1179 importance_hash: Hash256([0; 32]),
1180 };
1181 let switched = Notice::Switched {
1182 common: 10,
1183 old: tip(11, 0xAA),
1184 new: tip(12, 0xBB),
1185 peer: PeerId(1),
1186 };
1187 assert_eq!(
1188 switched.to_string(),
1189 format!(
1190 "枝を取り替えました: 分かれ目 10、深さ 1、元の先端 {}(高さ 11)→ 新しい先端 {}(高さ 12)、ピア 1",
1191 "AA".repeat(32),
1192 "BB".repeat(32)
1193 )
1194 );
1195 assert!(!switched.is_warning());
1196 let dropped = Notice::PeerDropped {
1197 peer: PeerId(3),
1198 message: "ピア 3 を外します: 切れました".to_owned(),
1199 };
1200 assert!(dropped.is_warning());
1201 assert_eq!(dropped.to_string(), "ピア 3 を外します: 切れました");
1202 }
1203}