witness_verify/
archive.rs1use std::collections::{BTreeMap, HashSet};
14use std::fs;
15use std::path::{Path, PathBuf};
16
17use clap::Args;
18use serde_json::json;
19use witness_core::Validation;
20use witness_core::keys::node_public;
21use witness_store::Seal;
22use witness_store::segment::{read_segment, verify_segment};
23
24#[derive(Debug, Args)]
25pub struct ArchiveArgs {
26 segments: PathBuf,
28 #[arg(long, default_value_t = 3)]
30 examples: usize,
31}
32
33#[derive(Default)]
34struct Tally {
35 segments: u64,
36 seals_broken: Vec<String>,
37 chain_breaks: Vec<String>,
38 lineage_switches: Vec<String>,
40 missing_total: u64,
41 missing_suspicious: Vec<String>,
44 records: u64,
45 valid: u64,
46 failures: BTreeMap<String, (u64, Vec<String>)>,
48 index_mismatch: u64,
49 keys: HashSet<Vec<u8>>,
50 full: u64,
51 partial: u64,
52}
53
54impl Tally {
55 fn fail(&mut self, reason: String, example: String, keep: usize) {
56 let e = self.failures.entry(reason).or_default();
57 e.0 += 1;
58 if e.1.len() < keep {
59 e.1.push(example);
60 }
61 }
62}
63
64pub fn seals(dir: &Path) -> Result<Vec<(PathBuf, Seal)>, Box<dyn std::error::Error>> {
65 let mut out = Vec::new();
66 for entry in fs::read_dir(dir)? {
67 let path = entry?.path();
68 if path.to_string_lossy().ends_with(".seal.json") {
69 let seal: Seal = serde_json::from_slice(&fs::read(&path)?)?;
70 out.push((path, seal));
71 }
72 }
73 out.sort_by_key(|(_, s)| s.sealed_ms);
74 Ok(out)
75}
76
77pub fn run(args: &ArchiveArgs) -> Result<bool, Box<dyn std::error::Error>> {
78 let mut t = Tally::default();
79 let mut prev: Option<Seal> = None;
80 for (seal_path, seal) in seals(&args.segments)? {
81 t.segments += 1;
82 let name = seal_path
83 .file_name()
84 .map(|n| n.to_string_lossy().into_owned())
85 .unwrap_or_default();
86 let seg_path = PathBuf::from(
87 seal_path
88 .to_string_lossy()
89 .replace(".seal.json", ".xwv.zst"),
90 );
91 if !verify_segment(&seg_path, &seal)? {
92 t.seals_broken.push(name.clone());
93 }
94 if let Some(p) = &prev {
95 if seal.prev_seal_hash.as_deref() != Some(p.seal_hash.as_str()) {
96 t.chain_breaks
97 .push(format!("{name}: link to previous seal"));
98 }
99 let empty =
101 seal.coverage_first > seal.coverage_last || p.coverage_first > p.coverage_last;
102 let tiles = seal.coverage_first == p.coverage_last.saturating_add(1);
103 let switch = seal.coverage_first.abs_diff(p.coverage_last) > 256;
107 if !empty && !tiles {
108 let what = format!(
109 "{name}: span {}.. after {}",
110 seal.coverage_first, p.coverage_last
111 );
112 if switch {
113 t.lineage_switches.push(what);
114 } else {
115 t.chain_breaks.push(what);
116 }
117 }
118 }
119 for [a, b] in &seal.missing_ledgers {
120 let n = u64::from(b.saturating_sub(*a)) + 1;
121 t.missing_total += n;
122 if n > 1000 {
123 t.missing_suspicious.push(format!("{name}: {a}..{b} ({n})"));
124 }
125 }
126 for rec in read_segment(&seg_path)? {
127 t.records += 1;
128 match Validation::parse(&rec.data) {
129 Err(e) => t.fail(
130 format!("does not parse: {e}"),
131 hex::encode_upper(&rec.data),
132 args.examples,
133 ),
134 Ok(v) => {
135 if v.ledger_sequence != rec.ledger_index {
136 t.index_mismatch += 1;
137 }
138 match v.verify() {
139 Ok(()) => {
140 t.valid += 1;
141 if v.is_full() {
142 t.full += 1;
143 } else {
144 t.partial += 1;
145 }
146 t.keys.insert(v.signing_pub_key);
147 }
148 Err(e) => t.fail(
149 format!("signature: {e}"),
150 format!(
151 "{} ledger {}",
152 node_public(&v.signing_pub_key),
153 v.ledger_sequence
154 ),
155 args.examples,
156 ),
157 }
158 }
159 }
160 }
161 prev = Some(seal);
162 }
163 let failed: u64 = t.failures.values().map(|(n, _)| n).sum();
164 let ok = t.seals_broken.is_empty()
165 && t.chain_breaks.is_empty()
166 && failed == 0
167 && t.index_mismatch == 0;
168 let failures: BTreeMap<_, _> = t
169 .failures
170 .iter()
171 .map(|(k, (n, ex))| (k.clone(), json!({"count": n, "examples": ex})))
172 .collect();
173 let report = json!({
174 "ok": ok,
175 "segments": t.segments,
176 "seals_broken": t.seals_broken,
177 "chain_breaks": t.chain_breaks,
178 "lineage_switches": t.lineage_switches,
179 "missing_ledgers_total": t.missing_total,
180 "missing_suspicious": t.missing_suspicious,
181 "records": t.records,
182 "signatures_valid": t.valid,
183 "full_validations": t.full,
184 "partial_validations": t.partial,
185 "signing_keys": t.keys.len(),
186 "ledger_index_mismatch": t.index_mismatch,
187 "failures": failures,
188 });
189 println!("{}", serde_json::to_string_pretty(&report)?);
190 Ok(ok)
191}