7326767f37
tools/vectors/gen_vectors.py makes the crypto vectors with tools independent of RustCrypto: Python hashlib (SHA-256), the OpenSSL 3.5 CLI (RSA-2048 test-only keys, X.509 certs, PKCS#1 v1.5 SHA-256 signatures, AES-128-ECB -nopad, AES-128-CBC) and .NET 10 AesGcm (gcm_vectors.cs). Output goes to crates/domistream/tests/fixtures (text only); not generated in this commit. tests/common: seeded and scripted RandomSource, fixture reader, an independent GF(2^8)/0x11D reference with Cauchy matrices, and test hosts that packetize video (PROTOCOL.md 5.2-5.3) and audio (6.2-6.4). Dev-dependencies: proptest (std only, no fork/timeout) and peak_alloc (MIT, counting allocator for the allocation-cap test).
718 lines
25 KiB
Rust
718 lines
25 KiB
Rust
//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8)
|
||
//! reference, and builders for video and audio streams. Test code: panics are the way a test fails.
|
||
|
||
#![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
|
||
|
||
use std::collections::HashMap;
|
||
|
||
use domistream::RandomSource;
|
||
|
||
// ------------------------------------------------------------------------------------------------ assertions
|
||
|
||
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
||
#[macro_export]
|
||
macro_rules! assert_err {
|
||
($e:expr, $p:pat) => {
|
||
match $e {
|
||
Err($p) => {}
|
||
other => panic!("expected Err({}), got {:?}", stringify!($p), other),
|
||
}
|
||
};
|
||
($e:expr, $p:pat, $($ctx:tt)+) => {
|
||
match $e {
|
||
Err($p) => {}
|
||
other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)),
|
||
}
|
||
};
|
||
}
|
||
|
||
/// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers.
|
||
#[macro_export]
|
||
macro_rules! assert_too_large {
|
||
($e:expr, $max:expr, $actual:expr) => {
|
||
match $e {
|
||
Err(domistream::Error::TooLarge { max, actual, .. }) => {
|
||
assert_eq!(max, $max, "TooLarge.max");
|
||
assert_eq!(actual, $actual, "TooLarge.actual");
|
||
}
|
||
other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other),
|
||
}
|
||
};
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ randomness
|
||
|
||
/// A seeded, deterministic random source (splitmix64). Never for production.
|
||
#[derive(Clone, Debug)]
|
||
pub struct SeqRng(u64);
|
||
|
||
impl SeqRng {
|
||
pub fn new(seed: u64) -> Self {
|
||
Self(seed)
|
||
}
|
||
|
||
pub fn next_u64(&mut self) -> u64 {
|
||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||
let mut z = self.0;
|
||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||
z ^ (z >> 31)
|
||
}
|
||
|
||
/// Uniform in `0..n` (n > 0); bias is irrelevant for test data.
|
||
pub fn below(&mut self, n: usize) -> usize {
|
||
(self.next_u64() % n as u64) as usize
|
||
}
|
||
|
||
pub fn bytes(&mut self, n: usize) -> Vec<u8> {
|
||
let mut v = vec![0; n];
|
||
self.fill(&mut v);
|
||
v
|
||
}
|
||
|
||
/// `count` distinct indices from `0..n`, sorted.
|
||
pub fn subset(&mut self, n: usize, count: usize) -> Vec<usize> {
|
||
let mut all: Vec<usize> = (0..n).collect();
|
||
for i in 0..count.min(n) {
|
||
let j = i + self.below(n - i);
|
||
all.swap(i, j);
|
||
}
|
||
let mut chosen = all[..count.min(n)].to_vec();
|
||
chosen.sort_unstable();
|
||
chosen
|
||
}
|
||
|
||
pub fn shuffle<T>(&mut self, items: &mut [T]) {
|
||
for i in (1..items.len()).rev() {
|
||
let j = self.below(i + 1);
|
||
items.swap(i, j);
|
||
}
|
||
}
|
||
}
|
||
|
||
impl RandomSource for SeqRng {
|
||
fn fill(&mut self, dest: &mut [u8]) {
|
||
for chunk in dest.chunks_mut(8) {
|
||
let word = self.next_u64().to_le_bytes();
|
||
chunk.copy_from_slice(&word[..chunk.len()]);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under
|
||
/// test draws more than was recorded.
|
||
#[derive(Debug)]
|
||
pub struct ScriptedRng {
|
||
bytes: Vec<u8>,
|
||
pos: usize,
|
||
}
|
||
|
||
impl ScriptedRng {
|
||
pub fn new(bytes: Vec<u8>) -> Self {
|
||
Self { bytes, pos: 0 }
|
||
}
|
||
|
||
pub fn drawn(&self) -> usize {
|
||
self.pos
|
||
}
|
||
}
|
||
|
||
impl RandomSource for ScriptedRng {
|
||
fn fill(&mut self, dest: &mut [u8]) {
|
||
let end = self.pos + dest.len();
|
||
assert!(
|
||
end <= self.bytes.len(),
|
||
"the code drew {} random bytes but the recorded transcript holds only {} \
|
||
(fixture assumption: salt, then C, then secret_c, 16 bytes each)",
|
||
end,
|
||
self.bytes.len()
|
||
);
|
||
dest.copy_from_slice(&self.bytes[self.pos..end]);
|
||
self.pos = end;
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ fixtures
|
||
|
||
pub fn hex(s: &str) -> Vec<u8> {
|
||
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||
if s == "-" {
|
||
return Vec::new();
|
||
}
|
||
assert!(s.len() % 2 == 0, "odd hex length");
|
||
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect()
|
||
}
|
||
|
||
pub fn to_hex(b: &[u8]) -> String {
|
||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||
}
|
||
|
||
pub fn to_hex_upper(b: &[u8]) -> String {
|
||
b.iter().map(|x| format!("{x:02X}")).collect()
|
||
}
|
||
|
||
/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`.
|
||
pub struct Vectors(HashMap<String, String>);
|
||
|
||
impl Vectors {
|
||
pub fn parse(text: &str) -> Self {
|
||
let mut map = HashMap::new();
|
||
for line in text.lines() {
|
||
let line = line.trim();
|
||
if line.is_empty() || line.starts_with('#') {
|
||
continue;
|
||
}
|
||
let (k, v) = line.split_once(" = ").expect("fixture line `name = value`");
|
||
map.insert(k.to_string(), v.to_string());
|
||
}
|
||
Self(map)
|
||
}
|
||
|
||
pub fn str(&self, name: &str) -> &str {
|
||
self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing"))
|
||
}
|
||
|
||
pub fn bytes(&self, name: &str) -> Vec<u8> {
|
||
hex(self.str(name))
|
||
}
|
||
|
||
pub fn arr16(&self, name: &str) -> [u8; 16] {
|
||
self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes"))
|
||
}
|
||
|
||
pub fn u32_hex(&self, name: &str) -> u32 {
|
||
u32::from_str_radix(self.str(name), 16).expect("hex u32")
|
||
}
|
||
}
|
||
|
||
pub fn pairing_vectors() -> Vectors {
|
||
Vectors::parse(include_str!("../fixtures/pairing.txt"))
|
||
}
|
||
|
||
pub fn control_vectors() -> Vectors {
|
||
Vectors::parse(include_str!("../fixtures/control_gcm.txt"))
|
||
}
|
||
|
||
pub fn video_vectors() -> Vectors {
|
||
Vectors::parse(include_str!("../fixtures/video_gcm.txt"))
|
||
}
|
||
|
||
pub fn audio_vectors() -> Vectors {
|
||
Vectors::parse(include_str!("../fixtures/audio_cbc.txt"))
|
||
}
|
||
|
||
pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem");
|
||
pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem");
|
||
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||
|
||
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||
let mut out = Vec::new();
|
||
let mut acc = 0u32;
|
||
let mut bits = 0;
|
||
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
|
||
let v = match c {
|
||
b'A'..=b'Z' => c - b'A',
|
||
b'a'..=b'z' => c - b'a' + 26,
|
||
b'0'..=b'9' => c - b'0' + 52,
|
||
b'+' => 62,
|
||
b'/' => 63,
|
||
b'=' => break,
|
||
_ => panic!("not base64: {c:#x}"),
|
||
};
|
||
acc = (acc << 6) | u32::from(v);
|
||
bits += 6;
|
||
if bits >= 8 {
|
||
bits -= 8;
|
||
out.push((acc >> bits) as u8);
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
/// The DER inside every `-----BEGIN <label>-----` block of a PEM text.
|
||
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
|
||
let begin = format!("-----BEGIN {label}-----");
|
||
let end = format!("-----END {label}-----");
|
||
let mut out = Vec::new();
|
||
let mut rest = pem;
|
||
while let Some(start) = rest.find(&begin) {
|
||
let after = &rest[start + begin.len()..];
|
||
let stop = after.find(&end).expect("PEM end line");
|
||
out.push(base64_decode(&after[..stop]));
|
||
rest = &after[stop + end.len()..];
|
||
}
|
||
out
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ HTTP helpers
|
||
|
||
/// Splits a `path?query` into the path and its decoded parameters, in order.
|
||
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
|
||
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
|
||
let params = query
|
||
.split('&')
|
||
.filter(|p| !p.is_empty())
|
||
.map(|p| {
|
||
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||
(percent_decode(k), percent_decode(v))
|
||
})
|
||
.collect();
|
||
(path.to_string(), params)
|
||
}
|
||
|
||
pub fn percent_decode(s: &str) -> String {
|
||
let b = s.as_bytes();
|
||
let mut out = Vec::new();
|
||
let mut i = 0;
|
||
while i < b.len() {
|
||
if b[i] == b'%' && i + 2 < b.len() {
|
||
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
|
||
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
|
||
i += 3;
|
||
} else if b[i] == b'+' {
|
||
out.push(b' ');
|
||
i += 1;
|
||
} else {
|
||
out.push(b[i]);
|
||
i += 1;
|
||
}
|
||
}
|
||
String::from_utf8(out).expect("decoded query is UTF-8")
|
||
}
|
||
|
||
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
|
||
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
|
||
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
|
||
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
|
||
&found[0].1
|
||
}
|
||
|
||
/// `<root status_code="200">` + elements + `</root>`.
|
||
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
|
||
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
|
||
}
|
||
|
||
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
|
||
/// single text is long and the element count stays small.
|
||
pub fn xml_filler(len: usize) -> String {
|
||
assert!(len >= 7, "filler needs at least 7 bytes");
|
||
let mut out = String::with_capacity(len);
|
||
let mut remaining = len;
|
||
while remaining > 0 {
|
||
let piece = if remaining <= 207 {
|
||
remaining
|
||
} else if remaining - 207 >= 7 {
|
||
207
|
||
} else {
|
||
remaining - 7
|
||
};
|
||
out.push_str("<x>");
|
||
out.extend(std::iter::repeat_n('a', piece - 7));
|
||
out.push_str("</x>");
|
||
remaining -= piece;
|
||
}
|
||
assert_eq!(out.len(), len);
|
||
out
|
||
}
|
||
|
||
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
|
||
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
|
||
let bare = xml_root(200, inner).len();
|
||
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
|
||
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
|
||
assert_eq!(doc.len(), total);
|
||
doc
|
||
}
|
||
|
||
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
|
||
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
|
||
if cur.len() == size {
|
||
out.push(cur.clone());
|
||
return;
|
||
}
|
||
for i in start..n {
|
||
cur.push(i);
|
||
go(i + 1, n, size, cur, out);
|
||
cur.pop();
|
||
}
|
||
}
|
||
let mut out = Vec::new();
|
||
go(0, n, size, &mut Vec::new(), &mut out);
|
||
out
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||
|
||
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
|
||
pub mod gf {
|
||
pub fn mul(mut a: u8, mut b: u8) -> u8 {
|
||
let mut p = 0u8;
|
||
while b != 0 {
|
||
if b & 1 != 0 {
|
||
p ^= a;
|
||
}
|
||
let carry = a & 0x80 != 0;
|
||
a <<= 1;
|
||
if carry {
|
||
a ^= 0x1D;
|
||
}
|
||
b >>= 1;
|
||
}
|
||
p
|
||
}
|
||
|
||
pub fn inv(a: u8) -> u8 {
|
||
assert!(a != 0, "no inverse of 0");
|
||
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
|
||
}
|
||
|
||
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
|
||
/// invertible, so `[I; C]` is MDS.
|
||
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
|
||
assert!(rows + cols <= 256);
|
||
let mut m = Vec::with_capacity(rows * cols);
|
||
for i in 0..rows {
|
||
for j in 0..cols {
|
||
m.push(inv((i as u8) ^ ((rows + j) as u8)));
|
||
}
|
||
}
|
||
m
|
||
}
|
||
|
||
/// Parity shards for `data` with a row-major `parity × data` matrix.
|
||
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
|
||
let k = data.len();
|
||
let len = data[0].len();
|
||
(0..parity)
|
||
.map(|r| {
|
||
(0..len)
|
||
.map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x])))
|
||
.collect()
|
||
})
|
||
.collect()
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ video
|
||
|
||
/// One video packet as the test host built it.
|
||
#[derive(Clone, Debug)]
|
||
pub struct VPkt {
|
||
pub bytes: Vec<u8>,
|
||
pub frame_index: u32,
|
||
pub block: u8,
|
||
pub shard_index: u16,
|
||
pub data_shards: u16,
|
||
pub parity_shards: u16,
|
||
pub is_parity: bool,
|
||
}
|
||
|
||
/// What a frame should come out as.
|
||
#[derive(Clone, Debug)]
|
||
pub struct VExpect {
|
||
pub frame_index: u32,
|
||
pub header: [u8; 8],
|
||
pub bitstream: Vec<u8>,
|
||
pub rtp_timestamp: u32,
|
||
}
|
||
|
||
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
|
||
#[derive(Clone, Debug)]
|
||
pub struct VideoHost {
|
||
pub packet_size: u16,
|
||
pub next_sequence: u16,
|
||
pub timestamp: u32,
|
||
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
|
||
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
|
||
pub scramble_parity_headers: bool,
|
||
}
|
||
|
||
impl VideoHost {
|
||
pub fn new(packet_size: u16) -> Self {
|
||
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
|
||
}
|
||
|
||
pub fn payload_len(&self) -> usize {
|
||
usize::from(self.packet_size) - 16
|
||
}
|
||
|
||
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
|
||
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
|
||
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||
let mut b = vec![0, 0, 0, 1, 0x65];
|
||
b.extend(rng.bytes(len.saturating_sub(6)));
|
||
b.push(0x80 | rng.bytes(1)[0]);
|
||
b
|
||
}
|
||
|
||
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
|
||
pub fn frame(
|
||
&mut self,
|
||
frame_index: u32,
|
||
bitstream: &[u8],
|
||
fec_percentage: u8,
|
||
blocks: usize,
|
||
) -> (Vec<VPkt>, VExpect) {
|
||
let payload_len = self.payload_len();
|
||
let total_len = 8 + bitstream.len();
|
||
let shards_total = total_len.div_ceil(payload_len);
|
||
let last_payload_len = total_len - (shards_total - 1) * payload_len;
|
||
let mut header = [0u8; 8];
|
||
header[0] = 0x01;
|
||
header[1..3].copy_from_slice(&7u16.to_le_bytes());
|
||
header[3] = 2; // key frame
|
||
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
|
||
let mut data = header.to_vec();
|
||
data.extend_from_slice(bitstream);
|
||
data.resize(shards_total * payload_len, 0);
|
||
|
||
let blocks = blocks.clamp(1, 4).min(shards_total);
|
||
let base = shards_total / blocks;
|
||
let extra = shards_total % blocks;
|
||
let last_block = (blocks - 1) as u8;
|
||
let mut packets = Vec::new();
|
||
let mut shard_offset = 0;
|
||
for b in 0..blocks {
|
||
let k = base + usize::from(b < extra);
|
||
let m = (k * usize::from(fec_percentage)).div_ceil(100);
|
||
assert!(k + m <= 255, "test frame needs k + m <= 255");
|
||
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||
for i in 0..k {
|
||
let global = shard_offset + i;
|
||
let mut flags = 0x01;
|
||
if global == 0 {
|
||
flags |= 0x04;
|
||
}
|
||
if global == shards_total - 1 {
|
||
flags |= 0x02;
|
||
}
|
||
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
|
||
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
|
||
shards.push(p);
|
||
}
|
||
if m > 0 {
|
||
let code = domistream::fec::ReedSolomon::new(k, m)
|
||
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
|
||
let shard_len = shards[0].len();
|
||
let mut work: Vec<Vec<u8>> = shards.clone();
|
||
if self.scramble_parity_headers {
|
||
for (i, s) in work.iter_mut().enumerate() {
|
||
for (x, byte) in s[..32].iter_mut().enumerate() {
|
||
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
|
||
}
|
||
}
|
||
}
|
||
work.extend((0..m).map(|_| vec![0u8; shard_len]));
|
||
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
|
||
for j in 0..m {
|
||
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
|
||
p.extend_from_slice(&work[k + j][32..]);
|
||
shards.push(p);
|
||
}
|
||
}
|
||
for (i, bytes) in shards.into_iter().enumerate() {
|
||
packets.push(VPkt {
|
||
bytes,
|
||
frame_index,
|
||
block: b as u8,
|
||
shard_index: i as u16,
|
||
data_shards: k as u16,
|
||
parity_shards: m as u16,
|
||
is_parity: i >= k,
|
||
});
|
||
}
|
||
shard_offset += k;
|
||
}
|
||
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
|
||
self.timestamp = self.timestamp.wrapping_add(1500);
|
||
(packets, expect)
|
||
}
|
||
|
||
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
|
||
/// timestamp).
|
||
#[allow(clippy::too_many_arguments)]
|
||
fn header(
|
||
&mut self,
|
||
frame_index: u32,
|
||
flags: u8,
|
||
block: u8,
|
||
last_block: u8,
|
||
shard_index: usize,
|
||
data_shards: usize,
|
||
fec_percentage: u8,
|
||
) -> Vec<u8> {
|
||
let seq = self.next_sequence;
|
||
self.next_sequence = self.next_sequence.wrapping_add(1);
|
||
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
|
||
p.extend_from_slice(&[0x90, 0x00]);
|
||
p.extend_from_slice(&seq.to_be_bytes());
|
||
p.extend_from_slice(&self.timestamp.to_be_bytes());
|
||
p.extend_from_slice(&0u32.to_be_bytes());
|
||
p.extend_from_slice(&[0; 4]);
|
||
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||
p.extend_from_slice(&frame_index.to_le_bytes());
|
||
p.push(flags);
|
||
p.push(0);
|
||
p.push(0x10);
|
||
p.push((block << 4) | (last_block << 6));
|
||
let fec_info =
|
||
(u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
|
||
p.extend_from_slice(&fec_info.to_le_bytes());
|
||
p
|
||
}
|
||
}
|
||
|
||
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub fn video_packet_bytes(
|
||
seq: u16,
|
||
timestamp: u32,
|
||
frame_index: u32,
|
||
flags: u8,
|
||
multi_fec_blocks: u8,
|
||
fec_info: u32,
|
||
payload: &[u8],
|
||
) -> Vec<u8> {
|
||
let mut p = vec![0x90, 0x00];
|
||
p.extend_from_slice(&seq.to_be_bytes());
|
||
p.extend_from_slice(×tamp.to_be_bytes());
|
||
p.extend_from_slice(&0u32.to_be_bytes());
|
||
p.extend_from_slice(&[0; 4]);
|
||
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||
p.extend_from_slice(&frame_index.to_le_bytes());
|
||
p.extend_from_slice(&[flags, 0, 0x10, multi_fec_blocks]);
|
||
p.extend_from_slice(&fec_info.to_le_bytes());
|
||
p.extend_from_slice(payload);
|
||
p
|
||
}
|
||
|
||
pub fn fec_info(fec_percentage: u8, shard_index: u16, data_shards: u16) -> u32 {
|
||
(u32::from(fec_percentage) << 4) | (u32::from(shard_index) << 12) | (u32::from(data_shards) << 22)
|
||
}
|
||
|
||
/// AES-128-GCM sealing of a plaintext video packet with the layout of `docs/PROTOCOL.md` 7, using RustCrypto as
|
||
/// the test oracle (checked against the .NET vectors in `media.rs`).
|
||
pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: &[u8]) -> Vec<u8> {
|
||
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||
let cipher = aes_gcm::Aes128Gcm::new_from_slice(key).expect("key");
|
||
let mut iv = [0u8; 12];
|
||
iv[..8].copy_from_slice(&counter.to_le_bytes());
|
||
iv[11] = b'V';
|
||
let mut buf = plaintext.to_vec();
|
||
let tag = cipher
|
||
.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into())
|
||
.expect("gcm encrypt");
|
||
let mut out = iv.to_vec();
|
||
out.extend_from_slice(&frame_number.to_le_bytes());
|
||
out.extend_from_slice(tag.as_slice());
|
||
out.extend_from_slice(&buf);
|
||
out
|
||
}
|
||
|
||
// ------------------------------------------------------------------------------------------------ audio
|
||
|
||
/// AES-128-CBC + PKCS#7 with the audio IV of `docs/PROTOCOL.md` 6.3 (`rikeyid + seq`, wrapping), RustCrypto as
|
||
/// the test oracle (checked against the openssl vectors in `media.rs`).
|
||
pub fn audio_encrypt(key: &[u8; 16], rikeyid: u32, seq: u16, plaintext: &[u8]) -> Vec<u8> {
|
||
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||
let mut iv = [0u8; 16];
|
||
iv[..4].copy_from_slice(&rikeyid.wrapping_add(u32::from(seq)).to_be_bytes());
|
||
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
|
||
buf[..plaintext.len()].copy_from_slice(plaintext);
|
||
let len = cbc::Encryptor::<aes::Aes128>::new(key.into(), &iv.into())
|
||
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
|
||
.expect("cbc encrypt")
|
||
.len();
|
||
buf.truncate(len);
|
||
buf
|
||
}
|
||
|
||
/// One audio packet as the test host built it.
|
||
#[derive(Clone, Debug)]
|
||
pub struct APkt {
|
||
pub bytes: Vec<u8>,
|
||
pub sequence: u16,
|
||
pub block: usize,
|
||
/// 0..4 data, 4..6 parity.
|
||
pub index: usize,
|
||
}
|
||
|
||
/// What a data packet should come out as.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub struct AExpect {
|
||
pub sequence: u16,
|
||
pub timestamp_ms: u32,
|
||
pub opus: Vec<u8>,
|
||
}
|
||
|
||
/// Parity packets' RTP sequence number: "continues after the 4 data packets" (PROTOCOL.md 6.2), read as
|
||
/// base + 4 + shard index. The depacketizer must key parity by the FEC header's base sequence, not by this.
|
||
pub fn audio_parity_rtp_sequence(base: u16, shard: u8) -> u16 {
|
||
base.wrapping_add(4).wrapping_add(u16::from(shard))
|
||
}
|
||
|
||
/// A test host for audio: blocks of 4 data + 2 parity packets (`docs/PROTOCOL.md` 6.2-6.4).
|
||
pub struct AudioHost {
|
||
pub key: [u8; 16],
|
||
pub rikeyid: u32,
|
||
pub encrypt: bool,
|
||
pub matrix: [u8; 8],
|
||
pub duration_ms: u32,
|
||
pub opus_len: usize,
|
||
}
|
||
|
||
impl AudioHost {
|
||
/// `blocks` consecutive blocks starting at `first_seq` (a multiple of 4) and `first_ts`.
|
||
pub fn blocks(&self, rng: &mut SeqRng, first_seq: u16, first_ts: u32, blocks: usize) -> (Vec<APkt>, Vec<AExpect>) {
|
||
assert_eq!(first_seq % 4, 0);
|
||
let mut packets = Vec::new();
|
||
let mut expect = Vec::new();
|
||
for b in 0..blocks {
|
||
let base_seq = first_seq.wrapping_add((4 * b) as u16);
|
||
let base_ts = first_ts.wrapping_add(4 * b as u32 * self.duration_ms);
|
||
let mut shards = Vec::new();
|
||
for i in 0..4u16 {
|
||
let seq = base_seq.wrapping_add(i);
|
||
let ts = base_ts.wrapping_add(u32::from(i) * self.duration_ms);
|
||
let opus = rng.bytes(self.opus_len);
|
||
let payload =
|
||
if self.encrypt { audio_encrypt(&self.key, self.rikeyid, seq, &opus) } else { opus.clone() };
|
||
let mut p = vec![0x80, 97];
|
||
p.extend_from_slice(&seq.to_be_bytes());
|
||
p.extend_from_slice(&ts.to_be_bytes());
|
||
p.extend_from_slice(&0u32.to_be_bytes());
|
||
p.extend_from_slice(&payload);
|
||
packets.push(APkt { bytes: p, sequence: seq, block: b, index: usize::from(i) });
|
||
expect.push(AExpect { sequence: seq, timestamp_ms: ts, opus });
|
||
shards.push(payload);
|
||
}
|
||
let parity = gf::encode(&self.matrix, &shards, 2);
|
||
for (j, par) in parity.iter().enumerate() {
|
||
let seq = audio_parity_rtp_sequence(base_seq, j as u8);
|
||
let mut p = vec![0x80, 127];
|
||
p.extend_from_slice(&seq.to_be_bytes());
|
||
p.extend_from_slice(&base_ts.to_be_bytes());
|
||
p.extend_from_slice(&0u32.to_be_bytes());
|
||
p.push(j as u8);
|
||
p.push(97);
|
||
p.extend_from_slice(&base_seq.to_be_bytes());
|
||
p.extend_from_slice(&base_ts.to_be_bytes());
|
||
p.extend_from_slice(&0u32.to_be_bytes());
|
||
p.extend_from_slice(par);
|
||
packets.push(APkt { bytes: p, sequence: seq, block: b, index: 4 + j });
|
||
}
|
||
}
|
||
(packets, expect)
|
||
}
|
||
}
|
||
|
||
/// The 2 × 4 Cauchy parity matrix the audio tests pass through `AudioFec::ParityMatrix` (U16 is unmeasured; any
|
||
/// MDS matrix must work).
|
||
pub fn audio_test_matrix() -> [u8; 8] {
|
||
gf::cauchy(2, 4).try_into().expect("2x4")
|
||
}
|