logicaffeine_base/describe.rs
1//! # Integer-sequence description-length codec (the MDL primitive)
2//!
3//! A pure, self-contained engine that describes an `&[i64]` by the **shortest** program in a fixed
4//! menu of closed-form generators — affine (`base + i·stride`), geometric (`base · ratioⁱ`), a
5//! degree-≤4 polynomial (finite-difference seeds), a periodic block, a sparse dominant-value form, a
6//! sandboxed [`GenExpr`] generator, and the columnar fallbacks (delta, delta-of-delta,
7//! frame-of-reference bit-pack, run-length, dictionary, raw byte column, plain zig-zag varint). Each
8//! candidate is a complete self-delimiting byte string; [`consider`] keeps the smallest, so the
9//! result is **never larger than plain varint**.
10//!
11//! [`describe_int_seq`] is a *computable upper bound on the Kolmogorov complexity* of the sequence
12//! over this description language, and [`decode_int_seq`] is its exact inverse — decode reproduces
13//! the sequence bit-for-bit, so the encoded bytes are a **re-checkable witness** for that bound.
14//!
15//! This is the same codec the wire layer (`logicaffeine_compile`'s `marshal`) uses for its
16//! `WireStructure::Auto` int columns; it lives here in the leaf crate so both the wire codec and the
17//! proof layer share one implementation of the format. The crate has no I/O and no receiver policy,
18//! so the DoS bound (`max_elements`) is a **parameter**, supplied by each caller.
19
20// ---- Tuning + format constants -------------------------------------------------------------
21
22/// A cap on a length prefix's pre-allocation, so a corrupt huge count can't ask for gigabytes up
23/// front; the actual reads still bound-check every element.
24const PREALLOC_CAP: usize = 4096;
25
26/// The longest repeating block the periodic detector will consider.
27const PERIOD_CAP: usize = 512;
28
29/// The highest polynomial degree the generator detector will fit (degree 1 is the affine case).
30pub const MAX_POLY_DEGREE: usize = 4;
31
32/// The highest constant-coefficient linear-recurrence order the detector will fit. Order 2 already
33/// covers Fibonacci / Lucas / Pell and any LFSR of that length (this is Berlekamp–Massey over ℤ).
34pub const MAX_RECUR_ORDER: usize = 4;
35
36/// The largest byte column on which the GF(2) LFSR detector runs. Berlekamp–Massey is `O(bits²)`, so
37/// this bounds the deep-attack cost; it runs only as a LAST RESORT on columns nothing else compressed.
38const LFSR_MAX_BYTES: usize = 512;
39
40/// The largest byte column on which the 2-adic FCSR detector runs (bignum rational reconstruction).
41const FCSR_MAX_BYTES: usize = 256;
42
43/// A decode cap so a corrupt run-length can't ask for terabytes of output.
44const RLE_MAX_TOTAL: usize = 1 << 28;
45
46/// A hostile/garbage [`GenExpr`] tree is rejected past this many nodes.
47pub const MAX_GEN_NODES: u32 = 256;
48
49/// …or this deep — bounds both decode recursion and eval.
50pub const MAX_GEN_DEPTH: u32 = 32;
51
52/// The nesting cap for a periodic column whose block is itself a column (bounds decode recursion).
53const DECODE_MAX_DEPTH: u32 = 32;
54
55/// A generous element cap for the standalone [`decode_int_seq`] (which has no receiver policy): a
56/// tampered generator descriptor still cannot materialize more than this many elements.
57const DEFAULT_MAX_ELEMENTS: usize = 1 << 28;
58
59// The `T_INTS_*` tags for the Auto column menu. These bytes are the wire format; the wider tag space
60// (structs, strings, floats, …) lives in the wire codec that also speaks these.
61pub const T_INTS: u8 = 19; // adaptive-sign zig-zag varint per element (the plain baseline)
62pub const T_INTS_AFFINE: u8 = 32; // closed-form: base + stride·i (3 numbers, no data)
63pub const T_INTS_DELTA: u8 = 39; // first + zig-zag successive differences — monotone columns
64pub const T_INTS_DOD: u8 = 40; // first + first delta + zig-zag second differences — near-linear
65pub const T_INTS_FOR: u8 = 41; // min + bit-width + bit-packed (v-min) residuals — clustered
66pub const T_INTS_RLE: u8 = 42; // (value, run-length) pairs — runs of repeats
67pub const T_INTS_DICT: u8 = 43; // distinct values + bit-packed indices — low cardinality
68pub const T_INTS_POLY: u8 = 50; // degree + (degree+1) finite-difference seeds — a polynomial column
69pub const T_GEN: u8 = 51; // a serialized GenExpr over the index `i` (the general generator form)
70pub const T_BYTES: u8 = 53; // raw 1-byte-per-element blob — a byte column
71pub const T_INTS_GEOMETRIC: u8 = 61; // closed-form: base · ratioⁱ (3 numbers, no data)
72pub const T_INTS_PERIODIC: u8 = 62; // cyclic: period p + count + one block → pattern[i % p]
73pub const T_INTS_SPARSE: u8 = 67; // dominant value + (delta-index, value) exceptions — sparse
74pub const T_INTS_LRECUR: u8 = 82; // constant-coefficient linear recurrence: order + coeffs + seeds
75pub const T_INTS_LFSR: u8 = 83; // GF(2) LFSR: byte count + linear complexity L + L feedback taps + L seed bits
76pub const T_INTS_FCSR: u8 = 84; // 2-adic FCSR: byte count + rational p/q (p then q, each sign+len+LE bytes)
77
78// ---- Varint / zig-zag primitives -----------------------------------------------------------
79
80/// LEB128 unsigned varint: 7 bits per byte, high bit = continuation.
81#[inline]
82pub fn write_uvarint(mut x: u64, out: &mut Vec<u8>) {
83 while x >= 0x80 {
84 out.push((x as u8) | 0x80);
85 x >>= 7;
86 }
87 out.push(x as u8);
88}
89
90/// Read a LEB128 unsigned varint. `None` on an overlong/overflowing encoding or a short buffer.
91#[inline]
92pub fn read_uvarint(buf: &[u8], pos: &mut usize) -> Option<u64> {
93 let mut result = 0u64;
94 let mut shift = 0u32;
95 loop {
96 let b = *buf.get(*pos)?;
97 *pos += 1;
98 if shift >= 64 {
99 return None; // overlong / overflow
100 }
101 result |= u64::from(b & 0x7f) << shift;
102 if b & 0x80 == 0 {
103 return Some(result);
104 }
105 shift += 7;
106 }
107}
108
109/// Map a signed integer to an unsigned one with small magnitudes near zero (for varint).
110#[inline]
111pub fn zigzag(x: i64) -> u64 {
112 ((x << 1) ^ (x >> 63)) as u64
113}
114
115/// The inverse of [`zigzag`].
116#[inline]
117pub fn unzigzag(x: u64) -> i64 {
118 ((x >> 1) as i64) ^ -((x & 1) as i64)
119}
120
121/// The number of bytes [`write_uvarint`] would emit for `x`.
122pub fn uvarint_byte_len(x: u64) -> usize {
123 (((64 - x.leading_zeros()).max(1) + 6) / 7) as usize
124}
125
126/// The plain baseline column (`T_INTS`): an adaptive-sign header (`(n << 1) | signed`) then a
127/// varint per element — zig-zag when any value is negative, plain LEB128 otherwise.
128pub fn leb128_encode<I: Iterator<Item = i64> + Clone>(out: &mut Vec<u8>, vals: I, n: usize) {
129 let signed = vals.clone().any(|x| x < 0);
130 write_uvarint(((n as u64) << 1) | signed as u64, out);
131 out.reserve(n * 2);
132 if signed {
133 for x in vals {
134 write_uvarint(zigzag(x), out);
135 }
136 } else {
137 for x in vals {
138 write_uvarint(x as u64, out);
139 }
140 }
141}
142
143// ---- Bit packing ---------------------------------------------------------------------------
144
145/// Pack `vals` LSB-first at `width` bits each (1..=64). The inverse of [`bitunpack`].
146pub fn bitpack(vals: &[u64], width: u8) -> Vec<u8> {
147 if width == 0 {
148 return Vec::new();
149 }
150 let total_bits = vals.len().saturating_mul(width as usize);
151 let mut out = vec![0u8; total_bits.div_ceil(8)];
152 let mut bitpos = 0usize;
153 for &val in vals {
154 let mut bits = val;
155 let mut remaining = width as usize;
156 while remaining > 0 {
157 let byte = bitpos / 8;
158 let off = bitpos % 8;
159 let take = remaining.min(8 - off);
160 let mask = (1u64 << take) - 1;
161 out[byte] |= ((bits & mask) as u8) << off;
162 bits >>= take;
163 bitpos += take;
164 remaining -= take;
165 }
166 }
167 out
168}
169
170/// Read `count` LSB-first `width`-bit values from `bytes`. `None` if `bytes` is too short. The
171/// inverse of [`bitpack`].
172pub fn bitunpack(bytes: &[u8], count: usize, width: u8) -> Option<Vec<u64>> {
173 if width == 0 || width > 64 {
174 return None;
175 }
176 let total_bits = count.checked_mul(width as usize)?;
177 if bytes.len() < total_bits.div_ceil(8) {
178 return None;
179 }
180 let mut out = Vec::with_capacity(count.min(PREALLOC_CAP));
181 let mut bitpos = 0usize;
182 for _ in 0..count {
183 let mut val = 0u64;
184 let mut got = 0usize;
185 while got < width as usize {
186 let byte = bitpos / 8;
187 let off = bitpos % 8;
188 let take = (width as usize - got).min(8 - off);
189 let mask = (1u64 << take) - 1;
190 val |= (((bytes[byte] >> off) as u64) & mask) << got;
191 got += take;
192 bitpos += take;
193 }
194 out.push(val);
195 }
196 Some(out)
197}
198
199// ---- The sandboxed generator IR (ship the computation, not the data) -----------------------
200
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202pub enum GenCmp {
203 Eq,
204 Ne,
205 Lt,
206 Le,
207 Gt,
208 Ge,
209}
210
211/// A restricted, pure, TOTAL expression over the element index `i`. Every op is total (div/mod by
212/// zero is 0, wrapping i64 arithmetic), and a malformed/hostile tree is bounded at decode by a node
213/// budget + depth cap, so evaluation can never panic, diverge, overflow, or escape.
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub enum GenExpr {
216 Index,
217 Const(i64),
218 Add(Box<GenExpr>, Box<GenExpr>),
219 Sub(Box<GenExpr>, Box<GenExpr>),
220 Mul(Box<GenExpr>, Box<GenExpr>),
221 Div(Box<GenExpr>, Box<GenExpr>),
222 Mod(Box<GenExpr>, Box<GenExpr>),
223 Select {
224 op: GenCmp,
225 lhs: Box<GenExpr>,
226 rhs: Box<GenExpr>,
227 then: Box<GenExpr>,
228 els: Box<GenExpr>,
229 },
230}
231
232/// Evaluate a generator at index `i`. TOTAL: div/mod by zero is 0; all arithmetic wraps.
233pub fn gen_eval(e: &GenExpr, i: i64) -> i64 {
234 match e {
235 GenExpr::Index => i,
236 GenExpr::Const(c) => *c,
237 GenExpr::Add(a, b) => gen_eval(a, i).wrapping_add(gen_eval(b, i)),
238 GenExpr::Sub(a, b) => gen_eval(a, i).wrapping_sub(gen_eval(b, i)),
239 GenExpr::Mul(a, b) => gen_eval(a, i).wrapping_mul(gen_eval(b, i)),
240 GenExpr::Div(a, b) => {
241 let d = gen_eval(b, i);
242 if d == 0 {
243 0
244 } else {
245 gen_eval(a, i).wrapping_div(d)
246 }
247 }
248 GenExpr::Mod(a, b) => {
249 let d = gen_eval(b, i);
250 if d == 0 {
251 0
252 } else {
253 gen_eval(a, i).wrapping_rem(d)
254 }
255 }
256 GenExpr::Select {
257 op,
258 lhs,
259 rhs,
260 then,
261 els,
262 } => {
263 let (l, r) = (gen_eval(lhs, i), gen_eval(rhs, i));
264 let c = match op {
265 GenCmp::Eq => l == r,
266 GenCmp::Ne => l != r,
267 GenCmp::Lt => l < r,
268 GenCmp::Le => l <= r,
269 GenCmp::Gt => l > r,
270 GenCmp::Ge => l >= r,
271 };
272 if c {
273 gen_eval(then, i)
274 } else {
275 gen_eval(els, i)
276 }
277 }
278 }
279}
280
281/// Serialize a generator pre-order: a 1-byte node tag, then children. Self-delimiting.
282pub fn serialize_gen(e: &GenExpr, out: &mut Vec<u8>) {
283 match e {
284 GenExpr::Index => out.push(0),
285 GenExpr::Const(c) => {
286 out.push(1);
287 write_uvarint(zigzag(*c), out);
288 }
289 GenExpr::Add(a, b) => {
290 out.push(2);
291 serialize_gen(a, out);
292 serialize_gen(b, out);
293 }
294 GenExpr::Sub(a, b) => {
295 out.push(3);
296 serialize_gen(a, out);
297 serialize_gen(b, out);
298 }
299 GenExpr::Mul(a, b) => {
300 out.push(4);
301 serialize_gen(a, out);
302 serialize_gen(b, out);
303 }
304 GenExpr::Div(a, b) => {
305 out.push(5);
306 serialize_gen(a, out);
307 serialize_gen(b, out);
308 }
309 GenExpr::Mod(a, b) => {
310 out.push(6);
311 serialize_gen(a, out);
312 serialize_gen(b, out);
313 }
314 GenExpr::Select {
315 op,
316 lhs,
317 rhs,
318 then,
319 els,
320 } => {
321 out.push(7);
322 out.push(*op as u8);
323 serialize_gen(lhs, out);
324 serialize_gen(rhs, out);
325 serialize_gen(then, out);
326 serialize_gen(els, out);
327 }
328 }
329}
330
331/// Parse a generator under a node `budget` and `depth` cap — a garbage/hostile tree returns `None`.
332pub fn deserialize_gen(
333 buf: &[u8],
334 pos: &mut usize,
335 budget: &mut u32,
336 depth: u32,
337) -> Option<GenExpr> {
338 if depth > MAX_GEN_DEPTH || *budget == 0 {
339 return None;
340 }
341 *budget -= 1;
342 let tag = *buf.get(*pos)?;
343 *pos += 1;
344 Some(match tag {
345 0 => GenExpr::Index,
346 1 => GenExpr::Const(unzigzag(read_uvarint(buf, pos)?)),
347 2..=6 => {
348 let a = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
349 let b = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
350 match tag {
351 2 => GenExpr::Add(a, b),
352 3 => GenExpr::Sub(a, b),
353 4 => GenExpr::Mul(a, b),
354 5 => GenExpr::Div(a, b),
355 _ => GenExpr::Mod(a, b),
356 }
357 }
358 7 => {
359 let op = match *buf.get(*pos)? {
360 0 => GenCmp::Eq,
361 1 => GenCmp::Ne,
362 2 => GenCmp::Lt,
363 3 => GenCmp::Le,
364 4 => GenCmp::Gt,
365 5 => GenCmp::Ge,
366 _ => return None,
367 };
368 *pos += 1;
369 let lhs = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
370 let rhs = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
371 let then = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
372 let els = Box::new(deserialize_gen(buf, pos, budget, depth + 1)?);
373 GenExpr::Select {
374 op,
375 lhs,
376 rhs,
377 then,
378 els,
379 }
380 }
381 _ => return None,
382 })
383}
384
385// ---- Column-shape detectors ----------------------------------------------------------------
386
387/// If `v` is an exact affine progression `base + stride·i`, return `(base, stride)`.
388pub fn detect_affine(v: &[i64]) -> Option<(i64, i64)> {
389 if v.len() < 2 {
390 return None;
391 }
392 let base = v[0];
393 let stride = v[1].wrapping_sub(v[0]);
394 for (i, &x) in v.iter().enumerate() {
395 if base.wrapping_add((i as i64).wrapping_mul(stride)) != x {
396 return None;
397 }
398 }
399 Some((base, stride))
400}
401
402/// If `v` is an exact geometric progression `base · ratioⁱ` (≥3 elements, confirmed by replaying the
403/// decoder's wrapping arithmetic), return `(base, ratio)`.
404pub fn detect_geometric(v: &[i64]) -> Option<(i64, i64)> {
405 if v.len() < 3 {
406 return None;
407 }
408 let base = v[0];
409 if base == 0 || v[1].checked_rem(base)? != 0 {
410 return None;
411 }
412 let ratio = v[1].checked_div(base)?;
413 if ratio == 0 || ratio == 1 {
414 return None;
415 }
416 let mut cur = base;
417 for &x in v {
418 if cur != x {
419 return None;
420 }
421 cur = cur.wrapping_mul(ratio);
422 }
423 Some((base, ratio))
424}
425
426/// If `v` is an exact cyclic repetition of a minimal block of period `2 ≤ p ≤ min(len/2, cap)`,
427/// return `p`.
428pub fn detect_period(v: &[i64]) -> Option<usize> {
429 let n = v.len();
430 if n < 4 {
431 return None;
432 }
433 let cap = (n / 2).min(PERIOD_CAP);
434 'p: for p in 2..=cap {
435 for i in p..n {
436 if v[i] != v[i - p] {
437 continue 'p;
438 }
439 }
440 return Some(p);
441 }
442 None
443}
444
445/// If one value dominates the column (covers ≥ ¾), return it and the sorted `(index, value)`
446/// exceptions.
447pub fn detect_sparse(v: &[i64]) -> Option<(i64, Vec<(usize, i64)>)> {
448 if v.len() < 8 {
449 return None;
450 }
451 let mut cand = v[0];
452 let mut count: i64 = 0;
453 for &x in v {
454 if count == 0 {
455 cand = x;
456 count = 1;
457 } else if x == cand {
458 count += 1;
459 } else {
460 count -= 1;
461 }
462 }
463 let occ = v.iter().filter(|&&x| x == cand).count();
464 if v.len() - occ > v.len() / 4 {
465 return None; // not dominant enough — the exception list wouldn't beat the menu
466 }
467 let exceptions: Vec<(usize, i64)> = v
468 .iter()
469 .enumerate()
470 .filter(|(_, &x)| x != cand)
471 .map(|(i, &x)| (i, x))
472 .collect();
473 Some((cand, exceptions))
474}
475
476/// Recognize `v` as a polynomial column (degree ≤ [`MAX_POLY_DEGREE`]) via finite differences and
477/// return `(degree, seeds)` — the k+1 leading-edge seeds, confirmed by exact reconstruction.
478pub fn detect_poly_generator(v: &[i64]) -> Option<(u8, Vec<i64>)> {
479 if v.len() < 3 {
480 return None;
481 }
482 let mut levels: Vec<Vec<i64>> = Vec::with_capacity(MAX_POLY_DEGREE + 1);
483 levels.push(v.to_vec());
484 for d in 0..MAX_POLY_DEGREE {
485 let prev = &levels[d];
486 if prev.len() < 2 {
487 break;
488 }
489 let mut next = Vec::with_capacity(prev.len() - 1);
490 for w in prev.windows(2) {
491 next.push(w[1].checked_sub(w[0])?); // a difference overflow → fall back to the menu
492 }
493 if next.len() >= 2 && next.iter().all(|&x| x == next[0]) {
494 let degree = (d + 1) as u8;
495 let mut seeds: Vec<i64> = levels.iter().map(|lvl| lvl[0]).collect();
496 seeds.push(next[0]);
497 if reconstruct_poly(&seeds, v.len()) == v {
498 return Some((degree, seeds));
499 }
500 return None;
501 }
502 levels.push(next);
503 }
504 None
505}
506
507/// Replay a polynomial column from its finite-difference seeds via a difference engine.
508pub fn reconstruct_poly(seeds: &[i64], n: usize) -> Vec<i64> {
509 let mut diffs = seeds.to_vec();
510 let mut out = Vec::with_capacity(n.min(PREALLOC_CAP));
511 for _ in 0..n {
512 out.push(diffs[0]);
513 for j in 0..diffs.len().saturating_sub(1) {
514 diffs[j] = diffs[j].wrapping_add(diffs[j + 1]);
515 }
516 }
517 out
518}
519
520/// Recognize `v` as a constant-coefficient linear recurrence `v[i] = Σⱼ cⱼ·v[i-1-j]` of minimal order
521/// `k ≤ [`MAX_RECUR_ORDER`]` with **integer** coefficients, and return `(coeffs, seeds)` — `k`
522/// coefficients + the first `k` values. This is exactly Berlekamp–Massey over ℤ: it captures Fibonacci,
523/// Lucas, Pell, and any linear-feedback sequence — none of which the polynomial detector can reach
524/// (their finite differences never settle). The coefficients are solved exactly (Cramer over `i128`)
525/// from the smallest `2k` terms and then CONFIRMED by replaying the recurrence with the SAME wrapping
526/// arithmetic the decoder uses, so a match certifies a bit-exact reconstruction.
527pub fn detect_linear_recurrence(v: &[i64]) -> Option<(Vec<i64>, Vec<i64>)> {
528 let n = v.len();
529 for k in 1..=MAX_RECUR_ORDER.min(n / 2) {
530 if let Some(coeffs) = solve_recurrence(v, k) {
531 if reconstruct_recurrence(&coeffs, &v[..k], n) == v {
532 return Some((coeffs, v[..k].to_vec()));
533 }
534 }
535 }
536 None
537}
538
539/// Solve the `k×k` linear system for integer recurrence coefficients from the smallest `2k` terms via
540/// Cramer's rule over `i128`. `None` if the system is singular, a coefficient is non-integer or
541/// out-of-`i64`, or a determinant overflows.
542fn solve_recurrence(v: &[i64], k: usize) -> Option<Vec<i64>> {
543 let mut m = vec![vec![0i128; k]; k];
544 let mut b = vec![0i128; k];
545 for r in 0..k {
546 for j in 0..k {
547 m[r][j] = v[k + r - 1 - j] as i128; // coefficient of c_{j+1} in the equation for v[k+r]
548 }
549 b[r] = v[k + r] as i128;
550 }
551 let det_m = det_i128(&m)?;
552 if det_m == 0 {
553 return None;
554 }
555 let mut coeffs = Vec::with_capacity(k);
556 for j in 0..k {
557 let mut mj = m.clone();
558 for (r, br) in b.iter().enumerate() {
559 mj[r][j] = *br;
560 }
561 let det_j = det_i128(&mj)?;
562 if det_j % det_m != 0 {
563 return None; // non-integer coefficient — not an exact integer recurrence
564 }
565 let c = det_j / det_m;
566 if c < i64::MIN as i128 || c > i64::MAX as i128 {
567 return None;
568 }
569 coeffs.push(c as i64);
570 }
571 Some(coeffs)
572}
573
574/// A checked `i128` determinant by Laplace expansion (used only for `k ≤ [`MAX_RECUR_ORDER`]`, so at
575/// most `4! = 24` terms). `None` on overflow.
576fn det_i128(m: &[Vec<i128>]) -> Option<i128> {
577 let k = m.len();
578 match k {
579 1 => Some(m[0][0]),
580 2 => m[0][0]
581 .checked_mul(m[1][1])?
582 .checked_sub(m[0][1].checked_mul(m[1][0])?),
583 _ => {
584 let mut acc: i128 = 0;
585 for j in 0..k {
586 let minor: Vec<Vec<i128>> = (1..k)
587 .map(|r| (0..k).filter(|&c| c != j).map(|c| m[r][c]).collect())
588 .collect();
589 let cof = m[0][j].checked_mul(det_i128(&minor)?)?;
590 acc = if j % 2 == 0 {
591 acc.checked_add(cof)?
592 } else {
593 acc.checked_sub(cof)?
594 };
595 }
596 Some(acc)
597 }
598 }
599}
600
601/// Replay a linear recurrence from `coeffs` and the first `seeds.len()` values, wrapping (matches the
602/// decoder, so a confirmed fit is exact across all of `i64`). `n` values out.
603fn reconstruct_recurrence(coeffs: &[i64], seeds: &[i64], n: usize) -> Vec<i64> {
604 let k = coeffs.len();
605 // Guard: without `k` seeds the recurrence cannot start — return what seeds we have (a malformed
606 // decode then simply fails the equality/round-trip check rather than indexing out of bounds).
607 if seeds.len() < k {
608 return seeds[..seeds.len().min(n)].to_vec();
609 }
610 let mut out = Vec::with_capacity(n.min(PREALLOC_CAP));
611 out.extend_from_slice(&seeds[..k.min(n)]);
612 for i in k..n {
613 let mut acc = 0i64;
614 for j in 0..k {
615 acc = acc.wrapping_add(coeffs[j].wrapping_mul(out[i - 1 - j]));
616 }
617 out.push(acc);
618 }
619 out.truncate(n);
620 out
621}
622
623// ---- Berlekamp–Massey over an arbitrary field: the shortest LFSR (the LFSR attack, as a compressor) --
624//
625// The Berlekamp–Massey algorithm finds the shortest linear-feedback shift register generating a
626// sequence over ANY field. Over GF(2) it is the classic bit-LFSR attack; over GF(2⁸) it is the
627// *word*-oriented LFSR attack (a byte stream whose bytes are a GF(256)-linear recurrence). A word-LFSR
628// of order `L` is also a bit-LFSR of order `≤ 8L`, so GF(2) already *catches* it — but GF(2⁸) reports
629// the natural word complexity and runs in `O(n²)` byte-ops instead of `O((8n)²)` bit-ops.
630
631/// The minimal field interface Berlekamp–Massey needs.
632pub trait FieldElem: Copy + PartialEq {
633 fn zero() -> Self;
634 fn one() -> Self;
635 fn add(self, o: Self) -> Self;
636 fn sub(self, o: Self) -> Self;
637 fn mul(self, o: Self) -> Self;
638 /// Multiplicative inverse; only called on nonzero elements.
639 fn inv(self) -> Self;
640}
641
642/// GF(2) — a single bit.
643#[derive(Clone, Copy, PartialEq, Eq, Debug)]
644pub struct Gf2(pub bool);
645impl FieldElem for Gf2 {
646 fn zero() -> Self {
647 Gf2(false)
648 }
649 fn one() -> Self {
650 Gf2(true)
651 }
652 fn add(self, o: Self) -> Self {
653 Gf2(self.0 ^ o.0)
654 }
655 fn sub(self, o: Self) -> Self {
656 Gf2(self.0 ^ o.0)
657 }
658 fn mul(self, o: Self) -> Self {
659 Gf2(self.0 && o.0)
660 }
661 fn inv(self) -> Self {
662 self
663 } // 1⁻¹ = 1 (the only nonzero element)
664}
665
666/// GF(2⁸) — the Rijndael/AES field (reduction polynomial `x⁸+x⁴+x³+x²+1`), one byte per element.
667#[derive(Clone, Copy, PartialEq, Eq, Debug)]
668pub struct Gf256(pub u8);
669
670fn gf256_xtime(a: u8) -> u8 {
671 (a << 1) ^ (if a & 0x80 != 0 { 0x1B } else { 0 })
672}
673/// `(log, exp)` tables for GF(2⁸) with generator 3: `exp[i] = 3ⁱ`, `log` its inverse. `exp` is doubled
674/// to length 512 so a product's log index never needs a modular reduction.
675fn gf256_tables() -> &'static (Vec<u8>, Vec<u8>) {
676 static T: std::sync::OnceLock<(Vec<u8>, Vec<u8>)> = std::sync::OnceLock::new();
677 T.get_or_init(|| {
678 let mut exp = vec![0u8; 512];
679 let mut log = vec![0u8; 256];
680 let mut x = 1u8;
681 for i in 0..255usize {
682 exp[i] = x;
683 log[x as usize] = i as u8;
684 x ^= gf256_xtime(x); // x ← x·3 = x·2 ⊕ x
685 }
686 for i in 255..512 {
687 exp[i] = exp[i - 255];
688 }
689 (log, exp)
690 })
691}
692impl FieldElem for Gf256 {
693 fn zero() -> Self {
694 Gf256(0)
695 }
696 fn one() -> Self {
697 Gf256(1)
698 }
699 fn add(self, o: Self) -> Self {
700 Gf256(self.0 ^ o.0)
701 }
702 fn sub(self, o: Self) -> Self {
703 Gf256(self.0 ^ o.0)
704 }
705 fn mul(self, o: Self) -> Self {
706 if self.0 == 0 || o.0 == 0 {
707 return Gf256(0);
708 }
709 let (log, exp) = gf256_tables();
710 Gf256(exp[log[self.0 as usize] as usize + log[o.0 as usize] as usize])
711 }
712 fn inv(self) -> Self {
713 let (log, exp) = gf256_tables();
714 Gf256(exp[255 - log[self.0 as usize] as usize])
715 }
716}
717
718/// **Berlekamp–Massey over a field.** Returns `(L, taps)` where `L` is the linear complexity and `taps`
719/// are the connection-polynomial coefficients `c₁..c_L`; the recurrence is `s[i] = -Σⱼ c_{j+1}·s[i-1-j]`.
720pub fn berlekamp_massey_field<F: FieldElem>(s: &[F]) -> (usize, Vec<F>) {
721 let n = s.len();
722 let mut c = vec![F::zero(); n + 1];
723 let mut b = vec![F::zero(); n + 1];
724 c[0] = F::one();
725 b[0] = F::one();
726 let mut l = 0usize;
727 let mut m = 1usize;
728 let mut b_disc = F::one(); // the discrepancy at the last length change
729 for nn in 0..n {
730 let mut d = s[nn];
731 for i in 1..=l {
732 d = d.add(c[i].mul(s[nn - i]));
733 }
734 if d == F::zero() {
735 m += 1;
736 } else {
737 let coef = d.mul(b_disc.inv());
738 let t = c.clone();
739 for i in 0..=n {
740 if i + m <= n && b[i] != F::zero() {
741 c[i + m] = c[i + m].sub(coef.mul(b[i]));
742 }
743 }
744 if 2 * l <= nn {
745 l = nn + 1 - l;
746 b = t;
747 b_disc = d;
748 m = 1;
749 } else {
750 m += 1;
751 }
752 }
753 }
754 let taps = if l == 0 {
755 Vec::new()
756 } else {
757 c[1..=l].to_vec()
758 };
759 (l, taps)
760}
761
762/// Replay a field LFSR: emit `seed`, then `s[i] = -Σⱼ tapsⱼ·s[i-1-j]` (the connection recurrence).
763pub fn lfsr_generate_field<F: FieldElem>(taps: &[F], seed: &[F], total: usize) -> Vec<F> {
764 let l = taps.len();
765 let mut out = Vec::with_capacity(total);
766 out.extend_from_slice(&seed[..l.min(seed.len()).min(total)]);
767 for i in l..total {
768 let mut acc = F::zero();
769 for j in 0..l {
770 acc = acc.add(taps[j].mul(out[i - 1 - j]));
771 }
772 out.push(F::zero().sub(acc));
773 }
774 out.truncate(total);
775 out
776}
777
778/// **Berlekamp–Massey over GF(2)** — the shortest bit-LFSR. Thin wrapper over [`berlekamp_massey_field`]
779/// (see it for the full semantics). For an LFSR keystream `L` is the register length; for random ≈ n/2.
780pub fn berlekamp_massey_gf2(s: &[bool]) -> (usize, Vec<bool>) {
781 let elems: Vec<Gf2> = s.iter().map(|&b| Gf2(b)).collect();
782 let (l, taps) = berlekamp_massey_field(&elems);
783 (l, taps.into_iter().map(|g| g.0).collect())
784}
785
786/// Replay a GF(2) LFSR: `s[i] = ⊕ⱼ tapsⱼ · s[i-1-j]`. The inverse of [`berlekamp_massey_gf2`].
787pub fn lfsr_generate(taps: &[bool], seed: &[bool], total: usize) -> Vec<bool> {
788 let t: Vec<Gf2> = taps.iter().map(|&b| Gf2(b)).collect();
789 let sd: Vec<Gf2> = seed.iter().map(|&b| Gf2(b)).collect();
790 lfsr_generate_field(&t, &sd, total)
791 .into_iter()
792 .map(|g| g.0)
793 .collect()
794}
795
796/// If a byte column is a GF(2) LFSR keystream — its `8·n`-bit expansion has linear complexity `L` and
797/// the length-`L` LFSR regenerates every bit — return `(L, taps, seed_bits)`. Only worthwhile when `L`
798/// is well below the bit count (else the raw byte column wins and `consider` keeps it).
799fn detect_lfsr_bytes(v: &[i64]) -> Option<(usize, Vec<bool>, Vec<bool>)> {
800 let bits = bytes_to_bits(v);
801 let (l, taps) = berlekamp_massey_gf2(&bits);
802 if l == 0 || l >= bits.len() {
803 return None;
804 }
805 let seed = bits[..l].to_vec();
806 if lfsr_generate(&taps, &seed, bits.len()) != bits {
807 return None; // the LFSR does not regenerate the whole column — not a clean keystream
808 }
809 Some((l, taps, seed))
810}
811
812/// Expand a byte column to its LSB-first bit sequence (bit `j` of byte `i` is `(byte_i >> j) & 1`).
813pub fn bytes_to_bits(v: &[i64]) -> Vec<bool> {
814 let mut bits = Vec::with_capacity(v.len().saturating_mul(8));
815 for &x in v {
816 let byte = x as u8;
817 for j in 0..8 {
818 bits.push((byte >> j) & 1 == 1);
819 }
820 }
821 bits
822}
823
824/// Pack an LSB-first bit sequence back into bytes (the inverse of [`bytes_to_bits`]); a trailing
825/// partial group is zero-padded.
826pub fn bits_to_bytes(bits: &[bool]) -> Vec<i64> {
827 bits.chunks(8)
828 .map(|chunk| {
829 let mut byte = 0u8;
830 for (j, &bit) in chunk.iter().enumerate() {
831 if bit {
832 byte |= 1 << j;
833 }
834 }
835 byte as i64
836 })
837 .collect()
838}
839
840// ---- 2-adic complexity / FCSR: the carry-based attack (what every LINEAR tool misses) -----------
841//
842// A feedback-with-carry shift register (FCSR) generates a bit sequence whose 2-adic value `Σ sᵢ2ⁱ`
843// equals a rational `p/q` with `q` ODD; the register is defined by the connection integer `q`. Because
844// the carry makes the map NON-linear over GF(2), an FCSR keystream (mod-2ⁿ LCGs, summation combiners,
845// the Marsaglia add-with-carry family) is invisible to Berlekamp–Massey over any field. The 2-adic
846// analogue — the **Rational Approximation Algorithm** (Klapper–Goresky), here via rational
847// reconstruction over the integers — recovers `p/q` and its *2-adic complexity* `≈ log₂ max(|p|,|q|)`.
848
849/// gcd of `|a|`, `|b|` by the Euclidean algorithm over `BigInt`.
850fn bigint_gcd_local(
851 a: &crate::numeric::BigInt,
852 b: &crate::numeric::BigInt,
853) -> crate::numeric::BigInt {
854 let (mut a, mut b) = (a.abs(), b.abs());
855 while !b.is_zero() {
856 let r = a
857 .div_rem(&b)
858 .map(|(_, r)| r)
859 .unwrap_or_else(crate::numeric::BigInt::zero);
860 a = b;
861 b = r;
862 }
863 a
864}
865
866/// The bit length of `|x|` (`0` for zero).
867fn bigint_bitlen(x: &crate::numeric::BigInt) -> usize {
868 let (_, bytes) = x.to_le_bytes();
869 for (i, &b) in bytes.iter().enumerate().rev() {
870 if b != 0 {
871 return i * 8 + (8 - b.leading_zeros() as usize);
872 }
873 }
874 0
875}
876
877/// **Rational reconstruction of a bit sequence as a 2-adic number.** Returns `(p, q)` with `q` odd and
878/// positive and `p/q ≡ Σ sᵢ2ⁱ (mod 2ⁿ)` — the shortest FCSR generating the sequence. `None` when no
879/// odd-denominator rational fits (an algorithmically-random sequence has no small FCSR).
880pub fn two_adic_reconstruct(
881 bits: &[bool],
882) -> Option<(crate::numeric::BigInt, crate::numeric::BigInt)> {
883 use crate::numeric::BigInt;
884 let n = bits.len();
885 if n == 0 {
886 return None;
887 }
888 let two = BigInt::from_i64(2);
889 // α = Σ bits[i]·2ⁱ, and N = 2ⁿ.
890 let mut alpha = BigInt::zero();
891 let mut pow2 = BigInt::from_i64(1);
892 for &bit in bits {
893 if bit {
894 alpha = alpha.add(&pow2);
895 }
896 pow2 = pow2.mul(&two);
897 }
898 let n_big = pow2; // 2ⁿ
899 // Extended Euclid keeping rᵢ ≡ tᵢ·α (mod N); stop at the first rᵢ with rᵢ² ≤ N.
900 let (mut r0, mut t0) = (n_big.clone(), BigInt::zero());
901 let (mut r1, mut t1) = (alpha, BigInt::from_i64(1));
902 while !r1.is_zero() && r1.mul(&r1) > n_big {
903 let (quot, rem) = r0.div_rem(&r1)?;
904 let t2 = t0.sub(".mul(&t1));
905 r0 = r1;
906 t0 = t1;
907 r1 = rem;
908 t1 = t2;
909 }
910 let (mut p, mut q) = (r1, t1);
911 if q.is_zero() {
912 return None;
913 }
914 if q.is_negative() {
915 p = BigInt::zero().sub(&p);
916 q = BigInt::zero().sub(&q);
917 }
918 // Reduce to lowest terms — the rational reconstruction can return a non-coprime `p/q` (a common
919 // factor `g` gives the same 2-adic value `pg/qg`); reducing yields the minimal FCSR and the true
920 // 2-adic complexity.
921 let g = bigint_gcd_local(&p, &q);
922 if !g.is_zero() && g != BigInt::from_i64(1) {
923 p = p.div_rem(&g).map(|(quot, _)| quot)?;
924 q = q.div_rem(&g).map(|(quot, _)| quot)?;
925 }
926 if !q.is_odd() {
927 return None; // no odd-denominator (FCSR) rational — treat as incompressible
928 }
929 Some((p, q))
930}
931
932/// Generate `n` bits of the FCSR keystream for `p/q` (`q` odd) — the 2-adic expansion, by repeated
933/// 2-adic division. The inverse of [`two_adic_reconstruct`].
934pub fn fcsr_generate(
935 p: &crate::numeric::BigInt,
936 q: &crate::numeric::BigInt,
937 n: usize,
938) -> Vec<bool> {
939 use crate::numeric::BigInt;
940 let two = BigInt::from_i64(2);
941 let mut r = p.clone();
942 let mut bits = Vec::with_capacity(n);
943 for _ in 0..n {
944 let bit = r.is_odd();
945 bits.push(bit);
946 if bit {
947 r = r.sub(q);
948 }
949 // r ← r/2 (exact: r − bit·q is even because q is odd).
950 r = r
951 .div_rem(&two)
952 .map(|(quot, _)| quot)
953 .unwrap_or_else(BigInt::zero);
954 }
955 bits
956}
957
958/// The **2-adic complexity** of a bit sequence: `≈ log₂ max(|p|,|q|)` for its FCSR rational `p/q`. Low ⇒
959/// a carry-based keystream (an FCSR / add-with-carry generator); `≈ n/2` for a random sequence.
960pub fn two_adic_complexity(bits: &[bool]) -> usize {
961 match two_adic_reconstruct(bits) {
962 Some((p, q)) => bigint_bitlen(&p).max(bigint_bitlen(&q)),
963 None => bits.len(),
964 }
965}
966
967/// The **maximal order complexity** (Jansen) of a bit sequence: the length of the shortest feedback
968/// shift register — **linear OR nonlinear** — that generates it, i.e. the smallest `L` such that every
969/// length-`L` window has a unique successor (`s[i] = f(s[i-1],…,s[i-L])` for some feedback function
970/// `f`). It is the TOP of the FSR complexity hierarchy — `MOC ≤ 2-adic complexity` and `MOC ≤ linear
971/// complexity` — so it catches nonlinear generators (NFSRs, algebraic combiners with memory) that fool
972/// both Berlekamp–Massey and the 2-adic Rational Approximation. Low relative to `n` ⇒ a short-register
973/// generator; `≈ n/2` for a random sequence. Consistency is monotone in `L`, so we binary-search it.
974pub fn maximal_order_complexity(bits: &[bool]) -> usize {
975 let n = bits.len();
976 if n == 0 {
977 return 0;
978 }
979 // Is every length-`l` window followed by a unique bit?
980 let consistent = |l: usize| -> bool {
981 if l >= n {
982 return true;
983 }
984 let mut succ: std::collections::HashMap<&[bool], bool> = std::collections::HashMap::new();
985 for i in 0..(n - l) {
986 match succ.insert(&bits[i..i + l], bits[i + l]) {
987 Some(prev) if prev != bits[i + l] => return false,
988 _ => {}
989 }
990 }
991 true
992 };
993 // The smallest `L` in `[0, n]` with `consistent(L)`.
994 let (mut lo, mut hi) = (0usize, n);
995 while lo < hi {
996 let mid = (lo + hi) / 2;
997 if consistent(mid) {
998 hi = mid;
999 } else {
1000 lo = mid + 1;
1001 }
1002 }
1003 lo
1004}
1005
1006// ---- Algebraic recurrence: the degree-`d` generalization of Berlekamp–Massey (the OPEN rung) ------
1007//
1008// Maximal order complexity certifies that a sequence is generated by a length-`L` feedback register,
1009// but the register's feedback function `f` is a full `2^L` truth table — as large as the data — so a
1010// low MOC is a structural *weakness* without a compressor. The algebraic recovery closes that gap when
1011// `f` has *low degree*: model `s[i] = f(s[i-1],…,s[i-L])` as a GF(2) polynomial and recover its sparse
1012// **algebraic normal form** by linearization. Each monomial of degree `≤ d` over the `L` window bits is
1013// treated as an independent unknown; each output position gives one linear equation in those unknowns;
1014// a GF(2) Gaussian solve returns the ANF coefficients. For a degree-`d` feedback this is `M = Σₖ₌₀ᵈ
1015// C(L,k) = O(Lᵈ)` coefficients — vastly smaller than the `2^L` truth table — so a low-degree nonlinear
1016// generator (a quadratic NFSR, an algebraic filter with memory) is *compressed*, not merely diagnosed.
1017// This is the algebraic attack (Courtois–Meier linearization) recast as an MDL codec. It stays cheap
1018// only while `d` is small; a high-degree `f` sends `M → 2^L` and the sequence back to the ceiling.
1019
1020/// The monomials of degree `≤ d` over `l` window variables, each as a sorted variable-index list
1021/// (`[]` = the constant `1`). The ANF basis for the algebraic recurrence solve.
1022fn monomials(l: usize, d: usize) -> Vec<Vec<usize>> {
1023 fn combos(start: usize, l: usize, k: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
1024 if cur.len() == k {
1025 out.push(cur.clone());
1026 return;
1027 }
1028 for v in start..l {
1029 cur.push(v);
1030 combos(v + 1, l, k, cur, out);
1031 cur.pop();
1032 }
1033 }
1034 let mut out = vec![Vec::new()];
1035 for k in 1..=d.min(l) {
1036 combos(0, l, k, &mut Vec::new(), &mut out);
1037 }
1038 out
1039}
1040
1041/// Evaluate a monomial (an AND of window bits; the empty product is the constant `1`) on a window.
1042fn eval_monomial(mono: &[usize], window: &[bool]) -> bool {
1043 mono.iter().all(|&v| window[v])
1044}
1045
1046/// Solve a GF(2) linear system `A·c = b` for a particular solution `c` (free variables set to `0`), with
1047/// rows given as `(coefficient bitmask over `ncols` columns, rhs bit)`. Full Gaussian elimination to
1048/// reduced row-echelon form over any number of columns (bitset rows, so `> 64` unknowns are fine).
1049/// Returns `None` if the system is inconsistent.
1050fn solve_gf2_system(rows: &[(Vec<u64>, bool)], ncols: usize) -> Option<Vec<bool>> {
1051 let words = ncols.div_ceil(64).max(1);
1052 let mut mat: Vec<(Vec<u64>, bool)> = rows.to_vec();
1053 let mut pivot_row_of_col = vec![usize::MAX; ncols];
1054 let mut r = 0usize;
1055 for c in 0..ncols {
1056 let (w, bit) = (c / 64, 1u64 << (c % 64));
1057 let Some(pr) = (r..mat.len()).find(|&i| mat[i].0[w] & bit != 0) else {
1058 continue;
1059 };
1060 mat.swap(r, pr);
1061 for i in 0..mat.len() {
1062 if i != r && mat[i].0[w] & bit != 0 {
1063 for k in 0..words {
1064 mat[i].0[k] ^= mat[r].0[k];
1065 }
1066 mat[i].1 ^= mat[r].1;
1067 }
1068 }
1069 pivot_row_of_col[c] = r;
1070 r += 1;
1071 }
1072 // A row that reduced to `0 = 1` proves the system inconsistent.
1073 if mat
1074 .iter()
1075 .any(|(coeff, rhs)| *rhs && coeff.iter().all(|&w| w == 0))
1076 {
1077 return None;
1078 }
1079 // Free variables are `0`; each pivot variable equals its row's rhs (that row now has only its own
1080 // pivot among the pivot columns, so the free-variables-zero assignment reads straight off the rhs).
1081 let mut c = vec![false; ncols];
1082 for col in 0..ncols {
1083 if pivot_row_of_col[col] != usize::MAX {
1084 c[col] = mat[pivot_row_of_col[col]].1;
1085 }
1086 }
1087 Some(c)
1088}
1089
1090/// Recover the **algebraic normal form** of a degree-`≤ d`, order-`l` nonlinear feedback: the ANF
1091/// coefficient vector over `monomials(l, d)` such that replaying `s[i] = ⊕ₘ cₘ · monomialₘ(window)`
1092/// reproduces `bits` exactly. Returns `None` if no such low-degree feedback fits (the GF(2) system is
1093/// inconsistent, or the recovered coefficients fail to regenerate the sequence). This is the degree-`d`
1094/// generalization of [`berlekamp_massey_gf2`] (which is the `d = 1` case): it compresses low-degree
1095/// nonlinear generators that fool the linear, 2-adic, and maximal-order tests.
1096pub fn detect_algebraic_recurrence(bits: &[bool], l: usize, d: usize) -> Option<Vec<bool>> {
1097 if l == 0 || bits.len() <= l {
1098 return None;
1099 }
1100 let monos = monomials(l, d);
1101 let m = monos.len();
1102 let words = m.div_ceil(64).max(1);
1103 let mut rows: Vec<(Vec<u64>, bool)> = Vec::with_capacity(bits.len() - l);
1104 for i in l..bits.len() {
1105 // Window variable `v` is `s[i-1-v]`, matching [`algebraic_generate`].
1106 let window: Vec<bool> = (0..l).map(|v| bits[i - 1 - v]).collect();
1107 let mut coeff = vec![0u64; words];
1108 for (mi, mono) in monos.iter().enumerate() {
1109 if eval_monomial(mono, &window) {
1110 coeff[mi / 64] |= 1u64 << (mi % 64);
1111 }
1112 }
1113 rows.push((coeff, bits[i]));
1114 }
1115 let coeffs = solve_gf2_system(&rows, m)?;
1116 if algebraic_generate(l, d, &coeffs, &bits[..l], bits.len()) != bits {
1117 return None; // the recovered feedback does not regenerate the whole sequence
1118 }
1119 Some(coeffs)
1120}
1121
1122/// Replay a degree-`d`, order-`l` algebraic feedback register from ANF coefficients over
1123/// `monomials(l, d)` and an `l`-bit seed: `s[i] = ⊕ₘ coeffsₘ · monomialₘ(s[i-1],…,s[i-l])`. The
1124/// inverse of [`detect_algebraic_recurrence`].
1125pub fn algebraic_generate(
1126 l: usize,
1127 d: usize,
1128 coeffs: &[bool],
1129 seed: &[bool],
1130 total: usize,
1131) -> Vec<bool> {
1132 let monos = monomials(l, d);
1133 let mut out: Vec<bool> = seed.iter().take(l).copied().collect();
1134 for i in l..total {
1135 let window: Vec<bool> = (0..l).map(|v| out[i - 1 - v]).collect();
1136 let mut bit = false;
1137 for (mi, mono) in monos.iter().enumerate() {
1138 if coeffs.get(mi).copied().unwrap_or(false) && eval_monomial(mono, &window) {
1139 bit ^= true;
1140 }
1141 }
1142 out.push(bit);
1143 }
1144 out.truncate(total);
1145 out
1146}
1147
1148/// The **algebraic complexity** of a bit sequence at maximal degree `max_degree`: the smallest order
1149/// `l` for which [`detect_algebraic_recurrence`] recovers a degree-`≤ max_degree` feedback, together
1150/// with the ANF coefficient count `M` (the true description size — `O(lᵈ)`, not the `2^l` truth table).
1151/// `None` if no order `≤ bits.len()/2` admits such a feedback at that degree.
1152pub fn algebraic_complexity(bits: &[bool], max_degree: usize) -> Option<(usize, usize)> {
1153 for l in 1..=(bits.len() / 2) {
1154 if let Some(coeffs) = detect_algebraic_recurrence(bits, l, max_degree) {
1155 let used = coeffs.iter().filter(|&&c| c).count();
1156 return Some((l, used.max(1)));
1157 }
1158 }
1159 None
1160}
1161
1162// ---- Correlation attack: divide-and-conquer on nonlinear COMBINER generators (the hidden-state rung) --
1163//
1164// A nonlinear combiner runs several LFSRs in parallel and emits `z[i] = C(a₁[i],…,aₖ[i])` for a Boolean
1165// combining function `C`. Every rung so far is blind to it: `z` is a function of the *hidden* register
1166// outputs, not of its own past, so no feedback recovery (linear, word, carry, maximal-order, or
1167// algebraic) applies. But if `C` is correlated with one input — `Pr[z = aⱼ] = p ≠ ½` — then `z` is a
1168// noisy copy of that single LFSR through a binary symmetric channel, and Siegenthaler's attack recovers
1169// `aⱼ`'s initial state ALONE: try each of the `2^Lⱼ − 1` nonzero states, keep the one whose output best
1170// agrees with `z`. This is divide-and-conquer — cost `Σⱼ 2^Lⱼ` instead of `2^(Σ Lⱼ)` — and it isolates
1171// each constituent register independently. It is the classical break the earlier rungs cannot express.
1172
1173/// The certified result of a correlation attack on one target LFSR: the recovered initial state and the
1174/// statistical edge it carries. The `init_state` is a re-checkable witness — regenerate the LFSR from it
1175/// and it reproduces the register the keystream leaks.
1176#[derive(Clone, Debug, PartialEq)]
1177pub struct CorrelationAttack {
1178 /// The register length `L` (`= taps.len()`).
1179 pub register_len: usize,
1180 /// The recovered initial state — the `L`-bit LFSR seed that best correlates with the keystream.
1181 pub init_state: Vec<bool>,
1182 /// `Pr[z = a]` over the sample — the correlation `p` (or `1 − p` if the leak is anti-correlated).
1183 pub agreement: f64,
1184 /// `|agreement − ½|` — the statistical edge; compare against [`spurious_bias_floor`].
1185 pub bias: f64,
1186 /// The number of keystream bits scored, `n`.
1187 pub samples: usize,
1188}
1189
1190/// Siegenthaler's basic correlation attack: recover the initial state of the length-`L` LFSR with
1191/// feedback `taps` that best correlates with `keystream`, by exhaustive search over the `2^L − 1`
1192/// nonzero initial states (each scored by agreement with the keystream). Returns the best state with its
1193/// bias — significant only when `bias` clears [`spurious_bias_floor`]`(L, n)`. Cost `O(2^L·n)`; returns
1194/// `None` for an empty register, a register longer than the keystream, or `L > 20` (past the exhaustive
1195/// cap — the domain of the fast-correlation attack, its scaling successor).
1196pub fn correlation_attack(keystream: &[bool], taps: &[bool]) -> Option<CorrelationAttack> {
1197 let l = taps.len();
1198 let n = keystream.len();
1199 if l == 0 || l > 20 || n <= l {
1200 return None;
1201 }
1202 let mut best: Option<CorrelationAttack> = None;
1203 for code in 1u64..(1u64 << l) {
1204 let seed: Vec<bool> = (0..l).map(|k| (code >> k) & 1 == 1).collect();
1205 let stream = lfsr_generate(taps, &seed, n);
1206 let agree = stream.iter().zip(keystream).filter(|(a, b)| a == b).count();
1207 let bias = (agree as f64 / n as f64 - 0.5).abs();
1208 if best.as_ref().is_none_or(|b| bias > b.bias) {
1209 best = Some(CorrelationAttack {
1210 register_len: l,
1211 init_state: seed,
1212 agreement: agree as f64 / n as f64,
1213 bias,
1214 samples: n,
1215 });
1216 }
1217 }
1218 best
1219}
1220
1221/// The spurious-bias floor: the expected maximum `|agreement − ½|` when the best of `2^register_len`
1222/// *uncorrelated* states is chosen on `n` samples — `≈ √(L·ln2 / 2n)`, from the tail of the maximum of
1223/// `2^L` centered binomials. A recovered [`CorrelationAttack::bias`] well above this floor is a genuine
1224/// correlation (a certified combiner leak); at or below it, the register does not measurably leak.
1225pub fn spurious_bias_floor(register_len: usize, samples: usize) -> f64 {
1226 if samples == 0 {
1227 return 1.0;
1228 }
1229 ((register_len as f64) * std::f64::consts::LN_2 / (2.0 * samples as f64)).sqrt()
1230}
1231
1232// ---- Walsh spectrum & linear cryptanalysis: EVERY linear approximation at once (generalize Rung E) ---
1233//
1234// The correlation attack read ONE correlation, `Pr[z = aⱼ]`. Linear cryptanalysis reads them all. For a
1235// Boolean combining/filter function `C` on `n` inputs, the Walsh–Hadamard transform of its ±1 form
1236// `F(x) = (−1)^C(x)` is `Ŵ(w) = Σₓ (−1)^{C(x) ⊕ ⟨w,x⟩}` — the signed correlation of `C` with EVERY linear
1237// function `⟨w,x⟩` simultaneously, with `Pr[C(x)=⟨w,x⟩] = ½ + Ŵ(w)/2^{n+1}`. Rung E is exactly the slice
1238// at weight-1 masks (`w = eⱼ`); the full spectrum exposes the multi-register approximations E is blind
1239// to — a function can be first-order correlation-immune (every weight-1 `Ŵ` vanishes, so E finds
1240// nothing) yet leak a weight-2 approximation with large bias. The largest `|Ŵ(w)|` is the best linear
1241// approximation (the distinguisher); `nonlinearity = 2^{n-1} − ½·max|Ŵ|` measures distance to the
1242// nearest affine function. The symmetry break: one FWHT diagonalizes the whole correlation structure.
1243// Ceiling: a BENT function has a FLAT spectrum (all `|Ŵ| = 2^{n/2}`) — maximal nonlinearity, no
1244// exploitable linear approximation, the linear-incompressible residue.
1245
1246/// The Walsh–Hadamard transform in place (the `±1` butterfly), on a slice whose length is a power of 2.
1247/// `a[w]` becomes `Σₓ a[x]·(−1)^{⟨w,x⟩}`.
1248pub fn fast_walsh_hadamard(a: &mut [i64]) {
1249 let n = a.len();
1250 debug_assert!(
1251 n.is_power_of_two(),
1252 "Walsh–Hadamard length must be a power of two"
1253 );
1254 let mut len = 1;
1255 while len < n {
1256 let mut i = 0;
1257 while i < n {
1258 for j in i..i + len {
1259 let (x, y) = (a[j], a[j + len]);
1260 a[j] = x + y;
1261 a[j + len] = x - y;
1262 }
1263 i += 2 * len;
1264 }
1265 len <<= 1;
1266 }
1267}
1268
1269/// The Walsh spectrum of a Boolean function given as its `2ⁿ`-entry truth table: `Ŵ(w) = Σₓ (−1)^{C(x) ⊕
1270/// ⟨w,x⟩}`, the signed correlation of `C` with every linear function `⟨w,x⟩`. Index `w` is the linear
1271/// mask (bit `i` selects variable `i`). `None` if the length is not a positive power of two.
1272pub fn walsh_spectrum(truth: &[bool]) -> Option<Vec<i64>> {
1273 if truth.is_empty() || !truth.len().is_power_of_two() {
1274 return None;
1275 }
1276 let mut a: Vec<i64> = truth.iter().map(|&b| if b { -1 } else { 1 }).collect();
1277 fast_walsh_hadamard(&mut a);
1278 Some(a)
1279}
1280
1281/// The best linear approximation of a Boolean function: the mask `w` maximizing `|Ŵ(w)|`, with its bias
1282/// `|Pr[C(x)=⟨w,x⟩] − ½| = |Ŵ(w)| / 2^{n+1}`. When `skip_zero`, the trivial constant mask `w = 0` (which
1283/// measures `C`'s own imbalance) is excluded. Returns `(mask, bias)`, or `None` for a malformed table.
1284pub fn best_linear_approximation(truth: &[bool], skip_zero: bool) -> Option<(usize, f64)> {
1285 let spec = walsh_spectrum(truth)?;
1286 let denom = 2.0 * truth.len() as f64; // 2^{n+1}
1287 spec.iter()
1288 .enumerate()
1289 .skip(usize::from(skip_zero))
1290 .max_by_key(|(_, &c)| c.unsigned_abs())
1291 .map(|(w, &c)| (w, c.unsigned_abs() as f64 / denom))
1292}
1293
1294/// The nonlinearity of a Boolean function: `2^{n-1} − ½·maxₘ|Ŵ(w)|` — its Hamming distance to the nearest
1295/// affine function. High ⇒ resistant to linear approximation; maximal (bent, `n` even) ⇒ `2^{n-1} −
1296/// 2^{n/2−1}`. `None` for a malformed table.
1297pub fn nonlinearity(truth: &[bool]) -> Option<u64> {
1298 let spec = walsh_spectrum(truth)?;
1299 let max_abs = spec.iter().map(|&c| c.unsigned_abs()).max()?;
1300 Some((truth.len() as u64) / 2 - max_abs / 2)
1301}
1302
1303/// The correlation-immunity order of a Boolean function (Xiao–Massey): the largest `m` such that every
1304/// Walsh coefficient at a mask of Hamming weight `1..=m` vanishes. Order `≥ 1` ⇒ IMMUNE to the
1305/// first-order correlation attack (Rung E finds nothing) — yet a higher-weight coefficient may still
1306/// leak, which [`best_linear_approximation`] surfaces. `None` for a malformed table.
1307pub fn correlation_immunity_order(truth: &[bool]) -> Option<usize> {
1308 let spec = walsh_spectrum(truth)?;
1309 let n = truth.len().trailing_zeros() as usize;
1310 for m in 1..=n {
1311 let vanishes = spec
1312 .iter()
1313 .enumerate()
1314 .filter(|(w, _)| w.count_ones() as usize == m)
1315 .all(|(_, &c)| c == 0);
1316 if !vanishes {
1317 return Some(m - 1);
1318 }
1319 }
1320 Some(n)
1321}
1322
1323/// The algebraic normal form (ANF) of a Boolean function: coefficients over the `2ⁿ` monomials `∏_{i∈S}
1324/// xᵢ` (S a variable bitmask), via the binary Möbius transform — the GF(2) dual of the Walsh–Hadamard
1325/// butterfly, and its own inverse over GF(2) (applying it to the ANF returns the truth table). `anf[S]` is
1326/// `true` iff the monomial `∏_{i∈S} xᵢ` is present. `None` for a malformed table.
1327pub fn anf(truth: &[bool]) -> Option<Vec<bool>> {
1328 if truth.is_empty() || !truth.len().is_power_of_two() {
1329 return None;
1330 }
1331 let n = truth.len().trailing_zeros();
1332 let mut a = truth.to_vec();
1333 for i in 0..n {
1334 let step = 1usize << i;
1335 let mut j = 0;
1336 while j < a.len() {
1337 for k in j..j + step {
1338 let lo = a[k];
1339 a[k + step] ^= lo;
1340 }
1341 j += step << 1;
1342 }
1343 }
1344 Some(a)
1345}
1346
1347/// The algebraic degree of a Boolean function: the largest number of variables in any monomial present in
1348/// its ANF (0 for a constant, 1 for affine, up to `n`). `None` for a malformed table.
1349pub fn algebraic_degree(truth: &[bool]) -> Option<usize> {
1350 let a = anf(truth)?;
1351 Some(
1352 a.iter()
1353 .enumerate()
1354 .filter(|(_, &c)| c)
1355 .map(|(m, _)| (m as u64).count_ones() as usize)
1356 .max()
1357 .unwrap_or(0),
1358 )
1359}
1360
1361/// The autocorrelation spectrum of a Boolean function: `r_f(a) = Σ_x (−1)^{f(x) ⊕ f(x⊕a)}`, the correlation
1362/// of `f` with its shift by `a`. Computed by Wiener–Khinchin — the Walsh transform of the squared Walsh
1363/// spectrum, scaled by `2ⁿ` — so it costs one extra butterfly over [`walsh_spectrum`]. `r_f(0) = 2ⁿ`
1364/// always; `|r_f(a)| = 2ⁿ` exactly when the derivative `f(x⊕a) ⊕ f(x)` is CONSTANT — i.e. `a` is a linear
1365/// structure. `None` for a malformed table.
1366pub fn autocorrelation(truth: &[bool]) -> Option<Vec<i64>> {
1367 let mut w = walsh_spectrum(truth)?;
1368 for c in w.iter_mut() {
1369 *c *= *c;
1370 }
1371 fast_walsh_hadamard(&mut w);
1372 let scale = truth.len() as i64;
1373 for c in w.iter_mut() {
1374 *c /= scale;
1375 }
1376 Some(w)
1377}
1378
1379// ---- Algebraic immunity & annihilators: break the FILTER generator (the algebraic rung, Courtois–Meier)
1380//
1381// The correlation/Walsh rungs attack a combiner through its *statistical* leaks. The algebraic attack is
1382// exact: for a filter generator `z[t] = C(state_t)` (a single LFSR whose state is filtered by a nonlinear
1383// `C`), a low-degree ANNIHILATOR of `C` — a nonzero `g` with `g·C ≡ 0` — turns every keystream bit into a
1384// low-degree equation in the *initial state*. Where `z[t] = 1`, `C(state_t) = 1`, so `g(state_t) = 0`; and
1385// `state_t` is a LINEAR image of the initial state, so `g(state_t)` is a degree-`AI(C)` polynomial in the
1386// initial bits. Collect enough, linearize over monomials of degree `≤ AI(C)`, and solve for the whole
1387// state at once — polynomial for fixed `AI`, versus `2^L` brute force. The algebraic immunity `AI(C)` is
1388// the min degree of a nonzero annihilator of `C` or of `C⊕1`. The symmetry break: a low-degree
1389// annihilator is a hidden algebraic relation that compresses the `2^L` state search to a linear solve.
1390// Ceiling: a maximal-AI filter (`AI ≈ n/2`) leaves no low-degree relation — the algebraic-incompressible
1391// residue.
1392
1393/// A re-checkable annihilator witness: `coeffs` is the ANF (over `monomials(n_vars, degree)`) of a
1394/// nonzero `g` of degree `degree` that vanishes on `C`'s support (`annihilates_complement = false`) or on
1395/// `C`'s zero-set (`= true`, i.e. `g` annihilates `C ⊕ 1`).
1396#[derive(Clone, Debug, PartialEq, Eq)]
1397pub struct AnnihilatorWitness {
1398 pub n_vars: usize,
1399 pub degree: usize,
1400 pub coeffs: Vec<bool>,
1401 pub annihilates_complement: bool,
1402}
1403
1404/// A basis for the kernel `{c : A·c = 0}` over GF(2), `rows` being the coefficient bitmasks over `ncols`
1405/// columns: one basis vector per free column (that free variable set to 1, the pivots back-substituted).
1406/// Empty if the columns are independent. Bitset RREF, so `ncols > 64` is fine.
1407fn gf2_kernel_basis(rows: &[Vec<u64>], ncols: usize) -> Vec<Vec<bool>> {
1408 let words = ncols.div_ceil(64).max(1);
1409 let mut mat: Vec<Vec<u64>> = rows.to_vec();
1410 let mut pivot_row_of_col = vec![usize::MAX; ncols];
1411 let mut pivot_cols: Vec<usize> = Vec::new();
1412 let mut r = 0usize;
1413 for c in 0..ncols {
1414 let (w, bit) = (c / 64, 1u64 << (c % 64));
1415 let Some(pr) = (r..mat.len()).find(|&i| mat[i][w] & bit != 0) else {
1416 continue;
1417 };
1418 mat.swap(r, pr);
1419 for i in 0..mat.len() {
1420 if i != r && mat[i][w] & bit != 0 {
1421 for k in 0..words {
1422 mat[i][k] ^= mat[r][k];
1423 }
1424 }
1425 }
1426 pivot_row_of_col[c] = r;
1427 pivot_cols.push(c);
1428 r += 1;
1429 }
1430 // Each free column (no pivot) yields one basis vector: set it to 1, read pivots off their RREF rows
1431 // (a pivot row is `pivot_col ⊕ (free columns)`, so with only this free var at 1, `c[pivot] = row[free]`).
1432 (0..ncols)
1433 .filter(|&c| pivot_row_of_col[c] == usize::MAX)
1434 .map(|free| {
1435 let mut c = vec![false; ncols];
1436 c[free] = true;
1437 for &pc in &pivot_cols {
1438 let row = &mat[pivot_row_of_col[pc]];
1439 if (row[free / 64] >> (free % 64)) & 1 == 1 {
1440 c[pc] = true;
1441 }
1442 }
1443 c
1444 })
1445 .collect()
1446}
1447
1448/// A basis for the space of Boolean functions of degree `≤ d` (as ANF coefficients over [`monomials`]`(n,
1449/// d)`) that vanish on every point of `zero_set` (indices into `0..2ⁿ`) — every annihilator of that
1450/// support at that degree. Empty if only the zero function qualifies.
1451fn annihilator_basis(n: usize, d: usize, zero_set: &[usize]) -> Vec<Vec<bool>> {
1452 let monos = monomials(n, d);
1453 let m = monos.len();
1454 let words = m.div_ceil(64).max(1);
1455 let rows: Vec<Vec<u64>> = zero_set
1456 .iter()
1457 .map(|&x| {
1458 let window: Vec<bool> = (0..n).map(|i| (x >> i) & 1 == 1).collect();
1459 let mut coeff = vec![0u64; words];
1460 for (mi, mono) in monos.iter().enumerate() {
1461 if eval_monomial(mono, &window) {
1462 coeff[mi / 64] |= 1u64 << (mi % 64);
1463 }
1464 }
1465 coeff
1466 })
1467 .collect();
1468 gf2_kernel_basis(&rows, m)
1469}
1470
1471/// A single nonzero annihilator of `zero_set` at degree `≤ d`, or `None` if none exists.
1472fn annihilator(n: usize, d: usize, zero_set: &[usize]) -> Option<Vec<bool>> {
1473 annihilator_basis(n, d, zero_set).into_iter().next()
1474}
1475
1476/// The **algebraic immunity** of a Boolean function given as its `2ⁿ` truth table: the minimum degree of
1477/// a nonzero annihilator of `C` or of `C ⊕ 1`, together with a re-checkable witness. Searching degrees
1478/// ascending, the first hit is the minimum (no lower-degree annihilator exists, or an earlier degree
1479/// would have found it). `None` for a malformed table. `AI ≤ ⌈n/2⌉` always.
1480pub fn algebraic_immunity(truth: &[bool]) -> Option<(usize, AnnihilatorWitness)> {
1481 if truth.is_empty() || !truth.len().is_power_of_two() {
1482 return None;
1483 }
1484 let n = truth.len().trailing_zeros() as usize;
1485 let support: Vec<usize> = (0..truth.len()).filter(|&x| truth[x]).collect();
1486 let zeros: Vec<usize> = (0..truth.len()).filter(|&x| !truth[x]).collect();
1487 for d in 0..=n {
1488 if let Some(g) = annihilator(n, d, &support) {
1489 return Some((
1490 d,
1491 AnnihilatorWitness {
1492 n_vars: n,
1493 degree: d,
1494 coeffs: g,
1495 annihilates_complement: false,
1496 },
1497 ));
1498 }
1499 if let Some(g) = annihilator(n, d, &zeros) {
1500 return Some((
1501 d,
1502 AnnihilatorWitness {
1503 n_vars: n,
1504 degree: d,
1505 coeffs: g,
1506 annihilates_complement: true,
1507 },
1508 ));
1509 }
1510 }
1511 None
1512}
1513
1514/// Evaluate an ANF (coefficients over [`monomials`]`(n_vars, degree)`) at a point `x ∈ 0..2ⁿ`.
1515fn eval_anf(coeffs: &[bool], n_vars: usize, degree: usize, x: usize) -> bool {
1516 let window: Vec<bool> = (0..n_vars).map(|i| (x >> i) & 1 == 1).collect();
1517 monomials(n_vars, degree)
1518 .iter()
1519 .enumerate()
1520 .filter(|(mi, _)| coeffs.get(*mi).copied().unwrap_or(false))
1521 .fold(false, |acc, (_, mono)| acc ^ eval_monomial(mono, &window))
1522}
1523
1524/// Re-check an [`AnnihilatorWitness`] against a truth table with zero trust in the producer: the witness
1525/// is nonzero and vanishes on the required set (support of `C`, or of `C ⊕ 1`). Confirms the
1526/// algebraic-immunity claim independently.
1527pub fn verify_annihilator(truth: &[bool], w: &AnnihilatorWitness) -> bool {
1528 if w.coeffs.iter().all(|&c| !c) || monomials(w.n_vars, w.degree).len() != w.coeffs.len() {
1529 return false;
1530 }
1531 (0..truth.len()).all(|x| {
1532 let must_vanish = if w.annihilates_complement {
1533 !truth[x]
1534 } else {
1535 truth[x]
1536 };
1537 !must_vanish || !eval_anf(&w.coeffs, w.n_vars, w.degree, x)
1538 })
1539}
1540
1541/// Recover the initial state of a **filter generator** by the algebraic attack: a length-`l` LFSR with
1542/// feedback `taps` drives a filter `C` (truth table `filter_truth` over its `m = log₂` inputs, read as
1543/// `m` CONSECUTIVE state bits), emitting `keystream[t] = C(seq[t], …, seq[t+m−1])`. Using a min-degree
1544/// annihilator `g` of `C`, each applicable keystream bit becomes `g(⟨r_t,s₀⟩, …) = 0`, a degree-`AI`
1545/// equation in the initial state `s₀`; expanding over `s₀`-monomials of degree `≤ AI` and solving the
1546/// GF(2) system recovers `s₀`. Returns the `l`-bit initial state (verified by regeneration), or `None` if
1547/// there is no low-AI annihilator, the system is underdetermined, or `l > 64`.
1548pub fn algebraic_filter_attack(
1549 keystream: &[bool],
1550 taps: &[bool],
1551 filter_truth: &[bool],
1552) -> Option<Vec<bool>> {
1553 let l = taps.len();
1554 let n = keystream.len();
1555 if l == 0 || l > 64 || !filter_truth.len().is_power_of_two() {
1556 return None;
1557 }
1558 let m = filter_truth.len().trailing_zeros() as usize;
1559 if m == 0 || n < l + m {
1560 return None;
1561 }
1562 let (ai, _) = algebraic_immunity(filter_truth)?;
1563 if ai == 0 {
1564 return None; // a constant filter carries no state
1565 }
1566 let g_monos = monomials(m, ai);
1567 // The whole annihilator space at degree AI, from BOTH sides: functions vanishing on the filter's
1568 // support (applied where the keystream is 1) and on its zero-set (applied where it is 0). A single
1569 // annihilator underdetermines the linearized system; the full basis makes it full rank.
1570 let support: Vec<usize> = (0..filter_truth.len())
1571 .filter(|&x| filter_truth[x])
1572 .collect();
1573 let zeros: Vec<usize> = (0..filter_truth.len())
1574 .filter(|&x| !filter_truth[x])
1575 .collect();
1576 let ann_when_one = annihilator_basis(m, ai, &support);
1577 let ann_when_zero = annihilator_basis(m, ai, &zeros);
1578
1579 // Linear forms r_k (bitmask over the l initial-state bits) for each sequence position: seq[k]=⟨r_k,s₀⟩.
1580 let need = n + m;
1581 let mut r: Vec<u64> = Vec::with_capacity(need);
1582 for k in 0..need {
1583 if k < l {
1584 r.push(1u64 << k);
1585 } else {
1586 let mut acc = 0u64;
1587 for (j, &t) in taps.iter().enumerate() {
1588 if t {
1589 acc ^= r[k - 1 - j];
1590 }
1591 }
1592 r.push(acc);
1593 }
1594 }
1595
1596 // Column layout: monomials(l, ai), column 0 = the constant (pinned to 1 via a seed equation).
1597 let s_monos = monomials(l, ai);
1598 let ncols = s_monos.len();
1599 let col_of: std::collections::HashMap<u64, usize> = s_monos
1600 .iter()
1601 .enumerate()
1602 .map(|(i, mono)| (mono.iter().fold(0u64, |b, &v| b | (1u64 << v)), i))
1603 .collect();
1604 let words = ncols.div_ceil(64).max(1);
1605
1606 // Expand an annihilator `g(y₀,…,y_{m-1})` with `yᵢ = ⟨r_{t+i}, s₀⟩` into an equation row over the
1607 // s₀-monomials (the constant monomial, mask 0, moves to the right-hand side).
1608 let expand = |g: &[bool], t: usize| -> Option<(Vec<u64>, bool)> {
1609 let mut acc: std::collections::HashSet<u64> = std::collections::HashSet::new();
1610 for (gi, mono) in g_monos.iter().enumerate() {
1611 if !g[gi] {
1612 continue;
1613 }
1614 let mut poly: std::collections::HashSet<u64> = std::collections::HashSet::from([0u64]);
1615 for &i in mono {
1616 let form = r[t + i];
1617 let mut next: std::collections::HashSet<u64> = std::collections::HashSet::new();
1618 for &pm in &poly {
1619 let mut bits = form;
1620 while bits != 0 {
1621 let v = bits.trailing_zeros();
1622 bits &= bits - 1;
1623 let term = pm | (1u64 << v);
1624 if !next.insert(term) {
1625 next.remove(&term); // XOR: cancel duplicates
1626 }
1627 }
1628 }
1629 poly = next;
1630 }
1631 for pm in poly {
1632 if !acc.insert(pm) {
1633 acc.remove(&pm);
1634 }
1635 }
1636 }
1637 let mut coeff = vec![0u64; words];
1638 let mut rhs = false;
1639 for mask in acc {
1640 if mask == 0 {
1641 rhs = true;
1642 } else {
1643 coeff[*col_of.get(&mask)? / 64] |= 1u64 << (col_of[&mask] % 64);
1644 }
1645 }
1646 Some((coeff, rhs))
1647 };
1648
1649 let mut rows: Vec<(Vec<u64>, bool)> = Vec::new();
1650 let mut pin = vec![0u64; words];
1651 pin[0] = 1;
1652 rows.push((pin, true)); // pin the constant monomial to 1
1653
1654 for t in 0..n.saturating_sub(m - 1) {
1655 let anns = if keystream[t] {
1656 &ann_when_one
1657 } else {
1658 &ann_when_zero
1659 };
1660 for g in anns {
1661 rows.push(expand(g, t)?);
1662 }
1663 }
1664
1665 let sol = solve_gf2_system(&rows, ncols)?;
1666 // The degree-1 monomial columns hold the recovered state bits.
1667 let state: Vec<bool> = (0..l)
1668 .map(|i| col_of.get(&(1u64 << i)).map(|&ci| sol[ci]).unwrap_or(false))
1669 .collect();
1670
1671 // Verify by regeneration: the recovered state must reproduce the keystream exactly.
1672 let seq = lfsr_generate(taps, &state, need);
1673 let regen: Vec<bool> = (0..n)
1674 .map(|t| {
1675 let idx = (0..m).fold(0usize, |a, i| a | (usize::from(seq[t + i]) << i));
1676 filter_truth[idx]
1677 })
1678 .collect();
1679 (regen == keystream).then_some(state)
1680}
1681
1682// ---- Fast correlation attack: decode the LFSR-as-linear-code, no 2^L search (Meier–Staffelbach) ------
1683//
1684// The correlation attack (Rung E) recovered a leaking LFSR's initial state by exhaustive search over its
1685// 2^L states. The fast correlation attack removes the exponential: the LFSR's output is a codeword of a
1686// linear code (it satisfies its feedback recurrence at every position), so a noisy keystream `z = a ⊕
1687// noise` is a corrupted codeword, and recovering `a` is DECODING. The recurrence gives a low-weight
1688// parity check — `a[i] ⊕ ⊕ⱼ tapsⱼ·a[i−1−j] = 0` — and over GF(2) each squaring of the feedback
1689// polynomial (`g(x)^{2^k}`, the Frobenius map) gives another check of the SAME low weight, stretched.
1690// Instantiated at every anchor, these give many low-weight checks per bit; a Gallager hard-decision
1691// bit-flip decoder then flips the bits sitting in a majority of unsatisfied checks until the sequence
1692// satisfies its recurrence — a valid LFSR output — recovered in time polynomial in `L`, not `2^L`. The
1693// symmetry broken is the code's own automorphism: its dual carries low-weight words that pin the errors.
1694// Ceiling: too much noise (past the Meier–Staffelbach threshold) or a dense feedback polynomial (no
1695// low-weight checks) and the decoder cannot converge — the register resists.
1696
1697/// Meier–Staffelbach fast correlation attack: recover the initial state of the length-`L` LFSR with
1698/// feedback `taps` from a noisy keystream `keystream` (a `z = a ⊕ noise` binary symmetric channel), by
1699/// iterative bit-flip decoding against the low-weight parity checks the feedback recurrence and its
1700/// Frobenius squares generate. Returns the recovered `L`-bit initial state when decoding converges to a
1701/// valid LFSR output that agrees with the keystream noticeably better than chance, else `None` (too much
1702/// noise or too few low-weight checks — the register resists). Polynomial in `L` — no `2^L` search.
1703pub fn fast_correlation_attack(
1704 keystream: &[bool],
1705 taps: &[bool],
1706 max_iters: usize,
1707) -> Option<Vec<bool>> {
1708 let (n, l) = (keystream.len(), taps.len());
1709 if l == 0 || n <= 2 * l {
1710 return None;
1711 }
1712 // Base parity-check offsets (relative to an anchor `i`): position `i` and each `i − (1+j)` with a tap.
1713 let mut base: Vec<usize> = vec![0];
1714 for (j, &t) in taps.iter().enumerate() {
1715 if t {
1716 base.push(1 + j);
1717 }
1718 }
1719 // Frobenius: squaring the feedback polynomial doubles the offsets and preserves the weight, so each
1720 // level adds independent low-weight checks that reach further across the sequence.
1721 let mut checks: Vec<Vec<usize>> = Vec::new();
1722 let mut scale = 1usize;
1723 for _ in 0..4 {
1724 let span = base.iter().map(|&o| o * scale).max().unwrap_or(0);
1725 if span >= n {
1726 break;
1727 }
1728 for i in span..n {
1729 checks.push(base.iter().map(|&o| i - o * scale).collect());
1730 }
1731 scale *= 2;
1732 }
1733 if checks.is_empty() {
1734 return None;
1735 }
1736 let mut per_bit = vec![0usize; n];
1737 for c in &checks {
1738 for &p in c {
1739 per_bit[p] += 1;
1740 }
1741 }
1742
1743 let mut y = keystream.to_vec();
1744 for _ in 0..max_iters {
1745 let mut votes = vec![0usize; n];
1746 let mut all_satisfied = true;
1747 for c in &checks {
1748 if c.iter().fold(false, |a, &p| a ^ y[p]) {
1749 all_satisfied = false;
1750 for &p in c {
1751 votes[p] += 1;
1752 }
1753 }
1754 }
1755 if all_satisfied {
1756 break;
1757 }
1758 let mut flipped = false;
1759 for i in 0..n {
1760 if per_bit[i] > 0 && votes[i] * 2 > per_bit[i] {
1761 y[i] ^= true;
1762 flipped = true;
1763 }
1764 }
1765 if !flipped {
1766 break; // stuck below the flip threshold — decoding cannot progress
1767 }
1768 }
1769
1770 // Accept only a genuine codeword (the recurrence holds everywhere) that correlates with the keystream.
1771 let state = y[..l].to_vec();
1772 let regen = lfsr_generate(taps, &state, n);
1773 if regen != y {
1774 return None;
1775 }
1776 let agree = regen.iter().zip(keystream).filter(|(a, b)| a == b).count() as f64 / n as f64;
1777 (agree > 0.6).then_some(state)
1778}
1779
1780// ---- Clock control / decimation: break the shrinking generator (the structural rung) -----------------
1781//
1782// Every rung so far assumes the keystream is a fixed function of register state read at a fixed cadence.
1783// A clock-controlled generator breaks that: in the SHRINKING GENERATOR a clock register `A` gates a data
1784// register `S`, emitting `S[i]` only when `A[i] = 1` and dropping it otherwise. The output is therefore a
1785// DATA-DEPENDENT decimation of `S` — it is not a fixed function of either register's own past, so no
1786// feedback, correlation, algebraic, or linear rung applies, and its linear complexity is enormous
1787// (≈ `2^{L_S}`). But the decimation is the exploitable symmetry: guess the clock register's `2^{L_A}`
1788// states (divide-and-conquer on the CLOCK alone), and a correct guess fixes the emit positions
1789// `{i : A[i] = 1}`. Each output bit is then `S` at a known position — `output[k] = ⟨r_{iₖ}, s₀⟩`, a
1790// LINEAR equation in `S`'s initial state — so a GF(2) solve recovers `S` and the whole generator falls.
1791// Ceiling: a large or securely-clocked control register makes the clock guess itself exponential.
1792
1793/// The shrinking generator: clock register `A` (feedback `a_taps`, seed `a_seed`) gates data register `S`
1794/// (feedback `s_taps`, seed `s_seed`), emitting `S`'s bit exactly when `A`'s bit is `1`, until `out_len`
1795/// bits are produced. Its output is a data-dependent decimation of `S` with very high linear complexity.
1796pub fn shrinking_generator(
1797 a_taps: &[bool],
1798 a_seed: &[bool],
1799 s_taps: &[bool],
1800 s_seed: &[bool],
1801 out_len: usize,
1802) -> Vec<bool> {
1803 let clocks = out_len.saturating_mul(4) + 64; // A = 1 about half the time; 4× gives ample headroom
1804 let a = lfsr_generate(a_taps, a_seed, clocks);
1805 let s = lfsr_generate(s_taps, s_seed, clocks);
1806 let mut out = Vec::with_capacity(out_len);
1807 for i in 0..clocks {
1808 if a[i] {
1809 out.push(s[i]);
1810 if out.len() == out_len {
1811 break;
1812 }
1813 }
1814 }
1815 out
1816}
1817
1818/// Attack the shrinking generator: recover the initial states of both the clock register `A` (feedback
1819/// `a_taps`) and the data register `S` (feedback `s_taps`) from `output` alone, by divide-and-conquer on
1820/// the clock. Each of the `2^{L_A}` clock states is tried; a guess fixes the emit positions, turning every
1821/// output bit into a linear equation `⟨r_{iₖ}, s₀⟩ = output[k]` in `S`'s initial state, solved over GF(2)
1822/// and verified by regeneration. Returns `(a_state, s_state)` for the first guess that reproduces the
1823/// output, or `None` (clock register too large — `L_A > 22` — or no consistent state). Exponential in
1824/// `L_A` only, not `L_A + L_S`.
1825pub fn attack_shrinking_generator(
1826 output: &[bool],
1827 a_taps: &[bool],
1828 s_taps: &[bool],
1829) -> Option<(Vec<bool>, Vec<bool>)> {
1830 let (la, ls) = (a_taps.len(), s_taps.len());
1831 let m = output.len();
1832 if la == 0 || la > 22 || ls == 0 || ls > 64 || m < ls {
1833 return None;
1834 }
1835 let clocks = m.saturating_mul(4) + 64;
1836 // S's linear forms r_k (bitmask over its ls initial-state bits): S[k] = ⟨r_k, s₀⟩.
1837 let mut r: Vec<u64> = Vec::with_capacity(clocks);
1838 for k in 0..clocks {
1839 if k < ls {
1840 r.push(1u64 << k);
1841 } else {
1842 let mut acc = 0u64;
1843 for (j, &t) in s_taps.iter().enumerate() {
1844 if t {
1845 acc ^= r[k - 1 - j];
1846 }
1847 }
1848 r.push(acc);
1849 }
1850 }
1851 let words = ls.div_ceil(64).max(1);
1852 for code in 1u64..(1u64 << la) {
1853 let a_seed: Vec<bool> = (0..la).map(|k| (code >> k) & 1 == 1).collect();
1854 let a = lfsr_generate(a_taps, &a_seed, clocks);
1855 let mut positions = Vec::with_capacity(m);
1856 for (i, &bit) in a.iter().enumerate() {
1857 if bit {
1858 positions.push(i);
1859 if positions.len() == m {
1860 break;
1861 }
1862 }
1863 }
1864 if positions.len() < m {
1865 continue; // this clock did not emit enough bits
1866 }
1867 let rows: Vec<(Vec<u64>, bool)> = positions
1868 .iter()
1869 .enumerate()
1870 .map(|(k, &pos)| {
1871 let mut coeff = vec![0u64; words];
1872 coeff[0] = r[pos];
1873 (coeff, output[k])
1874 })
1875 .collect();
1876 if let Some(sol) = solve_gf2_system(&rows, ls) {
1877 let s_seed: Vec<bool> = sol[..ls].to_vec();
1878 if shrinking_generator(a_taps, &a_seed, s_taps, &s_seed, m) == output {
1879 return Some((a_seed, s_seed));
1880 }
1881 }
1882 }
1883 None
1884}
1885
1886// ---- XL / Gröbner escalation: solve where linearization underdetermines (the algebraic capstone) -----
1887//
1888// The algebraic-immunity rung linearizes a degree-`AI` system over its monomials and solves. When the
1889// number of monomials outruns the equations, that linear solve is underdetermined and stalls. The XL
1890// (eXtended Linearization) algorithm escalates: MULTIPLY each equation by monomials to manufacture more
1891// equations of bounded degree, then linearize the enlarged system. Multiplication surfaces implicit
1892// lower-degree consequences — the "degree fall" — that the original degree could not express, so a system
1893// unsolvable by linearization becomes solvable at a higher operating degree. And an inconsistency that
1894// only appears after multiplication is a REFUTATION: proof the system has no solution (the same certified
1895// UNSAT the algebraic-DRAT bridge consumes). The symmetry broken is the polynomial ideal's own structure
1896// — its Gröbner basis of implicit relations. Ceiling: the regularity degree — a truly random high-degree
1897// system forces the operating degree (and the monomial count) up to the wall.
1898
1899/// The outcome of an XL solve over GF(2).
1900#[derive(Clone, Debug, PartialEq, Eq)]
1901pub enum PolySolveResult {
1902 /// A satisfying assignment, verified against the original equations.
1903 Solved(Vec<bool>),
1904 /// The system is unsatisfiable — a certified refutation (the linearized system became inconsistent).
1905 Refuted,
1906 /// No verdict at the operating degrees tried (raise `max_degree`).
1907 Undetermined,
1908}
1909
1910/// All monomials of degree `≤ deg` over `n` variables, as bitmasks (`≤ 64` variables).
1911fn monomial_masks(n: usize, deg: usize) -> Vec<u64> {
1912 monomials(n, deg)
1913 .iter()
1914 .map(|mono| mono.iter().fold(0u64, |b, &v| b | (1u64 << v)))
1915 .collect()
1916}
1917
1918/// Evaluate a monomial (bitmask; `0` = the constant `1`) at an assignment.
1919fn eval_mask(mask: u64, x: &[bool]) -> bool {
1920 let mut m = mask;
1921 let mut v = true;
1922 while m != 0 {
1923 v &= x[m.trailing_zeros() as usize];
1924 m &= m - 1;
1925 }
1926 v
1927}
1928
1929/// Does `x` satisfy every equation (each an XOR of monomials that must be `0`)?
1930fn verify_poly_system(eqs: &[Vec<u64>], x: &[bool]) -> bool {
1931 eqs.iter()
1932 .all(|eq| !eq.iter().fold(false, |a, &m| a ^ eval_mask(m, x)))
1933}
1934
1935/// Solve a Boolean polynomial system over GF(2) by **XL** (eXtended Linearization). Each equation is an
1936/// XOR of monomials (bitmasks over the `n_vars` variables, `x²=x`; mask `0` is the constant) that must be
1937/// `0`. For each operating degree `d = 1..=max_degree`, every equation is multiplied by all monomials of
1938/// degree `≤ d − deg(eq)`, the enlarged system is linearized over the degree-`≤ d` monomials (with the
1939/// constant pinned to `1`) and solved: an inconsistency proves the system unsatisfiable ([`Refuted`]), a
1940/// solution whose degree-1 part satisfies the original equations is returned ([`Solved`]), otherwise the
1941/// degree is raised. This solves systems the plain degree-`d` linearization cannot, and refutes ones it
1942/// cannot see contradictory.
1943///
1944/// [`Refuted`]: PolySolveResult::Refuted
1945/// [`Solved`]: PolySolveResult::Solved
1946pub fn solve_polynomial_system_gf2(
1947 eqs: &[Vec<u64>],
1948 n_vars: usize,
1949 max_degree: usize,
1950) -> PolySolveResult {
1951 for d in 1..=max_degree {
1952 let cols = monomial_masks(n_vars, d);
1953 let col_of: std::collections::HashMap<u64, usize> =
1954 cols.iter().enumerate().map(|(i, &m)| (m, i)).collect();
1955 let ncols = cols.len();
1956 let words = ncols.div_ceil(64).max(1);
1957
1958 let mut rows: Vec<(Vec<u64>, bool)> = Vec::new();
1959 // Pin the constant monomial to 1.
1960 let mut pin = vec![0u64; words];
1961 let c0 = col_of[&0];
1962 pin[c0 / 64] |= 1u64 << (c0 % 64);
1963 rows.push((pin, true));
1964
1965 for eq in eqs {
1966 let deg_eq = eq
1967 .iter()
1968 .map(|m| m.count_ones() as usize)
1969 .max()
1970 .unwrap_or(0);
1971 if deg_eq > d {
1972 continue; // cannot be represented at this operating degree yet
1973 }
1974 for mu in monomial_masks(n_vars, d - deg_eq) {
1975 // Multiply the equation by `mu` (monomial product = OR of masks over GF(2)).
1976 let mut acc: std::collections::HashSet<u64> = std::collections::HashSet::new();
1977 for &m in eq {
1978 let prod = m | mu;
1979 if !acc.insert(prod) {
1980 acc.remove(&prod); // XOR cancellation
1981 }
1982 }
1983 if acc.is_empty() {
1984 continue;
1985 }
1986 let mut coeff = vec![0u64; words];
1987 let mut rhs = false;
1988 for mask in acc {
1989 if mask == 0 {
1990 rhs = true;
1991 } else if let Some(&ci) = col_of.get(&mask) {
1992 coeff[ci / 64] |= 1u64 << (ci % 64);
1993 }
1994 }
1995 rows.push((coeff, rhs));
1996 }
1997 }
1998
1999 match solve_gf2_system(&rows, ncols) {
2000 None => return PolySolveResult::Refuted,
2001 Some(sol) => {
2002 let x: Vec<bool> = (0..n_vars)
2003 .map(|i| col_of.get(&(1u64 << i)).map(|&ci| sol[ci]).unwrap_or(false))
2004 .collect();
2005 if verify_poly_system(eqs, &x) {
2006 return PolySolveResult::Solved(x);
2007 }
2008 }
2009 }
2010 }
2011 PolySolveResult::Undetermined
2012}
2013
2014/// Serialize a `BigInt` as sign byte + varint length + little-endian magnitude, trimmed to minimal
2015/// length (`to_le_bytes` is limb-aligned, so a small value would otherwise carry trailing zero bytes).
2016fn write_bigint(x: &crate::numeric::BigInt, out: &mut Vec<u8>) {
2017 let (neg, mut bytes) = x.to_le_bytes();
2018 while bytes.last() == Some(&0) {
2019 bytes.pop();
2020 }
2021 out.push(neg as u8);
2022 write_uvarint(bytes.len() as u64, out);
2023 out.extend_from_slice(&bytes);
2024}
2025
2026/// The inverse of [`write_bigint`].
2027fn read_bigint(buf: &[u8], pos: &mut usize) -> Option<crate::numeric::BigInt> {
2028 let neg = *buf.get(*pos)? != 0;
2029 *pos += 1;
2030 let len = read_uvarint(buf, pos)? as usize;
2031 let bytes = buf.get(*pos..pos.checked_add(len)?)?;
2032 *pos += len;
2033 Some(crate::numeric::BigInt::from_le_bytes(neg, bytes))
2034}
2035
2036/// If a byte column is an FCSR (carry-based) keystream — its bit expansion is the 2-adic rational
2037/// `p/q` and that rational regenerates every bit — return `(p, q)`. Catches carry generators (add-with-
2038/// carry, mod-2ⁿ LCGs) that fool every linear generator; `consider` keeps it only when `p/q` beats raw.
2039fn detect_fcsr_bytes(v: &[i64]) -> Option<(crate::numeric::BigInt, crate::numeric::BigInt)> {
2040 let bits = bytes_to_bits(v);
2041 let (p, q) = two_adic_reconstruct(&bits)?;
2042 if fcsr_generate(&p, &q, bits.len()) != bits {
2043 return None;
2044 }
2045 Some((p, q))
2046}
2047
2048/// Recognize `v[i] = a + b·(i mod p)` for a small period `p` and synthesize the generator.
2049pub fn detect_modular_affine(v: &[i64]) -> Option<GenExpr> {
2050 const MAX_PERIOD: usize = 16;
2051 if v.len() < 4 {
2052 return None;
2053 }
2054 for p in 2..=MAX_PERIOD.min(v.len() / 2) {
2055 let a = v[0];
2056 let b = v[1].wrapping_sub(v[0]);
2057 if b != 0 && (0..v.len()).all(|i| v[i] == a.wrapping_add(b.wrapping_mul((i % p) as i64))) {
2058 return Some(GenExpr::Add(
2059 Box::new(GenExpr::Const(a)),
2060 Box::new(GenExpr::Mul(
2061 Box::new(GenExpr::Const(b)),
2062 Box::new(GenExpr::Mod(
2063 Box::new(GenExpr::Index),
2064 Box::new(GenExpr::Const(p as i64)),
2065 )),
2066 )),
2067 ));
2068 }
2069 }
2070 None
2071}
2072
2073// ---- Columnar fallback encoders ------------------------------------------------------------
2074
2075/// Delta: first value then zig-zag successive differences. Wins on monotone columns.
2076pub fn delta_encode(out: &mut Vec<u8>, v: &[i64]) {
2077 out.push(T_INTS_DELTA);
2078 write_uvarint(v.len() as u64, out);
2079 if let Some(&first) = v.first() {
2080 write_uvarint(zigzag(first), out);
2081 let mut prev = first;
2082 for &x in &v[1..] {
2083 write_uvarint(zigzag(x.wrapping_sub(prev)), out);
2084 prev = x;
2085 }
2086 }
2087}
2088
2089/// Delta-of-delta: first value, first delta, then zig-zag second differences. Wins on near-linear
2090/// progressions (timestamps with jitter).
2091pub fn dod_encode(out: &mut Vec<u8>, v: &[i64]) {
2092 out.push(T_INTS_DOD);
2093 write_uvarint(v.len() as u64, out);
2094 if v.is_empty() {
2095 return;
2096 }
2097 write_uvarint(zigzag(v[0]), out);
2098 if v.len() == 1 {
2099 return;
2100 }
2101 let mut prev_delta = v[1].wrapping_sub(v[0]);
2102 write_uvarint(zigzag(prev_delta), out);
2103 let mut prev = v[1];
2104 for &x in &v[2..] {
2105 let d = x.wrapping_sub(prev);
2106 write_uvarint(zigzag(d.wrapping_sub(prev_delta)), out);
2107 prev_delta = d;
2108 prev = x;
2109 }
2110}
2111
2112/// Frame-of-reference: subtract the column minimum, bit-pack the residuals. Wins on clustered
2113/// columns (a small range around any base).
2114pub fn for_encode(out: &mut Vec<u8>, v: &[i64]) {
2115 out.push(T_INTS_FOR);
2116 write_uvarint(v.len() as u64, out);
2117 let min = v.iter().copied().min().unwrap_or(0);
2118 write_uvarint(zigzag(min), out);
2119 if v.is_empty() {
2120 out.push(0);
2121 return;
2122 }
2123 let max = v.iter().copied().max().unwrap();
2124 let range = (max as u64).wrapping_sub(min as u64);
2125 let width = if range == 0 {
2126 0
2127 } else {
2128 (64 - range.leading_zeros()) as u8
2129 };
2130 out.push(width);
2131 if width > 0 {
2132 let residuals: Vec<u64> = v
2133 .iter()
2134 .map(|&x| (x as u64).wrapping_sub(min as u64))
2135 .collect();
2136 out.extend_from_slice(&bitpack(&residuals, width));
2137 }
2138}
2139
2140/// Run-length: (value, run-length) pairs. Wins on columns of repeated runs.
2141pub fn rle_encode(out: &mut Vec<u8>, v: &[i64]) {
2142 let mut runs: Vec<(i64, u64)> = Vec::new();
2143 for &x in v {
2144 match runs.last_mut() {
2145 Some(last) if last.0 == x => last.1 += 1,
2146 _ => runs.push((x, 1)),
2147 }
2148 }
2149 out.push(T_INTS_RLE);
2150 write_uvarint(runs.len() as u64, out);
2151 for (val, len) in runs {
2152 write_uvarint(zigzag(val), out);
2153 write_uvarint(len, out);
2154 }
2155}
2156
2157/// Dictionary: distinct values (first-seen order) then a bit-packed index column. Wins on
2158/// low-cardinality columns.
2159pub fn dict_encode(v: &[i64]) -> Vec<u8> {
2160 let mut dict: Vec<i64> = Vec::new();
2161 let mut index_of: std::collections::HashMap<i64, u64> = std::collections::HashMap::new();
2162 let mut indices: Vec<u64> = Vec::with_capacity(v.len());
2163 for &x in v {
2164 let idx = *index_of.entry(x).or_insert_with(|| {
2165 dict.push(x);
2166 (dict.len() - 1) as u64
2167 });
2168 indices.push(idx);
2169 }
2170 let mut out = vec![T_INTS_DICT];
2171 write_uvarint(dict.len() as u64, &mut out);
2172 for &d in &dict {
2173 write_uvarint(zigzag(d), &mut out);
2174 }
2175 write_uvarint(v.len() as u64, &mut out);
2176 let iw = if dict.len() <= 1 {
2177 0
2178 } else {
2179 (64 - ((dict.len() - 1) as u64).leading_zeros()) as u8
2180 };
2181 out.push(iw);
2182 if iw > 0 {
2183 out.extend_from_slice(&bitpack(&indices, iw));
2184 }
2185 out
2186}
2187
2188/// Keep `cand` if it is smaller than the current `best` — the MDL argmin over candidate encodings.
2189pub fn consider(best: &mut Vec<u8>, cand: Vec<u8>) {
2190 if cand.len() < best.len() {
2191 *best = cand;
2192 }
2193}
2194
2195// ---- The description engine (encode) -------------------------------------------------------
2196
2197/// Build every applicable column encoding and append the smallest to `out`. The plain-varint
2198/// baseline is always a candidate, so the result is never larger than the varint form.
2199pub fn emit_best_int_column(v: &[i64], out: &mut Vec<u8>) {
2200 let mut best = Vec::new();
2201 best.push(T_INTS);
2202 leb128_encode(&mut best, v.iter().copied(), v.len());
2203
2204 if let Some((base, stride)) = detect_affine(v) {
2205 let mut c = vec![T_INTS_AFFINE];
2206 write_uvarint(zigzag(base), &mut c);
2207 write_uvarint(zigzag(stride), &mut c);
2208 write_uvarint(v.len() as u64, &mut c);
2209 consider(&mut best, c);
2210 }
2211 if let Some((base, ratio)) = detect_geometric(v) {
2212 let mut c = vec![T_INTS_GEOMETRIC];
2213 write_uvarint(zigzag(base), &mut c);
2214 write_uvarint(zigzag(ratio), &mut c);
2215 write_uvarint(v.len() as u64, &mut c);
2216 consider(&mut best, c);
2217 }
2218 if let Some(p) = detect_period(v) {
2219 let mut c = vec![T_INTS_PERIODIC];
2220 write_uvarint(v.len() as u64, &mut c);
2221 emit_best_int_column(&v[..p], &mut c);
2222 consider(&mut best, c);
2223 }
2224 if let Some((dom, exc)) = detect_sparse(v) {
2225 let mut c = vec![T_INTS_SPARSE];
2226 write_uvarint(zigzag(dom), &mut c);
2227 write_uvarint(v.len() as u64, &mut c);
2228 write_uvarint(exc.len() as u64, &mut c);
2229 let mut prev = 0usize;
2230 for (i, x) in &exc {
2231 write_uvarint((i - prev) as u64, &mut c);
2232 prev = *i;
2233 write_uvarint(zigzag(*x), &mut c);
2234 }
2235 consider(&mut best, c);
2236 }
2237 if let Some((degree, seeds)) = detect_poly_generator(v) {
2238 let mut c = vec![T_INTS_POLY, degree];
2239 write_uvarint(v.len() as u64, &mut c);
2240 for &s in &seeds {
2241 write_uvarint(zigzag(s), &mut c);
2242 }
2243 consider(&mut best, c);
2244 }
2245 // Ship the GENERATOR, not the data: a linear-recurrence column (Fibonacci-class) becomes its order,
2246 // coefficients, and seeds — a handful of numbers regardless of n. Reaches sequences the polynomial
2247 // detector cannot (finite differences that never settle).
2248 if let Some((coeffs, seeds)) = detect_linear_recurrence(v) {
2249 let mut c = vec![T_INTS_LRECUR, coeffs.len() as u8];
2250 write_uvarint(v.len() as u64, &mut c);
2251 for &x in &coeffs {
2252 write_uvarint(zigzag(x), &mut c);
2253 }
2254 for &s in &seeds {
2255 write_uvarint(zigzag(s), &mut c);
2256 }
2257 consider(&mut best, c);
2258 }
2259 if let Some(expr) = detect_modular_affine(v) {
2260 let mut c = vec![T_GEN];
2261 serialize_gen(&expr, &mut c);
2262 write_uvarint(v.len() as u64, &mut c);
2263 consider(&mut best, c);
2264 }
2265 let mut delta = Vec::new();
2266 delta_encode(&mut delta, v);
2267 consider(&mut best, delta);
2268
2269 let mut dod = Vec::new();
2270 dod_encode(&mut dod, v);
2271 consider(&mut best, dod);
2272
2273 if !v.is_empty() && v.iter().all(|&x| (0..256).contains(&x)) {
2274 let mut b = vec![T_BYTES];
2275 write_uvarint(v.len() as u64, &mut b);
2276 b.extend(v.iter().map(|&x| x as u8));
2277 consider(&mut best, b);
2278 }
2279
2280 let mut for_c = Vec::new();
2281 for_encode(&mut for_c, v);
2282 consider(&mut best, for_c);
2283
2284 let mut rle = Vec::new();
2285 rle_encode(&mut rle, v);
2286 consider(&mut best, rle);
2287
2288 consider(&mut best, dict_encode(v));
2289
2290 // LAST RESORT — the LFSR attack: if this is a small byte column that NOTHING above compressed (it
2291 // looks random), run Berlekamp–Massey. A keystream from a short LFSR collapses to `O(L)` bits even
2292 // though every other generator sees noise. Gated by size and by "nothing else worked", so the
2293 // `O(bits²)` cost is paid only where it can pay off.
2294 if !v.is_empty()
2295 && v.len() <= LFSR_MAX_BYTES
2296 && best.len() >= v.len()
2297 && v.iter().all(|&x| (0..256).contains(&x))
2298 {
2299 if let Some((l, taps, seed)) = detect_lfsr_bytes(v) {
2300 let mut c = vec![T_INTS_LFSR];
2301 write_uvarint(v.len() as u64, &mut c);
2302 write_uvarint(l as u64, &mut c);
2303 let tap_vals: Vec<u64> = taps.iter().map(|&b| b as u64).collect();
2304 c.extend_from_slice(&bitpack(&tap_vals, 1));
2305 let seed_vals: Vec<u64> = seed.iter().map(|&b| b as u64).collect();
2306 c.extend_from_slice(&bitpack(&seed_vals, 1));
2307 consider(&mut best, c);
2308 }
2309 }
2310
2311 // LAST RESORT — the CARRY attack: an FCSR keystream (add-with-carry / mod-2ⁿ LCG) fools every LINEAR
2312 // generator (its linear complexity is high), so it survives even the LFSR pass above. The 2-adic
2313 // Rational Approximation collapses it to a small rational `p/q`. Same gating as the LFSR pass, plus
2314 // its own size bound (the reconstruction is bignum).
2315 if !v.is_empty()
2316 && v.len() <= FCSR_MAX_BYTES
2317 && best.len() >= v.len()
2318 && v.iter().all(|&x| (0..256).contains(&x))
2319 {
2320 if let Some((p, q)) = detect_fcsr_bytes(v) {
2321 let mut c = vec![T_INTS_FCSR];
2322 write_uvarint(v.len() as u64, &mut c);
2323 write_bigint(&p, &mut c);
2324 write_bigint(&q, &mut c);
2325 consider(&mut best, c);
2326 }
2327 }
2328
2329 out.extend_from_slice(&best);
2330}
2331
2332/// The **computable upper bound on Kolmogorov complexity** of `v` over this description language:
2333/// the shortest self-delimiting program (from the generator menu) that reproduces `v`. The returned
2334/// bytes are a re-checkable witness — [`decode_int_seq`] reproduces `v` exactly.
2335pub fn describe_int_seq(v: &[i64]) -> Vec<u8> {
2336 let mut out = Vec::new();
2337 emit_best_int_column(v, &mut out);
2338 out
2339}
2340
2341// ---- The description engine (decode) -------------------------------------------------------
2342
2343/// Reject a decoded element count that exceeds `max_elements`, before any `count`-sized
2344/// materialization (the small-message-huge-output guard for generator columns).
2345#[inline]
2346fn bounded(n: u64, max_elements: usize) -> Option<usize> {
2347 let n = n as usize;
2348 (n <= max_elements).then_some(n)
2349}
2350
2351thread_local! {
2352 /// A shared, per-column-tree WORK budget for the generator columns. `max_elements` bounds the
2353 /// element COUNT, but the generators differ in per-element cost by orders of magnitude — an
2354 /// affine `wrapping_add` is one op, an FCSR bit is a 2-adic **bignum** step, an LFSR bit is an
2355 /// `O(L)` tap fold, a `T_GEN` element re-evaluates the whole expression tree — so a count-bound
2356 /// cannot bound wall-time. Each expensive generator charges its TRUE work (`produced ·
2357 /// per-element-cost`) here; once one column tree's running total exceeds `max_elements`
2358 /// work-units the decode is refused (clean `None`) BEFORE the (multi-minute) expansion runs.
2359 /// This is the small-descriptor / huge-work DoS gate the byte and count budgets cannot express.
2360 static DECODE_WORK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
2361}
2362
2363/// Charge `units` of generation work against [`DECODE_WORK`]; `None` once the budget
2364/// (`max_elements` work-units) is spent. Saturating, so a crafted huge `units` cannot wrap.
2365#[inline]
2366fn charge_work(units: u64, max_elements: usize) -> Option<()> {
2367 DECODE_WORK.with(|c| {
2368 let used = c.get().saturating_add(units);
2369 (used <= max_elements as u64).then(|| c.set(used))
2370 })
2371}
2372
2373/// Decode one int column whose tag byte has already been read as `tag`. The inverse of
2374/// [`emit_best_int_column`]; returns `None` for a non-int tag or a corrupt/hostile body.
2375/// `max_elements` caps generator expansion; `depth` bounds the periodic-block recursion.
2376pub fn decode_int_column_body(
2377 tag: u8,
2378 buf: &[u8],
2379 pos: &mut usize,
2380 max_elements: usize,
2381 depth: u32,
2382) -> Option<Vec<i64>> {
2383 // A fresh column tree starts with a full work budget; nested blocks (periodic) share it.
2384 if depth == 0 {
2385 DECODE_WORK.with(|c| c.set(0));
2386 }
2387 Some(match tag {
2388 // Adaptive sign: the count's low bit says whether the column was zig-zag encoded.
2389 T_INTS => {
2390 let header = read_uvarint(buf, pos)?;
2391 let signed = header & 1 == 1;
2392 let n = bounded(header >> 1, max_elements)?;
2393 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2394 for _ in 0..n {
2395 let u = read_uvarint(buf, pos)?;
2396 v.push(if signed { unzigzag(u) } else { u as i64 });
2397 }
2398 v
2399 }
2400 // Closed form `base + stride·i`, replayed with the SAME wrapping arithmetic the encoder verified.
2401 T_INTS_AFFINE => {
2402 let base = unzigzag(read_uvarint(buf, pos)?);
2403 let stride = unzigzag(read_uvarint(buf, pos)?);
2404 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2405 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2406 for i in 0..n {
2407 v.push(base.wrapping_add((i as i64).wrapping_mul(stride)));
2408 }
2409 v
2410 }
2411 // Geometric generator: replay `wrapping_mul` — exact even across overflow.
2412 T_INTS_GEOMETRIC => {
2413 let base = unzigzag(read_uvarint(buf, pos)?);
2414 let ratio = unzigzag(read_uvarint(buf, pos)?);
2415 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2416 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2417 let mut cur = base;
2418 for _ in 0..n {
2419 v.push(cur);
2420 cur = cur.wrapping_mul(ratio);
2421 }
2422 v
2423 }
2424 // Cyclic generator: decode the period BLOCK (itself a best-encoded column), emit `block[i % p]`.
2425 T_INTS_PERIODIC => {
2426 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2427 if depth >= DECODE_MAX_DEPTH {
2428 return None;
2429 }
2430 let block_tag = *buf.get(*pos)?;
2431 *pos += 1;
2432 let block = decode_int_column_body(block_tag, buf, pos, max_elements, depth + 1)?;
2433 let p = block.len();
2434 if p == 0 {
2435 return None; // an empty block has no period — malformed
2436 }
2437 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2438 for i in 0..n {
2439 v.push(block[i % p]);
2440 }
2441 v
2442 }
2443 // Sparse column: fill with the dominant value, patch the delta-indexed exceptions.
2444 T_INTS_SPARSE => {
2445 let dom = unzigzag(read_uvarint(buf, pos)?);
2446 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2447 let num_exc = bounded(read_uvarint(buf, pos)?, max_elements)?;
2448 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2449 v.resize(n, dom);
2450 let mut idx = 0usize;
2451 for _ in 0..num_exc {
2452 idx = idx.checked_add(read_uvarint(buf, pos)? as usize)?;
2453 let val = unzigzag(read_uvarint(buf, pos)?);
2454 *v.get_mut(idx)? = val; // out-of-range exception index → clean None
2455 }
2456 v
2457 }
2458 // Polynomial generator: read the degree-bounded seeds, replay the difference engine.
2459 T_INTS_POLY => {
2460 let degree = *buf.get(*pos)? as usize;
2461 *pos += 1;
2462 if degree > MAX_POLY_DEGREE {
2463 return None;
2464 }
2465 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2466 let mut seeds = Vec::with_capacity(degree + 1);
2467 for _ in 0..=degree {
2468 seeds.push(unzigzag(read_uvarint(buf, pos)?));
2469 }
2470 reconstruct_poly(&seeds, n)
2471 }
2472 // Linear-recurrence generator: read the order-bounded coefficients + seeds, replay the recurrence.
2473 T_INTS_LRECUR => {
2474 let k = *buf.get(*pos)? as usize;
2475 *pos += 1;
2476 if k == 0 || k > MAX_RECUR_ORDER {
2477 return None; // malformed / untrusted order
2478 }
2479 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2480 let mut coeffs = Vec::with_capacity(k);
2481 for _ in 0..k {
2482 coeffs.push(unzigzag(read_uvarint(buf, pos)?));
2483 }
2484 let mut seeds = Vec::with_capacity(k);
2485 for _ in 0..k {
2486 seeds.push(unzigzag(read_uvarint(buf, pos)?));
2487 }
2488 reconstruct_recurrence(&coeffs, &seeds, n)
2489 }
2490 // LFSR keystream: read the linear complexity L, the L feedback taps and L seed bits, then
2491 // replay the register for 8·n bits and pack back to n bytes.
2492 T_INTS_LFSR => {
2493 let n = bounded(read_uvarint(buf, pos)?, max_elements)?; // byte count
2494 let l = read_uvarint(buf, pos)? as usize;
2495 let total_bits = n.checked_mul(8)?;
2496 if l > total_bits {
2497 return None;
2498 }
2499 // Clocking the register is O(total_bits · L) — charge it so a huge keystream from a
2500 // tiny header is refused before the O(n²)-in-the-worst-case replay ever starts.
2501 charge_work(
2502 (total_bits as u64).saturating_mul(l.max(1) as u64),
2503 max_elements,
2504 )?;
2505 let nbytes = l.div_ceil(8);
2506 let tap_bytes = buf.get(*pos..pos.checked_add(nbytes)?)?;
2507 *pos += nbytes;
2508 let taps: Vec<bool> = bitunpack(tap_bytes, l, 1)?
2509 .into_iter()
2510 .map(|x| x == 1)
2511 .collect();
2512 let seed_bytes = buf.get(*pos..pos.checked_add(nbytes)?)?;
2513 *pos += nbytes;
2514 let seed: Vec<bool> = bitunpack(seed_bytes, l, 1)?
2515 .into_iter()
2516 .map(|x| x == 1)
2517 .collect();
2518 bits_to_bytes(&lfsr_generate(&taps, &seed, total_bits))
2519 }
2520 // FCSR keystream: read the byte count and the rational p/q, then replay the 2-adic expansion.
2521 T_INTS_FCSR => {
2522 let n = bounded(read_uvarint(buf, pos)?, max_elements)?; // byte count
2523 let p = read_bigint(buf, pos)?;
2524 let q = read_bigint(buf, pos)?;
2525 if !q.is_odd() {
2526 return None; // an FCSR connection integer must be odd
2527 }
2528 let total_bits = n.checked_mul(8)?;
2529 // Each 2-adic step is a bignum sub+halve on operands of ~max(|p|,|q|) limbs — charge
2530 // `total_bits · limbs` so a 10^8-bit keystream from a ~10-byte descriptor is refused
2531 // before the multi-minute expansion runs.
2532 let limbs = (bigint_bitlen(&p).max(bigint_bitlen(&q)) / 64 + 1) as u64;
2533 charge_work((total_bits as u64).saturating_mul(limbs), max_elements)?;
2534 bits_to_bytes(&fcsr_generate(&p, &q, total_bits))
2535 }
2536 // General generator: parse the bounded `GenExpr`, evaluate it at 0..n in the sandbox.
2537 T_GEN => {
2538 let mut budget = MAX_GEN_NODES;
2539 let expr = deserialize_gen(buf, pos, &mut budget, 0)?;
2540 let n = bounded(read_uvarint(buf, pos)?, max_elements)?;
2541 // Every element re-evaluates the whole expression tree — charge `n · nodes` so a wide
2542 // column over a big expression is refused before the eval loop.
2543 let nodes = (MAX_GEN_NODES - budget).max(1) as u64;
2544 charge_work((n as u64).saturating_mul(nodes), max_elements)?;
2545 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2546 for i in 0..n {
2547 v.push(gen_eval(&expr, i as i64));
2548 }
2549 v
2550 }
2551 // Byte column: read the count, widen each raw byte to an Int.
2552 T_BYTES => {
2553 let n = read_uvarint(buf, pos)? as usize;
2554 let raw = buf.get(*pos..pos.checked_add(n)?)?;
2555 *pos += n;
2556 raw.iter().map(|&b| b as i64).collect()
2557 }
2558 // Delta column: cumulative-sum the zig-zag differences.
2559 T_INTS_DELTA => {
2560 let n = read_uvarint(buf, pos)? as usize;
2561 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2562 if n > 0 {
2563 let mut cur = unzigzag(read_uvarint(buf, pos)?);
2564 v.push(cur);
2565 for _ in 1..n {
2566 cur = cur.wrapping_add(unzigzag(read_uvarint(buf, pos)?));
2567 v.push(cur);
2568 }
2569 }
2570 v
2571 }
2572 // Delta-of-delta column: double cumulative sum (the inverse of `dod_encode`).
2573 T_INTS_DOD => {
2574 let n = read_uvarint(buf, pos)? as usize;
2575 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2576 if n > 0 {
2577 let first = unzigzag(read_uvarint(buf, pos)?);
2578 v.push(first);
2579 if n > 1 {
2580 let mut prev_delta = unzigzag(read_uvarint(buf, pos)?);
2581 let mut prev = first.wrapping_add(prev_delta);
2582 v.push(prev);
2583 for _ in 2..n {
2584 prev_delta = prev_delta.wrapping_add(unzigzag(read_uvarint(buf, pos)?));
2585 prev = prev.wrapping_add(prev_delta);
2586 v.push(prev);
2587 }
2588 }
2589 }
2590 v
2591 }
2592 // Frame-of-reference column: unpack the bit-packed residuals, add the minimum.
2593 T_INTS_FOR => {
2594 let n = read_uvarint(buf, pos)? as usize;
2595 let min = unzigzag(read_uvarint(buf, pos)?);
2596 let width = *buf.get(*pos)?;
2597 *pos += 1;
2598 if width > 64 {
2599 return None;
2600 }
2601 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2602 if width == 0 {
2603 for _ in 0..n {
2604 v.push(min);
2605 }
2606 } else {
2607 let nbytes = n.checked_mul(width as usize)?.div_ceil(8);
2608 let bytes = buf.get(*pos..pos.checked_add(nbytes)?)?;
2609 *pos += nbytes;
2610 for r in bitunpack(bytes, n, width)? {
2611 v.push(r.wrapping_add(min as u64) as i64);
2612 }
2613 }
2614 v
2615 }
2616 // Run-length column: expand each (value, run-length) pair, capped against a corrupt length.
2617 T_INTS_RLE => {
2618 let runs = read_uvarint(buf, pos)? as usize;
2619 let mut v: Vec<i64> = Vec::new();
2620 for _ in 0..runs {
2621 let val = unzigzag(read_uvarint(buf, pos)?);
2622 let len = read_uvarint(buf, pos)? as usize;
2623 if v.len().checked_add(len)? > RLE_MAX_TOTAL {
2624 return None;
2625 }
2626 v.resize(v.len() + len, val);
2627 }
2628 v
2629 }
2630 // Dictionary column: read the distinct values, map the bit-packed indices back through them.
2631 T_INTS_DICT => {
2632 let d = read_uvarint(buf, pos)? as usize;
2633 let mut dict = Vec::with_capacity(d.min(PREALLOC_CAP));
2634 for _ in 0..d {
2635 dict.push(unzigzag(read_uvarint(buf, pos)?));
2636 }
2637 let n = read_uvarint(buf, pos)? as usize;
2638 let iw = *buf.get(*pos)?;
2639 *pos += 1;
2640 if iw > 64 {
2641 return None;
2642 }
2643 let mut v = Vec::with_capacity(n.min(PREALLOC_CAP));
2644 if iw == 0 {
2645 if n > 0 {
2646 let val = *dict.first()?;
2647 v.resize(n, val);
2648 }
2649 } else {
2650 let nbytes = n.checked_mul(iw as usize)?.div_ceil(8);
2651 let bytes = buf.get(*pos..pos.checked_add(nbytes)?)?;
2652 *pos += nbytes;
2653 for ix in bitunpack(bytes, n, iw)? {
2654 v.push(*dict.get(ix as usize)?);
2655 }
2656 }
2657 v
2658 }
2659 _ => return None,
2660 })
2661}
2662
2663/// Decode a full [`describe_int_seq`] byte string back to the exact sequence. Requires the whole
2664/// buffer to be consumed (a clean round-trip witness). Uses a default element cap.
2665pub fn decode_int_seq(bytes: &[u8]) -> Option<Vec<i64>> {
2666 let mut pos = 0usize;
2667 let tag = *bytes.get(pos)?;
2668 pos += 1;
2669 let v = decode_int_column_body(tag, bytes, &mut pos, DEFAULT_MAX_ELEMENTS, 0)?;
2670 (pos == bytes.len()).then_some(v)
2671}
2672
2673#[cfg(test)]
2674#[path = "../../logicaffeine_tests/unit/logicaffeine_base/describe/tests.rs"]
2675mod tests;