Skip to main content

witness_archiver/
nunl.rs

1//! Negative UNL per flag ledger.
2//!
3//! The list of validators disabled by the network changes only in flag
4//! ledgers (every 256). On each new flag ledger the archiver asks its node
5//! for the NegativeUNL object in binary form and writes the response as a
6//! line in `negative_unl/observations.jsonl`, as is, including "object not
7//! found": an empty list is evidence too.
8//!
9//! For now this is on the node's word: proving that the object is in the
10//! state tree of the confirmed ledger is the job of inclusion proofs.
11
12use std::fs::{self, OpenOptions};
13use std::io::Write;
14use std::path::{Path, PathBuf};
15
16use serde_json::{Value, json};
17use witness_core::negative_unl::INDEX;
18
19/// The Negative UNL request id is a string containing the flag ledger. A
20/// number does not work: the xrpld JSON parser rejects integers wider than
21/// 32 bits and answers `jsonInvalid` without the request id (checked on
22/// 2026-10-24). A string is returned as is, and it cannot be confused with
23/// the numeric manifest request ids.
24const ID_PREFIX: &str = "nunl:";
25
26/// Ask not right away, but once the flag ledger is surely validated.
27const SETTLE: u32 = 4;
28
29#[derive(Debug)]
30pub struct Watch {
31    path: PathBuf,
32    last_flag: Option<u32>,
33}
34
35impl Watch {
36    pub fn open(data_dir: &Path) -> std::io::Result<Watch> {
37        let dir = data_dir.join("negative_unl");
38        fs::create_dir_all(&dir)?;
39        Ok(Watch {
40            path: dir.join("observations.jsonl"),
41            last_flag: None,
42        })
43    }
44
45    /// A request for the last validated flag ledger, if this process has not
46    /// asked about it yet.
47    pub fn request_for(&mut self, network_ledger: u32) -> Option<String> {
48        let flag = network_ledger.checked_sub(SETTLE)? / 256 * 256;
49        if flag == 0 || self.last_flag == Some(flag) {
50            return None;
51        }
52        self.last_flag = Some(flag);
53        Some(
54            json!({"id": format!("{ID_PREFIX}{flag}"), "command": "ledger_entry",
55                   "index": INDEX, "ledger_index": flag, "binary": true})
56            .to_string(),
57        )
58    }
59
60    fn flag_of(v: &Value) -> Option<u64> {
61        v.get("id")?.as_str()?.strip_prefix(ID_PREFIX)?.parse().ok()
62    }
63
64    pub fn is_ours(v: &Value) -> bool {
65        v.get("type").and_then(Value::as_str) == Some("response") && Self::flag_of(v).is_some()
66    }
67
68    /// Writes the node's response. Returns the flag ledger and the outcome: the
69    /// object size (0 means no object) or a node error of another kind.
70    pub fn absorb(
71        &mut self,
72        v: &Value,
73        at_ms: u64,
74    ) -> std::io::Result<(u64, Result<usize, String>)> {
75        let flag = Self::flag_of(v).unwrap_or(0);
76        let result = v.get("result").cloned().unwrap_or(Value::Null);
77        let node_binary = result.get("node_binary").and_then(Value::as_str);
78        // In a WebSocket error response the fields are at the top level, not in result.
79        let field = |k: &str| result.get(k).or_else(|| v.get(k)).cloned();
80        let error = field("error");
81        let line = json!({
82            "at_ms": at_ms,
83            "flag_ledger": flag,
84            "ledger_index": field("ledger_index"),
85            "ledger_hash": field("ledger_hash"),
86            "validated": field("validated"),
87            "status": v.get("status"),
88            "error": error,
89            "node_binary": node_binary,
90        });
91        let mut f = OpenOptions::new()
92            .create(true)
93            .append(true)
94            .open(&self.path)?;
95        f.write_all(format!("{line}\n").as_bytes())?;
96        f.sync_data()?;
97        let outcome = match (node_binary, error.as_ref().and_then(Value::as_str)) {
98            (Some(b), _) => Ok(b.len() / 2),
99            (None, Some("entryNotFound")) => Ok(0),
100            (None, e) => Err(e.unwrap_or("response without an object").to_owned()),
101        };
102        Ok((flag, outcome))
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn asks_once_per_flag_ledger_after_it_settles() {
112        let dir = tempfile::tempdir().unwrap();
113        let mut w = Watch::open(dir.path()).unwrap();
114        // 107,854,848 is a flag ledger; 3 ledgers later it is still too early to count it.
115        assert!(w.request_for(107_854_851).unwrap().contains("107854592"));
116        assert!(w.request_for(107_854_852).unwrap().contains("107854848"));
117        assert!(w.request_for(107_854_900).is_none());
118        assert!(w.request_for(107_855_108).unwrap().contains("107855104"));
119    }
120
121    #[test]
122    fn empty_answer_is_recorded_too() {
123        let dir = tempfile::tempdir().unwrap();
124        let mut w = Watch::open(dir.path()).unwrap();
125        let v = json!({"id": "nunl:107854848", "type": "response", "status": "error",
126                       "error": "entryNotFound", "result": {"ledger_index": 107_854_848}});
127        assert!(Watch::is_ours(&v));
128        assert_eq!(w.absorb(&v, 1).unwrap(), (107_854_848, Ok(0)));
129        let lost = json!({"id": "nunl:21767168", "type": "response", "status": "error",
130                          "error": "lgrNotFound"});
131        assert_eq!(
132            w.absorb(&lost, 2).unwrap(),
133            (21_767_168, Err("lgrNotFound".into()))
134        );
135        let log = fs::read_to_string(dir.path().join("negative_unl/observations.jsonl")).unwrap();
136        assert!(log.contains("entryNotFound"));
137        assert!(!Watch::is_ours(&json!({"id": 1000, "type": "response"})));
138    }
139}