Skip to main content

heika_chain/chain/
mod.rs

1//! チェーンの持ち主。実行の状態と DB を持ち、Tick ごとにピアの統計を聞いて、スコアが自分より高く先に進んでいる
2//! ピアから続きを取り、確かめて当て、ブロックごとに(索引もその場で)durable にコミットする。
3//!
4//! 同期は1度に1つのピアとだけ(catapult の `CompareChains` と同じ)。続きが自分の先端につながらないか、スコアが
5//! 高いのに先にいないピアとは、ブロックのハッシュを並べて分かれ目を探し、ピアの枝を取って、自分の状態を分かれ目まで
6//! 巻き戻して当てる。スコアが元より高くならなければ、元の枝に戻す(`docs/archive/tip.md`)。
7//!
8//! Tick ごとにピアの最新のファイナライズも聞き、自分の確かめたものより新しければ、そのエポックの証明を取って、
9//! 実行して求めた投票者で確かめる。通れば、指すブロックが手元にあればハッシュを比べ(違えば分かれ目を探す)、
10//! 確かめた確定を上げて証明をしまい、確定より [`CHECKPOINT_EPOCHS`] エポック下より古いチェックポイントを1つを
11//! 残して消す。刈り込むなら([`Keep`])、そのときに差分も消す。同じラウンドで違うブロックを指す証明が2つ
12//! 通ったら、止める。
13//!
14//! 確定が先端より上を指すあいだは、その高さに来たブロックが合わなければ弾くだけで、自分の枝がそこへ続くかは
15//! まだわからない。分かれ目を探すのも、巻き戻せる下限も、自分の枝の上にあるとわかっている確定
16//! ([`Chain::anchor`])から。
17
18use 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/// 答えるときに読む、チェーンの様子。中核は出来事を1つ済ませるたびに [`Chain::status`] で作り直す
54#[derive(Clone, Copy, Debug)]
55pub struct Status {
56    /// 実行した先端の高さ
57    pub height: u64,
58    /// 先端までのスコア。わからなければ 0
59    pub score: u128,
60    /// 確かめた一番新しいファイナライズ
61    pub finalized: FinalizedBlockHeader,
62}
63
64/// 確かめた確定より何エポック下までのチェックポイントを残すか(それより古いものは1つを残して消す)。
65/// 確定より下には巻き戻らないので、余裕を見て2エポック
66pub const CHECKPOINT_EPOCHS: u64 = 2;
67
68/// 刈り込みで、ファイナライズより何エポック下まで差分を残すか。状態と木のノードとで別々。
69/// 巻き戻しに使う差分が要るので、どちらも [`CHECKPOINT_EPOCHS`] 以上にする
70#[derive(Clone, Copy, Debug)]
71pub struct Keep {
72    pub state: u64,
73    pub trie: u64,
74    /// ブロック、ステートメント、ファイナライズの証明も、状態の差分の境から再開に要る分(
75    /// [`ChainConfig::blocks_for_restart`])を引いたところより前を消す
76    pub history: bool,
77}
78
79impl Keep {
80    /// 確定を `finalized` に上げたときに消すもの。`floor` は確定以下で一番新しいチェックポイントの高さ。`keep` が
81    /// なければ(アーカイブ)、チェックポイントだけを消す。
82    ///
83    /// 確定より上に分かれ目があって巻き戻すときは、分かれ目以下で一番新しいチェックポイントまで戻るので、`floor`
84    /// より上は消さない
85    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
107/// DB の実行した先端の状態を戻したもの
108pub struct Loaded {
109    pub executor: Executor,
110    /// 実行した最後のブロック
111    pub parent: Block,
112    /// 難易度を求めるのに要る、直前のブロックの統計(古い順、`maxDifficultyBlocks` まで)
113    pub statistics: VecDeque<BlockStatistic>,
114    pub tip: Tip,
115}
116
117/// 保存の口 `store` の、実行した先端の状態を、書かずに戻す。二度入れを弾くハッシュも、直前のブロックから覚え直す
118///
119/// `partial` なら、アカウントの表を全部はメモリに持たない([`Executor::restore_partial`])
120pub 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        // 行から木を組み直すには、アカウントが全部要る
156        if partial {
157            return Err("しまった木の根が StateHash と合いません".into());
158        }
159        executor.rebuild_trees();
160    }
161    // ここから先の木のノードの変化を、ブロックごとに書く
162    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
181/// しまった証明のうち、指す高さが実行した高さ `tip` 以下で、指すブロックがしまったものと合う一番新しいもの
182/// ([`Chain::anchor`])。なければ Nemesis。ここより下は分かれていない
183///
184/// 先端より上を指す証明は飛ばす。それが自分の枝の上かは、そこまで実行するまでわからない。ブロックを消した高さを
185/// 指す証明は、突き合わせられないので、そのまま使う
186async 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
207/// 実行の状態の高さで、親のブロック、難易度の統計、Tip を DB から読み、二度入れを弾くハッシュを直前の
208/// ブロックから覚え直す
209async 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    /// 頼んで返事を待っている数
251    pending: usize,
252}
253
254enum Sync {
255    Idle,
256    /// 自分の先端の続きを取っている
257    Extending {
258        peer: PeerId,
259    },
260    /// 分かれ目を探している。`from` から自分とピアのハッシュを比べる
261    Comparing {
262        peer: PeerId,
263        from: u64,
264    },
265    /// 分かれ目 `common` から先の、ピアの枝を取っている
266    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/// ピアを外すときの罰。catapult と同じく、締め出すのは、どの規則から見ても壊れているものを返したときだけ
285#[derive(Clone, Copy, PartialEq, Eq, Debug)]
286pub enum Penalty {
287    /// 通信に失敗したか、こちらの都合。間を空けてまた試してよい
288    None,
289    /// こちらの規則と状態で合わないものを返した。失敗を数え、間を長く空ける
290    Failure,
291    /// 状態を見ない確かめに落ちるもの(形、署名)を返した。しばらく締め出す
292    Ban,
293}
294
295/// チェーンの持ち主から、駆動役(ピアとのやりとりを実際にするもの)への指示。[`Chain::take_actions`] で受け取る
296#[derive(Debug)]
297pub enum Action {
298    /// このピアに頼む。返事は [`ChainEvent`] で [`Chain::handle`] に入れる。頼めなかったら `ChainEvent::Failed` を入れる
299    Command(PeerId, PeerCommand),
300    /// このピアとのやりとりをやめる。どれだけ罰するかは `penalty`
301    Disconnect { peer: PeerId, penalty: Penalty },
302    /// この時刻になったら [`ChainEvent::Wake`] を入れる
303    WakeAt(SystemTime),
304    /// この鍵が押し付けたブロックは、こちらの規則と状態で合わなかった。今の接続を切るが、締め出さない
305    /// (規則の割れたハードフォークのあいだ、向こう側は別の規則に従っているだけかもしれない)
306    RejectPush(PublicKey),
307    /// 使う側に知らせること(画面やログに出すかは使う側が決める)
308    Notify(Notice),
309    /// 先端の枝に、これらのトランザクションが入った。未承認の置き場から外す。置き場を渡したときだけ出す
310    Included(Vec<Hash256>),
311    /// 巻き戻して、これらのトランザクション(署名したもの)が先端の枝から外れた。未承認の置き場に戻す。
312    /// 置き場を渡したときだけ出す
313    Restored(Vec<Vec<u8>>),
314    /// ブロックを作ってみたら、このトランザクションで弾かれた。未承認の置き場から外し、REST には弾いたと答える
315    Dropped(Hash256),
316}
317
318/// 先端の段階で起きたこと。`Display` は CLI に出す文
319#[derive(Clone, Debug)]
320pub enum Notice {
321    /// 先端にブロックを足した。`pushed` なら、接続してきたピアが押し付けたもの
322    Accepted {
323        height: u64,
324        transactions: usize,
325        hash: Hash256,
326        pushed: bool,
327    },
328    /// 分かれ目 `common` から先を、ピアの枝に取り替えた
329    Switched {
330        common: u64,
331        old: Tip,
332        new: Tip,
333        peer: PeerId,
334    },
335    /// 証明を確かめて確定を上げた。`rows` は刈り込んで消した差分の行(刈り込まないなら `None`)
336    Finalized {
337        epoch: u32,
338        point: u32,
339        height: u64,
340        /// 証明をくれたピア。自分で投票を数えて組んだものなら `None`
341        peer: Option<PeerId>,
342        checkpoints: usize,
343        rows: Option<u64>,
344        /// 刈り込みに消し残しがあり、次の確定で続きを消す
345        remaining: bool,
346    },
347    /// 抜けていたか、途中のポイントのままだった前のエポックの証明をしまった
348    EarlierProof {
349        epoch: u32,
350        height: u64,
351        peer: PeerId,
352        partial: bool,
353    },
354    /// ピアの枝の時刻が今より `ahead` ミリ秒先なので、今は使わない
355    TooFarInFuture {
356        peer: PeerId,
357        height: u64,
358        ahead: u64,
359    },
360    /// ピアの言う確定が自分の先端より1エポック以上先にある。追いつく段階に戻る
361    Behind {
362        peer: PeerId,
363        finalized: u64,
364        tip: u64,
365    },
366    /// ハーベストして、親から `seconds` 秒の高さ `height` のブロックを作り、先端に足した
367    Produced {
368        height: u64,
369        hash: Hash256,
370        seconds: u64,
371        peers: usize,
372    },
373    /// ピアを外した。`message` はわけを含む文
374    PeerDropped { peer: PeerId, message: String },
375    /// そのほかの経過。`warning` なら、うまくいかなかったこと
376    Progress { message: String, warning: bool },
377}
378
379impl Notice {
380    /// うまくいかなかったことか(CLI は標準エラーに出す)
381    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
496/// 押し付けの数を知らせる間隔
497const PUSH_REPORT: Duration = Duration::from_secs(60);
498
499/// ハーベストの当たりを、親からどれだけ先まで探すか(ミリ秒)
500const HARVEST_HORIZON: u64 = 60 * 60 * 1000;
501/// 当たりがこれより近ければ(秒)、求めたことを知らせる
502const HARVEST_ANNOUNCE: u64 = 120;
503
504/// [`Chain::harvest_plan`] が返す、今の先端の上でのハーベストの当たり
505#[derive(Clone, Copy, PartialEq, Eq, Debug)]
506pub enum HarvestPlan {
507    /// 求めていない。ハーベストしないか、先端が変わってまだ求め直していないか、ピアの高さを聞けていないか、
508    /// ほかのピアが先にいて追いつくのを待っている
509    NotPlanned,
510    /// 親から1時間先までに当たりがない(作ったあと、次の先端を待つあいだも、これになる)
511    NoHit,
512    /// 高さ `height` のブロックを、時刻 `timestamp`(UTC)で作れる。作るのは、その時刻の
513    /// `maxBlockFutureTime` 前から
514    Hit { height: u64, timestamp: SystemTime },
515}
516
517/// ハーベストの予定。先端 `parent` の上で求めた、当たりの一番早い時刻と鍵の番号(なければ `None`)
518struct Planned {
519    parent: Hash256,
520    slot: Option<(u64, usize)>,
521    /// 当たりを求められた鍵の Importance の合計
522    importance: u64,
523}
524
525/// [`Chain::harvest_outlook`] が返す、ハーベストの見込み。画面に見せるための見積もりで、合意には使わない
526/// ([`crate::outlook`])
527#[derive(Clone, Copy, PartialEq, Debug)]
528pub struct HarvestOutlook {
529    /// 今の先端(作るブロックの親)の時刻(UTC)。当たりまでのメーターの始まり
530    pub parent: SystemTime,
531    /// 自分の鍵の Importance の合計
532    pub importance: u64,
533    /// 直近のブロックから見積もった、ハーベストしている Importance の合計(自分を含む)
534    pub active_importance: f64,
535    /// 1つのブロックを自分が作る見込み
536    pub per_block: f64,
537    /// 直近のブロックの平均の間隔(秒)
538    pub block_seconds: f64,
539    /// 次の当たりで、ほかのだれにも先を越されない見込み(同じ秒に並ぶものは半々)。当たりがなければ `None`
540    pub next: Option<f64>,
541}
542
543/// 作るブロックの親まわりの写し。[`produce::Parent`] はこれを借りる
544struct 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/// 押し付けられたブロックをどう扱ったかの数
563#[derive(Default)]
564struct PushCounts {
565    /// 数え始めた時刻
566    since: Option<SystemTime>,
567    /// 先端の次として使った
568    used: u64,
569    /// 先端の次として試したが、弾いた
570    rejected: u64,
571    /// もう持っている高さ
572    known: u64,
573    /// そのうち、受け入れてからどれだけ遅れて届いたかがわかったものの、遅れの合計と数
574    late_total: Duration,
575    late_count: u32,
576    /// 先端の次だが、同期の途中だった
577    syncing: u64,
578    /// 先端の次だが、自分の先端につながらない(枝が違う)
579    unlinked: u64,
580    /// 先端の次より先の高さ
581    ahead: u64,
582    /// 時刻がまだ来ていないので、来るまで持った
583    held: u64,
584    /// そのうち、時刻が来て受け入れた(`used` とは別に数える)
585    used_late: u64,
586    /// そのうち、時刻が来て試したが、弾いた(`rejected` とは別に数える)
587    rejected_late: u64,
588    /// 時刻がまだ来ていないが、もう 1 つ持っていたので捨てた
589    future: u64,
590    /// 先端と同じ親の上の別のブロックで、スコアが高いので先端と差し替えた
591    replaced: u64,
592    /// 先端と同じ親の上の別のブロックだが、スコアが先端より高くない
593    rival_worse: u64,
594    /// 先端と同じ親の上の別のブロックで、スコアは高いが、弾いた
595    rival_rejected: u64,
596    /// 先端と同じ親の上の別のブロックだが、確定より下か、同期の途中か、時刻がまだなので試さなかった
597    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    /// 先端と同じ親の上の別のブロックの数
614    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
662/// アカウントを全部はメモリに持たないときに、1ブロックで読み足して当て直す回数の上限
663const MAX_RETRIES: usize = 8;
664/// ブロックを作るときに、弾かれたトランザクションを外して作り直す回数の上限
665const MAX_DROPS: usize = 16;
666/// 当てる途中で、まだ読んでいない状態のキーを引いた
667#[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/// ブロックが正しくないので弾いた(DB を読めないなど、こちらの都合で受け入れられなかったのではない)。送って
679/// きた相手を罰してよいのは、これのときだけ
680#[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
695/// 枝を取り替えてみた結果([`Chain::replace`])
696enum Replaced {
697    /// 取り替えた
698    Done,
699    /// 元の枝に戻した。`penalty` は、枝を送ってきた相手への罰
700    Failed { message: String, penalty: Penalty },
701}
702
703fn is_invalid(error: &ChainError) -> bool {
704    error.downcast_ref::<Invalid>().is_some()
705}
706
707/// 先端の段階が終わったわけ
708pub enum Outcome {
709    /// 止める合図で止めた
710    Stopped,
711    /// ピアの言う確定が、自分の先端より1エポック以上先にある。追いつく段階でまとめて進める
712    Behind { finalized: u64 },
713}
714
715/// チェーンの持ち主
716pub 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    /// 確かめた一番新しいファイナライズ。先端より上を指すこともあり、そのときは、その高さに来たブロックが合わなければ弾く
729    finalized: FinalizedBlockHeader,
730    /// 確かめたファイナライズのうち、自分の枝の上にあるとわかっている一番新しいもの。そこより下は分かれていない。
731    /// `finalized` が先端以下なら同じ
732    anchor: FinalizedBlockHeader,
733    /// 頼んで返事を待っている証明
734    proof_requested: finality::ProofRequest,
735    /// ここより前のエポックの証明は、しまってあるか、取り直しを一度頼んだ。抜けを探すのはここから
736    backfilled: u32,
737    /// 刈り込むなら、残す差分
738    keep: Option<Keep>,
739    /// 押し付けられたブロックをどう扱ったかの数。1 分ごとに知らせて 0 に戻す
740    pushes: PushCounts,
741    /// 押し付けられた、先端の次につながるが時刻のまだ来ていないブロック。時刻が来たら受け入れる(
742    /// `docs/archive/tip.md` の「未来のブロックは、受け入れずに手元に持つ」)
743    held: Option<(Block, Vec<u8>, Option<PublicKey>)>,
744    /// 最近受け入れた高さと時刻。押し付けがどれだけ遅れて届いたかを測る
745    accepted_at: VecDeque<(u64, SystemTime)>,
746    /// ハーベストする鍵(署名の鍵、VRF の鍵)。空ならハーベストしない
747    harvesters: Arc<Vec<(PrivateKey, PrivateKey)>>,
748    /// 今の先端の上での、ハーベストの予定
749    planned: Option<Planned>,
750    /// 最後に知らせた、ハーベストできないわけ。同じものは繰り返さない
751    harvest_warning: Option<String>,
752    /// 未承認のトランザクションの置き場。なければ、トランザクションのないブロックを作る
753    pending: Option<Arc<dyn produce::Pending>>,
754    /// 作るブロックの受取先。なければ、署名した鍵のアドレス
755    beneficiary: Option<Address>,
756    /// 入れるトランザクションを、選んだあとに直す口
757    assemble: Option<Arc<dyn produce::Assemble>>,
758    /// 駆動役にまだ渡していない指示
759    actions: Vec<Action>,
760}
761
762impl<'a, S: ChainStore + StateSource> Chain<'a, S> {
763    /// `partial` なら、アカウントの表を全部はメモリに持たず、ブロックごとに要る分だけ読む
764    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        // 追いつく段階や先端の段階でしまった、一番新しい証明。なければ Nemesis。先端より上を指すこともある
773        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    /// 先端の段階で、`keys`(署名の鍵、VRF の鍵。リモートならリモートの鍵)でハーベストする
818    /// 動かしたまま入れ替えてよく、次に先端が変わるのを待たずに、当たりの時刻を求め直す
819    pub fn set_harvesters(&mut self, keys: Arc<Vec<(PrivateKey, PrivateKey)>>) {
820        self.harvesters = keys;
821        self.planned = None;
822    }
823
824    /// ブロックを作るときに、`pending` から候補をもらう。渡すと、先端の枝に入ったものと外れたものを
825    /// [`Action::Included`] と [`Action::Restored`] で知らせる
826    pub fn set_pending(&mut self, pending: Arc<dyn produce::Pending>) {
827        self.pending = Some(pending);
828    }
829
830    /// 作るブロックの受取先(報酬のうち受取先の分を受け取るアドレス)。`None` なら、署名した鍵のアドレスにする。
831    /// 委任を引き受けるノードは、運営者のアドレスにする
832    pub fn set_beneficiary(&mut self, beneficiary: Option<Address>) {
833        self.beneficiary = beneficiary;
834    }
835
836    /// ブロックを作るときに、手数料で選んだトランザクションを `assemble` に渡して直してもらう
837    pub fn set_assemble(&mut self, assemble: Arc<dyn produce::Assemble>) {
838        self.assemble = Some(assemble);
839    }
840
841    /// 確定を上げるたびに、残す分より下の差分を消す
842    pub fn set_keep(&mut self, keep: Keep) {
843        self.keep = Some(keep);
844    }
845
846    /// 実行した高さ
847    pub fn height(&self) -> u64 {
848        self.tip.height
849    }
850
851    /// 実行した先端
852    pub fn tip(&self) -> Tip {
853        self.tip
854    }
855
856    /// 今の先端の上で求めた、ハーベストの当たり。画面に「次の当たり」を出すときに読む
857    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    /// 今の先端の上で求めた、ハーベストの見込み。当たりを求めていないか、直近のブロックが足りなければ `None`
871    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        // 直近のブロックを自分も作っていたなら、見積もりに自分も入っている。入っていなくても、自分の分より小さくはしない
880        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    /// 接続してきたピアに答えるときの様子
898    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    /// メモリの状態の根が、先端のブロックの StateHash と合うか
907    pub fn state_matches(&mut self) -> bool {
908        self.executor.state_hash() == self.parent.state_hash
909    }
910
911    /// ピアなしで、先端の次のブロック `block` を確かめて当て、コミットする(調べもの用)。知らせは指示に積む
912    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    /// 分かれ目 `common` から先を、ピアなしで枝 `blocks` に取り替えてみる(`switch-check`)。取り替えたら真、
921    /// 通らないかスコアが高くなくて元の枝に戻したら偽
922    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        // ピアはいないので、知らせのほかの指示は捨てる
930        self.actions
931            .retain(|action| matches!(action, Action::Notify(_)));
932        Ok(self.tip.hash != before)
933    }
934
935    /// 確かめた確定のうち、自分の枝の上にあるとわかっている一番新しいもの。ここより下は分かれていない
936    pub fn anchor(&self) -> FinalizedBlockHeader {
937        self.anchor
938    }
939
940    /// 先端を、[`Self::anchor`] 以上の高さ `common` まで、ピアなしで巻き戻す。外れる枝は孤立ブロックの表に残す。
941    /// 追いつく段階の前に、実行した先端がピアのチェーンから外れていたときに使う(追いつく段階は先端の続きを
942    /// 取るだけで、分かれ目を探さない)
943    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    /// ピア `id` とやりとりを始めたことを知らせる。ほかのノードに教えるために、名乗りを聞く
976    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    /// 駆動役にまだ渡していない指示を受け取る
987    pub fn take_actions(&mut self) -> Vec<Action> {
988        std::mem::take(&mut self.actions)
989    }
990
991    /// 出来事を1つ受け取って進める。先端の段階を終えるなら、そのわけを返す。指示は [`Chain::take_actions`] で受け取る
992    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                // 1ブロックずつコミットする先端の段階では遅いので、まとめて書く追いつく段階に戻る。確定は
1023                // ピアの言うものだが、追いつく段階は終わりに証明を確かめる
1024                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    /// ピアから返事が1つ来た
1102    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    /// ピアに頼む。頼めなかったら、駆動役が `ChainEvent::Failed` で知らせる
1109    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    /// こちらの規則と状態で合わないものを返したピアを外し、わけ `message` を知らせる([`Penalty::Failure`])
1118    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    /// ピアを外す(わけはもう知らせてある)
1124    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        // 頼んだ証明は返ってこないので、次の Tick でほかのピアに頼み直す
1138        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}