-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyte_deserializer.rs
More file actions
569 lines (507 loc) · 17.6 KB
/
Copy pathbyte_deserializer.rs
File metadata and controls
569 lines (507 loc) · 17.6 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/// Allocation-free error type for the binary parser.
#[derive(Debug, Clone, Copy)]
pub enum ParseError {
OutOfBounds,
InvalidFormat,
}
/// Hand-rolled zero-copy parser; avoids `std::io::Cursor` overhead.
pub struct FastByteParser<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> FastByteParser<'a> {
#[inline(always)]
pub fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
#[inline(always)]
fn check_bounds(&self, needed: usize) -> Result<(), ParseError> {
// `pos` only advances past a passing check, so `pos <= len` always;
// the subtraction can't underflow. Phrased this way (not `pos + needed
// > len`) so a near-`u32::MAX` length can't wrap on the 32-bit guest
// and slip past the check into a panicking slice.
if needed > self.data.len() - self.pos {
Err(ParseError::OutOfBounds)
} else {
Ok(())
}
}
#[inline(always)]
fn read_u8(&mut self) -> Result<u8, ParseError> {
self.check_bounds(1)?;
let val = self.data[self.pos];
self.pos += 1;
Ok(val)
}
#[inline(always)]
fn read_u16(&mut self) -> Result<u16, ParseError> {
self.check_bounds(2)?;
let val = u16::from_le_bytes([self.data[self.pos], self.data[self.pos + 1]]);
self.pos += 2;
Ok(val)
}
#[inline(always)]
fn read_u32(&mut self) -> Result<u32, ParseError> {
self.check_bounds(4)?;
let val = u32::from_le_bytes([
self.data[self.pos],
self.data[self.pos + 1],
self.data[self.pos + 2],
self.data[self.pos + 3],
]);
self.pos += 4;
Ok(val)
}
#[inline(always)]
fn read_u64(&mut self) -> Result<u64, ParseError> {
self.check_bounds(8)?;
let val = u64::from_le_bytes([
self.data[self.pos],
self.data[self.pos + 1],
self.data[self.pos + 2],
self.data[self.pos + 3],
self.data[self.pos + 4],
self.data[self.pos + 5],
self.data[self.pos + 6],
self.data[self.pos + 7],
]);
self.pos += 8;
Ok(val)
}
#[inline(always)]
fn read_f64(&mut self) -> Result<f64, ParseError> {
self.check_bounds(8)?;
let val = f64::from_le_bytes([
self.data[self.pos],
self.data[self.pos + 1],
self.data[self.pos + 2],
self.data[self.pos + 3],
self.data[self.pos + 4],
self.data[self.pos + 5],
self.data[self.pos + 6],
self.data[self.pos + 7],
]);
self.pos += 8;
Ok(val)
}
#[inline(always)]
fn read_bytes_slice(&mut self) -> Result<&'a [u8], ParseError> {
let len = self.read_u32()? as usize;
self.check_bounds(len)?;
let bytes = &self.data[self.pos..self.pos + len];
self.pos += len;
Ok(bytes)
}
#[inline(always)]
fn read_short_bytes_slice(&mut self) -> Result<&'a [u8], ParseError> {
let len = self.read_u8()? as usize;
self.check_bounds(len)?;
let bytes = &self.data[self.pos..self.pos + len];
self.pos += len;
Ok(bytes)
}
#[inline(always)]
fn read_fixed_48(&mut self) -> Result<&'a [u8; 48], ParseError> {
self.check_bounds(48)?;
let slice = &self.data[self.pos..self.pos + 48];
self.pos += 48;
Ok(slice.try_into().unwrap())
}
#[inline(always)]
fn read_fixed_96(&mut self) -> Result<&'a [u8; 96], ParseError> {
self.check_bounds(96)?;
let slice = &self.data[self.pos..self.pos + 96];
self.pos += 96;
Ok(slice.try_into().unwrap())
}
/// Borrow the next `n` bytes and advance the cursor; consumers
/// decode entries lazily.
#[inline(always)]
fn read_n_bytes(&mut self, n: usize) -> Result<&'a [u8], ParseError> {
self.check_bounds(n)?;
let slice = &self.data[self.pos..self.pos + n];
self.pos += n;
Ok(slice)
}
}
/// Borrowed view over a serialised certificate; field slices index
/// directly into the source buffer.
#[derive(Debug)]
pub struct CertificateZeroCopy<'a> {
pub hash: &'a [u8],
pub previous_hash: &'a [u8],
pub epoch: u64,
pub metadata: MetadataBasicZeroCopy<'a>,
pub protocol_message: ProtocolMessageBasicZeroCopy<'a>,
pub signed_message: &'a [u8],
pub aggregate_verification_key: AggregateVerificationKeyParsed<'a>,
pub signature: SignatureBasicZeroCopy<'a>,
}
#[derive(Debug)]
pub struct MetadataBasicZeroCopy<'a> {
pub network: &'a [u8],
pub protocol_version: &'a [u8],
pub k: u64,
pub m: u64,
pub phi_f: f64,
pub initiated_at_timestamp: u64,
pub initiated_at_nanos: u32,
pub sealed_at_timestamp: u64,
pub sealed_at_nanos: u32,
pub signers: Vec<SignerBasicZeroCopy<'a>>,
}
#[derive(Debug)]
pub struct SignerBasicZeroCopy<'a> {
pub party_id: &'a [u8],
pub stake: u64,
}
#[derive(Debug)]
pub struct ProtocolMessageBasicZeroCopy<'a> {
pub parts: Vec<(u8, &'a [u8])>,
}
#[derive(Debug)]
pub struct AggregateVerificationKeyParsed<'a> {
pub root: &'a [u8], // 32-byte Blake2b<U32> Merkle root, borrowed.
pub nr_leaves: u64,
pub total_stake: u64,
}
#[derive(Debug)]
pub struct MultiSigParsed<'a> {
pub signatures: Vec<SignatureParsed<'a>>,
pub batch_proof_bytes: &'a [u8],
}
#[derive(Debug)]
pub struct SignatureParsed<'a> {
/// BLS G1 point, borrowed.
pub sigma_bytes: &'a [u8; 48],
/// `indexes_count` little-endian `u64`s, decoded on demand.
pub indexes_bytes: &'a [u8],
/// A single signer can win thousands of lottery indexes (few-signer,
/// large-quorum certs), so this is `u32`, not `u8`.
pub indexes_count: u32,
pub signer_index: u64,
/// BLS G2 point, borrowed.
pub vk_bytes: &'a [u8; 96],
pub stake: u64,
}
impl<'a> SignatureParsed<'a> {
#[inline]
pub fn indexes(&self) -> SignatureIndexIter<'a> {
SignatureIndexIter {
remaining: self.indexes_bytes,
}
}
#[inline]
pub fn indexes_len(&self) -> usize {
self.indexes_count as usize
}
}
/// Allocation-free iterator over [`SignatureParsed::indexes_bytes`].
pub struct SignatureIndexIter<'a> {
remaining: &'a [u8],
}
impl<'a> Iterator for SignatureIndexIter<'a> {
type Item = u64;
#[inline]
fn next(&mut self) -> Option<u64> {
if self.remaining.len() < 8 {
return None;
}
let (head, tail) = self.remaining.split_at(8);
self.remaining = tail;
Some(u64::from_le_bytes(head.try_into().unwrap()))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let n = self.remaining.len() / 8;
(n, Some(n))
}
}
impl ExactSizeIterator for SignatureIndexIter<'_> {}
#[derive(Debug)]
pub enum SignatureBasicZeroCopy<'a> {
Genesis {
signature_bytes: &'a [u8],
},
Multi {
entity_type_discriminant: u8,
/// At most three `u64`s per upstream `SignedEntityType`
/// (`CardanoBlocksTransactions` carries epoch, block number, and
/// offset). The discriminant identifies which slots are valid;
/// unused slots stay 0 and are never read.
entity_type_data: [u64; 3],
signature: MultiSigParsed<'a>,
},
}
#[inline]
pub fn certificate_from_bytes<'a>(bytes: &'a [u8]) -> Result<CertificateZeroCopy<'a>, ParseError> {
let mut parser = FastByteParser::new(bytes);
let hash = parser.read_bytes_slice()?;
let previous_hash = parser.read_bytes_slice()?;
let epoch = parser.read_u64()?;
let metadata = read_metadata_fast(&mut parser)?;
let protocol_message = read_protocol_message_fast(&mut parser)?;
let signed_message = parser.read_bytes_slice()?;
let aggregate_verification_key = read_aggregate_verification_key_fast(&mut parser)?;
let signature = read_signature_fast(&mut parser)?;
Ok(CertificateZeroCopy {
hash,
previous_hash,
epoch,
metadata,
protocol_message,
signed_message,
aggregate_verification_key,
signature,
})
}
#[inline]
fn read_metadata_fast<'a>(
parser: &mut FastByteParser<'a>,
) -> Result<MetadataBasicZeroCopy<'a>, ParseError> {
let network = parser.read_bytes_slice()?;
let protocol_version = parser.read_bytes_slice()?;
let k = parser.read_u64()?;
let m = parser.read_u64()?;
let phi_f = parser.read_f64()?;
let initiated_at_timestamp = parser.read_u64()?;
let initiated_at_nanos = parser.read_u32()?;
let sealed_at_timestamp = parser.read_u64()?;
let sealed_at_nanos = parser.read_u32()?;
let signers_count = parser.read_u16()? as usize;
let mut signers = Vec::with_capacity(signers_count);
for _ in 0..signers_count {
let party_id = parser.read_short_bytes_slice()?;
let stake = parser.read_u64()?;
signers.push(SignerBasicZeroCopy { party_id, stake });
}
Ok(MetadataBasicZeroCopy {
network,
protocol_version,
k,
m,
phi_f,
initiated_at_timestamp,
initiated_at_nanos,
sealed_at_timestamp,
sealed_at_nanos,
signers,
})
}
#[inline]
fn read_protocol_message_fast<'a>(
parser: &mut FastByteParser<'a>,
) -> Result<ProtocolMessageBasicZeroCopy<'a>, ParseError> {
let parts_count = parser.read_u8()? as usize;
let mut parts = Vec::with_capacity(parts_count);
for _ in 0..parts_count {
let key = parser.read_u8()?;
let value = parser.read_bytes_slice()?;
parts.push((key, value));
}
Ok(ProtocolMessageBasicZeroCopy { parts })
}
#[inline]
fn read_aggregate_verification_key_fast<'a>(
parser: &mut FastByteParser<'a>,
) -> Result<AggregateVerificationKeyParsed<'a>, ParseError> {
let root = parser.read_bytes_slice()?;
let nr_leaves = parser.read_u64()?;
let total_stake = parser.read_u64()?;
Ok(AggregateVerificationKeyParsed {
root,
nr_leaves,
total_stake,
})
}
#[inline]
fn read_multi_signature_fast<'a>(
parser: &mut FastByteParser<'a>,
) -> Result<MultiSigParsed<'a>, ParseError> {
let sig_count = parser.read_u16()? as usize;
let mut signatures = Vec::with_capacity(sig_count);
for _ in 0..sig_count {
let sigma_bytes = parser.read_fixed_48()?;
let idx_count = parser.read_u32()?;
// `* 8` can overflow `usize` on the 32-bit guest for an adversarial
// count; reject cleanly instead of wrapping.
let needed = (idx_count as usize)
.checked_mul(8)
.ok_or(ParseError::OutOfBounds)?;
let indexes_bytes = parser.read_n_bytes(needed)?;
let signer_index = parser.read_u64()?;
let vk_bytes = parser.read_fixed_96()?;
let stake = parser.read_u64()?;
signatures.push(SignatureParsed {
sigma_bytes,
indexes_bytes,
indexes_count: idx_count,
signer_index,
vk_bytes,
stake,
});
}
let batch_proof_bytes = parser.read_bytes_slice()?;
Ok(MultiSigParsed {
signatures,
batch_proof_bytes,
})
}
#[inline]
fn read_signature_fast<'a>(
parser: &mut FastByteParser<'a>,
) -> Result<SignatureBasicZeroCopy<'a>, ParseError> {
let discriminant = parser.read_u8()?;
match discriminant {
0 => {
let signature_bytes = parser.read_bytes_slice()?;
Ok(SignatureBasicZeroCopy::Genesis { signature_bytes })
}
1 => {
let entity_type_discriminant = parser.read_u8()?;
let entity_type_data = read_entity_type_data_fast(parser, entity_type_discriminant)?;
let signature = read_multi_signature_fast(parser)?;
Ok(SignatureBasicZeroCopy::Multi {
entity_type_discriminant,
entity_type_data,
signature,
})
}
_ => Err(ParseError::InvalidFormat),
}
}
/// Decode the inner `u64` fields of a `SignedEntityType` into a fixed
/// `[u64; 3]`. Variants with fewer fields leave the trailing slots `0`.
#[inline]
fn read_entity_type_data_fast(
parser: &mut FastByteParser,
discriminant: u8,
) -> Result<[u64; 3], ParseError> {
match discriminant {
0 | 1 => Ok([parser.read_u64()?, 0, 0]),
2..=4 => {
let a = parser.read_u64()?;
let b = parser.read_u64()?;
Ok([a, b, 0])
}
// CardanoBlocksTransactions: epoch, block number, offset.
5 => {
let a = parser.read_u64()?;
let b = parser.read_u64()?;
let c = parser.read_u64()?;
Ok([a, b, c])
}
_ => Err(ParseError::InvalidFormat),
}
}
#[cfg(test)]
mod entity_type_discriminant_tests {
//! Pin: parser admits discriminants 0..=5 and rejects everything
//! else. Tracks upstream Mithril's `SignedEntityType` arity (6
//! variants); a new variant or a removed one trips this test.
use super::{FastByteParser, ParseError, read_entity_type_data_fast};
const SCRATCH: [u8; 24] = [0u8; 24];
#[test]
fn rejects_discriminants_above_5() {
for d in 6u8..=255 {
let mut parser = FastByteParser::new(&SCRATCH);
let result = read_entity_type_data_fast(&mut parser, d);
assert!(
matches!(result, Err(ParseError::InvalidFormat)),
"discriminant {d} must reject; got {result:?}"
);
}
}
#[test]
fn accepts_discriminants_0_through_5() {
for d in 0u8..=5 {
let mut parser = FastByteParser::new(&SCRATCH);
let result = read_entity_type_data_fast(&mut parser, d);
assert!(result.is_ok(), "discriminant {d}: {result:?}");
}
}
}
#[cfg(test)]
mod bounds_overflow_tests {
//! `check_bounds` must reject without wrapping. The wrap only manifests
//! where `usize` is 32-bit (the guest); CI runs on a 64-bit host, so the
//! wrap itself is pinned at primitive width, and the parser is fuzzed for
//! panic-freedom on adversarial input.
use super::{ParseError, certificate_from_bytes};
#[test]
fn subtraction_form_is_wrap_safe_unlike_addition() {
// The shape `check_bounds` faces on the 32-bit guest: a length field
// near the type max with the cursor mid-buffer.
let (pos, needed, len) = (100u32, u32::MAX, 200u32);
// Old form `pos + needed > len`: the add wraps to 99, 99 > 200 is
// false — adversarial length wrongly passes as in-bounds.
assert!(pos.wrapping_add(needed) <= len, "demonstrates the wrap bug");
// New form `needed > len - pos`: u32::MAX > 100 — correctly rejected.
assert!(needed > len - pos, "subtraction form rejects");
}
#[test]
fn oversized_length_prefix_rejects_not_panics() {
// First field is a length-prefixed slice; a u32::MAX prefix with no
// payload must be a clean OutOfBounds, never a panic.
let bytes = [0xFFu8, 0xFF, 0xFF, 0xFF];
assert!(matches!(
certificate_from_bytes(&bytes),
Err(ParseError::OutOfBounds)
));
}
#[test]
fn malformed_bytes_never_panic() {
// Deterministic LCG over varied lengths and a sweep of oversized u32
// length prefixes at every offset; every input must yield Ok or Err.
let mut state: u64 = 0x9E3779B97F4A7C15;
let mut next = || {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
(state >> 33) as u32
};
let mut buf = Vec::with_capacity(512);
for len in 0..512usize {
buf.clear();
for _ in 0..len {
buf.push(next() as u8);
}
// Result is unused; the contract is that the call returns rather
// than panicking (catch is the test harness's own unwind guard).
let _ = certificate_from_bytes(&buf);
// Same buffer but with a 0xFFFFFFFF length prefix spliced at the
// front — exercises the read_bytes_slice wrap path directly.
let mut adv = vec![0xFFu8; 4];
adv.extend_from_slice(&buf);
let _ = certificate_from_bytes(&adv);
}
}
#[test]
fn valid_cert_byte_mutations_never_panic() {
// Structured fuzz: start from a real, parseable cert and corrupt it the
// way a wire error or adversary would — single-byte mutations and
// truncations — rather than from pure noise. Each length prefix flows
// through every length-driven read with a *valid* preamble in front, so
// it reaches deeper parser states than random bytes do. Every call must
// return (Ok or Err), never panic.
let valid = include_bytes!("../../testdata/cert_current.bin");
assert!(
certificate_from_bytes(valid).is_ok(),
"fixture cert_current.bin must parse as the fuzz baseline"
);
// Every truncation — exercises a clean cut at each offset.
for len in 0..valid.len() {
let _ = certificate_from_bytes(&valid[..len]);
}
// Single-byte mutations at a stride (full sweep would be 46k*3 parses;
// a stride still hits every field region). 0x00 / 0xFF / bit-flip flush
// out length fields, counts, and discriminants toward their edges.
let mut buf = valid.to_vec();
for pos in (0..valid.len()).step_by(7) {
let orig = buf[pos];
for m in [0x00u8, 0xFF, orig ^ 0xFF] {
buf[pos] = m;
let _ = certificate_from_bytes(&buf);
}
buf[pos] = orig;
}
}
}