Skip to main content

witness_store/
record.rs

1//! One archive record is one received validation.
2//!
3//! Record layout, all integers little-endian:
4//!
5//! ```text
6//! u32  length of the rest of the record (12 + length of the original)
7//! u64  time the archiver received it, ms since the Unix epoch
8//! u32  ledger index, for navigation without parsing the original
9//! ...  original: the raw signed validation (the stream's `data` field)
10//! ```
11//!
12//! The leading length lets crash recovery tell a complete record from one
13//! cut off halfway.
14
15/// A validation whose original is this large is certainly garbage. Real ones
16/// are about 233 bytes; with amendments and fees in the body, up to a couple
17/// hundred bytes more.
18pub const MAX_DATA_LEN: usize = 4096;
19
20const FIXED_LEN: usize = 12;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Record {
24    pub received_ms: u64,
25    pub ledger_index: u32,
26    /// The raw signed validation.
27    pub data: Vec<u8>,
28}
29
30impl Record {
31    pub fn encode_into(&self, out: &mut Vec<u8>) {
32        let body_len = u32::try_from(FIXED_LEN + self.data.len()).unwrap_or(u32::MAX);
33        out.extend_from_slice(&body_len.to_le_bytes());
34        out.extend_from_slice(&self.received_ms.to_le_bytes());
35        out.extend_from_slice(&self.ledger_index.to_le_bytes());
36        out.extend_from_slice(&self.data);
37    }
38
39    /// Parses the record at the start of `buf`.
40    ///
41    /// `Ok(None)` means there is not enough data for a whole record: either the
42    /// normal end of the journal or a torn tail after a crash.
43    pub fn decode(buf: &[u8]) -> Result<Option<(Record, usize)>, String> {
44        let Some(len_bytes) = buf.get(..4) else {
45            return Ok(None);
46        };
47        let body_len =
48            u32::from_le_bytes([len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]]) as usize;
49        if !(FIXED_LEN..=FIXED_LEN + MAX_DATA_LEN).contains(&body_len) {
50            return Err(format!("impossible record length {body_len}"));
51        }
52        let Some(body) = buf.get(4..4 + body_len) else {
53            return Ok(None);
54        };
55        let mut ms = [0u8; 8];
56        ms.copy_from_slice(&body[..8]);
57        let mut li = [0u8; 4];
58        li.copy_from_slice(&body[8..12]);
59        Ok(Some((
60            Record {
61                received_ms: u64::from_le_bytes(ms),
62                ledger_index: u32::from_le_bytes(li),
63                data: body[FIXED_LEN..].to_vec(),
64            },
65            4 + body_len,
66        )))
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    fn sample(i: u32) -> Record {
75        Record {
76            received_ms: 1_790_000_000_000 + u64::from(i),
77            ledger_index: 107_000_000 + i,
78            data: vec![0x22, 0x80, i as u8, 0x01],
79        }
80    }
81
82    #[test]
83    fn roundtrip() {
84        let mut buf = Vec::new();
85        for i in 0..3 {
86            sample(i).encode_into(&mut buf);
87        }
88        let mut at = 0;
89        for i in 0..3 {
90            let (r, used) = Record::decode(&buf[at..]).unwrap().unwrap();
91            assert_eq!(r, sample(i));
92            at += used;
93        }
94        assert_eq!(at, buf.len());
95        assert!(Record::decode(&buf[at..]).unwrap().is_none());
96    }
97
98    #[test]
99    fn torn_tail_is_not_an_error() {
100        let mut buf = Vec::new();
101        sample(7).encode_into(&mut buf);
102        for cut in 0..buf.len() {
103            assert!(
104                Record::decode(&buf[..cut]).unwrap().is_none(),
105                "cut at {cut}"
106            );
107        }
108    }
109
110    #[test]
111    fn garbage_length_is_rejected() {
112        let buf = [0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0];
113        assert!(Record::decode(&buf).is_err());
114    }
115}