Skip to main content

heika_store_redb/
chain_store.rs

1//! 中核(heika-chain)の保存の口 [`ChainStore`] を、[`Db`] で実装する。
2
3use std::time::Duration;
4// ブラウザ(wasm32-unknown-unknown)の std の Instant は呼ぶと panic するので、performance.now() を使うものにする
5#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
6use std::time::Instant;
7#[cfg(all(target_family = "wasm", target_os = "unknown"))]
8use web_time::Instant;
9
10use heika_chain::ChainError;
11use heika_chain::store::{BlockWrite, ChainStore, EXECUTOR_META, Prune, Pruned};
12use heika_core::patricia::SubCache;
13use heika_state_transition::executor::is_partial_row;
14
15use crate::{Change, Db, StateRow};
16
17/// 先端を追うあいだの刈り込みに、1回で使う時間の目安。まとまりの途中では止めないので、少し超えることがある
18const PRUNE_BUDGET: Duration = Duration::from_secs(2);
19
20impl ChainStore for Db {
21    async fn load_state(&self) -> Result<(Vec<u8>, Vec<StateRow>, Vec<StateRow>), ChainError> {
22        let meta = self.meta(EXECUTOR_META)?.ok_or("まだ実行していません")?;
23        Ok((meta, self.state_rows()?, self.trie_nodes()?))
24    }
25
26    async fn load_partial_state(
27        &self,
28    ) -> Result<(Vec<u8>, Vec<StateRow>, Vec<StateRow>), ChainError> {
29        let meta = self.meta(EXECUTOR_META)?.ok_or("まだ実行していません")?;
30        let mut rows = Vec::new();
31        for cache in SubCache::ALL {
32            // ハッシュロックは、期限の来ていないものを選ぶために読む
33            if cache != SubCache::HashLockInfo && is_partial_row(&[cache.index() as u8]) {
34                continue;
35            }
36            self.for_each_state_row(&[cache.index() as u8], &mut |key, value| {
37                rows.push((key.to_vec(), value.to_vec()));
38            })?;
39        }
40        // 大きい表の木は、必要なノードだけをあとで読む
41        let mut nodes = Vec::new();
42        for cache in SubCache::ALL {
43            if is_partial_row(&[cache.index() as u8]) {
44                continue;
45            }
46            self.for_each_trie_node(&[cache.index() as u8], &mut |key, value| {
47                nodes.push((key.to_vec(), value.to_vec()));
48            })?;
49        }
50        Ok((meta, rows, nodes))
51    }
52
53    async fn block(&self, height: u64) -> Result<Option<Vec<u8>>, ChainError> {
54        Ok(Db::block(self, height)?)
55    }
56
57    async fn blocks_from(&self) -> Result<u64, ChainError> {
58        Ok(Db::blocks_from(self)?)
59    }
60
61    async fn proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, ChainError> {
62        Ok(Db::proof(self, epoch)?)
63    }
64
65    async fn proofs_tip(&self) -> Result<u32, ChainError> {
66        Ok(Db::proofs_tip(self)?)
67    }
68
69    async fn voters(&self, epoch: u32) -> Result<Option<Vec<u8>>, ChainError> {
70        Ok(Db::voters(self, epoch)?)
71    }
72
73    async fn put_proof(&self, epoch: u32, proof: &[u8]) -> Result<(), ChainError> {
74        let mut batch = self.batch()?;
75        batch.put_proof(epoch, proof)?;
76        batch.commit()?;
77        Ok(())
78    }
79
80    async fn commit_block(&self, write: BlockWrite<'_>) -> Result<(), ChainError> {
81        let mut batch = self.batch()?;
82        batch.put_block(write.height, write.bytes)?;
83        batch.remove_orphan(write.height, &write.hash)?;
84        batch.set_state_at(write.height, write.state)?;
85        batch.set_trie_at(write.height, write.nodes)?;
86        batch.put_statement(write.height, &write.statement)?;
87        if let Some((epoch, voters)) = &write.voters {
88            batch.put_voters(*epoch, voters)?;
89        }
90        batch.put_meta(EXECUTOR_META, &write.meta)?;
91        batch.put_checkpoint(write.height, &write.meta)?;
92        batch.commit()?;
93        Ok(())
94    }
95
96    /// 1回で刈り込むのは `PRUNE_BUDGET`(2 秒)まで。アーカイブからライトにしたときなど、消すものが多くても先端を追うのを
97    /// 長く止めないように、残りは次に呼ばれたとき(次の確定)に続ける。どの刈り込みも、続きから消せる
98    async fn prune(&self, prune: Prune) -> Result<Pruned, ChainError> {
99        let checkpoints = self.prune_checkpoints(prune.checkpoints_below)?;
100        let deadline = Instant::now() + PRUNE_BUDGET;
101        let keep_going = || Instant::now() < deadline;
102        let mut rows = 0;
103        let mut remaining = false;
104        if let Some((state, trie)) = prune.history {
105            let pruned = self.prune_state_history(state, |_| keep_going())?;
106            rows += pruned.rows;
107            remaining |= !pruned.done;
108            if !remaining {
109                let pruned = self.prune_trie_history(trie, |_| keep_going())?;
110                rows += pruned.rows;
111                remaining |= !pruned.done;
112            }
113        }
114        if let Some((through, epoch)) = prune.blocks
115            && !remaining
116        {
117            let pruned = self.prune_history_while(through, epoch, keep_going)?;
118            rows += pruned.rows;
119            remaining |= !pruned.done;
120        }
121        Ok(Pruned {
122            checkpoints,
123            rows,
124            remaining,
125        })
126    }
127
128    async fn checkpoint_at_or_below(
129        &self,
130        height: u64,
131    ) -> Result<Option<(u64, Vec<u8>)>, ChainError> {
132        Ok(Db::checkpoint_at_or_below(self, height)?)
133    }
134
135    async fn changes_above(&self, height: u64) -> Result<Vec<Change>, ChainError> {
136        Ok(Db::changes_above(self, height)?)
137    }
138
139    async fn rollback(
140        &self,
141        height: u64,
142        voters_from: u32,
143        orphans: &[(u64, [u8; 32], &[u8])],
144    ) -> Result<(), ChainError> {
145        Db::rollback(self, height, voters_from, EXECUTOR_META, true, orphans)?;
146        Ok(())
147    }
148}