Skip to main content

heika_node/
copy.rs

1//! 止めたノードの DB を、設定の残し方(`storage.mode`)で刈り込んで、新しいファイルに写す。
2//!
3//! アーカイブをライトにするとき、その場で刈り込むと、消すものが多くて書き直しも多く、ファイルも縮まない。
4//! 残すものだけを写せば、写しは小さく、すぐにできる。`Archive` なら全部写すので、詰め直しになる。
5
6use std::path::Path;
7
8use heika_block::finalization::proof::proof_header;
9use heika_chain::chain::Keep;
10use heika_store_redb::{CopyBounds, Db};
11
12use crate::config::Manifest;
13use crate::driver::{NodeError, chain_config, keep, network_parameters};
14
15/// `manifest` のノードの DB を、刈り込んで `directory` に写す。ノードを止めてから使う
16pub fn copy_pruned(manifest: &Manifest, directory: &Path) -> Result<(), NodeError> {
17    let spec = &manifest.spec;
18    let config = chain_config(spec)?;
19    let parameters = network_parameters(spec)?;
20    let keep = keep(spec)?;
21    let db = Db::open_read_only(&spec.data_directory).map_err(|error| {
22        format!(
23            "{} の DB を開けません(ノードを止めてください): {error}",
24            spec.data_directory.display()
25        )
26    })?;
27    let finalized = match db.proofs_tip()? {
28        0 => 1,
29        epoch => proof_header(&db.proof(epoch)?.ok_or("しまった証明がありません")?)?.height,
30    };
31    let floor = db
32        .checkpoint_at_or_below(finalized)?
33        .map_or(0, |(height, _)| height);
34    let prune = Keep::plan(keep, &config, parameters, finalized, floor);
35    println!(
36        "確定した高さ {finalized} をもとに、{} の残し方で写します",
37        spec.storage.mode.name()
38    );
39    if let Some((state, trie)) = prune.history {
40        println!(
41            "状態の差分は高さ {} から、木のノードの差分は高さ {} から残します",
42            state + 1,
43            trie + 1
44        );
45    }
46    if let Some((through, epoch)) = prune.blocks {
47        println!(
48            "ブロックとステートメントは高さ {} から、証明はエポック {epoch} から残します",
49            through + 1
50        );
51    }
52    if std::fs::read_dir(directory).is_ok_and(|mut entries| entries.next().is_some()) {
53        return Err(format!("{} は空ではありません", directory.display()).into());
54    }
55    let target = Db::open(directory)?;
56    let bounds = prune.history.map(|(state, trie)| CopyBounds {
57        state,
58        trie,
59        statements: prune.blocks.map(|(through, _)| through),
60        blocks: prune.blocks,
61    });
62    db.copy_to(&target, bounds, spec.storage.searches(), |table, rows| {
63        println!("{table}: {rows} 行");
64        true
65    })?;
66    println!("差分の索引を作ります");
67    target.build_history(|table, height| {
68        println!("{table} の索引: 高さ {height} まで");
69        true
70    })?;
71    target.prune_checkpoints(prune.checkpoints_below)?;
72    println!("{} に写しました", directory.display());
73    Ok(())
74}