Skip to main content

witness_unl/
main.rs

1//! Collector of signed UNL lists.
2//!
3//! The quorum check needs the trust policy as of the ledger's date, but list
4//! publishers (vl.ripple.com, unl.xrplf.org) only serve the current version.
5//! Past versions cannot be obtained anywhere, so, as with validations, we
6//! build up the list history ourselves, starting from day one.
7//!
8//! What it does:
9//! - polls each publisher every `--interval-secs`;
10//! - stores each new response byte for byte: it contains the publisher's
11//!   signature and manifest, so authenticity can be checked later, without us;
12//! - writes every poll, successful or not, as a line in `observations.jsonl`:
13//!   when we looked, what the server answered, which list sequences were in
14//!   the response. This is our evidence of *when* a list was in effect; the
15//!   list itself does not say;
16//! - if a publisher's list sequence jumped by more than one, the observation
17//!   marks it: we never saw the intermediate versions.
18//!
19//! Layout: `<data-dir>/<publisher>/<sequence>-<hash>.json` for raw responses,
20//! `<data-dir>/observations.jsonl` for the poll log.
21
22use std::collections::HashMap;
23use std::fs::{self, OpenOptions};
24use std::io::Write;
25use std::path::{Path, PathBuf};
26use std::time::Duration;
27
28use base64::Engine;
29use clap::Parser;
30use serde_json::{Value, json};
31use tracing::{error, info, warn};
32use witness_core::sha512_half;
33
34/// A publisher response is tens of kilobytes; anything over a megabyte is not a list.
35const MAX_BODY: u64 = 1 << 20;
36
37#[derive(Debug, Parser)]
38#[command(version, about = "Collector of signed UNL lists")]
39struct Args {
40    /// Directory of the list archive.
41    #[arg(long, env = "WITNESS_UNL_DIR")]
42    data_dir: PathBuf,
43    /// Publishers as comma-separated name=url pairs. The name is the directory in the archive.
44    #[arg(
45        long,
46        env = "WITNESS_UNL_SITES",
47        value_delimiter = ',',
48        default_value = "vl.ripple.com=https://vl.ripple.com,unl.xrplf.org=https://unl.xrplf.org"
49    )]
50    sites: Vec<String>,
51    /// Pause between polls. Lists change every few weeks or months, but we want
52    /// to see a new version within the hour, not the next day.
53    #[arg(long, default_value_t = 600)]
54    interval_secs: u64,
55    /// Make one pass and exit, for manual checks.
56    #[arg(long)]
57    once: bool,
58}
59
60#[derive(Debug, Clone, PartialEq)]
61struct Site {
62    name: String,
63    url: String,
64}
65
66fn parse_site(s: &str) -> Result<Site, String> {
67    let (name, url) = s
68        .split_once('=')
69        .ok_or_else(|| format!("publisher \"{s}\": expected name=url"))?;
70    let name = name.trim();
71    if name.is_empty()
72        || !name
73            .chars()
74            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
75    {
76        return Err(format!(
77            "publisher name \"{name}\" is not a valid directory name"
78        ));
79    }
80    Ok(Site {
81        name: name.to_owned(),
82        url: url.trim().to_owned(),
83    })
84}
85
86/// What is inside a publisher response: the key and the list sequences. The
87/// parse is only for the log; the response is stored whole, not the parsed form.
88#[derive(Debug, Default, PartialEq)]
89struct Summary {
90    version: Option<u64>,
91    public_key: Option<String>,
92    /// For each list in the response: sequence, expiration, effective date
93    /// (the v2 format can carry lists that take effect "in the future"), and
94    /// the number of validators.
95    lists: Vec<ListInfo>,
96}
97
98#[derive(Debug, PartialEq)]
99struct ListInfo {
100    sequence: u64,
101    expiration: Option<u64>,
102    effective: Option<u64>,
103    validators: usize,
104}
105
106fn summarize(body: &[u8]) -> Result<Summary, String> {
107    let v: Value = serde_json::from_slice(body).map_err(|e| format!("json: {e}"))?;
108    let mut blobs: Vec<&str> = Vec::new();
109    if let Some(b) = v.get("blob").and_then(Value::as_str) {
110        blobs.push(b);
111    }
112    if let Some(arr) = v.get("blobs_v2").and_then(Value::as_array) {
113        blobs.extend(
114            arr.iter()
115                .filter_map(|x| x.get("blob").and_then(Value::as_str)),
116        );
117    }
118    if blobs.is_empty() {
119        return Err("response has neither blob nor blobs_v2".into());
120    }
121    let mut lists = Vec::new();
122    for b in blobs {
123        let raw = base64::engine::general_purpose::STANDARD
124            .decode(b)
125            .map_err(|e| format!("blob is not base64: {e}"))?;
126        let l: Value =
127            serde_json::from_slice(&raw).map_err(|e| format!("blob is not json: {e}"))?;
128        lists.push(ListInfo {
129            sequence: l
130                .get("sequence")
131                .and_then(Value::as_u64)
132                .ok_or("list has no sequence")?,
133            expiration: l.get("expiration").and_then(Value::as_u64),
134            effective: l.get("effective").and_then(Value::as_u64),
135            validators: l
136                .get("validators")
137                .and_then(Value::as_array)
138                .map_or(0, Vec::len),
139        });
140    }
141    Ok(Summary {
142        version: v.get("version").and_then(Value::as_u64),
143        public_key: v
144            .get("public_key")
145            .and_then(Value::as_str)
146            .map(str::to_owned),
147        lists,
148    })
149}
150
151fn append_line(path: &Path, v: &Value) -> std::io::Result<()> {
152    let mut f = OpenOptions::new().create(true).append(true).open(path)?;
153    f.write_all(format!("{v}\n").as_bytes())?;
154    f.sync_data()
155}
156
157/// State kept between polls: the last list sequence per publisher key, so
158/// that skipped versions can be noticed.
159#[derive(Debug, Default)]
160struct Seen {
161    last_sequence: HashMap<String, u64>,
162}
163
164impl Seen {
165    /// Restores the last sequences from responses already stored.
166    fn load(dir: &Path) -> Seen {
167        let mut seen = Seen::default();
168        let Ok(sites) = fs::read_dir(dir) else {
169            return seen;
170        };
171        for site in sites.flatten() {
172            let Ok(files) = fs::read_dir(site.path()) else {
173                continue;
174            };
175            for f in files.flatten() {
176                if let Ok(body) = fs::read(f.path())
177                    && let Ok(s) = summarize(&body)
178                {
179                    seen.note(&s);
180                }
181            }
182        }
183        seen
184    }
185
186    /// Records a response; returns the skipped sequences, if any.
187    fn note(&mut self, s: &Summary) -> Option<[u64; 2]> {
188        let key = s.public_key.clone()?;
189        let max = s.lists.iter().map(|l| l.sequence).max()?;
190        let last = self.last_sequence.get(&key).copied();
191        let gap = match last {
192            Some(prev) if max > prev + 1 => Some([prev + 1, max - 1]),
193            _ => None,
194        };
195        if last.is_none_or(|prev| max > prev) {
196            self.last_sequence.insert(key, max);
197        }
198        gap
199    }
200}
201
202struct Fetched {
203    status: u16,
204    headers: Value,
205    body: Vec<u8>,
206}
207
208fn fetch(agent: &ureq::Agent, url: &str) -> Result<Fetched, String> {
209    let mut resp = agent.get(url).call().map_err(|e| e.to_string())?;
210    let mut headers = serde_json::Map::new();
211    for name in ["date", "last-modified", "etag", "age", "cache-control"] {
212        if let Some(v) = resp.headers().get(name).and_then(|v| v.to_str().ok()) {
213            headers.insert(name.into(), Value::String(v.into()));
214        }
215    }
216    let body = resp
217        .body_mut()
218        .with_config()
219        .limit(MAX_BODY)
220        .read_to_vec()
221        .map_err(|e| format!("reading body: {e}"))?;
222    Ok(Fetched {
223        status: resp.status().as_u16(),
224        headers: Value::Object(headers),
225        body,
226    })
227}
228
229fn poll(agent: &ureq::Agent, site: &Site, dir: &Path, seen: &mut Seen) -> std::io::Result<()> {
230    let at_ms = witness_core::util::now_ms();
231    let mut obs = json!({"at_ms": at_ms, "site": site.name, "url": site.url});
232    match fetch(agent, &site.url) {
233        Err(e) => {
234            warn!("{}: {e}", site.name);
235            obs["error"] = Value::String(e);
236        }
237        Ok(f) => {
238            let hash = hex::encode_upper(sha512_half(&f.body));
239            obs["status"] = json!(f.status);
240            obs["headers"] = f.headers;
241            obs["body_hash"] = json!(hash);
242            obs["body_bytes"] = json!(f.body.len());
243            match summarize(&f.body) {
244                Err(e) => {
245                    warn!("{}: could not parse response: {e}", site.name);
246                    obs["error"] = json!(format!("parse: {e}"));
247                }
248                Ok(s) => {
249                    let max = s.lists.iter().map(|l| l.sequence).max().unwrap_or(0);
250                    obs["version"] = json!(s.version);
251                    obs["public_key"] = json!(s.public_key);
252                    obs["lists"] = s
253                        .lists
254                        .iter()
255                        .map(|l| {
256                            json!({"sequence": l.sequence, "expiration": l.expiration,
257                                   "effective": l.effective, "validators": l.validators})
258                        })
259                        .collect();
260                    if let Some([a, b]) = seen.note(&s) {
261                        warn!("{}: missed list versions {a}..{b}", site.name);
262                        obs["missed_sequences"] = json!([a, b]);
263                    }
264                    let site_dir = dir.join(&site.name);
265                    fs::create_dir_all(&site_dir)?;
266                    let path = site_dir.join(format!("{max:010}-{}.json", &hash[..16]));
267                    if !path.exists() {
268                        witness_core::util::write_atomic(&path, &f.body)?;
269                        info!(
270                            "{}: new version, list {max}, stored {}",
271                            site.name,
272                            path.display()
273                        );
274                        obs["stored"] = json!(true);
275                    }
276                }
277            }
278        }
279    }
280    append_line(&dir.join("observations.jsonl"), &obs)
281}
282
283fn main() {
284    tracing_subscriber::fmt()
285        .with_env_filter(
286            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
287        )
288        .without_time() // journald adds the timestamp
289        .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr()))
290        .init();
291    let args = Args::parse();
292    if let Err(e) = run(&args) {
293        error!("stopped with error: {e}");
294        std::process::exit(1);
295    }
296}
297
298fn run(args: &Args) -> Result<(), Box<dyn std::error::Error>> {
299    let sites = args
300        .sites
301        .iter()
302        .map(|s| parse_site(s))
303        .collect::<Result<Vec<_>, _>>()?;
304    fs::create_dir_all(&args.data_dir)?;
305    let agent: ureq::Agent = ureq::Agent::config_builder()
306        .timeout_global(Some(Duration::from_secs(30)))
307        .user_agent(concat!("xrpl-witness-unl/", env!("CARGO_PKG_VERSION")))
308        .build()
309        .into();
310    let mut seen = Seen::load(&args.data_dir);
311    info!(
312        "publishers: {}, polling every {} s, known keys: {}",
313        sites.len(),
314        args.interval_secs,
315        seen.last_sequence.len()
316    );
317    loop {
318        for site in &sites {
319            // A disk write error is a reason to stop: observations must not be
320            // lost silently. systemd will restart us, and alerting will notice.
321            poll(&agent, site, &args.data_dir, &mut seen)?;
322        }
323        if args.once {
324            return Ok(());
325        }
326        std::thread::sleep(Duration::from_secs(args.interval_secs));
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    fn response(seq: u64, v2: bool) -> Vec<u8> {
335        let list = json!({"sequence": seq, "expiration": 900, "validators": [{"a": 1}, {"b": 2}]});
336        let blob = base64::engine::general_purpose::STANDARD.encode(list.to_string());
337        let v = if v2 {
338            json!({"version": 2, "public_key": "ED00", "manifest": "m",
339                   "blobs_v2": [{"blob": blob, "signature": "s"}]})
340        } else {
341            json!({"version": 1, "public_key": "ED00", "manifest": "m",
342                   "blob": blob, "signature": "s"})
343        };
344        v.to_string().into_bytes()
345    }
346
347    #[test]
348    fn both_formats_are_summarized() {
349        for v2 in [false, true] {
350            let s = summarize(&response(85, v2)).unwrap();
351            assert_eq!(s.public_key.as_deref(), Some("ED00"));
352            assert_eq!(s.lists.len(), 1);
353            assert_eq!(s.lists[0].sequence, 85);
354            assert_eq!(s.lists[0].validators, 2);
355        }
356        assert!(summarize(br#"{"version":1}"#).is_err());
357    }
358
359    #[test]
360    fn skipped_versions_are_reported() {
361        let mut seen = Seen::default();
362        assert_eq!(seen.note(&summarize(&response(85, false)).unwrap()), None);
363        assert_eq!(seen.note(&summarize(&response(85, false)).unwrap()), None);
364        assert_eq!(seen.note(&summarize(&response(86, false)).unwrap()), None);
365        assert_eq!(
366            seen.note(&summarize(&response(90, false)).unwrap()),
367            Some([87, 89])
368        );
369    }
370
371    #[test]
372    fn site_names_are_safe_directories() {
373        assert_eq!(
374            parse_site("vl.ripple.com=https://vl.ripple.com").unwrap(),
375            Site {
376                name: "vl.ripple.com".into(),
377                url: "https://vl.ripple.com".into()
378            }
379        );
380        assert!(parse_site("../etc=https://x").is_err());
381        assert!(parse_site("no-url").is_err());
382    }
383
384    #[test]
385    fn seen_survives_restart() {
386        let dir = tempfile::tempdir().unwrap();
387        let site = dir.path().join("vl.ripple.com");
388        fs::create_dir_all(&site).unwrap();
389        fs::write(site.join("0000000085-AB.json"), response(85, false)).unwrap();
390        let mut seen = Seen::load(dir.path());
391        assert_eq!(
392            seen.note(&summarize(&response(87, false)).unwrap()),
393            Some([86, 86])
394        );
395    }
396}