Skip to main content

witness_verify/
quorum.rs

1//! Quorum check over the archive: whether each ledger in a range is
2//! confirmed by the validators the policy trusts.
3//!
4//! Everything comes from the archive and is checked again; the node is not
5//! trusted for anything:
6//! - UNL lists are the publishers' raw responses, and their signatures are
7//!   checked with the publisher keys from the policy (by default, the keys
8//!   from xrpld's default configuration);
9//! - when a list was in effect comes from the collector's poll log: a list
10//!   applies to ledgers after the moment we first saw it;
11//! - which validator is whose comes from verified manifests, both from the
12//!   lists and from the node;
13//! - every validation signature is checked.
14//!
15//! If we did not observe the policy as of the ledger (the list was seen
16//! later), the result is flagged: the check then uses the list we know, not
17//! the one that was certainly in effect.
18
19use std::collections::{BTreeMap, BTreeSet};
20use std::fs;
21use std::path::{Path, PathBuf};
22
23use clap::Args;
24use serde_json::{Value, json};
25use witness_core::evidence::signing_to_master;
26use witness_core::keys::node_public;
27use witness_core::negative_unl::NegativeUnl;
28use witness_core::quorum::{Key, Observed, assess};
29use witness_core::{Manifest, Validation};
30use witness_store::segment::read_segment;
31
32use crate::archive::seals;
33pub use witness_core::unlstore::{load_lists, policy_at};
34
35/// Publisher keys from xrpld's default `[validator_list_keys]`: vl.ripple.com and
36/// unl.xrplf.org.
37pub const DEFAULT_PUBLISHERS: [&str; 2] = [
38    "ED2677ABFFD1B33AC6FBC3062B71F1E8397C1505E1C42C64D11AD1B28FF73F4734",
39    "ED42AEC58B701EEBB77356FFFEC26F83C1F0407263530F068C7C73D392C7E06FD1",
40];
41
42#[derive(Debug, Args)]
43pub struct QuorumArgs {
44    /// Archive root: segments/, manifests/, unl/.
45    data_dir: PathBuf,
46    /// First ledger of the range. Defaults to 1000 ledgers ending one
47    /// late-arrival window before the edge of the archive: validations for the
48    /// latest ledgers are still in the open segment.
49    #[arg(long)]
50    from: Option<u32>,
51    #[arg(long)]
52    to: Option<u32>,
53    /// List publisher keys in hex. Defaults to xrpld's default publishers.
54    #[arg(long = "publisher")]
55    publishers: Vec<String>,
56    /// How many lists must contain a key. 0 means the xrpld default.
57    #[arg(long, default_value_t = 0)]
58    threshold: usize,
59    /// Keys trusted directly, like the `[validators]` section of the xrpld
60    /// config. Either `n9...` form or hex.
61    #[arg(long = "trust")]
62    local: Vec<String>,
63    /// Master keys disabled by the Negative UNL, in hex, for ledgers the archive
64    /// has no observation for (`negative_unl/observations.jsonl`).
65    #[arg(long = "negative-unl")]
66    negative_unl: Vec<String>,
67    /// Show a breakdown of every unconfirmed ledger.
68    #[arg(long)]
69    details: bool,
70}
71
72type Res<T> = Result<T, Box<dyn std::error::Error>>;
73
74/// Negative UNL per flag ledger, from the archiver's log. An "object not
75/// found" answer means an empty list; other errors are skipped, since we know
76/// nothing about such a flag ledger.
77fn load_negative_unl(dir: &Path) -> Res<BTreeMap<u32, BTreeSet<Key>>> {
78    let mut out = BTreeMap::new();
79    let Ok(log) = fs::read_to_string(dir.join("observations.jsonl")) else {
80        return Ok(out);
81    };
82    for line in log.lines() {
83        let Ok(v) = serde_json::from_str::<Value>(line) else {
84            continue;
85        };
86        let Some(flag) = v
87            .get("flag_ledger")
88            .and_then(Value::as_u64)
89            .and_then(|f| u32::try_from(f).ok())
90        else {
91            continue;
92        };
93        if let Some(bin) = v.get("node_binary").and_then(Value::as_str) {
94            let parsed = NegativeUnl::parse(&hex::decode(bin)?)
95                .map_err(|e| format!("Negative UNL at flag ledger {flag}: {e}"))?;
96            out.insert(
97                flag,
98                parsed.disabled.into_iter().map(|d| d.master_key).collect(),
99            );
100        } else if v.get("error").and_then(Value::as_str) == Some("entryNotFound") {
101            out.insert(flag, BTreeSet::new());
102        }
103    }
104    Ok(out)
105}
106
107pub fn run(args: &QuorumArgs) -> Res<bool> {
108    let publishers: Vec<Key> = if args.publishers.is_empty() {
109        DEFAULT_PUBLISHERS
110            .iter()
111            .map(hex::decode)
112            .collect::<Result<_, _>>()?
113    } else {
114        args.publishers
115            .iter()
116            .map(hex::decode)
117            .collect::<Result<_, _>>()?
118    };
119    let local: BTreeSet<Key> = args
120        .local
121        .iter()
122        .map(|s| {
123            witness_core::keys::parse_node_public(s)
124                .or_else(|| hex::decode(s).ok())
125                .ok_or_else(|| format!("could not parse key {s}"))
126        })
127        .collect::<Result<_, _>>()?;
128    let nunl: BTreeSet<Key> = args
129        .negative_unl
130        .iter()
131        .map(hex::decode)
132        .collect::<Result<_, _>>()?;
133
134    let mut manifests = Vec::new();
135    let mut list_problems = Vec::new();
136    let lists = load_lists(
137        &args.data_dir.join("unl"),
138        &publishers,
139        &mut manifests,
140        &mut list_problems,
141    )?;
142    for p in &list_problems {
143        eprintln!("{p}");
144    }
145    if lists.is_empty() {
146        return Err("the archive has no verified UNL list".into());
147    }
148    if let Ok(dir) = fs::read_dir(args.data_dir.join("manifests")) {
149        for e in dir.flatten() {
150            if e.path().extension().is_some_and(|x| x == "bin")
151                && let Ok(m) = Manifest::parse(&fs::read(e.path())?)
152            {
153                manifests.push(m);
154            }
155        }
156    }
157    let manifest_count = manifests.len();
158    let (to_master, manifests_rejected) = signing_to_master(&manifests);
159
160    // Default range: the archive's last 1000 ledgers.
161    let all_seals = seals(&args.data_dir.join("segments"))?;
162    let last = all_seals
163        .iter()
164        .map(|(_, s)| s.coverage_last)
165        .max()
166        .ok_or("the archive has no seals")?;
167    // Back off by the late-arrival window plus a margin for the median.
168    let to = args.to.unwrap_or(last.saturating_sub(64));
169    let from = args.from.unwrap_or(to.saturating_sub(999));
170
171    // Validations in the range: signature verified, inner ledger index matches.
172    let mut per_ledger: BTreeMap<u32, Vec<Observed>> = BTreeMap::new();
173    let mut first_ms: BTreeMap<u32, u64> = BTreeMap::new();
174    let mut bad_signatures = 0u64;
175    for (seal_path, seal) in &all_seals {
176        let reach = seal.nominal_last.saturating_add(512);
177        if seal.nominal_first > to.saturating_add(512) || reach < from {
178            continue;
179        }
180        let seg = PathBuf::from(
181            seal_path
182                .to_string_lossy()
183                .replace(".seal.json", ".xwv.zst"),
184        );
185        for rec in read_segment(&seg)? {
186            if !(from..=to).contains(&rec.ledger_index) {
187                continue;
188            }
189            let Ok(v) = Validation::parse(&rec.data) else {
190                bad_signatures += 1;
191                continue;
192            };
193            if v.verify().is_err() || v.ledger_sequence != rec.ledger_index {
194                bad_signatures += 1;
195                continue;
196            }
197            let e = first_ms.entry(v.ledger_sequence).or_insert(rec.received_ms);
198            *e = (*e).min(rec.received_ms);
199            per_ledger
200                .entry(v.ledger_sequence)
201                .or_default()
202                .push(Observed {
203                    master_key: to_master.get(&v.signing_pub_key).cloned(),
204                    signing_key: v.signing_pub_key.clone(),
205                    ledger_hash: v.ledger_hash,
206                    full: v.is_full(),
207                    signing_time: v.signing_time,
208                });
209        }
210    }
211
212    let mut confirmed = 0u64;
213    let mut unconfirmed = Vec::new();
214    let mut not_seen_count: BTreeMap<Key, u64> = BTreeMap::new();
215    let mut conflicts = Vec::new();
216    let mut unattributed: BTreeSet<Key> = BTreeSet::new();
217    let mut policy_gaps = 0u64;
218    let mut signers_min = usize::MAX;
219    let mut signers_sum = 0usize;
220    let mut summary_policy = None;
221    let ledgers_without_data: Vec<u32> = (from..=to)
222        .filter(|l| !per_ledger.contains_key(l))
223        .collect();
224    let observed_nunl = load_negative_unl(&args.data_dir.join("negative_unl"))?;
225    let mut nunl_unknown = 0u64;
226    let mut nunl_nonempty = 0u64;
227    for (ledger, obs) in &per_ledger {
228        // State as of the last flag ledger before this one: changes recorded
229        // in a flag ledger apply to the ledgers after it.
230        let ledger_nunl = match observed_nunl.range(..*ledger).next_back() {
231            Some((_, set)) => set,
232            None => {
233                nunl_unknown += 1;
234                &nunl
235            }
236        };
237        if !ledger_nunl.is_empty() {
238            nunl_nonempty += 1;
239        }
240        let (policy, observed_before) = policy_at(
241            &lists,
242            &publishers,
243            first_ms[ledger],
244            args.threshold,
245            &local,
246            ledger_nunl,
247        );
248        if !observed_before {
249            policy_gaps += 1;
250        }
251        let a = assess(&policy, obs);
252        summary_policy.get_or_insert_with(|| {
253            json!({
254                "publishers": publishers.iter().map(hex::encode_upper).collect::<Vec<_>>(),
255                "lists": policy.lists.iter().map(|l| json!({
256                    "publisher": hex::encode_upper(&l.publisher),
257                    "sequence": l.sequence,
258                    "validators": l.validators.len(),
259                })).collect::<Vec<_>>(),
260                "threshold": policy.threshold,
261                "trusted_directly": local.iter().map(|k| node_public(k)).collect::<Vec<_>>(),
262                "unl_size": a.unl_size,
263                "negative_unl": policy.negative_unl.iter().map(|k| node_public(k)).collect::<Vec<_>>(),
264                "quorum": a.quorum,
265            })
266        });
267        for k in &a.not_seen {
268            *not_seen_count.entry(k.clone()).or_default() += 1;
269        }
270        for k in &a.conflicting {
271            conflicts.push(json!({"ledger": ledger, "validator": node_public(k)}));
272        }
273        unattributed.extend(a.unattributed.iter().cloned());
274        match a.confirmed {
275            Some(h) => {
276                confirmed += 1;
277                let n = a.by_hash[&h].len();
278                signers_min = signers_min.min(n);
279                signers_sum += n;
280            }
281            None => {
282                let best = a.by_hash.values().map(BTreeSet::len).max().unwrap_or(0);
283                let mut entry = json!({"ledger": ledger, "best_signers": best, "quorum": a.quorum});
284                if args.details {
285                    entry["by_hash"] = a
286                        .by_hash
287                        .iter()
288                        .map(|(h, s)| (hex::encode_upper(h), json!(s.len())))
289                        .collect::<serde_json::Map<_, _>>()
290                        .into();
291                    entry["not_seen"] = a
292                        .not_seen
293                        .iter()
294                        .map(|k| node_public(k))
295                        .collect::<Vec<_>>()
296                        .into();
297                }
298                unconfirmed.push(entry);
299            }
300        }
301    }
302    let mut often_not_seen: Vec<(Key, u64)> = not_seen_count.into_iter().collect();
303    often_not_seen.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
304    let report = json!({
305        "range": [from, to],
306        "policy": summary_policy,
307        "policy_not_observed_before_ledger": policy_gaps,
308        "negative_unl": {
309            "flag_ledgers_observed": observed_nunl.len(),
310            "ledgers_without_observation": nunl_unknown,
311            "ledgers_with_disabled_validators": nunl_nonempty,
312        },
313        "manifests": {"total": manifest_count, "rejected": manifests_rejected, "signing_keys_mapped": to_master.len()},
314        "ledgers_with_validations": per_ledger.len(),
315        "ledgers_without_validations": ledgers_without_data.len(),
316        "confirmed": confirmed,
317        "unconfirmed": unconfirmed,
318        "signers_on_confirmed": {
319            "min": if confirmed > 0 { signers_min } else { 0 },
320            "avg": if confirmed > 0 { signers_sum as f64 / confirmed as f64 } else { 0.0 },
321        },
322        "conflicting_signatures": conflicts,
323        "invalid_validations_skipped": bad_signatures,
324        "unattributed_signing_keys": unattributed.len(),
325        "trusted_not_seen_most": often_not_seen.iter().take(5).map(|(k, n)| json!({"validator": node_public(k), "ledgers": n})).collect::<Vec<_>>(),
326    });
327    println!("{}", serde_json::to_string_pretty(&report)?);
328    Ok(unconfirmed.is_empty() && ledgers_without_data.is_empty())
329}