Files
punktfunk/crates/punktfunk-core/tests/loopback.rs
T
enricobuehler d36bec6e9d
android / android (push) Has been cancelled
apple / screenshots (push) Has been cancelled
apple / swift (push) Has been cancelled
arch / build-publish (push) Has been cancelled
audit / bun-audit (push) Failing after 13s
audit / cargo-audit (push) Has been cancelled
ci / bench (push) Has been cancelled
ci / docs-site (push) Has been cancelled
ci / rust (push) Has been cancelled
ci / web (push) Has been cancelled
deb / build-publish (push) Has been cancelled
deb / build-publish-host (push) Has been cancelled
decky / build-publish (push) Has been cancelled
docker / build-push (ci, ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Has been cancelled
docker / build-push (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Has been cancelled
docker / deploy-docs (push) Has been cancelled
docker / build-push (--build-arg FEDORA_VERSION=44, ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm) (push) Has been cancelled
docker / build-push (ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Has been cancelled
docker / build-push (ci, ci/rust-ci-noble.Dockerfile, punktfunk-rust-ci-noble) (push) Has been cancelled
docker / build-push (., web/Dockerfile, punktfunk-web) (push) Has been cancelled
flatpak / build-publish (push) Has been cancelled
release / apple (push) Successful in 10m1s
windows-host / package (push) Successful in 11m20s
windows-msix / package (arm64, C:\Users\Public\ffmpeg-arm64, --no-default-features, aarch64-pc-windows-msvc, C:\t-a64) (push) Successful in 3m29s
windows-msix / package (x64, C:\Users\Public\ffmpeg, , x86_64-pc-windows-msvc, C:\t) (push) Successful in 4m14s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 22m16s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 22m27s
windows / build (aarch64-pc-windows-msvc) (push) Successful in 5m28s
windows / build (x86_64-pc-windows-msvc) (push) Successful in 6m39s
feat(core+host): negotiate ChaCha20-Poly1305 as the session cipher for soft-AES clients
Lifts the ~100 Mbps decrypt ceiling on clients without hardware AES — the
armv7 soft-AES targets (webOS TVs), where AES-128-GCM resolves to fixsliced
software AES + software GHASH (~50-100 cpb) while ChaCha20-Poly1305's ARX
construction runs ~10-17 cpb portable, a 4-7x lift that PyroWave-on-TV needs
(design/chacha20-session-cipher.md).

Phase 1 (core crypto, no wire change): SessionKey merges cipher choice and
key material (invalid combinations unrepresentable, zeroize + redacted-Debug
discipline kept); SessionCrypto dispatches both aead-0.5 ciphers per call —
the salt||seq nonce scheme, per-direction salts, seq-as-AAD and replay
window carry over verbatim (same 96-bit nonce / 16-byte tag, const-asserted).
Config.key becomes SessionKey; validate's zero-key rejection follows the
active variant. The C ABI keeps its fixed 16-byte key mapped to AES — no
ABI_VERSION bump.

Phase 2 (negotiation): VIDEO_CAP_CHACHA20 (0x40) — support-plus-request in
one bit, the VIDEO_CAP_444 precedent. Welcome grows cipher@68 +
key_chacha@69..101, emitted only when non-zero so an AES session's Welcome
stays byte-identical to the pre-cipher form; decode is fail-closed (short
key or unknown id -> Err, never a silent AES fallback). No WIRE_VERSION
bump; downgrade resistance inherited from the pinned-TLS control channel.

Phase 3 (host): grant only when the client advertised the bit and the
PUNKTFUNK_CHACHA20 kill-switch (default on, documented) allows; fresh
32-byte per-session key from the same RNG discipline, legacy key field
stays independently random; resolved cipher logged at session start.

Verification: seal/open suites parameterized over both ciphers + a
cross-cipher tamper case; Welcome roundtrip/truncation/fail-closed tests;
ChaCha lossy-loopback soak (loss/replay is cipher-independent); bench
gains _chacha20 series (AES ids unchanged for CI history) — host-side
sealing line-rate-trivial on both x86 (~640 MiB/s) and Apple Silicon
(~535 MiB/s). punktfunk-probe drives the interop matrix via
PUNKTFUNK_CLIENT_CHACHA20=1 and logs the negotiated cipher.

Phase 4 (pf-webos pin bump + unconditional cap bit) follows the next
core release.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 22:50:00 +02:00

254 lines
9.0 KiB
Rust

//! Core acceptance: round-trip access units through the full host→client path
//! (packetize → FEC → loopback with simulated loss → recover → reassemble) and assert
//! byte-exact recovery, for both FEC schemes, with and without encryption. Plus
//! property tests over the FEC layer's loss patterns.
use proptest::prelude::*;
use punktfunk_core::config::{Config, FecConfig, FecScheme, ProtocolPhase, Role};
use punktfunk_core::crypto::SessionKey;
use punktfunk_core::fec::coder_for;
use punktfunk_core::input::{InputEvent, InputKind};
use punktfunk_core::session::Session;
use punktfunk_core::transport::loopback_pair;
fn config(role: Role, scheme: FecScheme, encrypt: bool, drop_period: u32) -> Config {
Config {
role,
phase: match scheme {
FecScheme::Gf8 => ProtocolPhase::P1GameStream,
FecScheme::Gf16 => ProtocolPhase::P2Punktfunk,
},
fec: FecConfig {
scheme,
fec_percent: 25,
max_data_per_block: 32,
},
shard_payload: 1024,
max_frame_bytes: 8 * 1024 * 1024,
encrypt,
key: SessionKey::Aes128Gcm([7u8; 16]),
salt: [1, 2, 3, 4],
loopback_drop_period: drop_period,
}
}
/// Drive `frames` access units host→client over a lossy loopback and assert each one
/// comes back byte-identical. Returns the client's final stats.
fn run_stream(
scheme: FecScheme,
encrypt: bool,
drop_period: u32,
frames: &[Vec<u8>],
) -> punktfunk_core::Stats {
let (host_tp, client_tp) = loopback_pair(drop_period, 0);
let mut host = Session::new(
config(Role::Host, scheme, encrypt, drop_period),
Box::new(host_tp),
)
.unwrap();
let mut client = Session::new(
config(Role::Client, scheme, encrypt, drop_period),
Box::new(client_tp),
)
.unwrap();
for (i, frame) in frames.iter().enumerate() {
host.submit_frame(frame, i as u64 * 1_000_000, 0).unwrap();
let got = client
.poll_frame()
.expect("frame should recover despite loss");
assert_eq!(&got.data, frame, "frame {i} mismatched after recovery");
assert_eq!(got.frame_index, i as u32);
assert_eq!(got.pts_ns, i as u64 * 1_000_000);
}
client.stats()
}
fn sample_frames() -> Vec<Vec<u8>> {
(0..5usize)
.map(|f| {
let len = 1 + f * 40_000; // 1, 40k, 80k, 120k, 160k → single- and multi-block
(0..len)
.map(|b| (b.wrapping_mul(31).wrapping_add(f * 7)) as u8)
.collect()
})
.collect()
}
#[test]
fn gf8_stream_recovers_under_loss() {
let frames = sample_frames();
// drop_period 8 deletes the 1st of every 8 packets → real data-shard loss.
let stats = run_stream(FecScheme::Gf8, false, 8, &frames);
assert_eq!(stats.frames_completed, frames.len() as u64);
assert!(
stats.fec_recovered_shards > 0,
"loss should have forced FEC recovery"
);
}
#[test]
fn gf16_stream_recovers_under_loss() {
let frames = sample_frames();
let stats = run_stream(FecScheme::Gf16, false, 8, &frames);
assert_eq!(stats.frames_completed, frames.len() as u64);
assert!(stats.fec_recovered_shards > 0);
}
#[test]
fn encrypted_stream_recovers_under_loss() {
let frames = sample_frames();
let stats = run_stream(FecScheme::Gf8, true, 8, &frames);
assert_eq!(stats.frames_completed, frames.len() as u64);
}
/// The negotiated ChaCha20-Poly1305 session cipher through the same lossy full-stream path:
/// loss/replay behavior is cipher-independent (the replay window keys off the authenticated
/// seq), so recovery must be byte-identical to the AES run above.
#[test]
fn chacha20_encrypted_stream_recovers_under_loss() {
let frames = sample_frames();
let mk = |role| {
let mut c = config(role, FecScheme::Gf16, true, 8);
c.key = SessionKey::ChaCha20Poly1305([7u8; 32]);
c
};
let (host_tp, client_tp) = loopback_pair(8, 0);
let mut host = Session::new(mk(Role::Host), Box::new(host_tp)).unwrap();
let mut client = Session::new(mk(Role::Client), Box::new(client_tp)).unwrap();
for (i, frame) in frames.iter().enumerate() {
host.submit_frame(frame, i as u64 * 1_000_000, 0).unwrap();
let got = client
.poll_frame()
.expect("frame should recover despite loss");
assert_eq!(&got.data, frame, "frame {i} mismatched after recovery");
}
assert!(client.stats().fec_recovered_shards > 0);
}
#[test]
fn lossless_stream_is_exact() {
let frames = sample_frames();
let stats = run_stream(FecScheme::Gf16, false, 0, &frames);
assert_eq!(stats.frames_completed, frames.len() as u64);
assert_eq!(
stats.fec_recovered_shards, 0,
"no loss → nothing to recover"
);
}
/// The client's latency-bound escape hatch: `flush_backlog` must discard every queued datagram
/// (counting them dropped), reset the reassembler so half-assembled frames from the flushed past
/// can't linger, and leave the session healthy — the next submitted frame recovers byte-exact.
#[test]
fn flush_backlog_discards_queue_and_recovers() {
let (host_tp, client_tp) = loopback_pair(0, 0);
let mut host = Session::new(
config(Role::Host, FecScheme::Gf16, false, 0),
Box::new(host_tp),
)
.unwrap();
let mut client = Session::new(
config(Role::Client, FecScheme::Gf16, false, 0),
Box::new(client_tp),
)
.unwrap();
let frames = sample_frames();
// Read one frame first so the client's recv ring exists and may hold an undelivered tail.
host.submit_frame(&frames[0], 0, 0).unwrap();
client.poll_frame().unwrap();
// Queue a multi-frame backlog, then flush it: everything pending is discarded.
for (i, f) in frames.iter().enumerate().skip(1) {
host.submit_frame(f, i as u64 * 1_000_000, 0).unwrap();
}
let flushed = client.flush_backlog().unwrap();
assert!(flushed > 0, "a queued backlog must be discarded");
assert_eq!(client.stats().packets_dropped, flushed);
assert!(
matches!(
client.poll_frame(),
Err(punktfunk_core::PunktfunkError::NoFrame)
),
"nothing pending after a flush"
);
// The stream resumes cleanly: the next frame (the "recovery keyframe") completes byte-exact.
let recovery = vec![0xA5u8; 100_000];
host.submit_frame(&recovery, 99_000_000, 0).unwrap();
let got = client.poll_frame().expect("post-flush frame completes");
assert_eq!(got.data, recovery);
}
#[test]
fn input_round_trips_client_to_host() {
let (host_tp, client_tp) = loopback_pair(0, 0);
let mut host = Session::new(
config(Role::Host, FecScheme::Gf8, false, 0),
Box::new(host_tp),
)
.unwrap();
let mut client = Session::new(
config(Role::Client, FecScheme::Gf8, false, 0),
Box::new(client_tp),
)
.unwrap();
let sent = InputEvent {
kind: InputKind::MouseMove,
_pad: [0; 3],
code: 0,
x: -7,
y: 13,
flags: 0,
};
client.send_input(&sent).unwrap();
let got = host
.poll_input()
.unwrap()
.expect("host should receive the input event");
assert_eq!(got, sent);
}
// ---- property tests over the FEC layer --------------------------------------
proptest! {
/// For random shard counts and an erasure set within the recovery budget, every
/// original shard is reconstructed byte-identically — for both backends.
#[test]
fn fec_recovers_any_loss_within_budget(
k in 1usize..40,
extra in 0usize..16, // recovery beyond the bare minimum
shard_half in 1usize..64, // shard_len = 2*shard_half (even)
seed in any::<u64>(),
) {
let m = (extra + 1).min(40);
let shard_len = shard_half * 2;
for coder in [coder_for(FecScheme::Gf8), coder_for(FecScheme::Gf16)] {
// Gf8 ceiling: data + recovery <= 255.
if matches!(coder.scheme(), FecScheme::Gf8) && k + m > 255 { continue; }
let data: Vec<Vec<u8>> = (0..k)
.map(|i| (0..shard_len).map(|b| (i ^ b).wrapping_add(seed as usize) as u8).collect())
.collect();
let refs: Vec<&[u8]> = data.iter().map(|s| s.as_slice()).collect();
let recovery = coder.encode(&refs, m).unwrap();
let mut received: Vec<Option<Vec<u8>>> =
data.iter().cloned().map(Some).chain(recovery.into_iter().map(Some)).collect();
// Erase up to `m` shards chosen by a cheap PRNG over the seed.
let total = k + m;
let lose = (seed as usize % (m + 1)).min(m);
let mut s = seed | 1;
for _ in 0..lose {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
let idx = (s >> 33) as usize % total;
received[idx] = None;
}
let restored = coder.reconstruct(k, m, &mut received).unwrap();
prop_assert_eq!(restored, data);
}
}
}