1use std::cell::RefCell;
5use std::collections::BTreeMap;
6
7use heika_core::patricia::SubCache;
8
9use heika_state_transition::executor::ExecError;
10use heika_state_transition::executor::source::StateSource;
11
12use crate::ChainError;
13use crate::store::{BlockWrite, ChainStore, Change, Prune, Pruned, StateRow};
14
15#[derive(Default)]
17pub struct MemoryStore {
18 inner: RefCell<Inner>,
19}
20
21#[derive(Default)]
22struct Inner {
23 meta: Vec<u8>,
24 state: BTreeMap<Vec<u8>, Vec<u8>>,
25 nodes: BTreeMap<Vec<u8>, Vec<u8>>,
26 undo: BTreeMap<u64, [Vec<Change>; 2]>,
28 history_from: u64,
30 blocks: BTreeMap<u64, Vec<u8>>,
31 blocks_from: u64,
32 statements: BTreeMap<u64, Vec<u8>>,
33 proofs: BTreeMap<u32, Vec<u8>>,
34 voters: BTreeMap<u32, Vec<u8>>,
35 checkpoints: BTreeMap<u64, Vec<u8>>,
36 orphans: BTreeMap<(u64, [u8; 32]), Vec<u8>>,
37}
38
39impl MemoryStore {
40 pub fn orphans(&self) -> Vec<(u64, [u8; 32])> {
42 self.inner.borrow().orphans.keys().copied().collect()
43 }
44}
45
46fn apply(rows: &mut BTreeMap<Vec<u8>, Vec<u8>>, changes: Vec<Change>) -> Vec<Change> {
48 changes
49 .into_iter()
50 .map(|(key, value)| {
51 let before = match value {
52 Some(value) => rows.insert(key.clone(), value),
53 None => rows.remove(&key),
54 };
55 (key, before)
56 })
57 .collect()
58}
59
60impl ChainStore for MemoryStore {
61 async fn load_state(&self) -> Result<(Vec<u8>, Vec<StateRow>, Vec<StateRow>), ChainError> {
62 let inner = self.inner.borrow();
63 let rows = |map: &BTreeMap<Vec<u8>, Vec<u8>>| {
64 map.iter()
65 .map(|(key, value)| (key.clone(), value.clone()))
66 .collect()
67 };
68 Ok((inner.meta.clone(), rows(&inner.state), rows(&inner.nodes)))
69 }
70
71 async fn load_partial_state(
72 &self,
73 ) -> Result<(Vec<u8>, Vec<StateRow>, Vec<StateRow>), ChainError> {
74 let inner = self.inner.borrow();
75 let hash_lock = SubCache::HashLockInfo.index() as u8;
76 let rows = inner
77 .state
78 .iter()
79 .filter(|(key, _)| {
80 key.first() == Some(&hash_lock)
81 || !heika_state_transition::executor::is_partial_row(key)
82 })
83 .map(|(key, value)| (key.clone(), value.clone()))
84 .collect();
85 let nodes = inner
86 .nodes
87 .iter()
88 .filter(|(key, _)| !heika_state_transition::executor::is_partial_row(key))
89 .map(|(key, value)| (key.clone(), value.clone()))
90 .collect();
91 Ok((inner.meta.clone(), rows, nodes))
92 }
93
94 async fn block(&self, height: u64) -> Result<Option<Vec<u8>>, ChainError> {
95 Ok(self.inner.borrow().blocks.get(&height).cloned())
96 }
97
98 async fn blocks_from(&self) -> Result<u64, ChainError> {
99 Ok(self.inner.borrow().blocks_from)
100 }
101
102 async fn proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, ChainError> {
103 Ok(self.inner.borrow().proofs.get(&epoch).cloned())
104 }
105
106 async fn proofs_tip(&self) -> Result<u32, ChainError> {
107 Ok(self
108 .inner
109 .borrow()
110 .proofs
111 .keys()
112 .next_back()
113 .copied()
114 .unwrap_or(0))
115 }
116
117 async fn voters(&self, epoch: u32) -> Result<Option<Vec<u8>>, ChainError> {
118 Ok(self.inner.borrow().voters.get(&epoch).cloned())
119 }
120
121 async fn put_proof(&self, epoch: u32, proof: &[u8]) -> Result<(), ChainError> {
122 self.inner.borrow_mut().proofs.insert(epoch, proof.to_vec());
123 Ok(())
124 }
125
126 async fn commit_block(&self, write: BlockWrite<'_>) -> Result<(), ChainError> {
127 let mut inner = self.inner.borrow_mut();
128 let inner = &mut *inner;
129 let state = apply(&mut inner.state, write.state);
130 let nodes = apply(&mut inner.nodes, write.nodes);
131 inner.undo.insert(write.height, [state, nodes]);
132 inner.blocks.insert(write.height, write.bytes.to_vec());
133 inner.orphans.remove(&(write.height, write.hash));
134 inner.statements.insert(write.height, write.statement);
135 if let Some((epoch, voters)) = write.voters {
136 inner.voters.insert(epoch, voters);
137 }
138 inner.checkpoints.insert(write.height, write.meta.clone());
139 inner.meta = write.meta;
140 Ok(())
141 }
142
143 async fn prune(&self, prune: Prune) -> Result<Pruned, ChainError> {
144 let mut inner = self.inner.borrow_mut();
145 let inner = &mut *inner;
146 let kept = inner.checkpoints.split_off(&prune.checkpoints_below);
147 let checkpoints = std::mem::replace(&mut inner.checkpoints, kept).len();
148 let mut rows = 0;
149 if let Some((state, trie)) = prune.history {
150 for (height, [state_undo, node_undo]) in &mut inner.undo {
151 if *height <= state {
152 rows += std::mem::take(state_undo).len() as u64;
153 }
154 if *height <= trie {
155 rows += std::mem::take(node_undo).len() as u64;
156 }
157 }
158 let through = state.min(trie);
159 inner.undo = inner.undo.split_off(&(through + 1));
160 inner.history_from = inner.history_from.max(through + 1);
161 }
162 if let Some((through, epoch)) = prune.blocks {
163 for table in [&mut inner.blocks, &mut inner.statements] {
164 let kept = table.split_off(&(through + 1));
165 rows += std::mem::replace(table, kept).len() as u64;
166 }
167 let kept = inner.proofs.split_off(&epoch);
168 rows += std::mem::replace(&mut inner.proofs, kept).len() as u64;
169 inner.blocks_from = inner.blocks_from.max(through + 1);
170 }
171 Ok(Pruned {
172 checkpoints,
173 rows,
174 remaining: false,
175 })
176 }
177
178 async fn checkpoint_at_or_below(
179 &self,
180 height: u64,
181 ) -> Result<Option<(u64, Vec<u8>)>, ChainError> {
182 Ok(self
183 .inner
184 .borrow()
185 .checkpoints
186 .range(..=height)
187 .next_back()
188 .map(|(height, meta)| (*height, meta.clone())))
189 }
190
191 async fn changes_above(&self, height: u64) -> Result<Vec<Change>, ChainError> {
192 let inner = self.inner.borrow();
193 if height < inner.history_from {
194 return Err(format!(
195 "高さ {height} の差分はありません({} から)",
196 inner.history_from
197 )
198 .into());
199 }
200 let mut rows = BTreeMap::new();
202 for [state, _] in inner.undo.range(height + 1..).map(|(_, undo)| undo) {
203 for (key, before) in state {
204 rows.entry(key.clone()).or_insert_with(|| before.clone());
205 }
206 }
207 Ok(rows.into_iter().collect())
208 }
209
210 async fn rollback(
211 &self,
212 height: u64,
213 voters_from: u32,
214 orphans: &[(u64, [u8; 32], &[u8])],
215 ) -> Result<(), ChainError> {
216 let mut inner = self.inner.borrow_mut();
217 let inner = &mut *inner;
218 let (checkpoint, meta) = inner
219 .checkpoints
220 .range(..=height)
221 .next_back()
222 .map(|(height, meta)| (*height, meta.clone()))
223 .ok_or("巻き戻せるチェックポイントがありません")?;
224 if checkpoint < inner.history_from {
225 return Err(format!(
226 "高さ {checkpoint} の差分はありません({} から)",
227 inner.history_from
228 )
229 .into());
230 }
231 for (_, [state, nodes]) in inner.undo.split_off(&(checkpoint + 1)).into_iter().rev() {
233 for (rows, undo) in [(&mut inner.state, state), (&mut inner.nodes, nodes)] {
234 for (key, before) in undo.into_iter().rev() {
235 match before {
236 Some(value) => rows.insert(key, value),
237 None => rows.remove(&key),
238 };
239 }
240 }
241 }
242 inner.statements.split_off(&(checkpoint + 1));
243 inner.checkpoints.split_off(&(checkpoint + 1));
244 inner.blocks.split_off(&(height + 1));
245 for (height, hash, block) in orphans {
246 inner.orphans.insert((*height, *hash), block.to_vec());
247 }
248 inner.voters.split_off(&voters_from);
249 inner.meta = meta;
250 Ok(())
251 }
252}
253
254impl StateSource for MemoryStore {
255 fn row(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
256 Ok(self.inner.borrow().state.get(key).cloned())
257 }
258
259 fn node(&self, key: &[u8]) -> Result<Option<Vec<u8>>, ExecError> {
260 Ok(self.inner.borrow().nodes.get(key).cloned())
261 }
262
263 fn for_each_row(
264 &self,
265 prefix: &[u8],
266 visit: &mut dyn FnMut(&[u8], &[u8]),
267 ) -> Result<(), ExecError> {
268 let inner = self.inner.borrow();
269 for (key, value) in inner.state.range(prefix.to_vec()..) {
270 if !key.starts_with(prefix) {
271 break;
272 }
273 visit(key, value);
274 }
275 Ok(())
276 }
277}