Skip to main content

ledger_engine/
confirm.rs

1//! Confirmation of ledgers by a validator quorum, independent of the ledger
2//! source.
3//!
4//! Whether a ledger is validated by the network is decided not by the node but by
5//! the signatures of UNL validators. Validations come from the nodes' `validations`
6//! stream, and each signature is checked on arrival. UNL membership comes from the
7//! publisher lists in the `witness-unl` collector archive; responses are checked
8//! against pinned publisher keys on every load. A signing key is mapped to its
9//! master key using the manifests from the same lists, and for validators that
10//! rotated keys after the list was published, using a manifest fetched from the node
11//! (it is signed by the master key and checked the same way).
12//!
13//! The rule is the same as in evidence bundle verification (`full-unl`): 80% of
14//! the whole UNL, full validations only, Negative UNL not taken into account. The lists
15//! are those in effect at the ledger's time according to the signed validations, and the quorum must
16//! hold for every combination of lists in effect. The source can
17//! delay or hide validations (then the ledger simply won't be confirmed),
18//! but it can't forge a signature.
19//!
20//! If ledger N is confirmed, so are all ledgers loaded before it: the ingester
21//! has already checked that each one's parent hash is the hash of the previous ledger.
22
23use std::collections::{BTreeMap, BTreeSet, HashMap};
24use std::path::PathBuf;
25use std::sync::{Arc, Mutex, MutexGuard};
26use std::time::{Duration, Instant};
27
28use base64::Engine as _;
29use futures_util::{SinkExt, StreamExt};
30use serde_json::{Value, json};
31use tokio_tungstenite::connect_async;
32use tokio_tungstenite::tungstenite::Message;
33use tracing::{info, warn};
34use witness_core::evidence::signing_to_master;
35use witness_core::keys::node_public;
36use witness_core::manifest::Manifest;
37#[cfg(test)]
38use witness_core::quorum::Policy;
39use witness_core::quorum::{Key, Observed, decide, policies_between};
40use witness_core::unlstore::{Seen, load_lists};
41use witness_core::validation::Validation;
42
43/// Validations older than this many ledgers behind the newest one are forgotten.
44const KEEP_LEDGERS: u32 = 4096;
45/// Raw validations (for evidence bundles) are kept for this many recent
46/// ledgers; beyond that, ledgers are proven by anchor evidence
47/// saved in storage and a chain of headers.
48const RAW_LEDGERS: u32 = 512;
49/// How far ahead of the latest ledger of known validators validations are
50/// stored: anything further is not our stream or a different network.
51const AHEAD: u32 = 64;
52/// Maximum validations per ledger: the network has dozens of validators.
53const PER_LEDGER: usize = 1024;
54/// How often to reread the list archive.
55const RELOAD_LISTS: Duration = Duration::from_secs(600);
56/// Minimum interval between asking the node about an unknown signing key.
57const MANIFEST_RETRY: Duration = Duration::from_secs(3600);
58const FIRST_MANIFEST_ID: u64 = 1000;
59
60/// Result of checking a ledger.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Verdict {
63    pub confirmed: bool,
64    pub signers: usize,
65    pub quorum: usize,
66    pub unl_size: usize,
67    /// Vote time window used to pick the lists: the evidence bundle
68    /// takes publisher responses from the same window so that bundle verification
69    /// reproduces this decision.
70    pub window: Option<(u32, u32)>,
71}
72
73#[derive(Debug, Default)]
74pub struct Stats {
75    pub connected: bool,
76    pub validations: u64,
77    pub rejected: u64,
78    pub manifests: u64,
79}
80
81#[derive(Debug)]
82struct Lists {
83    seen: Vec<Seen>,
84    manifests: Vec<Manifest>,
85    loaded: Option<Instant>,
86}
87
88/// Verified validation: signing key, hash, full flag, signing time.
89type Checked = (Key, [u8; 32], bool, u32);
90/// Raw validation: bytes, when received (Unix ms), ledger hash, signing key.
91type RawValidation = (Vec<u8>, u64, [u8; 32], Key);
92
93#[derive(Debug)]
94struct Inner {
95    lists: Lists,
96    /// Manifests from the node for keys that are not in the lists.
97    node_manifests: Vec<Manifest>,
98    /// The same manifests as bytes, for evidence bundles.
99    node_manifests_raw: Vec<Vec<u8>>,
100    /// Ledger → raw validations: (bytes, when received, ledger hash).
101    raw: BTreeMap<u32, Vec<RawValidation>>,
102    to_master: HashMap<Key, Key>,
103    /// Validator master keys from the lists: their validations move the retention window.
104    known: BTreeSet<Key>,
105    /// Highest ledger sequence seen in validations from known validators.
106    top: u32,
107    /// Ledger → verified validations: (signing key, hash, full flag, signing time).
108    validations: BTreeMap<u32, Vec<Checked>>,
109    asked: HashMap<Key, Instant>,
110    stats: Stats,
111}
112
113#[derive(Debug, Clone)]
114pub struct Confirmer {
115    publishers: Vec<Key>,
116    unl_dir: PathBuf,
117    inner: Arc<Mutex<Inner>>,
118}
119
120impl Confirmer {
121    pub fn new(publishers: Vec<Key>, unl_dir: PathBuf) -> Confirmer {
122        Confirmer {
123            publishers,
124            unl_dir,
125            inner: Arc::new(Mutex::new(Inner {
126                lists: Lists {
127                    seen: Vec::new(),
128                    manifests: Vec::new(),
129                    loaded: None,
130                },
131                node_manifests: Vec::new(),
132                node_manifests_raw: Vec::new(),
133                raw: BTreeMap::new(),
134                to_master: HashMap::new(),
135                known: BTreeSet::new(),
136                top: 0,
137                validations: BTreeMap::new(),
138                asked: HashMap::new(),
139                stats: Stats::default(),
140            })),
141        }
142    }
143
144    fn lock(&self) -> MutexGuard<'_, Inner> {
145        self.inner.lock().unwrap_or_else(|p| p.into_inner())
146    }
147
148    /// Rereads the list archive when due; rebuilds the key mapping.
149    fn refresh_lists(&self, g: &mut Inner) {
150        if g.lists.loaded.is_some_and(|t| t.elapsed() < RELOAD_LISTS) {
151            return;
152        }
153        let mut manifests = Vec::new();
154        let mut problems = Vec::new();
155        match load_lists(
156            &self.unl_dir,
157            &self.publishers,
158            &mut manifests,
159            &mut problems,
160        ) {
161            Ok(seen) => {
162                for p in problems {
163                    warn!("UNL lists: {p}");
164                }
165                g.lists = Lists {
166                    seen,
167                    manifests,
168                    loaded: Some(Instant::now()),
169                };
170                rebuild_masters(g);
171            }
172            Err(e) => {
173                warn!("UNL lists not read: {e}");
174                g.lists.loaded = Some(Instant::now());
175            }
176        }
177    }
178
179    /// Each configured publisher's latest list: publisher, sequence, number of
180    /// validators, expiration (seconds since the XRPL epoch).
181    pub fn latest_lists(&self) -> Vec<(Key, u64, usize, Option<u32>)> {
182        let mut g = self.lock();
183        self.refresh_lists(&mut g);
184        let mut latest: BTreeMap<Key, (u64, usize, Option<u32>)> = BTreeMap::new();
185        for s in &g.lists.seen {
186            let l = &s.list;
187            if latest
188                .get(&l.publisher)
189                .is_none_or(|(seq, _, _)| *seq < l.sequence)
190            {
191                latest.insert(
192                    l.publisher.clone(),
193                    (l.sequence, l.validators.len(), l.expiration),
194                );
195            }
196        }
197        latest
198            .into_iter()
199            .map(|(p, (seq, n, exp))| (p, seq, n, exp))
200            .collect()
201    }
202
203    pub fn stats(&self) -> (bool, u64, u64, u64) {
204        let g = self.lock();
205        (
206            g.stats.connected,
207            g.stats.validations,
208            g.stats.rejected,
209            g.stats.manifests,
210        )
211    }
212
213    /// Accepts a raw validation: the signature must check out.
214    ///
215    /// Only validations from known validators move the retention window;
216    /// otherwise a stranger's valid signature with a distant sequence could
217    /// wipe the buffers and the quorum of the current ledger. Sequences beyond the window, ahead or behind, are not
218    /// stored, and a ledger gets at most `PER_LEDGER` entries. A full
219    /// validation replaces a partial one from the same key for the same hash.
220    pub fn add_validation(&self, raw: &[u8]) -> Result<Key, String> {
221        let v = Validation::parse(raw).map_err(|e| e.to_string());
222        let mut g = self.lock();
223        let v = match v.and_then(|v| v.verify().map(|()| v).map_err(|e| e.to_string())) {
224            Ok(v) => v,
225            Err(e) => {
226                g.stats.rejected += 1;
227                return Err(e);
228            }
229        };
230        g.stats.validations += 1;
231        self.refresh_lists(&mut g);
232        let seq = v.ledger_sequence;
233        let trusted = g
234            .to_master
235            .get(&v.signing_pub_key)
236            .is_some_and(|m| g.known.contains(m));
237        if trusted && seq > g.top {
238            g.top = seq;
239        }
240        if g.top > 0
241            && (seq.saturating_add(KEEP_LEDGERS) < g.top || seq > g.top.saturating_add(AHEAD))
242        {
243            return Ok(v.signing_pub_key);
244        }
245        let now = std::time::SystemTime::now()
246            .duration_since(std::time::UNIX_EPOCH)
247            .map(|d| d.as_millis() as u64)
248            .unwrap_or(0);
249        let entry: Checked = (
250            v.signing_pub_key.clone(),
251            v.ledger_hash,
252            v.is_full(),
253            v.signing_time,
254        );
255        let list = g.validations.entry(seq).or_default();
256        match list
257            .iter()
258            .position(|(k, h, ..)| *k == v.signing_pub_key && *h == v.ledger_hash)
259        {
260            // A repeat does nothing; a full one after a partial one replaces it.
261            Some(i) if list[i].2 || !v.is_full() => {}
262            Some(i) => {
263                list[i] = entry;
264                if let Some(r) = g.raw.get_mut(&seq).and_then(|rs| {
265                    rs.iter_mut()
266                        .find(|r| r.3 == v.signing_pub_key && r.2 == v.ledger_hash)
267                }) {
268                    *r = (raw.to_vec(), now, v.ledger_hash, v.signing_pub_key.clone());
269                }
270            }
271            None if list.len() >= PER_LEDGER => {}
272            None => {
273                list.push(entry);
274                g.raw.entry(seq).or_default().push((
275                    raw.to_vec(),
276                    now,
277                    v.ledger_hash,
278                    v.signing_pub_key.clone(),
279                ));
280            }
281        }
282        // Without known validators (lists not read yet) there is no window:
283        // keep the latest sequences, however many arrive.
284        let newest = if g.top > 0 {
285            g.top
286        } else {
287            g.validations.keys().next_back().copied().unwrap_or(0)
288        };
289        let keep = newest.saturating_sub(RAW_LEDGERS);
290        g.raw = g.raw.split_off(&keep);
291        let keep = newest.saturating_sub(KEEP_LEDGERS);
292        g.validations = g.validations.split_off(&keep);
293        Ok(v.signing_pub_key)
294    }
295
296    /// Whether to ask the node for this signing key's manifest.
297    fn should_ask(&self, signing_key: &Key) -> bool {
298        let mut g = self.lock();
299        self.refresh_lists(&mut g);
300        if g.to_master.contains_key(signing_key) {
301            return false;
302        }
303        match g.asked.get(signing_key) {
304            Some(t) if t.elapsed() < MANIFEST_RETRY => false,
305            _ => {
306                g.asked.insert(signing_key.clone(), Instant::now());
307                true
308            }
309        }
310    }
311
312    /// Manifest from the node: it enters the mapping only if the signatures check out.
313    pub fn add_manifest(&self, raw: &[u8]) {
314        if let Ok(m) = Manifest::parse(raw) {
315            let mut g = self.lock();
316            // The node sends the same manifest on every request.
317            if g.node_manifests_raw.iter().any(|r| r == raw) {
318                return;
319            }
320            g.node_manifests.push(m);
321            g.node_manifests_raw.push(raw.to_vec());
322            g.stats.manifests += 1;
323            rebuild_masters(&mut g);
324        }
325    }
326
327    /// Raw validations of the ledger for this hash: (bytes, when received).
328    pub fn validations_for(&self, sequence: u32, hash: &[u8; 32]) -> Vec<(Vec<u8>, u64)> {
329        self.lock()
330            .raw
331            .get(&sequence)
332            .into_iter()
333            .flatten()
334            .filter(|(_, _, h, _)| h == hash)
335            .map(|(r, t, ..)| (r.clone(), *t))
336            .collect()
337    }
338
339    /// Publisher responses whose lists were in effect at any moment of the window
340    /// `[from, to]` (seconds since the XRPL epoch): (site, body, when first
341    /// seen).
342    pub fn publisher_responses(&self, from: u32, to: u32) -> Vec<(String, Vec<u8>, u64)> {
343        let mut g = self.lock();
344        self.refresh_lists(&mut g);
345        let lists: Vec<_> = g.lists.seen.iter().map(|s| s.list.clone()).collect();
346        let mut out: Vec<(String, Vec<u8>, u64)> = Vec::new();
347        let set = policies_between(&lists, &self.publishers, from, to, 0, &BTreeSet::new());
348        for p in set.policies {
349            for l in p.lists {
350                if let Some(seen) = g
351                    .lists
352                    .seen
353                    .iter()
354                    .find(|s| s.list.publisher == l.publisher && s.list.sequence == l.sequence)
355                    && !out.iter().any(|(_, b, _)| *b == seen.body)
356                {
357                    out.push((seen.site.clone(), seen.body.clone(), seen.first_seen_ms));
358                }
359            }
360        }
361        out
362    }
363
364    /// Manifests from the node as bytes, for validators that rotated keys after the list was published.
365    pub fn node_manifests(&self) -> Vec<Vec<u8>> {
366        self.lock().node_manifests_raw.clone()
367    }
368
369    pub fn publishers(&self) -> Vec<Key> {
370        self.publishers.clone()
371    }
372
373    /// Whether the ledger hash reached a full-UNL quorum under every policy that
374    /// could have been in effect during its vote time window, by the same rule
375    /// as evidence bundle verification (`quorum::decide`).
376    pub fn check(&self, sequence: u32, hash: &[u8; 32]) -> Verdict {
377        let mut g = self.lock();
378        self.refresh_lists(&mut g);
379        let lists: Vec<_> = g.lists.seen.iter().map(|s| s.list.clone()).collect();
380        let vals = g
381            .validations
382            .get(&sequence)
383            .map(Vec::as_slice)
384            .unwrap_or_default();
385        let observed: Vec<Observed> = vals
386            .iter()
387            .map(|(k, h, full, t)| Observed {
388                signing_key: k.clone(),
389                master_key: g.to_master.get(k).cloned(),
390                ledger_hash: *h,
391                full: *full,
392                signing_time: *t,
393            })
394            .collect();
395        Self::verdict_of(&lists, &self.publishers, &observed, hash)
396    }
397
398    /// The same decision from raw validations, for anchor evidence from
399    /// storage: unparseable ones and ones with bad signatures are not counted.
400    pub fn check_raw(&self, sequence: u32, raws: &[Vec<u8>], hash: &[u8; 32]) -> Verdict {
401        let mut g = self.lock();
402        self.refresh_lists(&mut g);
403        let lists: Vec<_> = g.lists.seen.iter().map(|s| s.list.clone()).collect();
404        let observed: Vec<Observed> = raws
405            .iter()
406            .filter_map(|r| Validation::parse(r).ok())
407            .filter(|v| v.verify().is_ok() && v.ledger_sequence == sequence)
408            .map(|v| Observed {
409                master_key: g.to_master.get(&v.signing_pub_key).cloned(),
410                full: v.is_full(),
411                ledger_hash: v.ledger_hash,
412                signing_time: v.signing_time,
413                signing_key: v.signing_pub_key,
414            })
415            .collect();
416        Self::verdict_of(&lists, &self.publishers, &observed, hash)
417    }
418
419    fn verdict_of(
420        lists: &[witness_core::quorum::PublishedList],
421        publishers: &[Key],
422        observed: &[Observed],
423        hash: &[u8; 32],
424    ) -> Verdict {
425        let d = decide(lists, publishers, 0, &BTreeSet::new(), observed, hash);
426        Verdict {
427            confirmed: d.confirmed,
428            signers: d
429                .assessed
430                .iter()
431                .map(|a| a.by_hash.get(hash).map_or(0, BTreeSet::len))
432                .min()
433                .unwrap_or(0),
434            quorum: d.assessed.iter().map(|a| a.quorum).max().unwrap_or(0),
435            unl_size: d.assessed.iter().map(|a| a.unl_size).max().unwrap_or(0),
436            window: d.window,
437        }
438    }
439}
440
441#[cfg(test)]
442fn verdict(policy: &Policy, observed: &[Observed], hash: &[u8; 32]) -> Verdict {
443    let a = witness_core::quorum::assess(policy, observed);
444    Verdict {
445        confirmed: a.confirmed.as_ref() == Some(hash),
446        signers: a.by_hash.get(hash).map_or(0, BTreeSet::len),
447        quorum: a.quorum,
448        unl_size: a.unl_size,
449        window: None,
450    }
451}
452
453fn rebuild_masters(g: &mut Inner) {
454    let mut all = g.lists.manifests.clone();
455    all.extend(g.node_manifests.iter().cloned());
456    g.to_master = signing_to_master(&all).0;
457    g.known = g
458        .lists
459        .seen
460        .iter()
461        .flat_map(|s| s.list.validators.iter().cloned())
462        .collect();
463}
464
465/// Listens to the node's validation stream for the life of the process; reconnects on drop.
466/// Messages of the node's `validations` and `manifests` streams, as received,
467/// for clients subscribed to them (`subs::forward_streams`).
468pub type NodeStreams = tokio::sync::broadcast::Sender<Arc<str>>;
469
470pub async fn listen(url: String, confirmer: Confirmer, streams: Option<NodeStreams>) {
471    let mut backoff = Duration::from_secs(1);
472    loop {
473        match session(&url, &confirmer, streams.as_ref()).await {
474            Ok(()) => backoff = Duration::from_secs(1),
475            Err(e) => warn!("validations {url}: {e}"),
476        }
477        confirmer.lock().stats.connected = false;
478        tokio::time::sleep(backoff).await;
479        backoff = (backoff * 2).min(Duration::from_secs(60));
480    }
481}
482
483async fn session(url: &str, c: &Confirmer, streams: Option<&NodeStreams>) -> Result<(), String> {
484    let (mut ws, _) = connect_async(url).await.map_err(|e| e.to_string())?;
485    let subscribe =
486        json!({"id": 1, "command": "subscribe", "streams": ["validations", "manifests"]});
487    ws.send(Message::text(subscribe.to_string()))
488        .await
489        .map_err(|e| e.to_string())?;
490    info!("validations: connected to {url}");
491    c.lock().stats.connected = true;
492    let mut next_id = FIRST_MANIFEST_ID;
493    let mut last = Instant::now();
494    let mut tick = tokio::time::interval(Duration::from_secs(5));
495    loop {
496        tokio::select! {
497            msg = ws.next() => {
498                let text = match msg {
499                    Some(Ok(Message::Text(t))) => t,
500                    Some(Ok(Message::Close(_))) | None => return Err("connection closed".into()),
501                    Some(Ok(_)) => continue,
502                    Some(Err(e)) => return Err(e.to_string()),
503                };
504                let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };
505                let kind = v.get("type").and_then(Value::as_str);
506                if let Some(s) = streams
507                    && matches!(kind, Some("validationReceived" | "manifestReceived"))
508                {
509                    // No receivers is not an error: nobody is subscribed.
510                    let _ = s.send(Arc::from(text.as_str()));
511                }
512                if kind == Some("validationReceived") {
513                    last = Instant::now();
514                    let Some(raw) = v.get("data").and_then(Value::as_str).and_then(|d| hex::decode(d).ok()) else {
515                        continue;
516                    };
517                    if let Ok(key) = c.add_validation(&raw)
518                        && c.should_ask(&key)
519                    {
520                        let req = json!({"id": next_id, "command": "manifest", "public_key": node_public(&key)});
521                        next_id += 1;
522                        ws.send(Message::text(req.to_string())).await.map_err(|e| e.to_string())?;
523                    }
524                } else if v.get("id").and_then(Value::as_u64).is_some_and(|id| id >= FIRST_MANIFEST_ID)
525                    && let Some(raw) = v
526                        .get("result")
527                        .and_then(|r| r.get("manifest"))
528                        .and_then(Value::as_str)
529                        .and_then(|m| base64::engine::general_purpose::STANDARD.decode(m).ok())
530                {
531                    c.add_manifest(&raw);
532                }
533            }
534            _ = tick.tick() => {
535                // Validations arrive several times a second: a minute of silence
536                // means the stream died silently.
537                if last.elapsed() > Duration::from_secs(60) {
538                    return Err("no validations for a minute".into());
539                }
540            }
541        }
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use witness_core::quorum::PublishedList;
549
550    #[test]
551    fn verdict_needs_quorum_of_full_unl() {
552        let unl: BTreeSet<Key> = (0..10u8).map(|i| vec![i]).collect();
553        let policy = Policy {
554            lists: vec![PublishedList {
555                publisher: vec![0xED],
556                sequence: 1,
557                validators: unl,
558                effective: None,
559                expiration: None,
560                manifest_sequence: 1,
561            }],
562            threshold: 1,
563            local: BTreeSet::new(),
564            negative_unl: BTreeSet::new(),
565        };
566        let hash = [7u8; 32];
567        let obs = |n: u8| -> Vec<Observed> {
568            (0..n)
569                .map(|i| Observed {
570                    signing_key: vec![i],
571                    master_key: Some(vec![i]),
572                    ledger_hash: hash,
573                    full: true,
574                    signing_time: 100,
575                })
576                .collect()
577        };
578        let v = verdict(&policy, &obs(7), &hash);
579        assert_eq!((v.confirmed, v.quorum, v.signers), (false, 8, 7));
580        assert!(verdict(&policy, &obs(8), &hash).confirmed);
581        // A quorum for a different hash does not confirm ours.
582        assert!(!verdict(&policy, &obs(8), &[1u8; 32]).confirmed);
583    }
584
585    /// A real mainnet ledger, 107 855 813: validations and publisher responses
586    /// from a witness-core evidence bundle.
587    #[test]
588    fn real_ledger_is_confirmed_and_a_forged_hash_is_not() {
589        let b: Value = serde_json::from_str(include_str!(
590            "../../witness-core/tests/fixtures/evidence-107855813.json"
591        ))
592        .unwrap();
593        let dir = tempfile::tempdir().unwrap();
594        for (i, r) in b["publisher_responses"]
595            .as_array()
596            .unwrap()
597            .iter()
598            .enumerate()
599        {
600            let site = dir.path().join(r["site"].as_str().unwrap());
601            std::fs::create_dir_all(&site).unwrap();
602            let body = base64::engine::general_purpose::STANDARD
603                .decode(r["body"].as_str().unwrap())
604                .unwrap();
605            std::fs::write(site.join(format!("{i}.json")), body).unwrap();
606        }
607        let publishers: Vec<Key> = [
608            "ED2677ABFFD1B33AC6FBC3062B71F1E8397C1505E1C42C64D11AD1B28FF73F4734",
609            "ED42AEC58B701EEBB77356FFFEC26F83C1F0407263530F068C7C73D392C7E06FD1",
610        ]
611        .iter()
612        .map(|h| hex::decode(h).unwrap())
613        .collect();
614        let c = Confirmer::new(publishers, dir.path().to_path_buf());
615        let seq = u32::try_from(b["ledger_index"].as_u64().unwrap()).unwrap();
616        let hash: [u8; 32] = hex::decode(b["ledger_hash"].as_str().unwrap())
617            .unwrap()
618            .try_into()
619            .unwrap();
620        // Without validations there is nothing to confirm with.
621        assert!(!c.check(seq, &hash).confirmed);
622        for v in b["validations"].as_array().unwrap() {
623            let _ = c.add_validation(&hex::decode(v["data"].as_str().unwrap()).unwrap());
624        }
625        let v = c.check(seq, &hash);
626        assert!(v.confirmed, "{v:?}");
627        assert_eq!((v.unl_size, v.quorum), (35, 28));
628        // A chain the source built itself won't reach quorum.
629        assert!(!c.check(seq, &[0x42; 32]).confirmed);
630        // A corrupted signature is rejected.
631        let mut bad = hex::decode(b["validations"][0]["data"].as_str().unwrap()).unwrap();
632        let n = bad.len();
633        bad[n - 1] ^= 1;
634        assert!(c.add_validation(&bad).is_err());
635
636        // A genuine signature from a stranger's key with a distant sequence
637        // does not move the retention window or wipe the quorum.
638        let raw_before = c.validations_for(seq, &hash).len();
639        for far in [seq + 1_000_000, seq.saturating_sub(100_000), u32::MAX] {
640            assert!(
641                c.add_validation(&foreign(far, true, 77, [9; 32], 1))
642                    .is_ok()
643            );
644        }
645        assert!(c.check(seq, &hash).confirmed);
646        assert_eq!(c.validations_for(seq, &hash).len(), raw_before);
647        assert!(
648            c.lock()
649                .validations
650                .keys()
651                .all(|k| k.abs_diff(seq) <= KEEP_LEDGERS)
652        );
653    }
654
655    /// Signed validation from the test key `seed`.
656    fn foreign(seq: u32, full: bool, seed: u8, hash: [u8; 32], time: u32) -> Vec<u8> {
657        use ed25519_dalek::{Signer, SigningKey};
658        let k = SigningKey::from_bytes(&[seed; 32]);
659        let mut pk = vec![0xED];
660        pk.extend(k.verifying_key().to_bytes());
661        let mut fields = vec![0x22];
662        fields.extend(u32::from(full).to_be_bytes());
663        fields.push(0x26);
664        fields.extend(seq.to_be_bytes());
665        fields.push(0x29);
666        fields.extend(time.to_be_bytes());
667        fields.push(0x51);
668        fields.extend(hash);
669        fields.push(0x73);
670        fields.push(pk.len() as u8);
671        fields.extend(&pk);
672        let mut data = b"VAL\x00".to_vec();
673        data.extend(&fields);
674        let sig = k.sign(&data).to_bytes();
675        fields.push(0x76);
676        fields.push(sig.len() as u8);
677        fields.extend(sig);
678        fields
679    }
680
681    /// A full validation after a partial one from the same key for the same
682    /// hash replaces it, and a partial one after a full one breaks nothing.
683    #[test]
684    fn full_validation_replaces_partial() {
685        let dir = tempfile::tempdir().unwrap();
686        let c = Confirmer::new(Vec::new(), dir.path().to_path_buf());
687        let full_of = |c: &Confirmer| -> Vec<bool> {
688            c.lock().validations[&100].iter().map(|v| v.2).collect()
689        };
690        c.add_validation(&foreign(100, false, 5, [1; 32], 10))
691            .unwrap();
692        assert_eq!(full_of(&c), vec![false]);
693        let full = foreign(100, true, 5, [1; 32], 11);
694        c.add_validation(&full).unwrap();
695        assert_eq!(full_of(&c), vec![true]);
696        assert_eq!(c.validations_for(100, &[1; 32]).len(), 1);
697        assert_eq!(c.validations_for(100, &[1; 32])[0].0, full);
698        c.add_validation(&foreign(100, false, 5, [1; 32], 12))
699            .unwrap();
700        assert_eq!(full_of(&c), vec![true]);
701        assert_eq!(c.validations_for(100, &[1; 32])[0].0, full);
702    }
703}