1use std::collections::BTreeMap;
19use std::fs;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22
23use serde_json::{Value, json};
24use witness_core::sha512_half;
25
26use crate::cold::{Cold, sync_write};
27use crate::index::{AccountId, entries};
28use crate::state::TxPosition;
29use crate::txindex::{
30 AccountFile, AccountIndex, Posting, TxHashFile, build_account_index_v2, build_tx_index_tops,
31 top64,
32};
33
34type Res<T> = Result<T, String>;
35
36const LGR_MAGIC: &[u8; 6] = b"XWLH\x00\x01";
37const LGR_SPARSE: usize = 256;
39
40fn io(e: std::io::Error) -> String {
41 e.to_string()
42}
43
44fn corrupt(what: impl std::fmt::Display) -> String {
45 format!("corrupt_history: cold history index: {what}")
46}
47
48fn names(dir: &Path, first: u32) -> [PathBuf; 4] {
49 ["xtxh", "xacc", "lgr", "json"].map(|e| dir.join(format!("coldidx-{first:010}.{e}")))
50}
51
52pub fn build(dir: &Path, cold: &Cold, first: u32, last: u32) -> Res<Value> {
55 if first > last {
56 return Err("empty range".into());
57 }
58 let mut counts = Vec::with_capacity((last - first + 1) as usize);
59 let mut tops: Vec<(u64, u32)> = Vec::new();
60 let mut postings: BTreeMap<AccountId, Vec<Posting>> = BTreeMap::new();
61 let mut hashes: Vec<([u8; 32], u32)> = Vec::with_capacity(counts.capacity());
62 let mut parent: Option<[u8; 32]> = None;
63 let mut ord = 0u32;
64 for seq in first..=last {
65 let l = cold
66 .ledger(seq, false)?
67 .ok_or(format!("ledger {seq} is not in the cold history"))?;
68 let h = l.header()?;
69 if h.sequence != seq || parent.is_some_and(|p| p != h.parent_hash) {
70 return Err(format!("ledger {seq}: header chain is broken"));
71 }
72 parent = Some(h.hash());
73 hashes.push((h.hash(), seq));
74 let es = entries(&l)?;
75 counts.push(es.len() as u32);
76 for e in es {
77 tops.push((top64(&e.id), ord));
78 ord = ord
79 .checked_add(1)
80 .ok_or("more than 2^32 transactions in the partition")?;
81 for a in e.accounts {
82 postings.entry(a).or_default().push((seq, e.index));
83 }
84 }
85 }
86 for v in postings.values_mut() {
87 v.sort_unstable();
88 v.dedup();
89 }
90 let txs = tops.len();
91 let xtxh = build_tx_index_tops(first, &counts, tops);
92 let xacc = build_account_index_v2(first, &counts, &postings)?;
93 let ai = AccountIndex::open(&xacc)?;
95 for (a, ps) in &postings {
96 if ai.postings(a)? != *ps {
97 return Err(format!(
98 "account history {} does not match",
99 hex::encode_upper(a)
100 ));
101 }
102 }
103 let accounts = postings.len();
104 drop((ai, postings));
105 hashes.sort_unstable();
106 let mut lgr = LGR_MAGIC.to_vec();
107 lgr.extend((hashes.len() as u32).to_le_bytes());
108 for (h, s) in &hashes {
109 lgr.extend(h);
110 lgr.extend(s.to_le_bytes());
111 }
112 let [pt, pa, pl, pm] = names(dir, first);
113 sync_write(&pt, &xtxh)?;
114 sync_write(&pa, &xacc)?;
115 sync_write(&pl, &lgr)?;
116 let tf = TxHashFile::open(&pt)?;
118 for seq in first..=last {
119 let l = cold.ledger(seq, false)?.ok_or("ledger disappeared")?;
120 for (p, (tx, _)) in l.transactions.iter().enumerate() {
121 let id = witness_core::shamap::tx_id(tx);
122 if !tf.candidates(&id)?.contains(&(seq, p as u32)) {
123 return Err(format!(
124 "transaction {} not found in XTXH",
125 hex::encode_upper(id)
126 ));
127 }
128 }
129 }
130 let file =
131 |b: &[u8]| json!({"bytes": b.len(), "sha512half": hex::encode_upper(sha512_half(b))});
132 let manifest = json!({
133 "format": "astraea-coldidx/1",
134 "first": first,
135 "last": last,
136 "ledgers": last - first + 1,
137 "transactions": txs,
138 "accounts": accounts,
139 "files": {"xtxh": file(&xtxh), "xacc": file(&xacc), "lgr": file(&lgr)},
140 });
141 let m = serde_json::to_vec_pretty(&manifest).map_err(|e| e.to_string())?;
142 sync_write(&pm, &m)?;
143 fs::File::open(dir).and_then(|d| d.sync_all()).map_err(io)?;
144 Ok(manifest)
145}
146
147#[derive(Debug)]
149pub struct ColdIndex {
150 pub first: u32,
151 pub last: u32,
152 tx: TxHashFile,
153 acc: AccountFile,
154 lgr: fs::File,
155 lgr_sparse: Vec<[u8; 32]>,
157 bytes: u64,
159}
160
161impl ColdIndex {
162 fn open(dir: &Path, m: &Value) -> Res<ColdIndex> {
163 let num = |k: &str| m[k].as_u64().and_then(|v| u32::try_from(v).ok());
164 let (Some(first), Some(last)) = (num("first"), num("last")) else {
165 return Err(corrupt("range in the manifest"));
166 };
167 let [pt, pa, pl, _] = names(dir, first);
168 for (p, k) in [(&pt, "xtxh"), (&pa, "xacc"), (&pl, "lgr")] {
169 let len = fs::metadata(p).map_err(io)?.len();
170 if Some(len) != m["files"][k]["bytes"].as_u64() {
171 return Err(corrupt(format!("wrong size of {k}")));
172 }
173 }
174 let tx = TxHashFile::open(&pt).map_err(corrupt)?;
175 if (tx.first(), tx.last()) != (first, last) {
176 return Err(corrupt("XTXH range does not match the manifest"));
177 }
178 let acc = AccountFile::open(&pa).map_err(corrupt)?;
179 let lgr = fs::File::open(&pl).map_err(io)?;
180 let b = pread(&lgr, 0, 10).map_err(|_| corrupt("ledger hashes: not XWLH"))?;
181 if b.get(..6) != Some(LGR_MAGIC.as_slice()) {
182 return Err(corrupt("ledger hashes: not XWLH"));
183 }
184 let n = u32::from_le_bytes([b[6], b[7], b[8], b[9]]) as usize;
185 let len = lgr.metadata().map_err(io)?.len();
186 if len != 10 + n as u64 * 36 || n != (last - first + 1) as usize {
187 return Err(corrupt("ledger hashes: length"));
188 }
189 let mut lgr_sparse = Vec::with_capacity(n / LGR_SPARSE + 1);
190 for k in (0..n).step_by(LGR_SPARSE) {
191 let h = pread(&lgr, 10 + k as u64 * 36, 32)?;
192 lgr_sparse.push(h.try_into().map_err(|_| corrupt("ledger hashes"))?);
193 }
194 let bytes = m["files"]
195 .as_object()
196 .map_or(0, |f| f.values().filter_map(|v| v["bytes"].as_u64()).sum());
197 Ok(ColdIndex {
198 first,
199 last,
200 tx,
201 acc,
202 lgr,
203 lgr_sparse,
204 bytes,
205 })
206 }
207
208 fn ledger_by_hash(&self, h: &[u8; 32]) -> Res<Option<u32>> {
209 let Some(k) = self.lgr_sparse.partition_point(|x| x <= h).checked_sub(1) else {
210 return Ok(None);
211 };
212 let n = (self.last - self.first + 1) as usize;
213 let from = k * LGR_SPARSE;
214 let cnt = LGR_SPARSE.min(n - from);
215 let b = pread(&self.lgr, 10 + from as u64 * 36, cnt * 36)?;
216 let recs = b.as_chunks::<36>().0;
217 Ok(recs
218 .binary_search_by(|r| r[..32].cmp(h))
219 .ok()
220 .map(|i| u32::from_le_bytes(recs[i][32..].try_into().unwrap_or_default())))
221 }
222}
223
224fn pread(f: &fs::File, at: u64, len: usize) -> Res<Vec<u8>> {
225 use std::os::unix::fs::FileExt;
226 let mut b = vec![0u8; len];
227 f.read_exact_at(&mut b, at).map_err(io)?;
228 Ok(b)
229}
230
231#[derive(Debug, Default)]
233pub struct ColdIndexes {
234 parts: Vec<Arc<ColdIndex>>,
235}
236
237impl ColdIndexes {
238 pub fn open(dir: &Path) -> Res<ColdIndexes> {
239 ColdIndexes::open_with(dir, &ColdIndexes::default())
240 }
241
242 pub fn open_with(dir: &Path, prev: &ColdIndexes) -> Res<ColdIndexes> {
245 let mut parts = Vec::new();
246 let Ok(entries) = fs::read_dir(dir) else {
247 return Ok(ColdIndexes::default());
248 };
249 for e in entries {
250 let p = e.map_err(io)?.path();
251 let name = p
252 .file_name()
253 .map(|n| n.to_string_lossy().into_owned())
254 .unwrap_or_default();
255 if !(name.starts_with("coldidx-") && name.ends_with(".json")) {
256 continue;
257 }
258 let known = name["coldidx-".len()..name.len() - ".json".len()]
259 .parse::<u32>()
260 .ok()
261 .and_then(|f| prev.parts.iter().find(|x| x.first == f));
262 if let Some(x) = known {
263 parts.push(x.clone());
264 continue;
265 }
266 let m: Value = serde_json::from_slice(&fs::read(&p).map_err(io)?).map_err(corrupt)?;
267 if m["format"] != "astraea-coldidx/1" {
268 return Err(corrupt(format!("{name}: unknown format")));
269 }
270 parts.push(Arc::new(ColdIndex::open(dir, &m)?));
271 }
272 parts.sort_by_key(|p| p.first);
273 if parts.windows(2).any(|w| w[1].first <= w[0].last) {
274 return Err(corrupt("partitions overlap"));
275 }
276 Ok(ColdIndexes { parts })
277 }
278
279 pub fn parts(&self) -> usize {
280 self.parts.len()
281 }
282
283 pub fn bytes(&self) -> u64 {
285 self.parts.iter().map(|p| p.bytes).sum()
286 }
287
288 pub fn first_contiguous_to(&self, end: u32) -> Option<u32> {
291 let mut k = self
292 .parts
293 .iter()
294 .rposition(|p| p.first <= end && end <= p.last)?;
295 while k > 0 && self.parts[k - 1].last + 1 == self.parts[k].first {
296 k -= 1;
297 }
298 Some(self.parts[k].first)
299 }
300
301 pub fn ledger_by_hash(&self, h: &[u8; 32]) -> Res<Option<u32>> {
302 for p in &self.parts {
303 if let Some(seq) = p.ledger_by_hash(h)? {
304 return Ok(Some(seq));
305 }
306 }
307 Ok(None)
308 }
309
310 pub fn tx_candidates(&self, h: &[u8; 32]) -> Res<Vec<(u32, u32)>> {
312 let mut out = Vec::new();
313 for p in &self.parts {
314 out.extend(p.tx.candidates(h)?);
315 }
316 Ok(out)
317 }
318
319 pub fn account_tx(
322 &self,
323 account: &AccountId,
324 lo: TxPosition,
325 hi: TxPosition,
326 forward: bool,
327 limit: usize,
328 ) -> Res<Vec<TxPosition>> {
329 let mut out = Vec::new();
330 let parts: Box<dyn Iterator<Item = &Arc<ColdIndex>>> = if forward {
331 Box::new(self.parts.iter())
332 } else {
333 Box::new(self.parts.iter().rev())
334 };
335 for p in parts {
336 if out.len() >= limit {
337 break;
338 }
339 crate::limits::check()?;
340 let a = lo.max(TxPosition {
341 ledger: p.first,
342 index: 0,
343 });
344 let b = hi.min(TxPosition {
345 ledger: p.last,
346 index: u32::MAX,
347 });
348 if a > b {
349 continue;
350 }
351 let got = p.acc.range(
352 account,
353 (a.ledger, a.index),
354 (b.ledger, b.index),
355 limit - out.len(),
356 !forward,
357 )?;
358 out.extend(
359 got.into_iter()
360 .map(|(ledger, index)| TxPosition { ledger, index }),
361 );
362 }
363 Ok(out)
364 }
365}
366
367pub type Shared = Arc<ColdIndexes>;
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use crate::cold::{Kinds, write};
374 use crate::ledger::Ledger;
375 use witness_core::ledger::LedgerHeader;
376
377 fn chain(first: u32, n: u32) -> Vec<Ledger> {
380 let mut out = Vec::new();
381 let mut parent = [0u8; 32];
382 for k in 0..n {
383 let mut header = vec![0u8; 118];
384 header[..4].copy_from_slice(&(first + k).to_be_bytes());
385 header[12..44].copy_from_slice(&parent);
386 parent = LedgerHeader::parse(&header).unwrap().hash();
387 out.push(Ledger {
388 header,
389 transactions: vec![],
390 changes: vec![],
391 });
392 }
393 out
394 }
395
396 #[test]
397 fn partitions_route_ledger_hashes_and_contiguity() {
398 let dir = tempfile::tempdir().unwrap();
399 let ls = chain(100, 600);
401 write(dir.path(), &ls[..520], Kinds::Explicit).unwrap();
402 write(dir.path(), &ls[520..], Kinds::Explicit).unwrap();
403 let cold = Cold::open(dir.path()).unwrap();
404 build(dir.path(), &cold, 620, 699).unwrap();
405 let first = ColdIndexes::open(dir.path()).unwrap();
406 assert_eq!(first.first_contiguous_to(699), Some(620));
407 build(dir.path(), &cold, 100, 619).unwrap();
408 let ix = ColdIndexes::open_with(dir.path(), &first).unwrap();
409 assert_eq!(ix.parts(), 2);
410 assert!(Arc::ptr_eq(&ix.parts[1], &first.parts[0]));
412 assert_eq!(ix.first_contiguous_to(699), Some(100));
413 assert_eq!(ix.first_contiguous_to(698), Some(100));
414 assert_eq!(ix.first_contiguous_to(700), None);
415 for l in &ls {
416 let h = l.header().unwrap();
417 assert_eq!(ix.ledger_by_hash(&h.hash()).unwrap(), Some(h.sequence));
418 }
419 assert_eq!(ix.ledger_by_hash(&[7; 32]).unwrap(), None);
420 assert!(build(dir.path(), &cold, 99, 105).is_err());
421 }
422}