Skip to main content

heika_store_redb/
replay.rs

1//! 取ってきたブロックを、Nemesis から順に確かめて実行し、まとめて書く。スレッドを使わないので、ブラウザ(wasm)でも動く。
2//!
3//! heika-node の追いつく段階(`catch_up`)と同じ確かめを、1つのスレッドで順にする。取る、実行する、書くを重ねない
4//! ので遅いが、どこからブロックを取るか(P2P、REST、手元のファイル)は呼ぶ側が決められる。
5//!
6//! 確かめること(どれも、実行した状態から求めた値とブロックが合うか):
7//! - 前後に依らないところ([`verify_alone`]): 署名、TransactionsHash、トランザクションの署名と連署
8//! - つながり([`verify_link`])と、高さ 1 が決めた Nemesis であること
9//! - 難易度、ブロックを出した人の当たりと VRF の証明
10//! - 当てたあとの StateHash と ReceiptsHash
11//!
12//! [`Replay::push`] で当てたものは、[`Replay::commit`] するまで DB に残らない。途中で弾いたら、その [`Replay`] は
13//! 捨てて、[`Replay::open`] で最後のコミットから開き直す。
14//!
15//! 残し方([`Keep`])を渡せば、ノードの追いつく段階と同じく刈り込みながら進む。目標の高さ([`Replay::set_target`])から
16//! 残す分を引いたところより下では状態と木の差分を書かず、コミットのたびに、古いブロック、ステートメント、
17//! チェックポイント、差分を少しずつ(1回 2 秒まで)消す。
18//!
19//! `partial` なら、大きい状態の表(アカウントなど)を全部はメモリに持たず、ブロックごとに要る行と木のノードだけを読む
20//! (tip の段階の `Chain` と同じ)。読むのは書きかけの中からなので、まだコミットしていないブロックの変化も見える。
21//! 足りないものを引いたら、当てる前に戻して読み足し、当て直す。
22
23use std::collections::VecDeque;
24use std::fmt;
25
26use heika_block::Block;
27use heika_block::finalization::FinalizedBlockHeader;
28use heika_block::finalization::proof::{VotingSet, verify_proof};
29use heika_block::scoring::{BlockStatistic, difficulty};
30use heika_chain::chain::Keep;
31use heika_chain::store::{ChainStore, EXECUTOR_META, now_or_never};
32use heika_chain::verify::{Tip, verify_alone, verify_link};
33use heika_core::hash::Hash256;
34use heika_core::network::NetworkParameters;
35use heika_core::vrf;
36use heika_state_transition::config::ChainConfig;
37use heika_state_transition::executor::Executor;
38use heika_state_transition::executor::source::StateSource;
39
40use crate::{Batch, Db, DbError};
41
42/// [`Replay`] が止まったわけ
43#[derive(Debug)]
44pub enum ReplayError {
45    /// 高さ `height` のブロックを確かめて弾いた。取ってきたところが正しくないか、組み直しを間違えた
46    Invalid { height: u64, reason: String },
47    /// DB か実行器の誤り。ブロックのせいではない
48    Failed(String),
49}
50
51impl fmt::Display for ReplayError {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Self::Invalid { height, reason } => write!(f, "高さ {height}: {reason}"),
55            Self::Failed(reason) => f.write_str(reason),
56        }
57    }
58}
59
60impl std::error::Error for ReplayError {}
61
62impl From<DbError> for ReplayError {
63    fn from(error: DbError) -> Self {
64        Self::Failed(error.to_string())
65    }
66}
67
68fn failed(error: impl fmt::Display) -> ReplayError {
69    ReplayError::Failed(error.to_string())
70}
71
72/// 足りない状態を読み足して当て直す回数の上限
73const MAX_RETRIES: usize = 8;
74
75/// 順に実行していくもの。DB の実行した高さから始まる
76pub struct Replay<'a> {
77    db: &'a Db,
78    parameters: &'static NetworkParameters,
79    nemesis: Hash256,
80    executor: Executor,
81    /// 実行した最後のブロック。まだ何も実行していなければ `None`
82    parent: Option<Block>,
83    tip: Option<Tip>,
84    /// 難易度を求める、直前のブロックの統計(古い順、`maxDifficultyBlocks` まで)
85    statistics: VecDeque<BlockStatistic>,
86    /// 書きかけ。最初に当てたときに作り、コミットで閉じる
87    batch: Option<Batch>,
88    /// 最後にコミットした高さ
89    committed: u64,
90    config: ChainConfig,
91    /// 刈り込むなら、残す分。`None` なら全部残す(アーカイブ)
92    keep: Option<Keep>,
93    /// 状態と木のそれぞれ、この高さ以下では差分を書かない
94    quiet_through: [Option<u64>; 2],
95    /// この高さ以下ではステートメントを書かない
96    statements_through: Option<u64>,
97    /// [`Replay::set_target`] で知らされた目標
98    target: u64,
99    /// 大きい状態の表を全部はメモリに持たない
100    partial: bool,
101}
102
103impl<'a> Replay<'a> {
104    /// `db` の、最後にコミットした高さから続ける。空の DB なら、次は Nemesis(ハッシュが `nemesis` のもの)
105    pub fn open(
106        db: &'a Db,
107        config: ChainConfig,
108        parameters: &'static NetworkParameters,
109        nemesis: Hash256,
110        keep: Option<Keep>,
111        partial: bool,
112    ) -> Result<Self, ReplayError> {
113        let seed = parameters.generation_hash_seed;
114        let lifetime = config
115            .max_transaction_lifetime
116            .max(config.max_bonded_transaction_lifetime);
117        // まだ何も実行していなければ、全部をメモリに持って Nemesis から始める(最初のコミットで、要るものだけを読む形に
118        // 開き直す)
119        let mut executor = match db.meta(EXECUTOR_META)? {
120            Some(_) if partial => {
121                let (meta, rows, nodes) =
122                    now_or_never(ChainStore::load_partial_state(db)).map_err(failed)?;
123                let mut executor = Executor::restore_partial(
124                    config.clone(),
125                    parameters.identifier,
126                    seed,
127                    rows,
128                    &meta,
129                )
130                .map_err(failed)?;
131                executor.restore_trees(nodes).map_err(failed)?;
132                executor.load_tree_roots(db).map_err(failed)?;
133                executor
134            }
135            Some(meta) => Executor::restore(
136                config.clone(),
137                parameters.identifier,
138                seed,
139                db.state_rows()?,
140                &meta,
141            )
142            .map_err(failed)?,
143            None => Executor::new(config.clone(), parameters.identifier, seed),
144        };
145        let start = executor.height();
146        let stored = |height: u64| -> Result<Block, ReplayError> {
147            let bytes = db
148                .block(height)?
149                .ok_or_else(|| failed(format!("実行した高さ {height} のブロックがありません")))?;
150            Block::from_bytes(&bytes).map_err(failed)
151        };
152
153        // 同じトランザクションの二度入れを弾くハッシュはしまっていないので、期限が残っているかもしれない直前の
154        // ブロックから覚え直す
155        let mut recent: Vec<Block> = Vec::new();
156        for height in (1..=start).rev() {
157            let block = stored(height)?;
158            if recent
159                .first()
160                .is_some_and(|last| block.timestamp + lifetime < last.timestamp)
161            {
162                break;
163            }
164            recent.push(block);
165        }
166        for block in recent.iter().rev() {
167            executor.remember_transactions(block).map_err(failed)?;
168        }
169
170        let window = parameters.max_difficulty_blocks;
171        let mut statistics = VecDeque::with_capacity(window);
172        for height in start.saturating_sub(window as u64 - 1).max(1)..=start {
173            statistics.push_back(BlockStatistic::from(&stored(height)?));
174        }
175        let parent = (start > 0).then(|| stored(start)).transpose()?;
176        let tip = match &parent {
177            None => None,
178            Some(block) => {
179                let grouping = parameters.importance_grouping;
180                let importance_height = (block.height / grouping * grouping).max(1);
181                let importance_hash = if importance_height == block.height {
182                    block.hash()
183                } else {
184                    stored(importance_height)?.hash()
185                };
186                Some(Tip {
187                    height: block.height,
188                    hash: block.hash(),
189                    importance_hash,
190                })
191            }
192        };
193
194        // 木を戻す。しまった木のノードがあれば、そこから戻して根を確かめる。まだ残していなければ、今の木を全部書いて
195        // から残し始める
196        let mut batch = db.batch()?;
197        batch.start_history(start)?;
198        let trie_started = db.trie_started()?;
199        let expected = parent.as_ref().map(|block| block.state_hash);
200        if executor.is_partial() {
201            // 行から木を組み直すには、アカウントが全部要る
202            if Some(executor.state_hash()) != expected {
203                return Err(failed("しまった木の根が StateHash と合いません"));
204            }
205        } else if trie_started && start > 0 {
206            executor.restore_trees(db.trie_nodes()?).map_err(failed)?;
207            if Some(executor.state_hash()) != expected {
208                executor.rebuild_trees();
209            }
210        }
211        executor.roots();
212        if trie_started {
213            executor.forget_node_changes();
214        } else {
215            batch.start_trie(start)?;
216            let nodes = executor
217                .all_nodes()
218                .ok_or_else(|| failed("全部のノードを持たない木から、ノードを全部は書けません"))?;
219            batch.set_trie_at(start, nodes.iter().map(|(key, node)| (key, Some(node))))?;
220        }
221        batch.commit()?;
222
223        Ok(Self {
224            db,
225            parameters,
226            nemesis,
227            executor,
228            parent,
229            tip,
230            statistics,
231            batch: None,
232            committed: start,
233            config,
234            keep,
235            quiet_through: [None; 2],
236            statements_through: None,
237            target: 0,
238            partial,
239        })
240    }
241
242    /// これから実行する目標の高さ(ふつうは確定した高さ)を知らせる。刈り込むなら、目標から残す分を引いたところより
243    /// 下では差分を書かないようにする。そこまでの差分は消す扱いにする(DB の差分の始まりを上げる)ので、目標は確定した
244    /// 高さより上にしない。書きかけがあれば、次のコミットのあとで当てる(redb は書く側が1つだけなので)
245    pub fn set_target(&mut self, target: u64) -> Result<(), ReplayError> {
246        self.target = self.target.max(target);
247        if self.batch.is_none() {
248            self.apply_target()?;
249        }
250        Ok(())
251    }
252
253    /// [`Replay::set_target`] の目標から、差分を書かない高さを決めて当てる。書きかけがないときに呼ぶ
254    fn apply_target(&mut self) -> Result<(), ReplayError> {
255        let Some(keep) = self.keep else {
256            return Ok(());
257        };
258        let grouping = self.parameters.voting_set_grouping;
259        let state = self.target.saturating_sub(keep.state * grouping);
260        let trie = self.target.saturating_sub(keep.trie * grouping);
261        if self.quiet_through == [Some(state), Some(trie)] {
262            return Ok(());
263        }
264        // 差分の始まりを上げてから、それより下を書かないようにする。残りの差分を消すのは commit のたびに少しずつ
265        self.db.prune_state_history(state, |_| false)?;
266        self.db.prune_trie_history(trie, |_| false)?;
267        self.quiet_through = [Some(state), Some(trie)];
268        if keep.history {
269            self.statements_through = Some(state.saturating_sub(self.config.blocks_for_restart()));
270        }
271        Ok(())
272    }
273
274    /// エポック `epoch` のファイナライズの証明を、実行して求めた投票者で確かめ、指すブロックが実行したものと同じなら
275    /// しまう。しまった証明は、先端を追う `Chain` が、確かめた確定として読む。書きかけがあれば先にコミットする。
276    /// 指すブロックがまだ実行していない高さなら、しまわずに `Ok(None)` を返す(もっと進めてから呼び直す)
277    pub fn store_proof(
278        &mut self,
279        epoch: u32,
280        proof: &[u8],
281    ) -> Result<Option<FinalizedBlockHeader>, ReplayError> {
282        self.commit()?;
283        let voters = self
284            .db
285            .voters(epoch)?
286            .and_then(|voters| VotingSet::decode(&voters))
287            .ok_or_else(|| failed(format!("エポック {epoch} の投票者がありません")))?;
288        let invalid = |reason: String| ReplayError::Invalid {
289            height: self.committed,
290            reason,
291        };
292        let header = verify_proof(
293            proof,
294            epoch,
295            &voters,
296            &self.config.finalization.proof_parameters(),
297        )
298        .map_err(|error| invalid(format!("エポック {epoch} の証明が通りません: {error}")))?;
299        if header.height > self.committed {
300            return Ok(None);
301        }
302        let bytes = self.db.block(header.height)?.ok_or_else(|| {
303            failed(format!(
304                "証明が指す高さ {} のブロックがありません",
305                header.height
306            ))
307        })?;
308        if Block::from_bytes(&bytes).map_err(failed)?.hash() != header.hash {
309            return Err(invalid(format!(
310                "エポック {epoch} の証明が、実行したものと違う高さ {} のブロックを指しています",
311                header.height
312            )));
313        }
314        let mut batch = self.db.batch()?;
315        batch.put_proof(epoch, proof)?;
316        batch.commit()?;
317        Ok(Some(header))
318    }
319
320    /// 実行した高さ(コミットしていない分も含む)
321    pub fn height(&self) -> u64 {
322        self.executor.height()
323    }
324
325    /// 最後にコミットした高さ
326    pub fn committed(&self) -> u64 {
327        self.committed
328    }
329
330    /// 実行した最後のブロックの StateHash。まだ何も実行していなければ `None`
331    pub fn state_hash(&self) -> Option<Hash256> {
332        self.parent.as_ref().map(|block| block.state_hash)
333    }
334
335    /// 次の高さのブロック `bytes` を確かめて当てる。コミットするまで DB には残らない。
336    ///
337    /// 弾いたら、この `Replay` は途中まで当たった状態なので捨て、[`Replay::open`] で開き直す
338    pub fn push(&mut self, bytes: Vec<u8>) -> Result<(), ReplayError> {
339        let height = self.executor.height() + 1;
340        let invalid = |reason: String| ReplayError::Invalid { height, reason };
341        let block = Block::from_bytes(&bytes).map_err(|error| invalid(error.to_string()))?;
342        if block.height != height {
343            return Err(invalid(format!("高さが {} です", block.height)));
344        }
345        verify_alone(self.parameters, &block).map_err(|error| invalid(error.to_string()))?;
346        let tip = verify_link(self.tip, &block).map_err(|error| invalid(error.to_string()))?;
347        if height == 1 && tip.hash != self.nemesis {
348            return Err(invalid("決めた Nemesis と違います".into()));
349        }
350
351        if self.batch.is_none() {
352            let mut batch = self.db.batch()?;
353            batch.quiet_through = self.quiet_through;
354            self.batch = Some(batch);
355        }
356        // 読むのは書きかけの中から。まだコミットしていない、前のブロックの変化も見える
357        let source: &dyn StateSource = self.batch.as_ref().expect("作った");
358        let read = |error| ReplayError::Failed(format!("状態を読めません: {error}"));
359        if self.executor.is_partial() {
360            let wanted = self.executor.wanted_for(&block);
361            self.executor.load_wanted(source, &wanted).map_err(read)?;
362        }
363
364        // 実行する前に、1つ前のブロックのあとの状態で、難易度とブロックを出した人を確かめる。Nemesis は信じる
365        if let Some(parent) = &self.parent {
366            let expected = difficulty(self.statistics.make_contiguous(), self.parameters);
367            if block.difficulty != expected {
368                return Err(invalid(format!(
369                    "難易度が {} で、直前のブロックから求めた {expected} と合いません",
370                    block.difficulty
371                )));
372            }
373            let key = loop {
374                let checked = self.executor.check_hit(parent, &block, self.parameters);
375                let missed = self.executor.take_missed();
376                if missed.is_empty() {
377                    break checked.map_err(|error| invalid(error.to_string()))?;
378                }
379                self.executor.load_wanted(source, &missed).map_err(read)?;
380            };
381            let alpha = parent.generation_hash();
382            if vrf::verify_with(
383                &key,
384                &alpha.0,
385                &block.generation_hash_proof,
386                self.parameters.vrf_checks(block.height),
387            )
388            .is_none()
389            {
390                return Err(invalid("ブロックを出した人: VRF の証明が通りません".into()));
391            }
392        }
393
394        // まだ読んでいないものを引いたら、当てる前に戻して読み足し、当て直す
395        let before = self.executor.encode_meta();
396        let mut retries = 0;
397        let state_hash = loop {
398            let applied = self.executor.apply(&block);
399            let state_hash = self.executor.state_hash();
400            let missed = self.executor.take_missed();
401            if missed.is_empty() {
402                applied.map_err(|error| invalid(error.to_string()))?;
403                break state_hash;
404            }
405            if retries == MAX_RETRIES {
406                return Err(ReplayError::Failed(format!(
407                    "高さ {height}: {MAX_RETRIES} 回読み足しても、読んでいない状態が {} 個あります",
408                    missed.len()
409                )));
410            }
411            retries += 1;
412            self.executor.undo_attempt(source, &before).map_err(read)?;
413            self.executor.load_wanted(source, &missed).map_err(read)?;
414        };
415        if state_hash != block.state_hash {
416            return Err(invalid(format!(
417                "StateHash が {state_hash} で、ブロックの {} と合いません",
418                block.state_hash
419            )));
420        }
421        let statement = self.executor.take_statement();
422        if statement.merkle_hash() != block.receipts_hash {
423            return Err(invalid("ReceiptsHash が合いません".into()));
424        }
425
426        let changes = self.executor.take_changes();
427        let state = changes
428            .puts
429            .into_iter()
430            .map(|(key, value)| (key, Some(value)))
431            .chain(changes.deletes.into_iter().map(|key| (key, None)));
432        let nodes = self.executor.take_node_changes();
433        let grouping = self.parameters.voting_set_grouping;
434        // エポック E の投票者は、E - 1 の最後の高さ(高さ 1 か、区切りの倍数)の状態で決まる
435        let next_epoch = if height == 1 {
436            Some(2)
437        } else if height.is_multiple_of(grouping) {
438            u32::try_from(height / grouping + 2).ok()
439        } else {
440            None
441        };
442        let batch = self.batch.as_mut().expect("作った");
443        batch.put_block(height, &bytes)?;
444        batch.set_state_at(height, state)?;
445        batch.set_trie_at(height, nodes)?;
446        if self
447            .statements_through
448            .is_none_or(|through| height > through)
449        {
450            batch.put_statement(height, &statement.to_bytes())?;
451        }
452        if let Some(epoch) = next_epoch {
453            batch.put_voters(epoch, &self.executor.voting_set(epoch).encode())?;
454        }
455
456        self.statistics.push_back(BlockStatistic::from(&block));
457        if self.statistics.len() > self.parameters.max_difficulty_blocks {
458            self.statistics.pop_front();
459        }
460        self.tip = Some(tip);
461        self.parent = Some(block);
462        // 変化は書きかけに書いたので、読み込んだ行と木のノードを手放す。次に要れば書きかけから読む
463        self.executor.release_loaded();
464        Ok(())
465    }
466
467    /// ここまで当てたものを書く。書き終えたら、次に開いたときはここから続く
468    pub fn commit(&mut self) -> Result<(), ReplayError> {
469        let Some(mut batch) = self.batch.take() else {
470            return Ok(());
471        };
472        let height = self.executor.height();
473        let meta = self.executor.encode_meta();
474        batch.put_meta(EXECUTOR_META, &meta)?;
475        batch.put_checkpoint(height, &meta)?;
476        batch.commit()?;
477        self.committed = height;
478        // コミットした高さを確定とみなして、残す分より古いものを消す。消しきれなければ次のコミットで続ける
479        let plan = Keep::plan(self.keep, &self.config, self.parameters, height, height);
480        now_or_never(ChainStore::prune(self.db, plan)).map_err(failed)?;
481        // Nemesis から全部をメモリに持って始めたなら、ここで要るものだけを読む形に開き直す
482        if self.partial && !self.executor.is_partial() {
483            let target = self.target;
484            *self = Self::open(
485                self.db,
486                self.config.clone(),
487                self.parameters,
488                self.nemesis,
489                self.keep,
490                true,
491            )?;
492            self.target = target;
493        }
494        self.apply_target()
495    }
496}