Skip to main content

witness_verify/
evidence.rs

1//! Evidence package: export from the archive and verification without it.
2//!
3//! `export` gathers everything needed to check a single ledger, using
4//! originals only (see `witness_core::evidence`). `evidence` checks such a
5//! package against your own trust policy without contacting us or a node.
6
7use std::collections::BTreeSet;
8use std::fs;
9use std::path::PathBuf;
10
11use base64::Engine;
12use clap::Args;
13use serde_json::Value;
14use witness_core::evidence::{
15    Bundle, FORMAT, FORMAT_V2, NegativeUnlEvidence, PolicySpec, Provenance, PublisherResponse,
16    Trust, ValidationEvidence, signing_to_master, verify,
17};
18use witness_core::quorum::{Key, PublishedList, policies_between};
19use witness_core::shamap::{prove, tx_id, tx_leaf_hash};
20use witness_core::txproof::TxProof;
21use witness_core::util::now_ms;
22use witness_core::{Manifest, Validation};
23use witness_store::segment::read_segment;
24
25use crate::archive::seals;
26use crate::quorum::{DEFAULT_PUBLISHERS, load_lists};
27
28type Res<T> = Result<T, Box<dyn std::error::Error>>;
29
30/// The verifier's trust policy, shared by export and check.
31#[derive(Debug, Args)]
32pub struct TrustArgs {
33    /// List publisher keys in hex. Defaults to xrpld's default publishers.
34    #[arg(long = "publisher")]
35    publishers: Vec<String>,
36    /// How many lists must contain a key. 0 means the xrpld default.
37    #[arg(long, default_value_t = 0)]
38    threshold: usize,
39    /// Directly trusted keys, `n9...` or hex.
40    #[arg(long = "trust")]
41    trusted_directly: Vec<String>,
42}
43
44impl TrustArgs {
45    fn trust(&self) -> Res<Trust> {
46        let publishers: Vec<Key> = if self.publishers.is_empty() {
47            DEFAULT_PUBLISHERS
48                .iter()
49                .map(hex::decode)
50                .collect::<Result<_, _>>()?
51        } else {
52            self.publishers
53                .iter()
54                .map(hex::decode)
55                .collect::<Result<_, _>>()?
56        };
57        let trusted_directly = self
58            .trusted_directly
59            .iter()
60            .map(|s| {
61                witness_core::keys::parse_node_public(s)
62                    .or_else(|| hex::decode(s).ok())
63                    .ok_or_else(|| format!("could not parse key {s}"))
64            })
65            .collect::<Result<_, _>>()?;
66        Ok(Trust {
67            publishers,
68            threshold: self.threshold,
69            trusted_directly,
70        })
71    }
72}
73
74#[derive(Debug, Args)]
75pub struct ExportArgs {
76    /// Archive root: segments/, manifests/, unl/, negative_unl/.
77    data_dir: PathBuf,
78    /// The ledger to build the package for.
79    #[arg(long)]
80    ledger: u32,
81    /// Transactions of this ledger to add inclusion proofs for (version 2
82    /// package). Hash in hex; may be given more than once.
83    #[arg(long = "tx")]
84    txs: Vec<String>,
85    /// JSON-RPC of a node or Clio server that has this ledger's transactions.
86    /// Only needed together with --tx. It is not trusted: the header is
87    /// checked against the hash confirmed by quorum.
88    #[arg(long)]
89    rpc: Option<String>,
90    #[command(flatten)]
91    trust: TrustArgs,
92}
93
94/// The ledger header and all its transactions with metadata.
95type LedgerTxs = (Vec<u8>, Vec<(Vec<u8>, Vec<u8>)>);
96
97/// Fetches the ledger header and all transactions with metadata from the node.
98fn fetch_ledger(rpc: &str, ledger: u32) -> Res<LedgerTxs> {
99    let body = serde_json::json!({"method": "ledger", "params": [{
100        "ledger_index": ledger, "transactions": true, "expand": true, "binary": true}]});
101    let mut resp = ureq::post(rpc)
102        .header("Content-Type", "application/json")
103        .send(body.to_string())?;
104    let text = resp
105        .body_mut()
106        .with_config()
107        .limit(256 << 20)
108        .read_to_string()?;
109    let v: Value = serde_json::from_str(&text)?;
110    let lg = &v["result"]["ledger"];
111    let header = hex::decode(
112        lg["ledger_data"]
113            .as_str()
114            .ok_or("node did not return the ledger header")?,
115    )?;
116    let mut txs = Vec::new();
117    for t in lg["transactions"]
118        .as_array()
119        .ok_or("node did not return the transactions")?
120    {
121        let tx = t["tx_blob"].as_str().ok_or("no tx_blob")?;
122        // xrpld returns metadata as meta, Clio as meta_blob.
123        let meta = t["meta_blob"]
124            .as_str()
125            .or_else(|| t["meta"].as_str())
126            .ok_or("no metadata")?;
127        txs.push((hex::decode(tx)?, hex::decode(meta)?));
128    }
129    Ok((header, txs))
130}
131
132/// Inclusion proofs for the selected transactions.
133fn tx_proofs(rpc: &str, ledger: u32, wanted: &[String]) -> Res<Vec<TxProof>> {
134    let (header, txs) = fetch_ledger(rpc, ledger)?;
135    let items: Vec<_> = txs
136        .iter()
137        .map(|(tx, meta)| {
138            let id = tx_id(tx);
139            (id, tx_leaf_hash(tx, meta, &id))
140        })
141        .collect();
142    let mut out = Vec::new();
143    for w in wanted {
144        let key: [u8; 32] = hex::decode(w)?
145            .try_into()
146            .map_err(|_| format!("hash {w} is not 32 bytes"))?;
147        let i = items
148            .iter()
149            .position(|(k, _)| *k == key)
150            .ok_or_else(|| format!("transaction {w} is not in ledger {ledger}"))?;
151        let path = prove(&items, &key).ok_or("could not build the proof path")?;
152        out.push(TxProof::new(&header, &txs[i].0, &txs[i].1, &path));
153    }
154    Ok(out)
155}
156
157#[derive(Debug, Args)]
158pub struct CheckArgs {
159    /// Evidence package file.
160    bundle: PathBuf,
161    #[command(flatten)]
162    trust: TrustArgs,
163}
164
165pub fn export(args: &ExportArgs) -> Res<bool> {
166    let trust = args.trust.trust()?;
167    let ledger = args.ledger;
168
169    // The ledger's validations, from every segment they may be in: late
170    // ones land in the next segment.
171    let mut validations = Vec::new();
172    let mut seal_hashes = BTreeSet::new();
173    let mut source = String::new();
174    for (path, seal) in seals(&args.data_dir.join("segments"))? {
175        let reach = seal.nominal_last.saturating_add(512);
176        if seal.nominal_first > ledger.saturating_add(512) || reach < ledger {
177            continue;
178        }
179        let seg = PathBuf::from(path.to_string_lossy().replace(".seal.json", ".xwv.zst"));
180        let mut found = false;
181        for rec in read_segment(&seg)? {
182            if rec.ledger_index == ledger {
183                found = true;
184                validations.push(ValidationEvidence {
185                    data: hex::encode_upper(&rec.data),
186                    received_ms: rec.received_ms,
187                });
188            }
189        }
190        if found {
191            seal_hashes.insert(seal.seal_hash.clone());
192            source.clone_from(&seal.source);
193        }
194    }
195    if validations.is_empty() {
196        return Err(format!("sealed segments have no validations for ledger {ledger}").into());
197    }
198
199    // Lists in effect for this ledger, as whole publisher responses.
200    let mut list_manifests = Vec::new();
201    let mut list_problems = Vec::new();
202    let lists = load_lists(
203        &args.data_dir.join("unl"),
204        &trust.publishers,
205        &mut list_manifests,
206        &mut list_problems,
207    )?;
208    for p in &list_problems {
209        eprintln!("{p}");
210    }
211    // The time window runs from the earliest to the latest signing time of
212    // full validations by known validators; the package gets every list that
213    // was in effect at any moment of the window. An extra list does no harm:
214    // the verifier picks the ones in effect during the window of votes for
215    // the hash being confirmed.
216    let to_master = signing_to_master(&list_manifests).0;
217    let known: BTreeSet<&Key> = lists
218        .iter()
219        .flat_map(|s| s.list.validators.iter())
220        .collect();
221    let times: Vec<u32> = validations
222        .iter()
223        .filter_map(|v| hex::decode(&v.data).ok())
224        .filter_map(|raw| Validation::parse(&raw).ok())
225        .filter(|v| {
226            v.is_full()
227                && to_master
228                    .get(&v.signing_pub_key)
229                    .is_some_and(|m| known.contains(m))
230        })
231        .map(|v| v.signing_time)
232        .collect();
233    let (from, to) = times
234        .iter()
235        .min()
236        .zip(times.iter().max())
237        .map(|(a, b)| (*a, *b))
238        .ok_or("no full validations from known validators: cannot determine the ledger time")?;
239    let all: Vec<PublishedList> = lists.iter().map(|s| s.list.clone()).collect();
240    let set = policies_between(
241        &all,
242        &trust.publishers,
243        from,
244        to,
245        trust.threshold,
246        &trust.trusted_directly,
247    );
248    for m in &set.missing {
249        eprintln!(
250            "publisher {}: no list in effect at the ledger time, the package will not confirm",
251            hex::encode_upper(m)
252        );
253    }
254    let policies = set.policies;
255    let mut responses: Vec<PublisherResponse> = Vec::new();
256    for chosen in policies.iter().flat_map(|p| p.lists.iter()) {
257        let Some(seen) = lists
258            .iter()
259            .find(|s| s.list.publisher == chosen.publisher && s.list.sequence == chosen.sequence)
260        else {
261            continue;
262        };
263        let body = base64::engine::general_purpose::STANDARD.encode(&seen.body);
264        if !responses.iter().any(|r| r.body == body) {
265            responses.push(PublisherResponse {
266                site: seen.site.clone(),
267                body,
268                first_seen_ms: (seen.first_seen_ms != u64::MAX).then_some(seen.first_seen_ms),
269            });
270        }
271    }
272
273    // Manifests from the node, only for keys that signed this ledger.
274    let signers: BTreeSet<Vec<u8>> = validations
275        .iter()
276        .filter_map(|v| hex::decode(&v.data).ok())
277        .filter_map(|raw| Validation::parse(&raw).ok())
278        .map(|v| v.signing_pub_key)
279        .collect();
280    let mut manifests = Vec::new();
281    if let Ok(dir) = fs::read_dir(args.data_dir.join("manifests")) {
282        for e in dir.flatten() {
283            if e.path().extension().is_none_or(|x| x != "bin") {
284                continue;
285            }
286            let raw = fs::read(e.path())?;
287            if let Ok(m) = Manifest::parse(&raw)
288                && m.signing_key.as_ref().is_some_and(|k| signers.contains(k))
289            {
290                manifests.push(hex::encode_upper(&raw));
291            }
292        }
293    }
294
295    // Negative UNL, from the last flag ledger before this one.
296    let mut negative_unl = None;
297    if let Ok(log) = fs::read_to_string(args.data_dir.join("negative_unl/observations.jsonl")) {
298        for line in log.lines() {
299            let Ok(v) = serde_json::from_str::<Value>(line) else {
300                continue;
301            };
302            let Some(flag) = v
303                .get("flag_ledger")
304                .and_then(Value::as_u64)
305                .and_then(|f| u32::try_from(f).ok())
306            else {
307                continue;
308            };
309            let binary = v.get("node_binary").and_then(Value::as_str);
310            let known =
311                binary.is_some() || v.get("error").and_then(Value::as_str) == Some("entryNotFound");
312            if !known || flag >= ledger {
313                continue;
314            }
315            if negative_unl
316                .as_ref()
317                .is_none_or(|n: &NegativeUnlEvidence| n.flag_ledger < flag)
318            {
319                negative_unl = Some(NegativeUnlEvidence {
320                    flag_ledger: flag,
321                    flag_ledger_hash: v
322                        .get("ledger_hash")
323                        .and_then(Value::as_str)
324                        .map(str::to_owned),
325                    node_binary: binary.map(str::to_owned),
326                });
327            }
328        }
329    }
330
331    let transactions = match (&args.rpc, args.txs.is_empty()) {
332        (_, true) => Vec::new(),
333        (Some(rpc), false) => tx_proofs(rpc, ledger, &args.txs)?,
334        (None, false) => return Err("--tx requires --rpc".into()),
335    };
336    let mut bundle = Bundle {
337        format: if transactions.is_empty() {
338            FORMAT
339        } else {
340            FORMAT_V2
341        }
342        .into(),
343        ledger_index: ledger,
344        ledger_hash: String::new(),
345        policy: PolicySpec {
346            publishers: trust.publishers.iter().map(hex::encode_upper).collect(),
347            threshold: trust.threshold,
348            trusted_directly: trust
349                .trusted_directly
350                .iter()
351                .map(hex::encode_upper)
352                .collect(),
353        },
354        publisher_responses: responses,
355        manifests,
356        negative_unl,
357        validations,
358        provenance: Provenance {
359            source,
360            exported_ms: now_ms(),
361            seals: seal_hashes.into_iter().collect(),
362        },
363        transactions,
364        chain: Vec::new(),
365        objects: Vec::new(),
366        skips: Vec::new(),
367    };
368    // The claimed hash is the one that reached quorum under this same policy.
369    let report = verify(&bundle, &trust);
370    let Some(hash) = report.confirmed_hash.clone() else {
371        eprintln!("{}", serde_json::to_string_pretty(&report)?);
372        return Err(
373            format!("ledger {ledger} is not confirmed by quorum, package not built").into(),
374        );
375    };
376    // The node is not trusted: its header must be the confirmed ledger.
377    if let Some(bad) = report.transactions.iter().find(|t| !t.in_confirmed_ledger) {
378        return Err(format!(
379            "transaction proof does not match the confirmed ledger: {:?}",
380            bad.error
381        )
382        .into());
383    }
384    bundle.ledger_hash = hash;
385    println!("{}", serde_json::to_string_pretty(&bundle)?);
386    Ok(true)
387}
388
389pub fn check(args: &CheckArgs) -> Res<bool> {
390    let trust = args.trust.trust()?;
391    let bundle: Bundle = serde_json::from_slice(&fs::read(&args.bundle)?)?;
392    let report = verify(&bundle, &trust);
393    println!("{}", serde_json::to_string_pretty(&report)?);
394    Ok(report.confirmed_hash.is_some()
395        && report.matches_claim
396        && report.problems.is_empty()
397        && report.transactions.iter().all(|t| t.in_confirmed_ledger)
398        && report.objects.iter().all(|o| o.proven))
399}