1use 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 pub source: String,
27 pub nominal_first: u32,
29 pub nominal_last: u32,
30 pub first_ledger: u32,
34 pub last_ledger: u32,
35 pub records: u64,
36 pub out_of_window: u64,
41 pub coverage_first: u32,
47 pub coverage_last: u32,
48 pub missing_ledgers: Vec<[u32; 2]>,
51 pub opened_ms: u64,
52 pub sealed_ms: u64,
53 pub raw_bytes: u64,
55 pub raw_hash: String,
57 pub prev_seal_hash: Option<String>,
59 pub seal_hash: String,
60}
61
62impl Seal {
63 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 pub fn is_intact(&self) -> bool {
78 self.seal_hash == self.compute_hash()
79 }
80}
81
82pub 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}