Skip to main content

witness_store/
seal.rs

1//! Seal of a closed segment.
2//!
3//! A seal commits to the segment's content (the uncompressed bytes) and
4//! references the hash of the previous seal. The seal chain makes the archive
5//! immutable after the fact: replacing any segment, or removing one from the
6//! middle, breaks every hash that follows.
7//!
8//! Compression is not part of the seal; it is a storage detail. A segment can
9//! be recompressed at another level or with another codec without changing
10//! the chain, and the check is always the same: decompress and compare the
11//! content hash.
12//!
13//! A seal is plain JSON next to the segment, so it can be read by eye and
14//! checked with any tool. The seal hash is SHA-512Half of its canonical JSON
15//! without the `seal_hash` field; field order is fixed by the struct order.
16
17use serde::{Deserialize, Serialize};
18use witness_core::sha512_half;
19
20pub const FORMAT: &str = "xrpl-witness/validations-segment/1";
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Seal {
24    pub format: String,
25    /// Which of our machines received these validations.
26    pub source: String,
27    /// Nominal range of the segment: [nominal_first, nominal_last].
28    pub nominal_first: u32,
29    pub nominal_last: u32,
30    /// Lowest and highest ledgers among records from our network. Late
31    /// validations from earlier ranges and early ones from the next range
32    /// also land here.
33    pub first_ledger: u32,
34    pub last_ledger: u32,
35    pub records: u64,
36    /// How many of `records` are far from the network's current ledger:
37    /// validations from other networks that leaked in through peer relaying,
38    /// or ones that arrived very late. They are stored, but do not count
39    /// toward completeness or the first/last ledgers.
40    pub out_of_window: u64,
41    /// The span this segment is responsible for keeping complete: from the
42    /// ledger after the last one in the previous seal up to its own last
43    /// ledger. Spans of adjacent segments meet with no gaps or overlaps, so
44    /// archiver downtime shows up as a gap in the next seal instead of
45    /// vanishing between them.
46    pub coverage_first: u32,
47    pub coverage_last: u32,
48    /// Ledgers in the coverage span for which no validation arrived at all,
49    /// as [from, to] ranges. A direct measure of completeness.
50    pub missing_ledgers: Vec<[u32; 2]>,
51    pub opened_ms: u64,
52    pub sealed_ms: u64,
53    /// Uncompressed size of the segment content.
54    pub raw_bytes: u64,
55    /// SHA-512Half of the uncompressed segment content, in hex.
56    pub raw_hash: String,
57    /// Hash of this source's previous seal; `None` for the very first one.
58    pub prev_seal_hash: Option<String>,
59    pub seal_hash: String,
60}
61
62impl Seal {
63    /// Seal hash: over all fields except `seal_hash` itself.
64    pub fn compute_hash(&self) -> String {
65        let mut unsealed = self.clone();
66        unsealed.seal_hash = String::new();
67        let canonical = serde_json::to_vec(&unsealed).unwrap_or_default();
68        hex::encode_upper(sha512_half(&canonical))
69    }
70
71    pub fn finalize(mut self) -> Seal {
72        self.seal_hash = self.compute_hash();
73        self
74    }
75
76    /// The seal has not been altered since it was sealed.
77    pub fn is_intact(&self) -> bool {
78        self.seal_hash == self.compute_hash()
79    }
80}
81
82/// Ledgers in [first, last] that are not in `seen`, merged into ranges.
83pub fn missing_ranges(first: u32, last: u32, seen: &[u32]) -> Vec<[u32; 2]> {
84    let mut have: Vec<u32> = seen
85        .iter()
86        .copied()
87        .filter(|l| (first..=last).contains(l))
88        .collect();
89    have.sort_unstable();
90    have.dedup();
91
92    let mut out = Vec::new();
93    let mut expect = first;
94    for l in have {
95        if l > expect {
96            out.push([expect, l - 1]);
97        }
98        expect = l.saturating_add(1);
99    }
100    if first <= last && expect <= last {
101        out.push([expect, last]);
102    }
103    out
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    fn seal() -> Seal {
111        Seal {
112            format: FORMAT.into(),
113            source: "archiver-a".into(),
114            nominal_first: 1024,
115            nominal_last: 2047,
116            first_ledger: 1020,
117            last_ledger: 2050,
118            records: 87_000,
119            out_of_window: 0,
120            coverage_first: 1020,
121            coverage_last: 2050,
122            missing_ledgers: vec![],
123            opened_ms: 1,
124            sealed_ms: 2,
125            raw_bytes: 3,
126            raw_hash: "AB".into(),
127            prev_seal_hash: None,
128            seal_hash: String::new(),
129        }
130        .finalize()
131    }
132
133    #[test]
134    fn seal_detects_tampering() {
135        let s = seal();
136        assert!(s.is_intact());
137        let mut t = s.clone();
138        t.records += 1;
139        assert!(!t.is_intact());
140    }
141
142    #[test]
143    fn seal_hash_survives_json_roundtrip() {
144        let s = seal();
145        let back: Seal = serde_json::from_str(&serde_json::to_string_pretty(&s).unwrap()).unwrap();
146        assert!(back.is_intact());
147        assert_eq!(back, s);
148    }
149
150    #[test]
151    fn missing_ranges_merge_into_runs() {
152        assert_eq!(
153            missing_ranges(10, 20, &[10, 11, 12, 15, 20]),
154            vec![[13, 14], [16, 19]]
155        );
156        assert_eq!(missing_ranges(10, 12, &[]), vec![[10, 12]]);
157        assert_eq!(
158            missing_ranges(10, 12, &[10, 11, 12, 99]),
159            Vec::<[u32; 2]>::new()
160        );
161        assert_eq!(missing_ranges(10, 12, &[12]), vec![[10, 11]]);
162    }
163}