1use std::fs::{self, File, OpenOptions};
13use std::io::{Read, Seek, SeekFrom, Write};
14use std::path::{Path, PathBuf};
15
16const MAGIC: &[u8; 6] = b"XWLE\x00\x01";
17
18#[derive(Debug)]
19pub struct LedgerLog {
20 dir: PathBuf,
21 segment_ledgers: u32,
22 zstd_level: i32,
23 file: File,
24 first: Option<u32>,
26 last: Option<u32>,
27 sealed_last: Option<u32>,
29 last_hash: Option<[u8; 32]>,
32}
33
34fn record_hash(body: &[u8]) -> Option<[u8; 32]> {
36 witness_core::ledger::LedgerHeader::parse(body.get(..witness_core::ledger::HEADER_LEN)?)
37 .ok()
38 .map(|h| h.hash())
39}
40
41fn sealed_last_hash(segments: &Path, last: Option<u32>) -> Result<Option<[u8; 32]>, String> {
43 let Some(last) = last else {
44 return Ok(None);
45 };
46 let suffix = format!("-{last:010}.xwle.zst");
47 for e in fs::read_dir(segments).map_err(|e| e.to_string())? {
48 let path = e.map_err(|e| e.to_string())?.path();
49 if path.to_string_lossy().ends_with(&suffix) {
50 let raw = zstd::decode_all(&fs::read(&path).map_err(|e| e.to_string())?[..])
51 .map_err(|e| e.to_string())?;
52 let (records, _) = parse_records(&raw)?;
53 return Ok(records.last().and_then(|(_, b)| record_hash(b)));
54 }
55 }
56 Ok(None)
57}
58
59pub fn read_journal(dir: &Path) -> Result<Vec<Vec<u8>>, String> {
62 let mut files: Vec<PathBuf> = fs::read_dir(dir.join("segments"))
63 .map_err(|e| e.to_string())?
64 .filter_map(|e| e.ok().map(|e| e.path()))
65 .filter(|p| p.to_string_lossy().ends_with(".xwle.zst"))
66 .collect();
67 files.sort();
68 let mut raws = Vec::new();
69 for f in files {
70 let zst = fs::read(&f).map_err(|e| e.to_string())?;
71 raws.push(zstd::decode_all(&zst[..]).map_err(|e| e.to_string())?);
72 }
73 match fs::read(dir.join("current.xwle")) {
74 Ok(raw) => raws.push(raw),
75 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
76 Err(e) => return Err(e.to_string()),
77 }
78 Ok(raws)
79}
80
81pub type Records<'a> = (Vec<(u32, &'a [u8])>, usize);
84
85pub fn parse_records(raw: &[u8]) -> Result<Records<'_>, String> {
86 if !raw.starts_with(MAGIC) {
87 return Err("not a ledger log".into());
88 }
89 let mut out = Vec::new();
90 let mut at = MAGIC.len();
91 while let Some(hdr) = raw.get(at..at + 8) {
92 let len = u32::from_le_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]) as usize;
93 let seq = u32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
94 let Some(body) = raw.get(at + 8..at + 8 + len) else {
95 break;
96 };
97 out.push((seq, body));
98 at += 8 + len;
99 }
100 Ok((out, at))
101}
102
103fn sealed_last(segments: &Path) -> std::io::Result<Option<u32>> {
105 let mut best = None;
106 for e in fs::read_dir(segments)? {
107 let name = e?.file_name().to_string_lossy().into_owned();
108 if let Some(last) = name
109 .strip_prefix("led-")
110 .and_then(|n| n.strip_suffix(".xwle.zst"))
111 .and_then(|n| n.split('-').nth(1))
112 .and_then(|n| n.parse::<u32>().ok())
113 {
114 best = best.max(Some(last));
115 }
116 }
117 Ok(best)
118}
119
120impl LedgerLog {
121 pub fn open(dir: &Path, segment_ledgers: u32, zstd_level: i32) -> Result<LedgerLog, String> {
122 let io = |e: std::io::Error| e.to_string();
123 fs::create_dir_all(dir.join("segments")).map_err(io)?;
124 let path = dir.join("current.xwle");
125 let mut file = OpenOptions::new()
126 .read(true)
127 .append(true)
128 .create(true)
129 .open(&path)
130 .map_err(io)?;
131 let mut raw = Vec::new();
132 file.read_to_end(&mut raw).map_err(io)?;
133 let (first, last, journal_hash) = if raw.is_empty() {
134 file.write_all(MAGIC).map_err(io)?;
135 file.sync_data().map_err(io)?;
136 (None, None, None)
137 } else {
138 let (records, end) = parse_records(&raw)?;
139 if end < raw.len() {
140 file.set_len(end as u64).map_err(io)?;
141 file.seek(SeekFrom::End(0)).map_err(io)?;
142 file.sync_data().map_err(io)?;
143 }
144 (
145 records.first().map(|r| r.0),
146 records.last().map(|r| r.0),
147 records.last().and_then(|(_, b)| record_hash(b)),
148 )
149 };
150 let sealed = sealed_last(&dir.join("segments")).map_err(io)?;
151 let last_hash = match journal_hash {
152 Some(h) => Some(h),
153 None => sealed_last_hash(&dir.join("segments"), sealed)?,
154 };
155 Ok(LedgerLog {
156 last_hash,
157 sealed_last: sealed,
158 dir: dir.to_owned(),
159 segment_ledgers,
160 zstd_level,
161 file,
162 first,
163 last,
164 })
165 }
166
167 pub fn last(&self) -> Option<u32> {
169 self.last.or(self.sealed_last)
170 }
171
172 pub fn last_hash(&self) -> Option<[u8; 32]> {
174 self.last_hash
175 }
176
177 pub fn append(&mut self, sequence: u32, ledger: &[u8]) -> Result<Option<PathBuf>, String> {
180 let io = |e: std::io::Error| e.to_string();
181 let mut rec = Vec::with_capacity(ledger.len() + 8);
182 rec.extend_from_slice(&(ledger.len() as u32).to_le_bytes());
183 rec.extend_from_slice(&sequence.to_le_bytes());
184 rec.extend_from_slice(ledger);
185 self.file.write_all(&rec).map_err(io)?;
186 self.file.sync_data().map_err(io)?;
187 self.first.get_or_insert(sequence);
188 self.last = Some(sequence);
189 self.last_hash = record_hash(ledger);
190 if (sequence + 1).is_multiple_of(self.segment_ledgers) {
191 return self.seal().map(Some);
192 }
193 Ok(None)
194 }
195
196 fn seal(&mut self) -> Result<PathBuf, String> {
197 let io = |e: std::io::Error| e.to_string();
198 let (Some(first), Some(last)) = (self.first, self.last) else {
199 return Err("an empty log cannot be sealed".into());
200 };
201 let journal = self.dir.join("current.xwle");
202 let raw = fs::read(&journal).map_err(io)?;
203 let zst = zstd::bulk::compress(&raw, self.zstd_level).map_err(io)?;
204 let path = self
205 .dir
206 .join("segments")
207 .join(format!("led-{first:010}-{last:010}.xwle.zst"));
208 witness_core::util::write_atomic(&path, &zst).map_err(io)?;
209 fs::remove_file(&journal).map_err(io)?;
211 self.file = OpenOptions::new()
212 .read(true)
213 .append(true)
214 .create(true)
215 .open(&journal)
216 .map_err(io)?;
217 self.file.write_all(MAGIC).map_err(io)?;
218 self.file.sync_data().map_err(io)?;
219 self.sealed_last = Some(last);
220 self.first = None;
221 self.last = None;
222 Ok(path)
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn appends_survive_restart_and_segments_rotate() {
232 let dir = tempfile::tempdir().unwrap();
233 {
234 let mut log = LedgerLog::open(dir.path(), 4, 3).unwrap();
235 assert_eq!(log.last(), None);
236 for s in 101..=106 {
237 let sealed = log.append(s, &[s as u8; 50]).unwrap();
238 assert_eq!(sealed.is_some(), s == 103);
240 }
241 }
242 let mut log = LedgerLog::open(dir.path(), 4, 3).unwrap();
243 assert_eq!(log.last(), Some(106));
244 assert_eq!(log.last_hash(), None);
246 log.append(107, &[7; 50]).unwrap();
247 let seg = dir
248 .path()
249 .join("segments/led-0000000104-0000000107.xwle.zst");
250 assert!(seg.exists());
251 let raw = zstd::decode_all(&fs::read(&seg).unwrap()[..]).unwrap();
252 let (records, _) = parse_records(&raw).unwrap();
253 assert_eq!(
254 records.iter().map(|r| r.0).collect::<Vec<_>>(),
255 vec![104, 105, 106, 107]
256 );
257 }
258
259 #[test]
260 fn torn_tail_is_cut() {
261 let dir = tempfile::tempdir().unwrap();
262 {
263 let mut log = LedgerLog::open(dir.path(), 1024, 3).unwrap();
264 log.append(5, &[1; 20]).unwrap();
265 }
266 let path = dir.path().join("current.xwle");
267 let mut f = OpenOptions::new().append(true).open(&path).unwrap();
268 f.write_all(&[100, 0, 0, 0, 6, 0, 0, 0, 1, 2]).unwrap();
269 let log = LedgerLog::open(dir.path(), 1024, 3).unwrap();
270 assert_eq!(log.last(), Some(5));
271 }
272
273 #[test]
274 fn last_hash_survives_restart_and_seal() {
275 use witness_core::ledger::{HEADER_LEN, LedgerHeader};
276 let dir = tempfile::tempdir().unwrap();
277 let ledger = |seq: u32| {
278 let mut h = vec![0u8; HEADER_LEN];
279 h[..4].copy_from_slice(&seq.to_be_bytes());
280 h
281 };
282 let expected = LedgerHeader::parse(&ledger(7)).unwrap().hash();
283 {
284 let mut log = LedgerLog::open(dir.path(), 4, 3).unwrap();
285 log.append(6, &ledger(6)).unwrap();
286 log.append(7, &ledger(7)).unwrap(); }
288 let log = LedgerLog::open(dir.path(), 4, 3).unwrap();
289 assert_eq!(log.last(), Some(7));
290 assert_eq!(log.last_hash(), Some(expected));
291 }
292}