logicaffeine_compile/concurrency/pnp.rs
1//! `PNP` — the information-theoretic true one-time pad tier, the last resort should
2//! computational cryptography fall (the `P = NP` scenario the name marks).
3//!
4//! Every other suite in [`super::channel`] — `Classic`, `Hybrid`, `PQ`, `PQ-Max` — rests on a
5//! hardness assumption (a lattice, a factoring, a discrete-log problem). If those assumptions
6//! collapse, so does the secrecy. This tier does not: a Vernam one-time pad is *perfectly secret*
7//! by Shannon's theorem, unconditionally, against a computationally unbounded adversary. The price
8//! Shannon exacts is exact and unavoidable — one truly random pad byte per plaintext byte, used
9//! once and never again — so this is a break-glass tier for crown-jewel traffic, not the bulk path.
10//!
11//! Two constraints define the design:
12//!
13//! 1. **A true pad, never a stream.** The pad is not grown from a seed by a PRG — that would be a
14//! stream cipher (computationally secure, and so it *would* fall with `P = NP`, defeating the
15//! entire purpose). The pad is pre-provisioned, externally-sourced true randomness, shared out of
16//! band. "Rotation" is a synchronized cursor advancing through that pool, consuming a fresh,
17//! never-reused segment per message.
18//! 2. **No randomness at runtime.** [`PnpSuite::seal`] / [`PnpSuite::open`] draw zero entropy — they
19//! are pure deterministic functions of `(pad, ledger, plaintext)`. All randomness is the pad.
20//!
21//! The pad is quality-gated at provisioning: a real pad is *incompressible* (`K(pad) ≈ |pad|`), so
22//! [`PadPool::shared`] rejects any pool the [`logicaffeine_proof::ait`] classifier can compress — a
23//! structured "pad" is a weak pad. (The connection is exact: a PRG-grown pad is by definition
24//! low-Kolmogorov-complexity, which is precisely what the classifier detects.)
25//!
26//! Confidentiality alone is not enough: XOR is malleable — flip a ciphertext bit and the plaintext
27//! bit flips, undetected. So each cover carries a **one-time Wegman–Carter MAC** (Poly1305 keyed by
28//! fresh pad bytes, [`logicaffeine_system::aead::poly1305`]); because the key is one-time pad
29//! material, the authentication is *also* information-theoretic, not computational.
30//!
31//! **Two regions per half.** A MAC key is only a secret while no ciphertext has exposed it, and a
32//! cover's keystream is exposed to anyone who knows its plaintext. So keystream and MAC keys never
33//! share pad: each directional half hands out keystream from its bottom, upward, and 32-byte MAC keys
34//! from its top, downward, one *key slot* per cover; the half is spent when the two meet. A cover names
35//! its key slot and its keystream offset, both under its tag, and a receiver keys the MAC only from the
36//! key region — were it to key the MAC from wherever a frame said, a cover placed over a known stretch
37//! of keystream would carry a MAC key its forger knows.
38//!
39//! **A durable ledger.** Reissuing a byte of pad is a two-time pad, and a cursor that lived only in
40//! the process would start at the bottom on every run. Every reservation is made through a
41//! [`PadLedgerStore`], which reads, advances and durably records the half's position under one
42//! exclusive hold before the frame exists, so a crash can only waste pad, and two holders of one ledger
43//! (two threads, two processes) never draw the same byte. The ledger also keeps the receive half's
44//! high-water key slot, so a cover opened before a restart is refused after it. A ledger that cannot
45//! be read closes the pad: it is never taken for a fresh one.
46//!
47//! **Speed.** `seal` writes the plaintext straight into the frame buffer and XORs the pad in place
48//! (one pass, LLVM-vectorized), then MACs a single *contiguous* region — no intermediate ciphertext
49//! copy, one allocation. Throughput is therefore bounded by Poly1305 (which has an AVX2 path) plus a
50//! memcpy-speed XOR: a one-time pad is cheap when the codec never copies the payload twice.
51//!
52//! **The next pad.** Net-new pad entropy cannot be produced inside the channel (Shannon), so the next
53//! pad is always fresh out-of-band randomness. What the codec provides is a *seamless, authenticated
54//! handoff*: each frame is tagged with its pad **epoch**; when a pool nears exhaustion a peer emits an
55//! authenticated **roll** cover (a kind-tagged cover, MAC'd by the *current* pad) committing to the
56//! next epoch's id and a hash of the next pad, so both sides confirm they hold identical bytes before
57//! switching.
58//!
59//! Frames ride the [`super::channel`] envelope:
60//!
61//! ```text
62//! [ CHAN_MAGIC | CHAN_VER | SUITE_PNP | kind:u8 | epoch:u32 | offset:u64 | len:u32 | slot:u64 | ct(len) | tag:16 ]
63//! ```
64
65use std::sync::{Arc, Mutex};
66
67use logicaffeine_proof::ait::{classify_bytes, CompressibilityClass};
68use logicaffeine_system::aead::poly1305;
69use logicaffeine_system::keccak::sha3_256_bytes;
70
71use super::channel::{
72 ActiveSession, ReplayWindow, CHAN_HEADER_LEN, CHAN_MAGIC, CHAN_VER, SUITE_PNP,
73};
74
75/// The one-time Poly1305 MAC key length: each cover takes one key slot of this many pad bytes from
76/// the top of its half, on top of the `len` keystream bytes it takes from the bottom.
77pub const MAC_KEY_LEN: usize = 32;
78
79/// The authenticator tag length (Poly1305).
80pub const TAG_LEN: usize = 16;
81
82/// Body field: cover kind ([`KIND_DATA`] / [`KIND_ROLL`]).
83const KIND_LEN: usize = 1;
84/// Body field: pad epoch this cover draws from.
85const EPOCH_LEN: usize = 4;
86/// Body field: half-local keystream offset of the cover.
87const OFF_LEN: usize = 8;
88/// Body field: payload length.
89const LEN_LEN: usize = 4;
90/// Body field: the key slot the cover's MAC key is drawn from.
91const SLOT_LEN: usize = 8;
92/// The fixed body preamble before the payload: `kind ‖ epoch ‖ offset ‖ len ‖ slot`.
93const PREAMBLE: usize = KIND_LEN + EPOCH_LEN + OFF_LEN + LEN_LEN + SLOT_LEN;
94
95/// A data cover: the payload is application ciphertext.
96const KIND_DATA: u8 = 0;
97/// A roll cover: the payload is `next_epoch:u32 ‖ next_commitment:32` — the authenticated handoff.
98const KIND_ROLL: u8 = 1;
99
100/// The default receiver reorder/replay window, in covers: a cover whose key slot is this many or more
101/// behind the newest one opened can no longer be told from a replay, and is refused. Forward jumps (a
102/// dropped cover skipped) are always fine.
103pub const RECV_WINDOW_COVERS: u64 = 4096;
104
105/// Which end of the shared pool this peer is. The pool is split identically on both peers into two
106/// directional halves so the two directions never draw overlapping pad — the same reasoning behind
107/// [`super::channel::derive_aead_key`]'s `i2r` / `r2i` split, made physical.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum Role {
110 /// The peer that draws its *send* pad from the first half (`i2r`).
111 Initiator,
112 /// The peer that draws its *send* pad from the second half (`r2i`).
113 Responder,
114}
115
116impl Role {
117 /// The role's name, as a `with pad … as <role>` clause spells it.
118 pub fn name(self) -> &'static str {
119 match self {
120 Role::Initiator => "initiator",
121 Role::Responder => "responder",
122 }
123 }
124}
125
126/// Why a pad pool was refused at provisioning.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum PadError {
129 /// The pool is too small to split into two directional halves.
130 TooSmall,
131 /// The pool is compressible — it carries exploitable structure and so is not truly random. A
132 /// real one-time pad is incompressible; a structured pool is a weak pool and is fail-closed.
133 Compressible,
134}
135
136/// Where one pad's two halves stand: what the send half has handed out, and how far the receive
137/// half has opened.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub struct PadLedger {
140 /// Keystream bytes the send half has handed out, from its bottom.
141 pub keystream: u64,
142 /// Key slots the send half has handed out, from its top.
143 pub key_slots: u64,
144 /// One past the newest key slot the receive half has opened; 0 when it has opened none.
145 pub opened_through: u64,
146}
147
148/// Why a ledger could not be read or recorded. Either way the pad is closed: a position that cannot be
149/// read could be a position that has already handed out every byte below it.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct LedgerError(pub String);
152
153impl std::fmt::Display for LedgerError {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 f.write_str(&self.0)
156 }
157}
158
159/// The durable record of a pad's position — the state whose loss would be catastrophic, because
160/// reissuing a byte the send half has handed out is a two-time pad.
161pub trait PadLedgerStore: Send + Sync {
162 /// Read the ledger, let `change` change it, and record the change durably before returning, all
163 /// under one exclusive hold: no other holder of this ledger reads it between the read and the
164 /// record. `change` answers `false` to leave the ledger as it was. Returns the ledger as it now
165 /// stands.
166 fn update(
167 &self,
168 change: &mut dyn FnMut(&mut PadLedger) -> bool,
169 ) -> Result<PadLedger, LedgerError>;
170}
171
172/// The in-memory ledger: correct for one process's sessions over a pad no other run will use.
173#[derive(Default)]
174pub struct MemLedger {
175 state: Mutex<PadLedger>,
176}
177
178impl PadLedgerStore for MemLedger {
179 fn update(
180 &self,
181 change: &mut dyn FnMut(&mut PadLedger) -> bool,
182 ) -> Result<PadLedger, LedgerError> {
183 let mut state = self
184 .state
185 .lock()
186 .unwrap_or_else(std::sync::PoisonError::into_inner);
187 change(&mut state);
188 Ok(*state)
189 }
190}
191
192/// The file ledger: the position lives in a file, every update holds an exclusive lock on a sibling
193/// lock file across its read and its record, and a record is written to a temporary file, synced,
194/// renamed over the ledger and the directory synced, so a crash leaves the old position or the new one
195/// and a restart resumes past every byte ever handed out. A missing ledger is a fresh pad; a ledger
196/// of any other shape, or one that cannot be read, is an error.
197#[cfg(not(target_arch = "wasm32"))]
198pub struct FileLedger {
199 path: std::path::PathBuf,
200}
201
202/// The first eight bytes of a file ledger: its format.
203#[cfg(not(target_arch = "wasm32"))]
204const LEDGER_MAGIC: &[u8; 8] = b"LGPNPLD1";
205
206/// A file ledger's length: its magic and three little-endian `u64`s.
207#[cfg(not(target_arch = "wasm32"))]
208const LEDGER_LEN: usize = 8 + 3 * 8;
209
210#[cfg(not(target_arch = "wasm32"))]
211impl FileLedger {
212 /// A ledger kept at `path` (created on its first record).
213 pub fn new(path: impl Into<std::path::PathBuf>) -> Self {
214 Self { path: path.into() }
215 }
216
217 /// The ledger a `with pad "<pad>" as <role>` session keeps beside its pad.
218 pub fn beside(pad: &std::path::Path, role: Role) -> Self {
219 let mut name = pad.as_os_str().to_owned();
220 name.push(format!(".{}.ledger", role.name()));
221 Self::new(std::path::PathBuf::from(name))
222 }
223
224 /// Where the ledger is kept.
225 pub fn path(&self) -> &std::path::Path {
226 &self.path
227 }
228
229 fn sibling(&self, suffix: &str) -> std::path::PathBuf {
230 let mut name = self.path.as_os_str().to_owned();
231 name.push(suffix);
232 std::path::PathBuf::from(name)
233 }
234
235 fn error(&self, what: &str, why: impl std::fmt::Display) -> LedgerError {
236 LedgerError(format!(
237 "the pad ledger '{}' {what}: {why}",
238 self.path.display()
239 ))
240 }
241
242 fn read(&self) -> Result<PadLedger, LedgerError> {
243 let bytes = match std::fs::read(&self.path) {
244 Ok(bytes) => bytes,
245 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(PadLedger::default()),
246 Err(e) => return Err(self.error("could not be read", e)),
247 };
248 if bytes.len() != LEDGER_LEN || &bytes[..8] != LEDGER_MAGIC {
249 return Err(self.error(
250 "is not a pad ledger",
251 format!(
252 "{} bytes, where a ledger is {LEDGER_LEN} beginning LGPNPLD1",
253 bytes.len()
254 ),
255 ));
256 }
257 let word = |i: usize| u64::from_le_bytes(bytes[8 + 8 * i..16 + 8 * i].try_into().unwrap());
258 Ok(PadLedger {
259 keystream: word(0),
260 key_slots: word(1),
261 opened_through: word(2),
262 })
263 }
264
265 fn record(&self, ledger: &PadLedger) -> Result<(), LedgerError> {
266 use std::io::Write;
267 let mut bytes = Vec::with_capacity(LEDGER_LEN);
268 bytes.extend_from_slice(LEDGER_MAGIC);
269 for word in [ledger.keystream, ledger.key_slots, ledger.opened_through] {
270 bytes.extend_from_slice(&word.to_le_bytes());
271 }
272 let temporary = self.sibling(".tmp");
273 let mut file =
274 std::fs::File::create(&temporary).map_err(|e| self.error("could not be written", e))?;
275 file.write_all(&bytes)
276 .map_err(|e| self.error("could not be written", e))?;
277 file.sync_all()
278 .map_err(|e| self.error("could not be synced", e))?;
279 std::fs::rename(&temporary, &self.path)
280 .map_err(|e| self.error("could not be replaced", e))?;
281 let directory = match self.path.parent() {
282 Some(dir) if !dir.as_os_str().is_empty() => dir,
283 _ => std::path::Path::new("."),
284 };
285 std::fs::File::open(directory)
286 .and_then(|dir| dir.sync_all())
287 .map_err(|e| self.error("could not be made durable in its directory", e))
288 }
289}
290
291#[cfg(not(target_arch = "wasm32"))]
292impl PadLedgerStore for FileLedger {
293 fn update(
294 &self,
295 change: &mut dyn FnMut(&mut PadLedger) -> bool,
296 ) -> Result<PadLedger, LedgerError> {
297 let lock = std::fs::OpenOptions::new()
298 .create(true)
299 .truncate(false)
300 .write(true)
301 .open(self.sibling(".lock"))
302 .map_err(|e| self.error("could not be locked", e))?;
303 lock.lock()
304 .map_err(|e| self.error("could not be locked", e))?;
305 let mut ledger = self.read()?;
306 if change(&mut ledger) {
307 self.record(&ledger)?;
308 }
309 Ok(ledger)
310 }
311}
312
313/// A keyed one-time-pad channel over one directional half of a [`PadPool`] at one pad epoch. A peer
314/// *seals* with the suite for its send direction and *opens* with the suite for its receive
315/// direction; because the two directions are different pad halves, a peer never seals and opens over
316/// the same bytes.
317pub struct PnpSuite {
318 pad: Arc<[u8]>,
319 base: usize,
320 len: usize,
321 epoch: u32,
322 ledger: Arc<dyn PadLedgerStore>,
323 recv: Mutex<RecvState>,
324}
325
326/// The receive half's memory of what it has opened: the exact window, once it has been resumed from
327/// the ledger's high-water mark.
328struct RecvState {
329 span: u64,
330 window: Option<ReplayWindow>,
331}
332
333impl PnpSuite {
334 fn over(pad: Arc<[u8]>, base: usize, len: usize, epoch: u32) -> Self {
335 Self {
336 pad,
337 base,
338 len,
339 epoch,
340 ledger: Arc::new(MemLedger::default()),
341 recv: Mutex::new(RecvState {
342 span: RECV_WINDOW_COVERS,
343 window: None,
344 }),
345 }
346 }
347
348 /// Keep this half's position in `ledger`: a durable one makes the position survive a restart.
349 pub fn with_ledger(self, ledger: Arc<dyn PadLedgerStore>) -> Self {
350 Self { ledger, ..self }
351 }
352
353 /// Set the receiver reorder/replay window, in covers: at least one, the newest.
354 pub fn with_recv_window(self, covers: u64) -> Self {
355 *self
356 .recv
357 .lock()
358 .unwrap_or_else(std::sync::PoisonError::into_inner) = RecvState {
359 span: covers.max(1),
360 window: None,
361 };
362 self
363 }
364
365 /// The pad epoch this suite draws from.
366 pub fn epoch(&self) -> u32 {
367 self.epoch
368 }
369
370 /// How many key slots this half holds.
371 fn slots(&self) -> u64 {
372 (self.len / MAC_KEY_LEN) as u64
373 }
374
375 /// The half-local start of key slot `slot`, counted down from the top.
376 fn key_start(&self, slot: u64) -> u64 {
377 self.len as u64 - MAC_KEY_LEN as u64 * (slot + 1)
378 }
379
380 /// Pad bytes neither region has handed out yet — the low-water gauge; 0 when the ledger cannot be
381 /// read. When this falls below `MAC_KEY_LEN` plus a message's length, [`PnpSuite::seal`] fails
382 /// closed.
383 pub fn send_remaining(&self) -> usize {
384 match self.ledger.update(&mut |_| false) {
385 Ok(l) => (self.len as u64)
386 .saturating_sub(l.keystream)
387 .saturating_sub(l.key_slots.saturating_mul(MAC_KEY_LEN as u64))
388 as usize,
389 Err(_) => 0,
390 }
391 }
392
393 /// Whether the send pad has dropped below `threshold` bytes — the signal to provision and roll to
394 /// the next epoch before exhaustion.
395 pub fn is_low(&self, threshold: usize) -> bool {
396 self.send_remaining() < threshold
397 }
398
399 /// Seal `blob` into a fresh data cover. `None` — fail-closed — when the pad is exhausted or its
400 /// ledger cannot be read or recorded.
401 pub fn seal(&self, blob: &[u8]) -> Option<Vec<u8>> {
402 self.seal_kind(KIND_DATA, blob)
403 }
404
405 /// Seal an authenticated **roll** cover announcing the next pad epoch and a commitment (hash) to
406 /// its bytes, using the current pad's one-time MAC. The peer confirms via [`PnpSuite::open_roll`]
407 /// that it holds the identical next pad before switching. `None` if the current pad is exhausted.
408 pub fn seal_roll(&self, next_epoch: u32, next_commitment: &[u8; 32]) -> Option<Vec<u8>> {
409 let mut payload = Vec::with_capacity(EPOCH_LEN + 32);
410 payload.extend_from_slice(&next_epoch.to_le_bytes());
411 payload.extend_from_slice(next_commitment);
412 self.seal_kind(KIND_ROLL, &payload)
413 }
414
415 /// Reserve the next cover of `len` keystream bytes: its key slot and its keystream offset, durably
416 /// recorded before the frame exists.
417 fn reserve(&self, len: u64) -> Option<(u64, u64)> {
418 let mut reserved = None;
419 self.ledger
420 .update(&mut |l| {
421 let slot = l.key_slots;
422 if slot >= self.slots() {
423 return false;
424 }
425 match l.keystream.checked_add(len) {
426 Some(end) if end <= self.key_start(slot) => {
427 reserved = Some((slot, l.keystream));
428 l.keystream = end;
429 l.key_slots = slot + 1;
430 true
431 }
432 _ => false,
433 }
434 })
435 .ok()?;
436 reserved
437 }
438
439 fn mac_key(&self, slot: u64) -> [u8; MAC_KEY_LEN] {
440 let at = self.base + self.key_start(slot) as usize;
441 self.pad[at..at + MAC_KEY_LEN]
442 .try_into()
443 .expect("a key slot is 32 bytes")
444 }
445
446 fn seal_kind(&self, kind: u8, blob: &[u8]) -> Option<Vec<u8>> {
447 let len = blob.len();
448 if len > u32::MAX as usize {
449 return None;
450 }
451 let (slot, offset) = self.reserve(len as u64)?;
452 let mac_key = self.mac_key(slot);
453
454 let mut out = Vec::with_capacity(CHAN_HEADER_LEN + PREAMBLE + len + TAG_LEN);
455 out.push(CHAN_MAGIC);
456 out.push(CHAN_VER);
457 out.extend_from_slice(&SUITE_PNP.to_le_bytes());
458 out.push(kind);
459 out.extend_from_slice(&self.epoch.to_le_bytes());
460 out.extend_from_slice(&offset.to_le_bytes());
461 out.extend_from_slice(&(len as u32).to_le_bytes());
462 out.extend_from_slice(&slot.to_le_bytes());
463 // Write ciphertext = plaintext ⊕ pad straight into the frame buffer via a vectorizable slice
464 // loop (the shape LLVM turns into SIMD): grow with a cheap memset, then overwrite in one pass.
465 let payload_start = CHAN_HEADER_LEN + PREAMBLE;
466 out.resize(payload_start + len, 0);
467 let at = self.base + offset as usize;
468 let xor = &self.pad[at..at + len];
469 for ((d, b), p) in out[payload_start..payload_start + len]
470 .iter_mut()
471 .zip(blob)
472 .zip(xor)
473 {
474 *d = b ^ p;
475 }
476
477 // MAC the contiguous body: kind ‖ epoch ‖ offset ‖ len ‖ slot ‖ ciphertext — no copy.
478 let tag = poly1305(&mac_key, &out[CHAN_HEADER_LEN..payload_start + len]);
479 out.extend_from_slice(&tag);
480 Some(out)
481 }
482
483 /// Open a data cover, or `None` on any malformed / tampered / replayed / wrong-epoch frame, or when
484 /// the ledger cannot record it.
485 pub fn open(&self, frame: &[u8]) -> Option<Vec<u8>> {
486 self.open_kind(KIND_DATA, frame)
487 }
488
489 /// Open a **roll** cover, returning the announced `(next_epoch, next_commitment)`. `None` on any
490 /// tampered / wrong-epoch / non-roll frame.
491 pub fn open_roll(&self, frame: &[u8]) -> Option<(u32, [u8; 32])> {
492 let pt = self.open_kind(KIND_ROLL, frame)?;
493 if pt.len() != EPOCH_LEN + 32 {
494 return None;
495 }
496 let next_epoch = u32::from_le_bytes(pt[0..EPOCH_LEN].try_into().ok()?);
497 let commitment: [u8; 32] = pt[EPOCH_LEN..EPOCH_LEN + 32].try_into().ok()?;
498 Some((next_epoch, commitment))
499 }
500
501 fn open_kind(&self, want_kind: u8, frame: &[u8]) -> Option<Vec<u8>> {
502 if frame.len() < CHAN_HEADER_LEN || frame[0] != CHAN_MAGIC || frame[1] != CHAN_VER {
503 return None;
504 }
505 if u16::from_le_bytes([frame[2], frame[3]]) != SUITE_PNP {
506 return None;
507 }
508 let body = &frame[CHAN_HEADER_LEN..];
509 if body.len() < PREAMBLE + TAG_LEN || body[0] != want_kind {
510 return None;
511 }
512 let epoch = u32::from_le_bytes(body[KIND_LEN..KIND_LEN + EPOCH_LEN].try_into().ok()?);
513 if epoch != self.epoch {
514 return None; // a cover from a different pad epoch
515 }
516 let off_at = KIND_LEN + EPOCH_LEN;
517 let offset = u64::from_le_bytes(body[off_at..off_at + OFF_LEN].try_into().ok()?);
518 let len_at = off_at + OFF_LEN;
519 let len = u32::from_le_bytes(body[len_at..len_at + LEN_LEN].try_into().ok()?) as usize;
520 let slot_at = len_at + LEN_LEN;
521 let slot = u64::from_le_bytes(body[slot_at..slot_at + SLOT_LEN].try_into().ok()?);
522 if body.len() != PREAMBLE + len + TAG_LEN || slot >= self.slots() {
523 return None;
524 }
525 if offset.checked_add(len as u64)? > self.key_start(slot) {
526 return None; // keystream reaching into the key region is no cover this half sealed
527 }
528 let tag = &body[PREAMBLE + len..];
529 let expect = poly1305(&self.mac_key(slot), &body[..PREAMBLE + len]);
530 if !ct_eq(&expect, tag) {
531 return None; // tamper — nothing recorded, so the genuine cover can still arrive
532 }
533
534 let mut recv = self
535 .recv
536 .lock()
537 .unwrap_or_else(std::sync::PoisonError::into_inner);
538 if recv.window.is_none() {
539 let through = self.ledger.update(&mut |_| false).ok()?.opened_through;
540 recv.window = Some(ReplayWindow::resumed_at(recv.span, through));
541 }
542 if !recv.window.as_ref().is_some_and(|w| w.admits(slot)) {
543 return None; // a replay, or beyond the reorder window
544 }
545 self.ledger
546 .update(&mut |l| {
547 let through = slot + 1;
548 if through > l.opened_through {
549 l.opened_through = through;
550 true
551 } else {
552 false
553 }
554 })
555 .ok()?;
556 if let Some(window) = recv.window.as_mut() {
557 window.accept(slot);
558 }
559 drop(recv);
560
561 let at = self.base + offset as usize;
562 let xor = &self.pad[at..at + len];
563 Some(
564 body[PREAMBLE..PREAMBLE + len]
565 .iter()
566 .zip(xor)
567 .map(|(c, p)| c ^ p)
568 .collect(),
569 )
570 }
571}
572
573/// A live bidirectional PNP session for the interpreter's send/receive seam: it seals outbound covers
574/// with this peer's send half and opens inbound covers with its receive half. Install it on the
575/// channel via [`super::channel::with_session`] / [`super::channel::install_session`] and every
576/// `Send` / receive on that thread is one-time-pad protected — fail-closed on exhaustion.
577pub struct PnpSession {
578 send: PnpSuite,
579 recv: PnpSuite,
580}
581
582impl PnpSession {
583 /// A session from an explicit send/receive suite pair.
584 pub fn new(send: PnpSuite, recv: PnpSuite) -> Self {
585 Self { send, recv }
586 }
587 /// The send half (seals outbound covers).
588 pub fn send(&self) -> &PnpSuite {
589 &self.send
590 }
591 /// The receive half (opens inbound covers).
592 pub fn recv(&self) -> &PnpSuite {
593 &self.recv
594 }
595}
596
597impl ActiveSession for PnpSession {
598 fn seal(&self, bytes: &[u8]) -> Option<Vec<u8>> {
599 self.send.seal(bytes)
600 }
601 fn open(&self, bytes: &[u8]) -> Option<Vec<u8>> {
602 self.recv.open(bytes)
603 }
604}
605
606/// A shared, pre-provisioned pool of true random bytes for one pad epoch, split into two directional
607/// halves. Both peers build an identical pool from the same out-of-band material and split it the
608/// same way, so each direction is a private, agreed pad both sides index into.
609pub struct PadPool {
610 pad: Arc<[u8]>,
611 split: usize,
612 epoch: u32,
613}
614
615impl PadPool {
616 /// Build a pool from shared true-random material, refusing it (fail-closed) if it is too small to
617 /// split or if the [`logicaffeine_proof::ait`] classifier finds it compressible — i.e. it is not
618 /// actually random. This is the pad-quality gate: a weak pad is never silently accepted.
619 pub fn shared(pad: Vec<u8>) -> Result<PadPool, PadError> {
620 if pad.len() < 2 {
621 return Err(PadError::TooSmall);
622 }
623 if classify_bytes(&pad).class != CompressibilityClass::Incompressible {
624 return Err(PadError::Compressible);
625 }
626 Ok(Self::shared_unchecked(pad))
627 }
628
629 /// Build a pool without the incompressibility gate — for trusted provisioning that has already
630 /// validated the material, and for tests that craft pad contents directly.
631 pub fn shared_unchecked(pad: Vec<u8>) -> PadPool {
632 let split = pad.len() / 2;
633 PadPool {
634 pad: pad.into(),
635 split,
636 epoch: 0,
637 }
638 }
639
640 /// Label this pool with a pad epoch (the id peers agree on for this pad in the rollover sequence).
641 pub fn with_epoch(mut self, epoch: u32) -> PadPool {
642 self.epoch = epoch;
643 self
644 }
645
646 /// The pad epoch of this pool.
647 pub fn epoch(&self) -> u32 {
648 self.epoch
649 }
650
651 /// A binding commitment to this pad — `SHA3-256(epoch ‖ pad)`. Both peers compute it from their
652 /// loaded material to confirm, over the authenticated [`PnpSuite::seal_roll`] handoff, that they
653 /// hold the identical next pad. Preimage-resistant, so it is safe to exchange; it reveals nothing
654 /// about the pad bytes.
655 pub fn commitment(&self) -> [u8; 32] {
656 let mut input = Vec::with_capacity(EPOCH_LEN + self.pad.len());
657 input.extend_from_slice(&self.epoch.to_le_bytes());
658 input.extend_from_slice(&self.pad);
659 sha3_256_bytes(&input)
660 }
661
662 /// Bytes available in each directional half.
663 pub fn direction_len(&self) -> usize {
664 self.split.min(self.pad.len() - self.split)
665 }
666
667 fn half(&self, first: bool) -> (usize, usize) {
668 if first {
669 (0, self.split)
670 } else {
671 (self.split, self.pad.len() - self.split)
672 }
673 }
674
675 /// The suite this peer seals outbound covers with (its send half).
676 pub fn send_suite(&self, role: Role) -> PnpSuite {
677 let (base, len) = self.half(role == Role::Initiator);
678 PnpSuite::over(self.pad.clone(), base, len, self.epoch)
679 }
680
681 /// The suite this peer opens inbound covers with (its receive half — the peer's send half).
682 pub fn recv_suite(&self, role: Role) -> PnpSuite {
683 let (base, len) = self.half(role == Role::Responder);
684 PnpSuite::over(self.pad.clone(), base, len, self.epoch)
685 }
686
687 /// A live [`PnpSession`] for `role` — seals with this peer's send half, opens with its receive
688 /// half — ready to install on the channel's active-session seam so the interpreter's Send/receive
689 /// path is one-time-pad protected end-to-end. Its position lives in memory: for a pad any other run
690 /// will use, [`PadPool::session_with_ledger`].
691 pub fn session(&self, role: Role) -> PnpSession {
692 PnpSession::new(self.send_suite(role), self.recv_suite(role))
693 }
694
695 /// A live [`PnpSession`] for `role` whose two halves keep their position in `ledger` (one ledger
696 /// for the pair: the send half records its reservations and the receive half its high-water mark).
697 pub fn session_with_ledger(&self, role: Role, ledger: Arc<dyn PadLedgerStore>) -> PnpSession {
698 PnpSession::new(
699 self.send_suite(role).with_ledger(ledger.clone()),
700 self.recv_suite(role).with_ledger(ledger),
701 )
702 }
703}
704
705/// The cover kind of a `PNP` frame (`KIND_DATA` / `KIND_ROLL`), or `None` if it is not a
706/// well-formed `PNP` frame — lets a receive loop dispatch data vs. handoff without opening.
707pub fn frame_kind(frame: &[u8]) -> Option<u8> {
708 if frame.len() < CHAN_HEADER_LEN + KIND_LEN
709 || frame[0] != CHAN_MAGIC
710 || frame[1] != CHAN_VER
711 || u16::from_le_bytes([frame[2], frame[3]]) != SUITE_PNP
712 {
713 return None;
714 }
715 Some(frame[CHAN_HEADER_LEN])
716}
717
718/// The half-local keystream offset a `PNP` frame draws from, or `None` if it is not a well-formed
719/// `PNP` frame. Useful for monitoring the pad high-water mark without opening the cover.
720pub fn frame_offset(frame: &[u8]) -> Option<u64> {
721 frame_word(frame, KIND_LEN + EPOCH_LEN)
722}
723
724/// The key slot a `PNP` frame's MAC key is drawn from, or `None` if it is not a well-formed `PNP`
725/// frame.
726pub fn frame_key_slot(frame: &[u8]) -> Option<u64> {
727 frame_word(frame, KIND_LEN + EPOCH_LEN + OFF_LEN + LEN_LEN)
728}
729
730fn frame_word(frame: &[u8], body_at: usize) -> Option<u64> {
731 let at = CHAN_HEADER_LEN + body_at;
732 if frame.len() < at + 8
733 || frame[0] != CHAN_MAGIC
734 || frame[1] != CHAN_VER
735 || u16::from_le_bytes([frame[2], frame[3]]) != SUITE_PNP
736 {
737 return None;
738 }
739 Some(u64::from_le_bytes(frame[at..at + 8].try_into().ok()?))
740}
741
742/// Constant-time tag comparison — no early return on the first differing byte.
743fn ct_eq(a: &[u8], b: &[u8]) -> bool {
744 if a.len() != b.len() {
745 return false;
746 }
747 let mut diff = 0u8;
748 for (x, y) in a.iter().zip(b) {
749 diff |= x ^ y;
750 }
751 diff == 0
752}
753
754#[cfg(test)]
755#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/concurrency/pnp/tests.rs"]
756mod tests;