Skip to main content

witness_core/
quorum.rs

1//! Quorum check: whether a ledger is confirmed by the validators that a given
2//! policy trusts.
3//!
4//! This is a separate claim from "the signature is valid". It is always
5//! relative to a trust policy (which UNL publishers we accept, how many lists
6//! must contain a key, who is temporarily disabled via the Negative UNL) and
7//! means nothing without that policy being stated.
8//!
9//! The calculation follows xrpld (`ValidatorList::calculateQuorum`): 80% of
10//! the effective validators (the UNL minus those disabled by the Negative UNL),
11//! but no less than 60% of the full UNL. It is computed in `float`, as there:
12//! rounding at the boundaries depends on it.
13//!
14//! What the check does not claim. If a trusted validator is not found among
15//! the signers, that means "we did not see its validation", not "it did not
16//! vote": a collector can miss validations.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20/// A key: the raw 33 bytes of a public key.
21pub type Key = Vec<u8>;
22
23/// How many lists must contain a key if no threshold is set. As in xrpld:
24/// with one or two publishers one list is enough, otherwise a majority.
25pub fn default_threshold(publishers: usize) -> usize {
26    if publishers < 3 {
27        1
28    } else {
29        publishers / 2 + 1
30    }
31}
32
33/// The xrpld quorum for a UNL of size `unl` with `effective` effective validators.
34pub fn quorum(unl: usize, effective: usize) -> usize {
35    let by_effective = (effective as f32 * 0.8f32).ceil();
36    let floor = (unl as f32 * 0.6f32).ceil();
37    by_effective.max(floor) as usize
38}
39
40/// One publisher list, with its signature already verified.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct PublishedList {
43    pub publisher: Key,
44    pub sequence: u64,
45    /// Master keys of the validators in the list.
46    pub validators: BTreeSet<Key>,
47    /// When it takes effect (v2 lists only), seconds since the XRPL epoch.
48    pub effective: Option<u32>,
49    /// When it expires, seconds since the XRPL epoch.
50    pub expiration: Option<u32>,
51    /// Sequence of the publisher manifest the list is signed under: lists
52    /// signed with a rotated publisher key are not counted.
53    pub manifest_sequence: u32,
54}
55
56impl PublishedList {
57    /// Whether the list is in effect at any moment of the window `[from, to]`.
58    pub fn valid_between(&self, from: u32, to: u32) -> bool {
59        self.effective.is_none_or(|e| e <= to) && self.expiration.is_none_or(|x| from < x)
60    }
61}
62
63/// The trust policy for a specific ledger.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Policy {
66    pub lists: Vec<PublishedList>,
67    pub threshold: usize,
68    /// Keys trusted directly, without a publisher: the `[validators]` section
69    /// of the xrpld config. The list threshold does not apply to them.
70    pub local: BTreeSet<Key>,
71    /// Master keys disabled by the Negative UNL on this ledger.
72    pub negative_unl: BTreeSet<Key>,
73}
74
75impl Policy {
76    /// Trusted: keys present in at least `threshold` lists, plus those
77    /// trusted directly.
78    pub fn trusted(&self) -> BTreeSet<Key> {
79        let mut count: BTreeMap<&Key, usize> = BTreeMap::new();
80        for l in &self.lists {
81            for k in &l.validators {
82                *count.entry(k).or_default() += 1;
83            }
84        }
85        count
86            .into_iter()
87            .filter(|&(_, n)| n >= self.threshold)
88            .map(|(k, _)| k.clone())
89            .chain(self.local.iter().cloned())
90            .collect()
91    }
92
93    /// Effective: trusted minus those disabled by the Negative UNL.
94    pub fn effective(&self) -> BTreeSet<Key> {
95        self.trusted()
96            .difference(&self.negative_unl)
97            .cloned()
98            .collect()
99    }
100}
101
102/// A validation for one ledger, with its signature already verified.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Observed {
105    pub signing_key: Key,
106    /// Master key from the manifest; `None` means there is no manifest and the
107    /// validator is not identified.
108    pub master_key: Option<Key>,
109    pub ledger_hash: [u8; 32],
110    pub full: bool,
111    /// Signing time from the validation itself, seconds since the XRPL epoch.
112    pub signing_time: u32,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct Assessment {
117    pub unl_size: usize,
118    pub effective_size: usize,
119    pub quorum: usize,
120    /// For each hash, the effective validators that signed it with a full
121    /// validation.
122    pub by_hash: BTreeMap<[u8; 32], BTreeSet<Key>>,
123    /// The hash that reached quorum, if any.
124    pub confirmed: Option<[u8; 32]>,
125    /// Effective validators whose validation we did not see.
126    pub not_seen: BTreeSet<Key>,
127    /// Effective validators that signed more than one hash.
128    pub conflicting: BTreeSet<Key>,
129    /// Signing keys without a manifest: we do not know whose they are.
130    pub unattributed: BTreeSet<Key>,
131    /// Signatures from validators disabled by the Negative UNL: not counted toward quorum.
132    pub from_negative_unl: BTreeSet<Key>,
133}
134
135/// The policies that could have been in effect, and the publishers that have
136/// no list in effect for that time.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct PolicySet {
139    pub policies: Vec<Policy>,
140    /// Configured publishers without a list in effect. If this is not empty the
141    /// policy is incomplete and nothing can be confirmed: without a publisher's
142    /// list the UNL is smaller, and the quorum would be computed from a smaller number.
143    pub missing: Vec<Key>,
144}
145
146/// All policies that could have been in effect at any moment of the window
147/// `[from, to]` (seconds since the XRPL epoch): for each publisher, the lists
148/// signed under its latest manifest and in effect within the window. Which of
149/// them the network used cannot be known without a signed publication time, so
150/// every combination is returned, and confirmation must hold for each one.
151pub fn policies_between(
152    lists: &[PublishedList],
153    publishers: &[Key],
154    from: u32,
155    to: u32,
156    threshold: usize,
157    local: &BTreeSet<Key>,
158) -> PolicySet {
159    let threshold = if threshold == 0 {
160        default_threshold(publishers.len())
161    } else {
162        threshold
163    };
164    let mut combos: Vec<Vec<PublishedList>> = vec![Vec::new()];
165    let mut missing = Vec::new();
166    for p in publishers {
167        let mine: Vec<&PublishedList> = lists.iter().filter(|l| &l.publisher == p).collect();
168        let top = mine.iter().map(|l| l.manifest_sequence).max();
169        let mut candidates: Vec<PublishedList> = Vec::new();
170        for l in mine {
171            if Some(l.manifest_sequence) == top
172                && l.valid_between(from, to)
173                && !candidates.iter().any(|c| c.sequence == l.sequence)
174            {
175                candidates.push(l.clone());
176            }
177        }
178        if candidates.is_empty() {
179            missing.push(p.clone());
180            continue;
181        }
182        combos = combos
183            .into_iter()
184            .flat_map(|c| {
185                candidates.iter().map(move |l| {
186                    let mut c = c.clone();
187                    c.push(l.clone());
188                    c
189                })
190            })
191            .collect();
192    }
193    PolicySet {
194        policies: combos
195            .into_iter()
196            .map(|lists| Policy {
197                lists,
198                threshold,
199                local: local.clone(),
200                negative_unl: BTreeSet::new(),
201            })
202            .collect(),
203        missing,
204    }
205}
206
207/// The decision for a ledger hash: the time window, the policies and the outcome for each.
208#[derive(Debug, Clone)]
209pub struct Decision {
210    /// The vote time window: from the earliest to the latest signing time of full
211    /// validations for this hash from known validators. `None` if there are none.
212    pub window: Option<(u32, u32)>,
213    pub set: PolicySet,
214    pub assessed: Vec<Assessment>,
215    /// The hash reached quorum under every policy of the window, and the policy is complete.
216    pub confirmed: bool,
217}
218
219/// Whether `hash` is confirmed under the verifier's policy. One rule shared by
220/// offline bundle verification and confirmation at load time.
221///
222/// The time used to pick lists is the window of signed vote times for this
223/// hash, not the median: duplicates and the order of validations do not change
224/// the window, and every list in effect at any moment of the window must give
225/// the same answer. A publisher with no list in effect in the window makes the
226/// policy incomplete, and there is no confirmation.
227pub fn decide(
228    lists: &[PublishedList],
229    publishers: &[Key],
230    threshold: usize,
231    local: &BTreeSet<Key>,
232    observed: &[Observed],
233    hash: &[u8; 32],
234) -> Decision {
235    let known: BTreeSet<&Key> = lists
236        .iter()
237        .flat_map(|l| l.validators.iter())
238        .chain(local.iter())
239        .collect();
240    let times = observed
241        .iter()
242        .filter(|o| o.full && o.ledger_hash == *hash)
243        .filter(|o| o.master_key.as_ref().is_some_and(|m| known.contains(m)))
244        .map(|o| o.signing_time);
245    let window = times.fold(None, |w: Option<(u32, u32)>, t| {
246        Some(w.map_or((t, t), |(a, b)| (a.min(t), b.max(t))))
247    });
248    let Some((from, to)) = window else {
249        return Decision {
250            window,
251            set: PolicySet {
252                policies: Vec::new(),
253                missing: Vec::new(),
254            },
255            assessed: Vec::new(),
256            confirmed: false,
257        };
258    };
259    let set = policies_between(lists, publishers, from, to, threshold, local);
260    let assessed: Vec<Assessment> = set.policies.iter().map(|p| assess(p, observed)).collect();
261    let confirmed = set.missing.is_empty()
262        && !assessed.is_empty()
263        && assessed.iter().all(|a| a.confirmed == Some(*hash));
264    Decision {
265        window,
266        set,
267        assessed,
268        confirmed,
269    }
270}
271
272pub fn assess(policy: &Policy, observed: &[Observed]) -> Assessment {
273    let trusted = policy.trusted();
274    let effective = policy.effective();
275    let mut by_hash: BTreeMap<[u8; 32], BTreeSet<Key>> = BTreeMap::new();
276    let mut hashes_of: BTreeMap<Key, BTreeSet<[u8; 32]>> = BTreeMap::new();
277    let mut unattributed = BTreeSet::new();
278    let mut from_negative_unl = BTreeSet::new();
279    for o in observed {
280        let Some(master) = &o.master_key else {
281            unattributed.insert(o.signing_key.clone());
282            continue;
283        };
284        if policy.negative_unl.contains(master) {
285            from_negative_unl.insert(master.clone());
286            continue;
287        }
288        if !effective.contains(master) {
289            continue;
290        }
291        hashes_of
292            .entry(master.clone())
293            .or_default()
294            .insert(o.ledger_hash);
295        // Only full validations count toward quorum: a partial one means "I saw
296        // this ledger", not "I accept it".
297        if o.full {
298            by_hash
299                .entry(o.ledger_hash)
300                .or_default()
301                .insert(master.clone());
302        }
303    }
304    let q = quorum(trusted.len(), effective.len());
305    let confirmed = by_hash
306        .iter()
307        .find(|(_, signers)| signers.len() >= q)
308        .map(|(h, _)| *h);
309    let not_seen = effective
310        .iter()
311        .filter(|k| !hashes_of.contains_key(*k))
312        .cloned()
313        .collect();
314    let conflicting = hashes_of
315        .into_iter()
316        .filter(|(_, hs)| hs.len() > 1)
317        .map(|(k, _)| k)
318        .collect();
319    Assessment {
320        unl_size: trusted.len(),
321        effective_size: effective.len(),
322        quorum: q,
323        by_hash,
324        confirmed,
325        not_seen,
326        conflicting,
327        unattributed,
328        from_negative_unl,
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    fn list(
337        publisher: u8,
338        seq: u64,
339        keys: &[u8],
340        effective: Option<u32>,
341        expiration: Option<u32>,
342        manifest: u32,
343    ) -> PublishedList {
344        PublishedList {
345            publisher: vec![publisher],
346            sequence: seq,
347            validators: keys.iter().map(|k| vec![*k]).collect(),
348            effective,
349            expiration,
350            manifest_sequence: manifest,
351        }
352    }
353
354    #[test]
355    fn lists_are_chosen_by_ledger_time() {
356        let lists = vec![
357            list(1, 10, &[1, 2], None, Some(100), 1), // expired by 150
358            list(1, 11, &[1, 2, 3], None, Some(200), 1), // in effect
359            list(1, 12, &[1, 4], Some(180), Some(300), 1), // takes effect later
360            list(1, 13, &[9], None, Some(500), 0),    // old publisher key
361            list(2, 5, &[5], None, Some(400), 2),
362            list(2, 6, &[5, 6], None, Some(400), 2), // also in effect
363        ];
364        let ps = policies_between(&lists, &[vec![1], vec![2]], 150, 150, 0, &BTreeSet::new());
365        assert!(ps.missing.is_empty());
366        let got: Vec<Vec<u64>> = ps
367            .policies
368            .iter()
369            .map(|p| p.lists.iter().map(|l| l.sequence).collect())
370            .collect();
371        assert_eq!(got, vec![vec![11, 5], vec![11, 6]]);
372        // Once all lists of the first publisher expire, the policy is incomplete.
373        let ps = policies_between(&lists, &[vec![1], vec![2]], 350, 350, 0, &BTreeSet::new());
374        assert_eq!(ps.missing, vec![vec![1]]);
375        // The 150..190 window also covers list 12, which takes effect at 180.
376        let ps = policies_between(&lists, &[vec![1], vec![2]], 150, 190, 0, &BTreeSet::new());
377        assert_eq!(ps.policies.len(), 4);
378    }
379
380    #[test]
381    fn quorum_matches_xrpld() {
382        // 2026-10-23: two lists of 35 give 36 trusted validators, and the node
383        // reports validation_quorum 29.
384        assert_eq!(quorum(36, 36), 29);
385        assert_eq!(quorum(35, 35), 28);
386        // The Negative UNL disabled two: 80% of 33.
387        assert_eq!(quorum(35, 33), 27);
388        // Too many disabled: the 60%-of-UNL floor kicks in.
389        assert_eq!(quorum(35, 20), 21);
390        assert_eq!(default_threshold(1), 1);
391        assert_eq!(default_threshold(2), 1);
392        assert_eq!(default_threshold(3), 2);
393        assert_eq!(default_threshold(4), 3);
394    }
395
396    fn key(i: u8) -> Key {
397        vec![i; 33]
398    }
399
400    fn policy(n: u8, negative: &[u8]) -> Policy {
401        Policy {
402            lists: vec![PublishedList {
403                publisher: key(200),
404                sequence: 1,
405                validators: (0..n).map(key).collect(),
406                effective: None,
407                expiration: None,
408                manifest_sequence: 1,
409            }],
410            threshold: 1,
411            local: BTreeSet::new(),
412            negative_unl: negative.iter().map(|&i| key(i)).collect(),
413        }
414    }
415
416    fn signed(i: u8, hash: u8, full: bool) -> Observed {
417        signed_at(i, hash, full, 100)
418    }
419
420    fn signed_at(i: u8, hash: u8, full: bool, signing_time: u32) -> Observed {
421        Observed {
422            signing_key: key(100 + i),
423            master_key: Some(key(i)),
424            ledger_hash: [hash; 32],
425            full,
426            signing_time,
427        }
428    }
429
430    fn listed(
431        publisher: u8,
432        seq: u64,
433        n: u8,
434        effective: Option<u32>,
435        exp: Option<u32>,
436    ) -> PublishedList {
437        PublishedList {
438            publisher: key(publisher),
439            sequence: seq,
440            validators: (0..n).map(key).collect(),
441            effective,
442            expiration: exp,
443            manifest_sequence: 1,
444        }
445    }
446
447    /// The first publisher has 5 validators, the second 10, and there are
448    /// four signatures. With both lists it is not confirmed; without the second
449    /// publisher's response it used to come out "confirmed" with quorum 4.
450    #[test]
451    fn missing_publisher_is_not_a_smaller_unl() {
452        let (a, b) = (
453            listed(200, 1, 5, None, None),
454            listed(201, 1, 10, None, None),
455        );
456        let pubs = [key(200), key(201)];
457        let obs: Vec<_> = (0..4).map(|i| signed(i, 1, true)).collect();
458        let both = decide(&[a.clone(), b], &pubs, 0, &BTreeSet::new(), &obs, &[1; 32]);
459        assert!(!both.confirmed);
460        assert_eq!(both.assessed[0].quorum, 8);
461        let one = decide(&[a], &pubs, 0, &BTreeSet::new(), &obs, &[1; 32]);
462        assert!(!one.confirmed);
463        assert_eq!(one.set.missing, vec![key(201)]);
464    }
465
466    /// An old list of 5 expires at 150, a new list of 10 is in effect from 150;
467    /// signatures at 149, 150, 150, 150. Duplicates of one validation no longer
468    /// shift the time toward the old list.
469    #[test]
470    fn duplicates_do_not_move_policy_time() {
471        let lists = [
472            listed(200, 1, 5, None, Some(150)),
473            listed(200, 2, 10, Some(150), None),
474        ];
475        let pubs = [key(200)];
476        let mut obs = vec![
477            signed_at(0, 1, true, 149),
478            signed_at(1, 1, true, 150),
479            signed_at(2, 1, true, 150),
480            signed_at(3, 1, true, 150),
481        ];
482        let base = decide(&lists, &pubs, 0, &BTreeSet::new(), &obs, &[1; 32]);
483        assert!(!base.confirmed);
484        assert_eq!(base.window, Some((149, 150)));
485        for _ in 0..4 {
486            obs.push(obs[0].clone());
487        }
488        let dup = decide(&lists, &pubs, 0, &BTreeSet::new(), &obs, &[1; 32]);
489        assert!(!dup.confirmed);
490        assert_eq!(dup.window, base.window);
491        obs.reverse();
492        assert!(!decide(&lists, &pubs, 0, &BTreeSet::new(), &obs, &[1; 32]).confirmed);
493        // The window touches both lists: confirmation only if both agree.
494        let all: Vec<_> = (0..10)
495            .map(|i| signed_at(i, 1, true, 149 + u32::from(i % 2)))
496            .collect();
497        let ok = decide(&lists, &pubs, 0, &BTreeSet::new(), &all, &[1; 32]);
498        assert!(ok.confirmed);
499        assert_eq!(ok.set.policies.len(), 2);
500    }
501
502    #[test]
503    fn ledger_is_confirmed_at_quorum_and_not_below() {
504        let p = policy(10, &[]);
505        assert_eq!(quorum(10, 10), 8);
506        let eight: Vec<_> = (0..8).map(|i| signed(i, 1, true)).collect();
507        let a = assess(&p, &eight);
508        assert_eq!(a.confirmed, Some([1; 32]));
509        assert_eq!(a.not_seen.len(), 2);
510        let seven = &eight[..7];
511        assert_eq!(assess(&p, seven).confirmed, None);
512    }
513
514    #[test]
515    fn partial_validations_do_not_count_but_are_seen() {
516        let p = policy(10, &[]);
517        let mut obs: Vec<_> = (0..7).map(|i| signed(i, 1, true)).collect();
518        obs.push(signed(7, 1, false));
519        let a = assess(&p, &obs);
520        assert_eq!(a.confirmed, None);
521        assert_eq!(a.not_seen.len(), 2);
522    }
523
524    #[test]
525    fn negative_unl_lowers_quorum_and_its_votes_do_not_count() {
526        // Two are disabled: the quorum, 80% of 8, is 7.
527        let p = policy(10, &[8, 9]);
528        let mut obs: Vec<_> = (0..7).map(|i| signed(i, 1, true)).collect();
529        obs.push(signed(9, 1, true));
530        let a = assess(&p, &obs);
531        assert_eq!(a.quorum, 7);
532        assert_eq!(a.effective_size, 8);
533        assert_eq!(a.confirmed, Some([1; 32]));
534        assert!(a.from_negative_unl.contains(&key(9)));
535        assert_eq!(a.by_hash[&[1; 32]].len(), 7);
536    }
537
538    #[test]
539    fn conflicts_and_unknown_keys_are_reported() {
540        let p = policy(10, &[]);
541        let mut obs: Vec<_> = (0..8).map(|i| signed(i, 1, true)).collect();
542        obs.push(signed(0, 2, true));
543        obs.push(Observed {
544            signing_key: key(150),
545            master_key: None,
546            ledger_hash: [1; 32],
547            full: true,
548            signing_time: 100,
549        });
550        let a = assess(&p, &obs);
551        assert_eq!(a.confirmed, Some([1; 32]));
552        assert!(a.conflicting.contains(&key(0)));
553        assert!(a.unattributed.contains(&key(150)));
554    }
555
556    #[test]
557    fn threshold_two_of_three_lists() {
558        let mk = |ks: &[u8]| PublishedList {
559            publisher: key(200),
560            sequence: 1,
561            validators: ks.iter().map(|&i| key(i)).collect(),
562            effective: None,
563            expiration: None,
564            manifest_sequence: 1,
565        };
566        let p = Policy {
567            lists: vec![mk(&[1, 2, 3]), mk(&[2, 3, 4]), mk(&[3, 4, 5])],
568            threshold: 2,
569            local: [9].iter().map(|&i| key(i)).collect(),
570            negative_unl: BTreeSet::new(),
571        };
572        // Key 9 is trusted directly, so the list threshold does not apply to it.
573        assert_eq!(
574            p.trusted(),
575            [2, 3, 4, 9]
576                .iter()
577                .map(|&i| key(i))
578                .collect::<BTreeSet<_>>()
579        );
580    }
581}