logicaffeine_compile/concurrency/
fec.rs1use logicaffeine_base::gf256::{invert, matmul, mul, pow};
19
20fn 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
33pub 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
60pub 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
103const FEC_MAGIC: u8 = 0xFE;
110const 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
154pub fn shard_header(bytes: &[u8]) -> Option<(u64, usize, usize)> {
158 parse_shard(bytes).map(|(h, _)| (h.msg_id, h.k, h.n))
159}
160
161pub 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
175pub fn reconstruct_redundant(received: &[Vec<u8>]) -> Option<(u64, Vec<u8>)> {
181 use std::collections::HashMap;
182 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 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;