bgpkit-snap 0.2.0

Versioned single-file container for prefix tries, with an append-only journal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! The 192-byte v4 header and the section table.
//!
//! Layout (all little endian):
//!
//! ```text
//!  0  magic "BGPKSNAP"       12  tree_id [16]       28  generation [16]
//! 44  base_seq u64           52  type_id [32]       84  file_len u64
//! 92  section_count u32      96  table_len u32     100  window [2 x i64]
//!116  reserved [32]         148  created_at i64    156  content_id [32]
//!188  crc32c u32
//! ```
//!
//! Bytes `0..148` are hashed; `created_at`, `content_id` and the crc follow, so
//! the hash input is one contiguous range with no exclusion puzzle.

use crate::Error;

/// The first eight bytes of every object.
pub const MAGIC: &[u8; 8] = b"BGPKSNAP";
/// Size of the fixed header.
pub const HEADER_LEN: usize = 192;
/// Bytes `0..HASH_END` are what the content id hashes; the provenance fields follow.
pub const HASH_END: usize = 148;
/// Layout version this build writes and reads.
pub const VERSION: u16 = 4;

/// One section table entry: 64 bytes.
pub const ENTRY_LEN: usize = 64;

/// The object records which journal stream it came from.
pub const FLAG_STREAM: u16 = 1 << 0;
/// The object claims a coverage window; without this flag the fields mean nothing.
pub const FLAG_WINDOW: u16 = 1 << 1;
const FLAG_KNOWN: u16 = FLAG_STREAM | FLAG_WINDOW;

/// Kind tag of the IPv4 trie section.
pub const KIND_V4: [u8; 4] = *b"V4\0\0";
/// Kind tag of the IPv6 trie section.
pub const KIND_V6: [u8; 4] = *b"V6\0\0";
/// Kind tag of a blob arena a profile carries.
pub const KIND_PAYLOAD: [u8; 4] = *b"PAY\0";

/// Section id of the IPv4 trie.
pub const ID_V4: u16 = 2;
/// Section id of the IPv6 trie.
pub const ID_V6: u16 = 3;
/// Kind tag of the optional counts section.
pub const KIND_STATS: [u8; 4] = *b"CNT\0";
/// Section id of the optional counts section: how many entries the tries hold, written
/// so a reader that does not know the value type can still report the number.
pub const ID_STATS: u16 = 4;
/// Length of the counts section body: version, reserved, and three u64 counts.
pub const STATS_LEN: usize = 32;
/// Version of the counts body this crate writes and reads.
const STATS_VERSION: u16 = 1;
/// Profile sections use ids 16 and above.
pub const FIRST_PROFILE_ID: u16 = 16;

/// How many entries the object's tries hold, per family and in total.
///
/// The writer records this so that the number is available without decoding a value: a
/// trie's node layout depends on the value type, so counting entries from the bytes needs
/// the type, while reading four `u64`s does not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Counts {
    /// Entries in both families.
    pub entries: u64,
    /// Entries in the IPv4 trie.
    pub v4: u64,
    /// Entries in the IPv6 trie.
    pub v6: u64,
}

impl Counts {
    /// The section body.
    pub fn encode(&self) -> [u8; STATS_LEN] {
        let mut b = [0u8; STATS_LEN];
        b[0..2].copy_from_slice(&STATS_VERSION.to_le_bytes());
        // bytes 2..4 stay zero: reserved, and a reader refuses them otherwise
        b[8..16].copy_from_slice(&self.entries.to_le_bytes());
        b[16..24].copy_from_slice(&self.v4.to_le_bytes());
        b[24..32].copy_from_slice(&self.v6.to_le_bytes());
        b
    }

    /// Read the body, or `None` when it is not a body this crate writes.
    pub fn parse(raw: &[u8]) -> Option<Self> {
        if raw.len() != STATS_LEN {
            return None;
        }
        if u16::from_le_bytes(raw[0..2].try_into().ok()?) != STATS_VERSION {
            return None;
        }
        if raw[2..4] != [0, 0] || raw[4..8] != [0, 0, 0, 0] {
            return None;
        }
        Some(Self {
            entries: u64::from_le_bytes(raw[8..16].try_into().ok()?),
            v4: u64::from_le_bytes(raw[16..24].try_into().ok()?),
            v6: u64::from_le_bytes(raw[24..32].try_into().ok()?),
        })
    }
}

/// Which journal stream an object came from, and where in it the object starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StreamRef {
    /// The tree this object is an instance of.
    pub tree_id: [u8; 16],
    /// The journal incarnation that wrote it.
    pub generation: [u8; 16],
    /// The sequence number of the last record the object covers.
    pub base_seq: u64,
}

/// What the first 192 bytes of an object say about the rest of it.
///
/// Every field here is a claim by the writer; `verify_bytes` and `Snapshot::open`
/// check the ones that can be checked against the bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
    /// See `FLAG_STREAM` and `FLAG_WINDOW`.
    pub flags: u16,
    /// The tree this object is an instance of; zero unless it came from a journal.
    pub tree_id: [u8; 16],
    /// The journal incarnation that wrote it; zero outside a journal.
    pub generation: [u8; 16],
    /// The last record the object covers; zero outside a journal.
    pub base_seq: u64,
    /// The value type, as NUL-padded `TYPE_ID`.
    pub type_id: [u8; 32],
    /// Total file size; the reader refuses a file that disagrees.
    pub file_len: u64,
    /// Number of rows in the section table.
    pub section_count: u32,
    /// Length of the section table in bytes.
    pub section_table_len: u32,
    /// Coverage claim, `(first, last)`, only meaningful with `FLAG_WINDOW`.
    pub window: [i64; 2],
    /// Unix seconds when the object was written; outside the content id.
    pub created_at: i64,
    /// BLAKE3 over the hashed range and the section bodies; identity, not provenance.
    pub content_id: [u8; 32],
}

impl Header {
    /// The value type as text, up to its first NUL.
    pub fn type_id_str(&self) -> String {
        let end = self
            .type_id
            .iter()
            .position(|b| *b == 0)
            .unwrap_or(self.type_id.len());
        String::from_utf8_lossy(&self.type_id[..end]).into_owned()
    }

    /// The content id as lower-case hex, which is how it is written in logs.
    pub fn content_id_hex(&self) -> String {
        hex32(&self.content_id)
    }

    /// The stream coordinates, when the object came from a journal.
    pub fn stream(&self) -> Option<StreamRef> {
        (self.flags & FLAG_STREAM != 0).then_some(StreamRef {
            tree_id: self.tree_id,
            generation: self.generation,
            base_seq: self.base_seq,
        })
    }

    /// The coverage claim, when the writer made one.
    pub fn window(&self) -> Option<(i64, i64)> {
        (self.flags & FLAG_WINDOW != 0).then_some((self.window[0], self.window[1]))
    }

    /// The header as the 192 bytes it is stored as.
    pub fn encode(&self) -> [u8; HEADER_LEN] {
        let mut b = [0u8; HEADER_LEN];
        b[0..8].copy_from_slice(MAGIC);
        b[8..10].copy_from_slice(&VERSION.to_le_bytes());
        b[10..12].copy_from_slice(&self.flags.to_le_bytes());
        b[12..28].copy_from_slice(&self.tree_id);
        b[28..44].copy_from_slice(&self.generation);
        b[44..52].copy_from_slice(&self.base_seq.to_le_bytes());
        b[52..84].copy_from_slice(&self.type_id);
        b[84..92].copy_from_slice(&self.file_len.to_le_bytes());
        b[92..96].copy_from_slice(&self.section_count.to_le_bytes());
        b[96..100].copy_from_slice(&self.section_table_len.to_le_bytes());
        b[100..108].copy_from_slice(&self.window[0].to_le_bytes());
        b[108..116].copy_from_slice(&self.window[1].to_le_bytes());
        b[148..156].copy_from_slice(&self.created_at.to_le_bytes());
        b[156..188].copy_from_slice(&self.content_id);
        let crc = crc32c::crc32c(&b[..188]);
        b[188..192].copy_from_slice(&crc.to_le_bytes());
        b
    }

    /// Parse and check everything that can be judged from the header alone.
    pub fn parse(raw: &[u8]) -> Result<Self, Error> {
        if raw.len() < HEADER_LEN {
            return Err(Error::Truncated {
                need: HEADER_LEN,
                have: raw.len(),
            });
        }
        if &raw[0..8] != MAGIC {
            return Err(Error::BadMagic);
        }
        let version = u16::from_le_bytes([raw[8], raw[9]]);
        if version != VERSION {
            return Err(Error::BadVersion(version));
        }
        let crc = u32::from_le_bytes(raw[188..192].try_into().expect("4 bytes"));
        if crc32c::crc32c(&raw[..188]) != crc {
            return Err(Error::BadHeaderCrc);
        }
        let flags = u16::from_le_bytes([raw[10], raw[11]]);
        if flags & !FLAG_KNOWN != 0 {
            return Err(Error::BadHeader("undefined flag bit"));
        }
        let mut type_id = [0u8; 32];
        type_id.copy_from_slice(&raw[52..84]);
        if !type_id.contains(&0) {
            return Err(Error::BadHeader("type id is not terminated"));
        }
        let end = type_id
            .iter()
            .position(|b| *b == 0)
            .unwrap_or(type_id.len());
        if type_id[..end]
            .iter()
            .any(|b| !b.is_ascii_graphic() || *b == b'"' || *b == b'\\')
        {
            return Err(Error::BadHeader("type id is not plain ASCII"));
        }
        if type_id[end..].iter().any(|b| *b != 0) {
            return Err(Error::BadHeader(
                "type id is not zero filled after its terminator",
            ));
        }
        if raw[116..148].iter().any(|b| *b != 0) {
            return Err(Error::BadHeader("reserved header bytes are not zero"));
        }
        let mut content_id = [0u8; 32];
        content_id.copy_from_slice(&raw[156..188]);
        if content_id == [0u8; 32] {
            return Err(Error::BadHeader("content id is zero"));
        }
        let mut tree_id = [0u8; 16];
        tree_id.copy_from_slice(&raw[12..28]);
        let mut generation = [0u8; 16];
        generation.copy_from_slice(&raw[28..44]);
        let base_seq = u64::from_le_bytes(raw[44..52].try_into().expect("8 bytes"));
        match flags & FLAG_STREAM {
            0 => {
                if tree_id != [0u8; 16] || generation != [0u8; 16] || base_seq != 0 {
                    return Err(Error::BadHeader("stream identity without the flag"));
                }
            }
            _ => {
                if tree_id == [0u8; 16] || generation == [0u8; 16] {
                    return Err(Error::BadHeader("stream flag without identity"));
                }
            }
        }
        let window = [
            i64::from_le_bytes(raw[100..108].try_into().expect("8 bytes")),
            i64::from_le_bytes(raw[108..116].try_into().expect("8 bytes")),
        ];
        match flags & FLAG_WINDOW {
            0 => {
                if window != [0, 0] {
                    return Err(Error::BadHeader("window without the flag"));
                }
            }
            _ => {
                if window[0] == 0 || window[1] == 0 || window[0] > window[1] {
                    return Err(Error::BadHeader("window is not a range"));
                }
            }
        }
        let created_at = i64::from_le_bytes(raw[148..156].try_into().expect("8 bytes"));
        if created_at == 0 {
            return Err(Error::BadHeader("created_at is zero"));
        }
        let header = Header {
            flags,
            tree_id,
            generation,
            base_seq,
            type_id,
            file_len: u64::from_le_bytes(raw[84..92].try_into().expect("8 bytes")),
            section_count: u32::from_le_bytes(raw[92..96].try_into().expect("4 bytes")),
            section_table_len: u32::from_le_bytes(raw[96..100].try_into().expect("4 bytes")),
            window,
            created_at,
            content_id,
        };
        // layout checks need the real file length, so a peek only parses; the
        // reader calls check_layout once it has the whole object
        Ok(header)
    }

    /// Cross-check the fields against the real length of the object: the claims a
    /// peek cannot verify and the reader must.
    pub fn check_layout(&self, actual_len: usize) -> Result<(), Error> {
        if self.file_len as usize != actual_len {
            return Err(Error::Truncated {
                need: self.file_len as usize,
                have: actual_len,
            });
        }
        let expected = (self.section_count as usize)
            .checked_mul(ENTRY_LEN)
            .ok_or(Error::BadHeader("section count overflows the table"))?;
        if expected != self.section_table_len as usize {
            return Err(Error::BadHeader("table length disagrees with the count"));
        }
        let Some(table_end) = (HEADER_LEN as u64).checked_add(self.section_table_len as u64) else {
            return Err(Error::BadHeader("table length overflows"));
        };
        if table_end > self.file_len {
            return Err(Error::BadHeader("table runs past the file"));
        }
        Ok(())
    }
}

/// One section table entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Entry {
    /// Section id, strictly ascending across the table.
    pub id: u16,
    /// Four-byte kind tag; the id and the tag must agree.
    pub kind: [u8; 4],
    /// A reader that does not implement this section must refuse the object.
    pub required: bool,
    /// Length of the section body, excluding the padding before it.
    pub len: u64,
}

impl Entry {
    /// The table row as 64 bytes.
    pub fn encode(&self) -> [u8; ENTRY_LEN] {
        let mut b = [0u8; ENTRY_LEN];
        b[0..2].copy_from_slice(&self.id.to_le_bytes());
        b[2..6].copy_from_slice(&self.kind);
        b[6..8].copy_from_slice(&(self.required as u16).to_le_bytes());
        b[8..16].copy_from_slice(&self.len.to_le_bytes());
        b
    }

    /// Read one table row, refusing an undefined flag or non-zero reserved bytes.
    pub fn parse(raw: &[u8]) -> Result<Self, Error> {
        if raw.len() < ENTRY_LEN {
            return Err(Error::Truncated {
                need: ENTRY_LEN,
                have: raw.len(),
            });
        }
        let flags = u16::from_le_bytes([raw[6], raw[7]]);
        if flags & !1 != 0 {
            return Err(Error::BadHeader("undefined section flag"));
        }
        if raw[16..ENTRY_LEN].iter().any(|b| *b != 0) {
            return Err(Error::BadHeader(
                "section entry reserved bytes are not zero",
            ));
        }
        let mut kind = [0u8; 4];
        kind.copy_from_slice(&raw[2..6]);
        Ok(Entry {
            id: u16::from_le_bytes([raw[0], raw[1]]),
            kind,
            required: flags & 1 != 0,
            len: u64::from_le_bytes(raw[8..16].try_into().expect("8 bytes")),
        })
    }
}

/// Lower-case hex of a four-byte tag, the form `state.json` stores.
pub fn hex4(bytes: &[u8; 4]) -> String {
    let mut s = String::with_capacity(8);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// The inverse of `hex4`; exactly eight hex characters or nothing.
pub fn hex4_to_bytes(text: &str) -> Option<[u8; 4]> {
    if text.len() != 8 {
        return None;
    }
    let mut out = [0u8; 4];
    for (i, chunk) in text.as_bytes().chunks(2).enumerate() {
        let pair = std::str::from_utf8(chunk).ok()?;
        out[i] = u8::from_str_radix(pair, 16).ok()?;
    }
    Some(out)
}

/// Lower-case hex of a 32-byte id.
pub fn hex32(bytes: &[u8; 32]) -> String {
    let mut s = String::with_capacity(64);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// Decode a 32-character hex string into 16 bytes, for callers that persist
/// identities as text.
pub fn hex_to_bytes(s: &str, out: &mut [u8; 16]) -> Result<(), crate::Error> {
    if s.len() != 32 || !s.is_ascii() {
        return Err(crate::Error::BadHeader("hex identity has the wrong length"));
    }
    for (i, byte) in out.iter_mut().enumerate() {
        let hi = (s.as_bytes()[i * 2] as char)
            .to_digit(16)
            .ok_or(crate::Error::BadHeader("hex identity is not hex"))?;
        let lo = (s.as_bytes()[i * 2 + 1] as char)
            .to_digit(16)
            .ok_or(crate::Error::BadHeader("hex identity is not hex"))?;
        *byte = ((hi << 4) | lo) as u8;
    }
    Ok(())
}

/// A 16-byte identity as 32 hex characters, the form `state.json` keeps.
pub fn hex16(bytes: &[u8; 16]) -> String {
    let mut s = String::with_capacity(32);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}