Skip to main content

logicaffeine_compile/concurrency/
fec.rs

1//! Reed-Solomon erasure coding over GF(2^8) — the wire codec's `redundant` knob.
2//!
3//! Split a payload into `k` data shards plus `n − k` parity shards; a receiver
4//! reconstructs the EXACT payload from ANY `k` of the `n` shards. This is the
5//! reconstructable axis no general wire format ships: drop, duplicate, or reorder up to
6//! `n − k` shards on a lossy link (UDP / multicast / BLE / LoRa) and the message still
7//! arrives, with no retransmit and no coordination.
8//!
9//! The code is **systematic** (the first `k` shards ARE the data chunks, so lossless
10//! delivery costs no decode) and **MDS** (any `k` shards suffice). The encoding matrix
11//! is a Vandermonde matrix made systematic by multiplying through the inverse of its own
12//! top `k×k` block: every `k`-row subset stays invertible, which is exactly the
13//! any-`k`-of-`n` guarantee.
14
15// GF(2^8) field arithmetic (mul/div/pow, matrix invert/matmul; primitive polynomial 0x11d) is the
16// shared substrate in `logicaffeine_base::gf256` — the same field the multivariate crypto and the
17// XL cryptanalysis engine build on. Reed-Solomon uses only its multiplicative structure.
18use logicaffeine_base::gf256::{invert, matmul, mul, pow};
19
20/// The systematic `n×k` encoding matrix: a Vandermonde (`V[i][j] = i^j`, distinct nodes
21/// `0..n` ⇒ any `k` rows invertible) multiplied through the inverse of its top `k×k`
22/// block, so the first `k` rows become the identity (data passes through unchanged) while
23/// the MDS property is preserved.
24fn encode_matrix(n: usize, k: usize) -> Option<Vec<Vec<u8>>> {
25    let vander: Vec<Vec<u8>> = (0..n)
26        .map(|i| (0..k).map(|j| pow(i as u8, j)).collect())
27        .collect();
28    let top = vander[0..k].to_vec();
29    let inv = invert(&top)?;
30    Some(matmul(&vander, &inv))
31}
32
33/// Encode `data` into `n` shards (`k` data + `n − k` parity). Returns the original byte
34/// length (for un-padding on decode) and the shards. `None` for a degenerate `(k, n)`
35/// (`k == 0`, `n < k`, or `n > 256` — GF(2^8) has only 256 distinct nodes).
36pub fn encode(data: &[u8], k: usize, n: usize) -> Option<(usize, Vec<Vec<u8>>)> {
37    if k == 0 || n < k || n > 256 {
38        return None;
39    }
40    let shard_len = data.len().div_ceil(k).max(1);
41    let mut padded = data.to_vec();
42    padded.resize(k * shard_len, 0);
43    let e = encode_matrix(n, k)?;
44    let shards = (0..n)
45        .map(|i| {
46            (0..shard_len)
47                .map(|b| {
48                    let mut acc = 0u8;
49                    for j in 0..k {
50                        acc ^= mul(e[i][j], padded[j * shard_len + b]);
51                    }
52                    acc
53                })
54                .collect()
55        })
56        .collect();
57    Some((data.len(), shards))
58}
59
60/// Reconstruct the payload from ANY `k` (index, shard) pairs out of the `n`. `None` if
61/// fewer than `k` distinct valid shards are present (then the message is unrecoverable).
62pub fn decode(orig_len: usize, k: usize, n: usize, have: &[(usize, Vec<u8>)]) -> Option<Vec<u8>> {
63    if k == 0 || n < k || n > 256 || have.is_empty() {
64        return None;
65    }
66    let shard_len = have[0].1.len();
67    let e = encode_matrix(n, k)?;
68    let mut idxs: Vec<usize> = Vec::with_capacity(k);
69    let mut rows: Vec<Vec<u8>> = Vec::with_capacity(k);
70    let mut vals: Vec<&Vec<u8>> = Vec::with_capacity(k);
71    for (idx, shard) in have {
72        if *idx >= n || shard.len() != shard_len || idxs.contains(idx) {
73            continue;
74        }
75        idxs.push(*idx);
76        rows.push(e[*idx].clone());
77        vals.push(shard);
78        if idxs.len() == k {
79            break;
80        }
81    }
82    if idxs.len() < k {
83        return None;
84    }
85    let minv = invert(&rows)?;
86    let mut data = vec![0u8; k * shard_len];
87    for b in 0..shard_len {
88        for j in 0..k {
89            let mut acc = 0u8;
90            for r in 0..k {
91                acc ^= mul(minv[j][r], vals[r][b]);
92            }
93            data[j * shard_len + b] = acc;
94        }
95    }
96    if orig_len > data.len() {
97        return None;
98    }
99    data.truncate(orig_len);
100    Some(data)
101}
102
103// ---- The `redundant` framing layer: self-describing FEC shards ----------------------
104//
105// Each shard is independently transmittable (its own packet on a lossy link). A fixed
106// header carries everything a receiver needs to group shards of the same message and
107// reconstruct it — no external state, no ordering assumption.
108
109const FEC_MAGIC: u8 = 0xFE;
110// magic(1) + msg_id(8) + k(2) + n(2) + orig_len(4) + index(2)
111const FEC_HEADER_LEN: usize = 1 + 8 + 2 + 2 + 4 + 2;
112
113fn frame_shard(
114    msg_id: u64,
115    k: usize,
116    n: usize,
117    orig_len: usize,
118    index: usize,
119    shard: &[u8],
120) -> Vec<u8> {
121    let mut out = Vec::with_capacity(FEC_HEADER_LEN + shard.len());
122    out.push(FEC_MAGIC);
123    out.extend_from_slice(&msg_id.to_le_bytes());
124    out.extend_from_slice(&(k as u16).to_le_bytes());
125    out.extend_from_slice(&(n as u16).to_le_bytes());
126    out.extend_from_slice(&(orig_len as u32).to_le_bytes());
127    out.extend_from_slice(&(index as u16).to_le_bytes());
128    out.extend_from_slice(shard);
129    out
130}
131
132struct ShardHeader {
133    msg_id: u64,
134    k: usize,
135    n: usize,
136    orig_len: usize,
137    index: usize,
138}
139
140fn parse_shard(bytes: &[u8]) -> Option<(ShardHeader, &[u8])> {
141    if bytes.len() < FEC_HEADER_LEN || bytes[0] != FEC_MAGIC {
142        return None;
143    }
144    let h = ShardHeader {
145        msg_id: u64::from_le_bytes(bytes[1..9].try_into().ok()?),
146        k: u16::from_le_bytes(bytes[9..11].try_into().ok()?) as usize,
147        n: u16::from_le_bytes(bytes[11..13].try_into().ok()?) as usize,
148        orig_len: u32::from_le_bytes(bytes[13..17].try_into().ok()?) as usize,
149        index: u16::from_le_bytes(bytes[17..19].try_into().ok()?) as usize,
150    };
151    Some((h, &bytes[FEC_HEADER_LEN..]))
152}
153
154/// Peek a framed shard's identity without copying its payload: `(msg_id, k, n)`. `None`
155/// if `bytes` is not a FEC shard (wrong magic / too short). Lets a receiver group shards
156/// by message and know how many it needs (`k`) before reconstructing.
157pub fn shard_header(bytes: &[u8]) -> Option<(u64, usize, usize)> {
158    parse_shard(bytes).map(|(h, _)| (h.msg_id, h.k, h.n))
159}
160
161/// Split a message into `n` self-describing FEC shards (`k` data + `n − k` parity),
162/// each independently transmittable. A receiver reconstructs the exact message from
163/// ANY `k` via [`reconstruct_redundant`]. `msg_id` groups a message's shards on the wire.
164pub fn frame_redundant(msg_id: u64, payload: &[u8], k: usize, n: usize) -> Option<Vec<Vec<u8>>> {
165    let (orig_len, shards) = encode(payload, k, n)?;
166    Some(
167        shards
168            .iter()
169            .enumerate()
170            .map(|(i, s)| frame_shard(msg_id, k, n, orig_len, i, s))
171            .collect(),
172    )
173}
174
175/// Reconstruct a message from a bag of received FEC shards. Groups by message id and
176/// reconstructs the first message that has at least `k` distinct shards present; returns
177/// its `(msg_id, payload)`. Shards from other messages, malformed shards, header-
178/// inconsistent shards, and duplicate indices are ignored. `None` if no message has
179/// reached its `k`-shard threshold.
180pub fn reconstruct_redundant(received: &[Vec<u8>]) -> Option<(u64, Vec<u8>)> {
181    use std::collections::HashMap;
182    // msg_id -> (k, n, orig_len, [(index, shard_bytes)])
183    let mut groups: HashMap<u64, (usize, usize, usize, Vec<(usize, Vec<u8>)>)> = HashMap::new();
184    for bytes in received {
185        let Some((h, shard)) = parse_shard(bytes) else {
186            continue;
187        };
188        let entry = groups
189            .entry(h.msg_id)
190            .or_insert((h.k, h.n, h.orig_len, Vec::new()));
191        // Accept only header-consistent shards with a not-yet-seen index.
192        if entry.0 == h.k
193            && entry.1 == h.n
194            && entry.2 == h.orig_len
195            && !entry.3.iter().any(|(i, _)| *i == h.index)
196        {
197            entry.3.push((h.index, shard.to_vec()));
198        }
199    }
200    for (msg_id, (k, n, orig_len, shards)) in groups {
201        if shards.len() >= k {
202            if let Some(data) = decode(orig_len, k, n, &shards) {
203                return Some((msg_id, data));
204            }
205        }
206    }
207    None
208}
209
210#[cfg(test)]
211#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/concurrency/fec/tests.rs"]
212mod tests;