Skip to main content

witness_archiver/
manifests.rs

1//! Validator manifests: the link between a signing key and a master key.
2//!
3//! The validation stream carries only the signing key. Which validator it
4//! belongs to is stated by the manifest, a record signed by the master key
5//! saying "my current signing key is such-and-such". Without it a signature
6//! cannot be matched to the UNL or to the validator's history. Manifests for
7//! UNL validators are inside the publishers' lists, but manifests for other
8//! validators are only available from nodes, so we ask the node.
9//!
10//! The first time it sees a signing key, the archiver sends its node a
11//! `manifest` command over the same connection. The response is stored byte
12//! for byte: the manifest is signed, so its authenticity can be checked later.
13//! A key rotation produces a new signing key, and therefore a new request.
14//!
15//! Layout: `manifests/<master-key>-<seq>-<hash>.bin` for raw manifests,
16//! `manifests/observations.jsonl` for every response received.
17
18use std::collections::{HashMap, HashSet};
19use std::fs::{self, OpenOptions};
20use std::io::Write;
21use std::path::{Path, PathBuf};
22
23use base64::Engine;
24use serde_json::{Value, json};
25use witness_core::sha512_half;
26
27/// The node does not know every manifest: as of 2026-10-23, 38 of the 112
28/// validators in the stream. The rest may reach it later, so unknown keys are
29/// asked about again, but no more than once an hour.
30const RETRY_MS: u64 = 3_600_000;
31
32/// Manifest request ids start here so they are not confused with the
33/// subscription (id 1).
34const FIRST_ID: u64 = 1000;
35
36#[derive(Debug)]
37pub struct Book {
38    dir: PathBuf,
39    asked: HashSet<String>,
40    /// Keys whose manifest the node did not know, and when to ask again.
41    retry_at: HashMap<String, u64>,
42    stored: HashSet<String>,
43    next_id: u64,
44    pub stored_total: u64,
45}
46
47/// Result of parsing the node's response.
48#[derive(Debug, PartialEq)]
49pub enum Outcome {
50    /// New manifest, stored.
51    Stored { master_key: String, seq: u64 },
52    /// Already stored.
53    Known,
54    /// The node does not know the manifest; usually a validator from another network.
55    Unknown,
56}
57
58impl Book {
59    pub fn open(data_dir: &Path) -> std::io::Result<Book> {
60        let dir = data_dir.join("manifests");
61        fs::create_dir_all(&dir)?;
62        let mut stored = HashSet::new();
63        for entry in fs::read_dir(&dir)? {
64            let name = entry?.file_name().to_string_lossy().into_owned();
65            if let Some(hash) = name.strip_suffix(".bin").and_then(|n| n.rsplit('-').next()) {
66                stored.insert(hash.to_owned());
67            }
68        }
69        Ok(Book {
70            dir,
71            asked: HashSet::new(),
72            retry_at: HashMap::new(),
73            stored,
74            next_id: FIRST_ID,
75            stored_total: 0,
76        })
77    }
78
79    /// A manifest request, if this key has not been asked about yet or it is
80    /// time to ask again.
81    pub fn request_for(&mut self, signing_key: &str, now_ms: u64) -> Option<String> {
82        if !self.asked.insert(signing_key.to_owned()) {
83            match self.retry_at.get(signing_key) {
84                Some(&at) if at <= now_ms => {
85                    self.retry_at.remove(signing_key);
86                }
87                _ => return None,
88            }
89        }
90        let id = self.next_id;
91        self.next_id += 1;
92        Some(json!({"id": id, "command": "manifest", "public_key": signing_key}).to_string())
93    }
94
95    /// A response to our manifest request, identified by the request id.
96    pub fn is_ours(v: &Value) -> bool {
97        v.get("type").and_then(Value::as_str) == Some("response")
98            && v.get("id")
99                .and_then(Value::as_u64)
100                .is_some_and(|id| id >= FIRST_ID)
101    }
102
103    /// Parses and stores the node's response.
104    pub fn absorb(&mut self, v: &Value, at_ms: u64) -> std::io::Result<Outcome> {
105        let result = v.get("result").cloned().unwrap_or(Value::Null);
106        let requested = result
107            .get("requested")
108            .and_then(Value::as_str)
109            .unwrap_or("");
110        let details = result.get("details").cloned().unwrap_or(Value::Null);
111        let Some(raw) = result
112            .get("manifest")
113            .and_then(Value::as_str)
114            .and_then(|m| base64::engine::general_purpose::STANDARD.decode(m).ok())
115        else {
116            if !requested.is_empty() {
117                self.retry_at.insert(requested.to_owned(), at_ms + RETRY_MS);
118            }
119            return Ok(Outcome::Unknown);
120        };
121        let hash = hex::encode_upper(sha512_half(&raw));
122        let short = &hash[..16];
123        if self.stored.contains(short) {
124            return Ok(Outcome::Known);
125        }
126        // The file name is taken from the node's word; the truth about the
127        // master key comes from verifying the manifest signature, but this is
128        // good enough for finding files by eye.
129        let master_key = details
130            .get("master_key")
131            .and_then(Value::as_str)
132            .filter(|k| k.chars().all(|c| c.is_ascii_alphanumeric()))
133            .unwrap_or("unknown")
134            .to_owned();
135        let seq = details.get("seq").and_then(Value::as_u64).unwrap_or(0);
136        let path = self.dir.join(format!("{master_key}-{seq:010}-{short}.bin"));
137        witness_core::util::write_atomic(&path, &raw)?;
138        let mut f = OpenOptions::new()
139            .create(true)
140            .append(true)
141            .open(self.dir.join("observations.jsonl"))?;
142        let line = json!({"at_ms": at_ms, "requested": requested, "details": details,
143                          "manifest_hash": hash, "file": path.file_name().map(|n| n.to_string_lossy())});
144        f.write_all(format!("{line}\n").as_bytes())?;
145        f.sync_data()?;
146        self.stored.insert(short.to_owned());
147        self.stored_total += 1;
148        Ok(Outcome::Stored { master_key, seq })
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    fn reply(id: u64, manifest: Option<&[u8]>) -> Value {
157        let mut result = json!({"requested": "n9Kkey"});
158        if let Some(m) = manifest {
159            result["manifest"] = json!(base64::engine::general_purpose::STANDARD.encode(m));
160            result["details"] = json!({"master_key": "nHBmaster", "seq": 3, "domain": "x.org"});
161        }
162        json!({"id": id, "type": "response", "status": "success", "result": result})
163    }
164
165    #[test]
166    fn each_key_is_asked_once() {
167        let dir = tempfile::tempdir().unwrap();
168        let mut b = Book::open(dir.path()).unwrap();
169        assert!(b.request_for("n9A", 0).is_some());
170        assert!(b.request_for("n9A", 0).is_none());
171        assert!(b.request_for("n9B", 0).unwrap().contains("\"id\":1001"));
172    }
173
174    #[test]
175    fn unknown_keys_are_asked_again_after_an_hour() {
176        let dir = tempfile::tempdir().unwrap();
177        let mut b = Book::open(dir.path()).unwrap();
178        assert!(b.request_for("n9Kkey", 0).is_some());
179        assert_eq!(b.absorb(&reply(1000, None), 10).unwrap(), Outcome::Unknown);
180        assert!(b.request_for("n9Kkey", 10 + RETRY_MS - 1).is_none());
181        assert!(b.request_for("n9Kkey", 10 + RETRY_MS).is_some());
182        assert!(b.request_for("n9Kkey", 10 + RETRY_MS).is_none());
183    }
184
185    #[test]
186    fn manifests_are_stored_once_and_survive_restart() {
187        let dir = tempfile::tempdir().unwrap();
188        let mut b = Book::open(dir.path()).unwrap();
189        let r = reply(1000, Some(b"raw-manifest"));
190        assert!(Book::is_ours(&r));
191        assert_eq!(
192            b.absorb(&r, 1).unwrap(),
193            Outcome::Stored {
194                master_key: "nHBmaster".into(),
195                seq: 3
196            }
197        );
198        assert_eq!(b.absorb(&r, 2).unwrap(), Outcome::Known);
199        let mut again = Book::open(dir.path()).unwrap();
200        assert_eq!(again.absorb(&r, 3).unwrap(), Outcome::Known);
201        assert_eq!(
202            again.absorb(&reply(1001, None), 4).unwrap(),
203            Outcome::Unknown
204        );
205        assert!(!Book::is_ours(&json!({"id": 1, "type": "response"})));
206    }
207}