1use 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#[derive(Debug)]
44pub enum ReplayError {
45 Invalid { height: u64, reason: String },
47 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
72const MAX_RETRIES: usize = 8;
74
75pub struct Replay<'a> {
77 db: &'a Db,
78 parameters: &'static NetworkParameters,
79 nemesis: Hash256,
80 executor: Executor,
81 parent: Option<Block>,
83 tip: Option<Tip>,
84 statistics: VecDeque<BlockStatistic>,
86 batch: Option<Batch>,
88 committed: u64,
90 config: ChainConfig,
91 keep: Option<Keep>,
93 quiet_through: [Option<u64>; 2],
95 statements_through: Option<u64>,
97 target: u64,
99 partial: bool,
101}
102
103impl<'a> Replay<'a> {
104 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 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 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 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 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 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 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 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 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 pub fn height(&self) -> u64 {
322 self.executor.height()
323 }
324
325 pub fn committed(&self) -> u64 {
327 self.committed
328 }
329
330 pub fn state_hash(&self) -> Option<Hash256> {
332 self.parent.as_ref().map(|block| block.state_hash)
333 }
334
335 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 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 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 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 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 self.executor.release_loaded();
464 Ok(())
465 }
466
467 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 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 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}