1mod fetch;
5mod proofs;
6
7use std::collections::{BTreeMap, VecDeque};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Mutex, mpsc};
10use std::time::{Duration, Instant};
11
12use heika_block::Block;
13use heika_block::finalization::proof::{closes_epoch, proof_header};
14use heika_block::scoring::{self, BlockStatistic, difficulty};
15use heika_chain::chain::Keep;
16use heika_chain::nemesis::nemesis_proof;
17use heika_chain::store::EXECUTOR_META;
18use heika_chain::verify::Tip;
19use heika_core::hash::Hash256;
20use heika_core::key::PublicKey;
21use heika_core::network::NetworkParameters;
22use heika_core::vrf::{self, GenerationHash, VrfProof};
23use heika_peer_protocol::ClientConnection;
24use heika_state_transition::config::ChainConfig;
25use heika_state_transition::executor::Executor;
26use heika_store_redb::{Db, DbError};
27
28use fetch::Fetched;
29pub(crate) use fetch::connect_any;
30pub use fetch::{Discovered, Peer};
31
32use crate::driver::NodeError;
33
34const PROFILE_EVERY: u64 = 500_000;
36
37const DURABLE_EVERY: u64 = 2;
39
40pub const DEFAULT_SAVE_EVERY: u64 = 50_000;
42
43pub struct Context<'a> {
45 pub parameters: &'static NetworkParameters,
46 pub nemesis: Hash256,
48 pub stopping: &'a (dyn Fn() -> bool + Sync),
50 pub connect: &'a (dyn Fn() -> Result<ClientConnection, NodeError> + Sync),
52}
53
54pub enum Source {
56 Stored,
58 Peers {
61 discovered: Discovered,
62 proof_peers: Vec<ClientConnection>,
63 finalized: u64,
64 },
65 Local { blocks: Vec<Block> },
67}
68
69enum Reader {
71 Stored,
72 Peers(Discovered),
73 Local(Vec<Block>),
74}
75
76pub fn execute(
80 db: &mut Db,
81 config: ChainConfig,
82 context: &Context<'_>,
83 source: Source,
84 keep: Option<Keep>,
85 save_every: u64,
86 to: Option<u64>,
87) -> Result<u64, NodeError> {
88 let finalization = config.finalization.clone();
89 let config_blocks_for_restart = config.blocks_for_restart();
90 let seed = context.parameters.generation_hash_seed;
91 let lifetime = config
92 .max_transaction_lifetime
93 .max(config.max_bonded_transaction_lifetime);
94 let mut executor = match db.meta(EXECUTOR_META)? {
95 Some(meta) => Executor::restore(
96 config,
97 context.parameters.identifier,
98 seed,
99 db.state_rows()?,
100 &meta,
101 )?,
102 None => Executor::new(config, context.parameters.identifier, seed),
103 };
104 let start = executor.height();
105 if executor.score().is_none() {
107 let started = Instant::now();
108 let mut total = scoring::NEMESIS_CHAIN_SCORE;
109 let mut last = None;
110 for height in 1..=start {
111 let bytes = db
112 .block(height)?
113 .ok_or("実行した高さのブロックがありません")?;
114 let current = BlockStatistic::from(&Block::from_bytes(&bytes)?);
115 if let Some(parent) = &last {
116 total += u128::from(scoring::block_score(parent, ¤t));
117 }
118 last = Some(current);
119 }
120 if let Some(last) = last {
121 executor.set_score(total, last);
122 eprintln!(
123 "高さ {start} までのスコアを、しまったブロックから求めました({:.0} 秒)",
124 started.elapsed().as_secs_f64()
125 );
126 }
127 }
128 let mut recent = Vec::new();
131 for height in (1..=start).rev() {
132 let block = Block::from_bytes(
133 &db.block(height)?
134 .ok_or("実行した高さのブロックがありません")?,
135 )?;
136 let done = recent
137 .first()
138 .is_some_and(|last: &Block| block.timestamp + lifetime < last.timestamp);
139 if done {
140 break;
141 }
142 recent.push(block);
143 }
144 for block in recent.iter().rev() {
145 executor.remember_transactions(block)?;
146 }
147 let fetching = matches!(source, Source::Peers { .. });
148 let (reader, proof_job, last) = match source {
149 Source::Stored => (Reader::Stored, None, db.blocks_tip()?),
150 Source::Local { blocks } => {
151 let last = blocks.last().map_or(0, |block| block.height);
152 (Reader::Local(blocks), None, last)
153 }
154 Source::Peers {
155 discovered,
156 mut proof_peers,
157 finalized,
158 } => {
159 println!(
160 "{} か所のピアからブロックを、{} か所から証明を取ります",
161 discovered.peers.len(),
162 proof_peers.len()
163 );
164 let current = proof_peers
165 .first_mut()
166 .and_then(|peer| peer.finalization_statistics().ok())
167 .map(|statistics| statistics.round.epoch);
168 (
169 Reader::Peers(discovered),
170 current.map(|current| (proof_peers, current)),
171 finalized,
172 )
173 }
174 };
175 let target = to.map_or(last, |to| to.min(last));
176 println!("高さ {} から {target} まで実行します", start + 1);
177 let first_epoch = first_proof_epoch(db, context.parameters)?;
179 let last_epoch = u32::try_from(target / finalization.voting_set_grouping + 1)?;
180 let proof_job = proof_job.map(|(peers, current): (Vec<ClientConnection>, u32)| {
181 (
182 peers,
183 first_epoch..current.min(last_epoch + 1).max(first_epoch),
184 )
185 });
186 let mut parent = match db.block(start)? {
188 Some(bytes) if start > 0 => Some(Block::from_bytes(&bytes)?),
189 _ => None,
190 };
191 let start_tip = parent
192 .as_ref()
193 .map(|block| tip_of(db, context.parameters, block))
194 .transpose()?;
195 let mut parent_generation_hash = parent
197 .as_ref()
198 .map_or(GenerationHash([0; 32]), Block::generation_hash);
199 let window = context.parameters.max_difficulty_blocks;
201 let mut statistics = VecDeque::with_capacity(window);
202 for height in start.saturating_sub(window as u64 - 1).max(1)..=start {
203 let bytes = db
204 .block(height)?
205 .ok_or("実行した高さのブロックがありません")?;
206 statistics.push_back(BlockStatistic::from(&Block::from_bytes(&bytes)?));
207 }
208 let mut progress = Progress::new(start);
209 let mut batch = db.batch()?;
212 batch.start_history(start)?;
213 let trie_started = db.trie_started()?;
214 if trie_started && start > 0 {
215 let started = Instant::now();
216 executor.restore_trees(db.trie_nodes()?)?;
217 let expected =
218 Block::from_bytes(&db.block(start)?.ok_or("戻した高さのブロックがありません")?)?
219 .state_hash;
220 if executor.state_hash() == expected {
221 eprintln!(
222 "しまった木のノードから木を戻しました({:.0} 秒)",
223 started.elapsed().as_secs_f64()
224 );
225 } else {
226 eprintln!("しまった木のノードの根が StateHash と合わないので、行から組み直します");
227 executor.rebuild_trees();
228 }
229 }
230 executor.roots();
231 if trie_started {
232 executor.forget_node_changes();
233 } else {
234 batch.start_trie(start)?;
235 let nodes = executor
236 .all_nodes()
237 .ok_or("全部のノードを持たない木から、ノードを全部は書けません")?;
238 batch.set_trie_at(start, nodes.iter().map(|(key, node)| (key, Some(node))))?;
239 }
240 batch.commit()?;
241 if let Some(keep) = keep {
242 prune_for_execution(db, context, keep, target)?;
243 }
244 let grouping = finalization.voting_set_grouping;
248 let history_through = keep.filter(|keep| keep.history).map(|keep| {
249 target
250 .saturating_sub(keep.state * grouping)
251 .saturating_sub(config_blocks_for_restart)
252 });
253 let drop_while_fetching = history_through.filter(|_| fetching);
254
255 db.defer_history();
257 let abandoned = AtomicBool::new(false);
261 let vrf_failure = Mutex::new(None);
263 let stop_proofs = || (context.stopping)() || abandoned.load(Ordering::Relaxed);
264 let (failure, interrupted, peer, prefetched, committed) = std::thread::scope(
265 |scope| -> Result<_, NodeError> {
266 let (block_sender, blocks) = mpsc::sync_channel::<Fetched>(256);
267 let (write_sender, writes) = mpsc::sync_channel::<Write>(256);
268 let (vrf_sender, vrf_jobs) = mpsc::sync_channel::<VrfJob>(256);
269 let db = &db;
270 let vrf_failure = &vrf_failure;
271 let fetching = matches!(reader, Reader::Peers(_));
272 let reader = scope.spawn(move || match reader {
273 Reader::Stored => read_stored(db, start, target, &block_sender),
274 Reader::Peers(found) => {
275 fetch::fetch(found, context, start_tip, target, &block_sender);
276 }
277 Reader::Local(blocks) => {
278 for block in blocks.into_iter().filter(|block| block.height > start) {
279 let bytes = block.as_bytes().to_vec();
280 if block_sender.send(Ok((block, Some(bytes)))).is_err() {
281 break;
282 }
283 }
284 }
285 });
286 let proof_fetcher = proof_job.map(|(peers, epochs)| {
287 scope.spawn(move || proofs::fetch(peers, epochs, &stop_proofs))
288 });
289 let verifier =
292 scope.spawn(move || {
293 for job in vrf_jobs {
294 match job {
295 VrfJob::Verify {
296 height,
297 key,
298 alpha,
299 proof,
300 checks,
301 } => {
302 if vrf::verify_with(&key, &alpha.0, &proof, checks).is_none() {
303 vrf_failure.lock().expect("not poisoned").get_or_insert(format!(
304 "高さ {height}: ブロックを出した人: VRF の証明が通りません"
305 ));
306 }
307 }
308 VrfJob::Flush(done) => {
309 let _ = done.send(());
310 }
311 }
312 }
313 });
314 let verified = || -> Result<(), String> {
316 let stopped = || "VRF の証明を確かめるスレッドが止まりました".to_owned();
317 let (done, wait) = mpsc::sync_channel(1);
318 vrf_sender
319 .send(VrfJob::Flush(done))
320 .map_err(|_| stopped())?;
321 wait.recv().map_err(|_| stopped())?;
322 vrf_failure
323 .lock()
324 .expect("not poisoned")
325 .take()
326 .map_or(Ok(()), Err)
327 };
328 let writer = scope.spawn(move || -> Result<([Duration; 2], u64), DbError> {
329 let mut spent = [Duration::ZERO; 2];
331 let mut segment = [Duration::ZERO; 2];
332 let mut segment_start = start + 1;
333 let mut committed = start;
335 let mut batch = db.batch()?;
336 batch.defer_history_after(start)?;
337 for write in writes {
338 if (context.stopping)() {
341 continue;
342 }
343 let started = Instant::now();
344 let commit = matches!(write, Write::Commit { .. });
345 match write {
346 Write::Height {
347 height,
348 block,
349 state,
350 nodes,
351 voters,
352 statement,
353 } => {
354 if let Some(block) = block {
355 batch.put_block(height, &block)?;
356 }
357 batch.set_state_at(height, state)?;
358 batch.set_trie_at(height, nodes)?;
359 if let Some(statement) = statement {
360 batch.put_statement(height, &statement)?;
361 }
362 if let Some((epoch, voters)) = voters {
363 batch.put_voters(epoch, &voters)?;
364 }
365 }
366 Write::Commit {
367 height,
368 meta,
369 durable,
370 drop_blocks_through,
371 } => {
372 if let Some(through) = drop_blocks_through {
373 batch.remove_blocks_through(through, |height| {
374 height == 1 || height.is_multiple_of(grouping)
375 })?;
376 }
377 batch.put_meta(EXECUTOR_META, &meta)?;
378 batch.put_checkpoint(height, &meta)?;
379 if durable {
380 batch.commit()?;
381 } else {
382 batch.commit_lazily()?;
383 }
384 batch = db.batch()?;
385 committed = height;
386 segment[1] += started.elapsed();
387 spent[1] += started.elapsed();
388 if height / PROFILE_EVERY
390 > segment_start.saturating_sub(1) / PROFILE_EVERY
391 {
392 report_writer(&format!("高さ {segment_start}〜{height}"), segment);
393 segment = [Duration::ZERO; 2];
394 segment_start = height + 1;
395 }
396 continue;
397 }
398 }
399 segment[usize::from(commit)] += started.elapsed();
400 spent[usize::from(commit)] += started.elapsed();
401 }
402 drop(batch);
404 db.batch()?.commit()?;
405 if segment != [Duration::ZERO; 2] {
406 report_writer(&format!("高さ {segment_start}〜"), segment);
407 }
408 Ok((spent, committed))
409 });
410 let mut uncommitted = false;
411 let mut failure = None;
412 let mut interrupted = None;
414 let mut phases = Phases::default();
415 let mut total = Phases::default();
417 let mut segment_start = start + 1;
418 while executor.height() < target && !(context.stopping)() {
419 let height = executor.height() + 1;
420 if let Some(error) = vrf_failure.lock().expect("not poisoned").take() {
421 failure = Some(error);
422 break;
423 }
424 let mut lap = Instant::now();
425 let (block, bytes) = match blocks.recv() {
426 Ok(Ok(fetched)) => fetched,
427 Ok(Err(error)) => {
428 interrupted = Some(error);
429 break;
430 }
431 Err(_) if (context.stopping)() => break,
433 Err(_) => {
434 interrupted = Some("ブロックを読むスレッドが止まりました".to_owned());
435 break;
436 }
437 };
438 phases.add(Phase::WaitBlocks, &mut lap);
439 let generation_hash = match &parent {
442 None => block.generation_hash(),
443 Some(parent) => {
444 let expected = difficulty(statistics.make_contiguous(), context.parameters);
445 if block.difficulty != expected {
446 failure = Some(format!(
447 "高さ {height}: 難易度が {} で、直前のブロックから求めた {expected} と合いません",
448 block.difficulty
449 ));
450 break;
451 }
452 match executor.check_hit(parent, &block, context.parameters) {
453 Ok(key) => {
454 let job = VrfJob::Verify {
455 height,
456 key,
457 alpha: parent_generation_hash,
458 proof: block.generation_hash_proof.clone(),
459 checks: context.parameters.vrf_checks(height),
460 };
461 if vrf_sender.send(job).is_err() {
462 failure = Some(
463 "VRF の証明を確かめるスレッドが止まりました".to_owned(),
464 );
465 break;
466 }
467 block.generation_hash()
468 }
469 Err(error) => {
470 failure = Some(format!("高さ {height}: {error}"));
471 break;
472 }
473 }
474 }
475 };
476 phases.add(Phase::Harvester, &mut lap);
477 if let Err(error) = executor.apply(&block) {
478 failure = Some(format!("高さ {height}: {error}"));
479 break;
480 }
481 phases.add(Phase::Apply, &mut lap);
482 let state_hash = executor.state_hash();
483 phases.add(Phase::Roots, &mut lap);
484 if state_hash != block.state_hash {
485 let roots = executor.roots();
487 let roots: Vec<String> = roots.iter().map(ToString::to_string).collect();
488 failure = Some(format!(
489 "高さ {height}: StateHash が合いません。9本の根: {}",
490 roots.join(" ")
491 ));
492 break;
493 }
494 let statement = executor.take_statement();
495 let receipts_hash = statement.merkle_hash();
496 phases.add(Phase::Statement, &mut lap);
497 if receipts_hash != block.receipts_hash {
498 failure = Some(format!(
499 "高さ {height}: ReceiptsHash が合いません。ステートメント: {statement:?}"
500 ));
501 break;
502 }
503 let changes = executor.take_changes();
504 let puts = changes
505 .puts
506 .into_iter()
507 .map(|(key, value)| (key, Some(value)));
508 let deletes = changes.deletes.into_iter().map(|key| (key, None));
509 let state = puts.chain(deletes).collect();
510 phases.add(Phase::Rows, &mut lap);
511 let nodes = executor.take_node_changes();
512 phases.add(Phase::Nodes, &mut lap);
513 let next_epoch = if height == 1 {
515 Some(2)
516 } else if height % grouping == 0 {
517 u32::try_from(height / grouping + 2).ok()
518 } else {
519 None
520 };
521 let write = Write::Height {
522 height,
523 block: bytes,
524 state,
525 nodes,
526 voters: next_epoch.map(|epoch| (epoch, executor.voting_set(epoch).encode())),
527 statement: (drop_while_fetching.is_none_or(|through| height > through))
528 .then(|| statement.to_bytes()),
529 };
530 uncommitted = true;
531 phases.add(Phase::Voters, &mut lap);
532 let mut sent = write_sender.send(write);
533 if sent.is_ok() && height % save_every == 0 {
534 if let Err(error) = verified() {
535 failure = Some(error);
536 break;
537 }
538 sent = write_sender.send(Write::Commit {
539 height,
540 meta: executor.encode_meta(),
541 durable: height % (save_every * DURABLE_EVERY) == 0,
542 drop_blocks_through: drop_while_fetching.map(|through| {
543 through.min(height.saturating_sub(config_blocks_for_restart))
544 }),
545 });
546 uncommitted = false;
547 }
548 if sent.is_err() {
549 break;
551 }
552 phases.add(Phase::WaitWriter, &mut lap);
553 statistics.push_back(BlockStatistic::from(&block));
554 if statistics.len() > window {
555 statistics.pop_front();
556 }
557 parent = Some(block);
558 parent_generation_hash = generation_hash;
559 progress.tick(height, target);
560 if height % PROFILE_EVERY == 0 {
561 phases.report(&format!("高さ {segment_start}〜{height}"));
562 total.add_all(&phases);
563 phases = Phases::default();
564 segment_start = height + 1;
565 }
566 }
567 if failure.is_none() && uncommitted && !(context.stopping)() {
568 match verified() {
571 Ok(()) => {
572 let _ = write_sender.send(Write::Commit {
573 height: executor.height(),
574 meta: executor.encode_meta(),
575 durable: true,
576 drop_blocks_through: None,
577 });
578 }
579 Err(error) => failure = Some(error),
580 }
581 }
582 if executor.height() < target || failure.is_some() {
583 abandoned.store(true, Ordering::Relaxed);
584 }
585 drop(vrf_sender);
586 verifier.join().expect("verifier does not panic");
587 drop(write_sender);
588 drop(blocks);
589 let (written, committed) = writer.join().expect("writer does not panic")?;
590 reader.join().expect("reader does not panic");
591 if executor.height() >= segment_start {
592 let label = format!("高さ {segment_start}〜{}", executor.height());
593 phases.report(&label);
594 }
595 total.add_all(&phases);
596 total.report("全体");
597 report_writer("全体", written);
598 let prefetched = proof_fetcher
599 .map(|fetcher| fetcher.join().expect("proof fetcher does not panic"))
600 .unwrap_or_default();
601 Ok((failure, interrupted, fetching, prefetched, committed))
602 },
603 )?;
604 if let Some(failure) = failure {
605 return Err(failure.into());
606 }
607 if let Some(error) = interrupted {
608 return Err(format!("高さ {} で止まりました: {error}", executor.height()).into());
610 }
611 if (context.stopping)() {
612 println!(
614 "高さ {committed} までをしまって止めました(実行した高さ {} までの残りは捨て、次に始めたときに実行し直します)。差分の索引は、続きを実行し終えるか index で作ります",
615 executor.height()
616 );
617 return Ok(committed);
618 }
619 build_history(db, context)?;
620 if peer {
621 sync_proofs(
622 context,
623 db,
624 &mut (context.connect)()?,
625 executor.height(),
626 prefetched,
627 )?;
628 }
629 if let Some(through) = history_through {
631 let started = Instant::now();
632 let epoch = u32::try_from(context.parameters.finalization_epoch(through))?;
633 let rows = db.prune_history(through, epoch)?;
634 println!(
635 "ブロックとステートメントを高さ {through} 以下で、証明をエポック {epoch} より前で、合わせて {rows} 行消しました({:.0} 秒)",
636 started.elapsed().as_secs_f64()
637 );
638 }
639 println!(
640 "高さ {} まで実行しました。StateHash {}、スコア {}",
641 executor.height(),
642 executor.state_hash(),
643 executor.score().unwrap_or_default()
644 );
645 Ok(executor.height())
646}
647
648enum VrfJob {
650 Verify {
652 height: u64,
653 key: PublicKey,
654 alpha: GenerationHash,
655 proof: VrfProof,
656 checks: vrf::Checks,
658 },
659 Flush(mpsc::SyncSender<()>),
661}
662
663#[derive(Clone, Copy)]
665enum Phase {
666 WaitBlocks,
668 Harvester,
670 Apply,
672 Roots,
674 Statement,
676 Rows,
678 Nodes,
680 Voters,
682 WaitWriter,
684}
685
686#[derive(Default)]
688struct Phases([Duration; 9]);
689
690impl Phases {
691 fn add(&mut self, phase: Phase, lap: &mut Instant) {
693 let now = Instant::now();
694 self.0[phase as usize] += now - *lap;
695 *lap = now;
696 }
697
698 fn add_all(&mut self, other: &Self) {
700 for (total, spent) in self.0.iter_mut().zip(other.0) {
701 *total += spent;
702 }
703 }
704
705 fn report(&self, label: &str) {
707 let seconds = |duration: Duration| duration.as_secs_f64();
708 let [
709 wait_blocks,
710 harvester,
711 apply,
712 roots,
713 statement,
714 rows,
715 nodes,
716 voters,
717 wait_writer,
718 ] = self.0.map(seconds);
719 eprintln!(
720 "{label}: 実行するスレッドの内訳(秒): ブロックを待つ {wait_blocks:.1}、難易度とブロックを出した人 {harvester:.1}、当てる {apply:.1}、\
721 根 {roots:.1}、ステートメント {statement:.1}、書く行 {rows:.1}、書く木のノード {nodes:.1}、\
722 投票者など {voters:.1}、書くのを待つ {wait_writer:.1}"
723 );
724 }
725}
726
727fn report_writer(label: &str, written: [Duration; 2]) {
729 eprintln!(
730 "{label}: 書くスレッドの内訳(秒): 書く {:.1}、コミット {:.1}",
731 written[0].as_secs_f64(),
732 written[1].as_secs_f64(),
733 );
734}
735
736fn read_stored(db: &Db, start: u64, target: u64, sender: &mpsc::SyncSender<Fetched>) {
738 for height in start + 1..=target {
739 let block = match db.block(height) {
740 Ok(Some(bytes)) => Block::from_bytes(&bytes)
741 .map(|block| (block, None))
742 .map_err(|error| error.to_string()),
743 Ok(None) => Err("途中のブロックがありません".to_owned()),
744 Err(error) => Err(error.to_string()),
745 };
746 let stop = block.is_err();
747 if sender.send(block).is_err() || stop {
748 break;
749 }
750 }
751}
752
753enum Write {
755 Height {
757 height: u64,
758 block: Option<Vec<u8>>,
760 state: Vec<(Vec<u8>, Option<Vec<u8>>)>,
761 nodes: Vec<(Vec<u8>, Option<Vec<u8>>)>,
762 voters: Option<(u32, Vec<u8>)>,
764 statement: Option<Vec<u8>>,
766 },
767 Commit {
770 height: u64,
771 meta: Vec<u8>,
772 durable: bool,
773 drop_blocks_through: Option<u64>,
775 },
776}
777
778fn prune_for_execution(
781 db: &mut Db,
782 context: &Context<'_>,
783 keep: Keep,
784 target: u64,
785) -> Result<(), NodeError> {
786 let grouping = context.parameters.voting_set_grouping;
787 let state = target.saturating_sub(keep.state * grouping);
788 let trie = target.saturating_sub(keep.trie * grouping);
789 let started = Instant::now();
790 let pruned_state = db.prune_state_history(state, |_| !(context.stopping)())?;
791 let pruned_trie = db.prune_trie_history(trie, |_| !(context.stopping)())?;
792 if !pruned_state.done || !pruned_trie.done {
793 return Err("刈り込みを途中で止めました。もう一度動かすと続きを消します".into());
794 }
795 db.quiet_history_through(state, trie);
796 println!(
797 "刈り込んで実行します。差分は、状態が高さ {state}、木のノードが高さ {trie} より上だけを残します(消した差分 {} 行、{:.0} 秒)",
798 pruned_state.rows + pruned_trie.rows,
799 started.elapsed().as_secs_f64()
800 );
801 Ok(())
802}
803
804fn sync_proofs(
808 context: &Context<'_>,
809 db: &Db,
810 node: &mut ClientConnection,
811 blocks_tip: u64,
812 mut prefetched: BTreeMap<u32, Vec<u8>>,
813) -> Result<(), NodeError> {
814 let current = node.finalization_statistics()?.round.epoch;
815 let first = first_proof_epoch(db, context.parameters)?;
816 let mut batch = db.batch()?;
817 let mut last = None;
818 let mut asked = 0;
819 for epoch in first..current {
820 if (context.stopping)() {
821 break;
822 }
823 let proof = match prefetched.remove(&epoch) {
824 Some(proof) => proof,
825 None if epoch == 1 => nemesis_proof(&context.nemesis),
828 None => {
829 asked += 1;
830 node.finalization_proof_at_epoch(epoch)?
831 .ok_or_else(|| format!("ノードがエポック {epoch} の証明を返しません"))?
832 }
833 };
834 if (epoch - first + 1).is_multiple_of(500) {
835 eprintln!(
836 "ファイナライズの証明をエポック {epoch} まで確かめました({} 件のうち、順に取ったもの {asked} 件)",
837 epoch - first + 1
838 );
839 }
840 let header = proof_header(&proof).map_err(|error| format!("エポック {epoch}: {error}"))?;
841 if header.round.epoch != epoch {
842 return Err(format!(
843 "エポック {epoch}: 証明のエポックが {} です",
844 header.round.epoch
845 )
846 .into());
847 }
848 if header.height > blocks_tip {
849 break;
850 }
851 let bytes = db.block(header.height)?.ok_or_else(|| {
852 format!(
853 "エポック {epoch}: 高さ {} のブロックがありません",
854 header.height
855 )
856 })?;
857 let hash = Block::from_bytes(&bytes)?.hash();
858 if hash != header.hash {
859 return Err(format!(
860 "エポック {epoch}: 証明が指す高さ {} のハッシュ {} が、しまったブロックの {hash} と違います",
861 header.height, header.hash
862 )
863 .into());
864 }
865 batch.put_proof(epoch, &proof)?;
866 last = Some((epoch, header.height));
867 if epoch % 100 == 0 {
868 batch.commit()?;
869 batch = db.batch()?;
870 }
871 }
872 batch.commit()?;
873 match last {
874 None => println!("足すファイナライズの証明はありませんでした"),
875 Some((epoch, height)) => println!(
876 "ファイナライズの証明をエポック {first} から {epoch}(高さ {height})までしまいました(順に取ったもの {asked} 件)"
877 ),
878 }
879 Ok(())
880}
881
882struct Progress {
884 started: Instant,
885 start_height: u64,
886 last: Instant,
887}
888
889impl Progress {
890 fn new(start_height: u64) -> Self {
891 let now = Instant::now();
892 Self {
893 started: now,
894 start_height,
895 last: now,
896 }
897 }
898
899 fn tick(&mut self, height: u64, target: u64) {
900 if self.last.elapsed() < Duration::from_secs(10) && height != target {
901 return;
902 }
903 self.last = Instant::now();
904 let seconds = self.started.elapsed().as_secs_f64().max(0.001);
905 let rate = (height - self.start_height) as f64 / seconds;
906 eprintln!("高さ {height} / {target}({rate:.0} ブロック/秒)");
907 }
908}
909
910fn tip_of(db: &Db, parameters: &NetworkParameters, block: &Block) -> Result<Tip, NodeError> {
912 let grouping = parameters.importance_grouping;
913 let importance_height = (block.height / grouping * grouping).max(1);
914 let importance_hash = if importance_height == block.height {
915 block.hash()
916 } else {
917 let bytes = db
918 .block(importance_height)?
919 .ok_or("最後の importance ブロックがありません")?;
920 Block::from_bytes(&bytes)?.hash()
921 };
922 Ok(Tip {
923 height: block.height,
924 hash: block.hash(),
925 importance_hash,
926 })
927}
928
929fn first_proof_epoch(db: &Db, parameters: &NetworkParameters) -> Result<u32, NodeError> {
932 let tip = db.proofs_tip()?;
933 let closed = match db.proof(tip)? {
934 Some(proof) => closes_epoch(&proof_header(&proof)?, parameters.voting_set_grouping),
935 None => true,
936 };
937 Ok(if closed { tip + 1 } else { tip })
938}
939
940fn build_history(db: &Db, context: &Context<'_>) -> Result<(), NodeError> {
941 let started = Instant::now();
942 let mut last = Instant::now();
943 let built = db.build_history(|name, height| {
944 if last.elapsed() >= Duration::from_secs(10) {
945 last = Instant::now();
946 eprintln!("差分の索引({name}): 高さ {height} まで");
947 }
948 !(context.stopping)()
949 })?;
950 if !built {
951 return Err("差分の索引を途中で止めました。続きは index で作ります".into());
952 }
953 eprintln!(
954 "差分の索引を作りました({:.0} 秒)",
955 started.elapsed().as_secs_f64()
956 );
957 Ok(())
958}