Skip to main content

md_codec/
chunk.rs

1//! Chunk header per SPEC v0.30 §2.2.
2//!
3//! Encodes the 37-bit chunked wire-format header. First-symbol layout
4//! MSB-first: `[v3][v2][v1][v0][chunked]` (4-bit version + 1-bit chunked-flag).
5//! Remainder: 20-bit chunk-set-id + 6-bit count-minus-1 + 6-bit index.
6//! Total = 4 + 1 + 20 + 6 + 6 = 37 bits.
7//!
8//! v0.34.0: also hosts [`decode_with_correction`] — the BCH-error-correcting
9//! decode entry point. Per chunk: parse → polymod-residue → (if non-zero)
10//! call [`crate::bch_decode::decode_regular_errors`] → apply corrections →
11//! re-encode → forward to [`reassemble`]. Atomic per plan §1 D28: any chunk
12//! exceeding the BCH `t = 4` capacity fails the whole call without partial
13//! output.
14
15use crate::bitstream::{BitReader, BitWriter};
16use crate::codex32::REGULAR_CODE_SYMBOLS_MAX;
17use crate::error::Error;
18use crate::header::Header;
19
20/// Wire header for a single chunk in a chunked v0.30 payload.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct ChunkHeader {
23    /// Wire-format version (4 bits). v0.30 = 4.
24    pub version: u8,
25    /// 20-bit chunk-set identifier shared by all chunks in a set.
26    pub chunk_set_id: u32,
27    /// Total number of chunks in the set; valid range `1..=64`.
28    pub count: u8,
29    /// Zero-based index of this chunk within the set; must be `< count`.
30    pub index: u8,
31}
32
33impl ChunkHeader {
34    /// Encode the chunk header into `w` as 37 bits.
35    ///
36    /// Returns an error if `count`, `index`, or `chunk_set_id` are out of range.
37    pub fn write(&self, w: &mut BitWriter) -> Result<(), Error> {
38        if !(1..=64).contains(&(self.count as u32)) {
39            return Err(Error::ChunkCountOutOfRange { count: self.count });
40        }
41        if self.index >= self.count {
42            return Err(Error::ChunkIndexOutOfRange {
43                index: self.index,
44                count: self.count,
45            });
46        }
47        if self.chunk_set_id >= (1 << 20) {
48            return Err(Error::ChunkSetIdOutOfRange {
49                id: self.chunk_set_id,
50            });
51        }
52        w.write_bits(u64::from(self.version & 0b1111), 4);
53        w.write_bits(1, 1); // chunked = 1
54        w.write_bits(u64::from(self.chunk_set_id), 20);
55        w.write_bits((self.count - 1) as u64, 6); // count-1 offset
56        w.write_bits(u64::from(self.index), 6);
57        Ok(())
58    }
59
60    /// Decode a chunk header (37 bits) from `r`.
61    ///
62    /// Returns [`Error::WireVersionMismatch`] if the 4-bit version field
63    /// is not `WF_REDESIGN_VERSION` per SPEC §2.5 (e.g., v0.x chunked
64    /// payloads where version=0 in the first 3 wire bits become version=0
65    /// or version=1 under the v0.30 4-bit read depending on prior bits).
66    /// Returns [`Error::ChunkHeaderChunkedFlagMissing`] if the chunked-flag
67    /// bit is not set after the version check passes.
68    pub fn read(r: &mut BitReader) -> Result<Self, Error> {
69        let version = r.read_bits(4)? as u8;
70        if version != Header::WF_REDESIGN_VERSION {
71            return Err(Error::WireVersionMismatch { got: version });
72        }
73        let chunked = r.read_bits(1)? != 0;
74        if !chunked {
75            return Err(Error::ChunkHeaderChunkedFlagMissing);
76        }
77        let chunk_set_id = r.read_bits(20)? as u32;
78        let count = (r.read_bits(6)? + 1) as u8;
79        let index = r.read_bits(6)? as u8;
80        Ok(Self {
81            version,
82            chunk_set_id,
83            count,
84            index,
85        })
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::header::Header;
93
94    #[test]
95    fn chunk_header_round_trip() {
96        let h = ChunkHeader {
97            version: Header::WF_REDESIGN_VERSION,
98            chunk_set_id: 0xABCDE,
99            count: 3,
100            index: 1,
101        };
102        let mut w = BitWriter::new();
103        h.write(&mut w).unwrap();
104        // 4 + 1 + 20 + 6 + 6 = 37 bits
105        assert_eq!(w.bit_len(), 37);
106        let bytes = w.into_bytes();
107        let mut r = BitReader::new(&bytes);
108        assert_eq!(ChunkHeader::read(&mut r).unwrap(), h);
109    }
110
111    #[test]
112    fn chunk_header_count_64_round_trip() {
113        let h = ChunkHeader {
114            version: Header::WF_REDESIGN_VERSION,
115            chunk_set_id: 0,
116            count: 64,
117            index: 63,
118        };
119        let mut w = BitWriter::new();
120        h.write(&mut w).unwrap();
121        let bytes = w.into_bytes();
122        let mut r = BitReader::new(&bytes);
123        assert_eq!(ChunkHeader::read(&mut r).unwrap(), h);
124    }
125
126    #[test]
127    fn chunk_header_count_zero_rejected() {
128        let h = ChunkHeader {
129            version: Header::WF_REDESIGN_VERSION,
130            chunk_set_id: 0,
131            count: 0,
132            index: 0,
133        };
134        let mut w = BitWriter::new();
135        assert!(matches!(
136            h.write(&mut w),
137            Err(Error::ChunkCountOutOfRange { count: 0 })
138        ));
139    }
140
141    /// SPEC v0.30 §2.5 v0.x rejection for chunk-header path. A wire crafted
142    /// with version=0 and chunked-flag=1 (the v0.30-layout interpretation of
143    /// what a v0.x chunked first-symbol becomes when reordered) must be
144    /// rejected with `WireVersionMismatch { got: 0 }`.
145    #[test]
146    fn chunk_header_rejects_v0x_version() {
147        // Construct first 5 bits MSB-first: [v3=0][v2=0][v1=0][v0=0][chunked=1]
148        //   = 0b00001 (numeric 1)
149        // Pad with 32 zero bits (chunk_set_id + count-1 + index) to reach
150        // the full 37-bit chunk header length. 37 bits packed MSB-first into
151        // 5 bytes (with 3 trailing zero bits beyond the bit limit).
152        // Easier: use BitWriter to build the wire deterministically.
153        let mut w = BitWriter::new();
154        w.write_bits(0, 4); // version = 0 (v0.x)
155        w.write_bits(1, 1); // chunked = 1
156        w.write_bits(0, 20); // chunk_set_id
157        w.write_bits(0, 6); // count-1
158        w.write_bits(0, 6); // index
159        assert_eq!(w.bit_len(), 37);
160        let bytes = w.into_bytes();
161        let mut r = BitReader::new(&bytes);
162        assert!(matches!(
163            ChunkHeader::read(&mut r),
164            Err(Error::WireVersionMismatch { got: 0 })
165        ));
166    }
167}
168
169use crate::identity::Md1EncodingId;
170
171/// Derive the 20-bit chunk-set-id from a [`Md1EncodingId`] by taking the
172/// top 20 bits of the underlying 16-byte hash, MSB-first.
173///
174/// The chunk-set-id groups chunks belonging to the same encoded payload.
175/// Returned value is in the range `0..=0xFFFFF`.
176pub fn derive_chunk_set_id(id: &Md1EncodingId) -> u32 {
177    // First 20 bits of Md1EncodingId[0..16], MSB-first.
178    let bytes = id.as_bytes();
179    ((bytes[0] as u32) << 12) | ((bytes[1] as u32) << 4) | ((bytes[2] as u32) >> 4)
180}
181
182#[cfg(test)]
183mod chunk_set_id_tests {
184    use super::*;
185
186    #[test]
187    fn derive_chunk_set_id_deterministic() {
188        let mut bytes = [0u8; 16];
189        bytes[0] = 0xab;
190        bytes[1] = 0xcd;
191        bytes[2] = 0xe1;
192        bytes[3] = 0x23;
193        let id = Md1EncodingId::new(bytes);
194        let csid_a = derive_chunk_set_id(&id);
195        let csid_b = derive_chunk_set_id(&id);
196        assert_eq!(csid_a, csid_b);
197    }
198
199    #[test]
200    fn derive_chunk_set_id_msb_first_extraction() {
201        // bytes[0]=0xAB, [1]=0xCD, [2]=0xEF: top 20 bits = 0xABCDE
202        let mut bytes = [0u8; 16];
203        bytes[0] = 0xAB;
204        bytes[1] = 0xCD;
205        bytes[2] = 0xEF;
206        let id = Md1EncodingId::new(bytes);
207        assert_eq!(derive_chunk_set_id(&id), 0xABCDE);
208    }
209}
210
211use crate::encode::Descriptor;
212
213/// Threshold (in payload bits) above which chunking is required. Derived from
214/// codex32 *regular*-form's 80-char data-part limit (per BIP 93): 3 HRP + 1
215/// separator + 64 data + 13 checksum (see `codex32::REGULAR_CHECKSUM_SYMBOLS`).
216/// Long-form codex32 was dropped in v0.12.0, so the legal data-symbol budget
217/// per chunk is 64 = 320 bits.
218/// Encoders attempt single-string emit first; if the codex32 wrapping reports
219/// "too long", split into N chunks.
220pub const SINGLE_STRING_PAYLOAD_BIT_LIMIT: usize = 64 * 5;
221
222/// Split a [`Descriptor`] into N codex32 md1 strings, each carrying a chunk
223/// header and a slice of the canonical payload.
224///
225/// Algorithm:
226/// 1. Encode the full payload (`encode_payload`).
227/// 2. Compute [`crate::identity::Md1EncodingId`]; derive `ChunkSetId`.
228/// 3. Choose chunk count N such that each chunk fits in codex32 long form
229///    after adding the 37-bit chunk header.
230/// 4. Split the payload into N approximately-equal byte-boundary slices.
231/// 5. For each chunk i: prepend chunk header (37 bits), wrap via codex32 with
232///    the chunked-flag bit set, emit md1 string.
233///
234/// Note: `bytes_per_chunk` could be 0 if `payload_bytes` were empty, but the
235/// encoder validates `n ≥ 1` so the payload is always non-empty.
236pub fn split(d: &Descriptor) -> Result<Vec<String>, Error> {
237    use crate::bitstream::BitWriter;
238    use crate::encode::encode_payload;
239    use crate::identity::compute_md1_encoding_id;
240
241    let (payload_bytes, _payload_bits) = encode_payload(d)?;
242
243    // Compute ChunkSetId from full-encoding hash.
244    let md1_id = compute_md1_encoding_id(d)?;
245    let chunk_set_id = derive_chunk_set_id(&md1_id);
246
247    // Choose chunk count from payload byte count (≤7 bits of trailing
248    // codex32-padding are tolerated by the reassembled-stream TLV-rollback).
249    let payload_bit_count_for_sizing = payload_bytes.len() * 8;
250    let chunks_needed = payload_bit_count_for_sizing.div_ceil(SINGLE_STRING_PAYLOAD_BIT_LIMIT);
251    if chunks_needed > 64 {
252        return Err(Error::ChunkCountExceedsMax {
253            needed: chunks_needed,
254        });
255    }
256    let count: u8 = if chunks_needed == 0 {
257        1
258    } else {
259        chunks_needed as u8
260    };
261
262    // Split payload into `count` byte-boundary slices.
263    let bytes_per_chunk = payload_bytes.len().div_ceil(count as usize);
264
265    let mut chunks = Vec::with_capacity(count as usize);
266    for index in 0..count {
267        let start_byte = (index as usize) * bytes_per_chunk;
268        let end_byte = ((index as usize + 1) * bytes_per_chunk).min(payload_bytes.len());
269        let chunk_payload_bytes = &payload_bytes[start_byte..end_byte];
270
271        // Build per-chunk wire: 37-bit chunk header + chunk-payload bytes
272        // (full 8 bits per byte, no further fractional content). Chunk's
273        // exact bit count = 37 + 8 × |chunk_payload_bytes|.
274        let header = ChunkHeader {
275            version: Header::WF_REDESIGN_VERSION,
276            chunk_set_id,
277            count,
278            index,
279        };
280        let mut w = BitWriter::new();
281        header.write(&mut w)?;
282        for byte in chunk_payload_bytes {
283            w.write_bits(u64::from(*byte), 8);
284        }
285        let chunk_bit_count = 37 + 8 * chunk_payload_bytes.len();
286        let bytes = w.into_bytes();
287        let s = crate::codex32::wrap_payload(&bytes, chunk_bit_count)?;
288        chunks.push(s);
289    }
290    Ok(chunks)
291}
292
293use crate::decode::decode_payload;
294
295/// Reassemble a [`Descriptor`] from N md1 codex32 strings.
296///
297/// Algorithm:
298/// 1. Unwrap each string via the codex32 layer (verifies BCH per chunk).
299/// 2. Parse the 37-bit chunk header from each.
300/// 3. Validate consistency: same version, chunk_set_id, count.
301/// 4. Sort by index; verify `0..count-1` with no gaps.
302/// 5. Concatenate per-chunk payload bytes.
303/// 6. Decode the reassembled payload via [`decode_payload`].
304/// 7. Verify the reassembled payload's derived chunk-set-id matches the
305///    chunk-set-id present in every chunk header (cross-chunk integrity).
306pub fn reassemble(strings: &[&str]) -> Result<Descriptor, Error> {
307    use crate::bitstream::BitReader;
308    use crate::codex32::unwrap_string;
309    use crate::identity::compute_md1_encoding_id;
310
311    if strings.is_empty() {
312        return Err(Error::ChunkSetEmpty);
313    }
314
315    // Unwrap each, parse 37-bit chunk header, then read whole payload bytes.
316    // Use the symbol-aligned bit count returned by `unwrap_string` (NOT
317    // `bytes.len() * 8`, which would over-estimate by up to 7 bits and break
318    // round-trip for chunks where symbol-padding plus byte-padding crosses a
319    // byte boundary — e.g. N=3, N=8, etc.).
320    let mut parsed: Vec<(ChunkHeader, Vec<u8>)> = Vec::with_capacity(strings.len());
321    for s in strings {
322        let (bytes, symbol_aligned_bit_count) = unwrap_string(s)?;
323        let mut r = BitReader::with_bit_limit(&bytes, symbol_aligned_bit_count);
324        let header = ChunkHeader::read(&mut r)?;
325        // Per encoder contract: chunk wire is exactly 37 + 8N bits. The
326        // symbol-aligned bit count is `ceil((37+8N)/5) * 5`, which is in
327        // [37+8N, 37+8N+4]. So `(symbol_aligned_bit_count - 37) / 8`
328        // (floor) recovers exactly N.
329        let payload_byte_count = (symbol_aligned_bit_count - 37) / 8;
330        let mut chunk_payload_bytes = Vec::with_capacity(payload_byte_count);
331        for _ in 0..payload_byte_count {
332            let v = r.read_bits(8)? as u8;
333            chunk_payload_bytes.push(v);
334        }
335        // Trailing ≤4 symbol-padding bits remain in r; discard.
336        parsed.push((header, chunk_payload_bytes));
337    }
338
339    // Validate consistency.
340    let (h0, _) = &parsed[0];
341    let expected_count = h0.count;
342    let expected_csid = h0.chunk_set_id;
343    let expected_version = h0.version;
344    for (h, _) in &parsed {
345        if h.count != expected_count
346            || h.chunk_set_id != expected_csid
347            || h.version != expected_version
348        {
349            return Err(Error::ChunkSetInconsistent);
350        }
351    }
352    if parsed.len() != expected_count as usize {
353        return Err(Error::ChunkSetIncomplete {
354            got: parsed.len(),
355            expected: expected_count as usize,
356        });
357    }
358
359    // Sort by index; verify 0..count-1 with no gaps.
360    parsed.sort_by_key(|(h, _)| h.index);
361    for (i, (h, _)) in parsed.iter().enumerate() {
362        if h.index as usize != i {
363            return Err(Error::ChunkIndexGap {
364                expected: i as u8,
365                got: h.index,
366            });
367        }
368    }
369
370    // Concatenate chunk payload bytes.
371    let mut full_bytes = Vec::new();
372    for (_, chunk_bytes) in &parsed {
373        full_bytes.extend_from_slice(chunk_bytes);
374    }
375
376    // Decode payload. bit_len = bytes.len() * 8; TLV-rollback handles trailing padding.
377    let descriptor = decode_payload(&full_bytes, full_bytes.len() * 8)?;
378
379    // Cross-chunk integrity check.
380    let md1_id = compute_md1_encoding_id(&descriptor)?;
381    let derived_csid = derive_chunk_set_id(&md1_id);
382    if derived_csid != expected_csid {
383        return Err(Error::ChunkSetIdMismatch {
384            expected: expected_csid,
385            derived: derived_csid,
386        });
387    }
388
389    Ok(descriptor)
390}
391
392// ---------------------------------------------------------------------------
393// v0.34.0: BCH-error-correcting decode (plan §1 D22 + §2.B.1).
394// ---------------------------------------------------------------------------
395
396/// Per-correction report emitted by [`decode_with_correction`]. One entry
397/// per repaired character. `position` is 0-indexed into the codex32
398/// data-part (i.e. the characters following the `md1` HRP + separator);
399/// `was` is the original (corrupted) char from the input; `now` is the
400/// corrected char.
401///
402/// Atomic per plan §1 D28: when [`decode_with_correction`] succeeds the
403/// returned vector aggregates corrections across all chunks; chunks that
404/// were already valid contribute nothing.
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct CorrectionDetail {
407    /// 0-indexed position of the chunk in the caller's `&[&str]` slice.
408    pub chunk_index: usize,
409    /// 0-indexed position of the corrected character within the chunk's
410    /// data-part (post-HRP-and-separator).
411    pub position: usize,
412    /// The original (corrupted) character at this position.
413    pub was: char,
414    /// The corrected character at this position.
415    pub now: char,
416}
417
418/// Local codex32 alphabet (BIP 173 lowercase). Each char = one 5-bit
419/// symbol. Duplicated from `codex32.rs` (which keeps it private) so this
420/// module doesn't widen the codex32 public surface; the mapping is
421/// constant per BIP 173.
422const CODEX32_ALPHABET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
423
424/// BIP 173 separator character between HRP and data-part for md1 strings.
425const HRP_PREFIX: &str = "md1";
426
427/// Parse a single md1 chunk into its 5-bit data-part symbol vector.
428/// Returns the data-with-checksum symbols (i.e. all symbols after `md1`).
429/// Visual separators (whitespace + `-`) are stripped per codex32 convention.
430fn parse_chunk_symbols(chunk: &str, chunk_index: usize) -> Result<Vec<u8>, Error> {
431    // BIP-173: reject mixed-case (per chunk). The correction path rejects too —
432    // case is lowercased before symbol mapping, so a case-flip is a zero-symbol-
433    // error event never in the BCH channel; a wholesale mixed-case string is a
434    // malformed encoding, not noise to correct. (Mirrors mk-codec's correcting
435    // decode, which rejects MixedCase before correction.)
436    if crate::codex32::is_mixed_case(chunk) {
437        return Err(Error::Codex32DecodeError(format!(
438            "chunk {chunk_index}: string mixes upper and lower case (BIP-173 forbids mixed case)"
439        )));
440    }
441    let lower = chunk.to_ascii_lowercase();
442    if !lower.starts_with(HRP_PREFIX) {
443        return Err(Error::Codex32DecodeError(format!(
444            "chunk {chunk_index}: string does not start with HRP md1"
445        )));
446    }
447    let rest = &lower[HRP_PREFIX.len()..];
448    let mut symbols: Vec<u8> = Vec::with_capacity(rest.len());
449    for c in rest.chars() {
450        if c.is_whitespace() || c == '-' {
451            continue;
452        }
453        let lc = c as u8;
454        let sym = CODEX32_ALPHABET
455            .iter()
456            .position(|&b| b == lc)
457            .ok_or_else(|| {
458                Error::Codex32DecodeError(format!(
459                    "chunk {chunk_index}: character {c:?} not in codex32 alphabet"
460                ))
461            })? as u8;
462        symbols.push(sym);
463    }
464    Ok(symbols)
465}
466
467/// Re-encode a 5-bit data-part symbol vector as a complete md1 string.
468fn encode_chunk_string(data_with_checksum: &[u8]) -> String {
469    let mut out = String::with_capacity(HRP_PREFIX.len() + data_with_checksum.len());
470    out.push_str(HRP_PREFIX);
471    for &v in data_with_checksum {
472        out.push(CODEX32_ALPHABET[(v & 0x1F) as usize] as char);
473    }
474    out
475}
476
477/// BCH-error-correcting decode for a chunk-set of md1 strings.
478///
479/// Per plan §1 Q1 lock — full-decode semantics: this is the single entry
480/// point that callers needing both "did anything get repaired?" AND "the
481/// fully-decoded descriptor" should use.
482///
483/// Algorithm:
484/// 1. For each chunk, parse the data-part into 5-bit symbols and compute
485///    the BCH polymod residue (`hrp_expand("md") || data_with_checksum`)
486///    XOR'd against [`crate::bch::MD_REGULAR_CONST`].
487/// 2. Residue `== 0` ⇒ chunk passes through unchanged.
488/// 3. Residue `!= 0` ⇒ invoke
489///    [`crate::bch_decode::decode_regular_errors`]. If `None`, return
490///    `Err(Error::TooManyErrors { chunk_index, bound: 8 })` per plan §2.B.4
491///    D29 error-mapping table.
492/// 4. Apply corrections to the chunk's symbol vector, re-encode as a
493///    fresh md1 string, and record one [`CorrectionDetail`] per repaired
494///    character.
495/// 5. After ALL chunks have been processed (any single uncorrectable
496///    chunk aborts atomically per plan §1 D28), forward the corrected
497///    chunk strings to [`reassemble`] to produce the [`Descriptor`].
498///
499/// On success returns `(Descriptor, Vec<CorrectionDetail>)`. The
500/// correction-detail vector is in (`chunk_index` ascending,
501/// `position` ascending within chunk) order; an empty vector means every
502/// input chunk was already a valid codeword.
503pub fn decode_with_correction(
504    strings: &[&str],
505) -> Result<(Descriptor, Vec<CorrectionDetail>), Error> {
506    if strings.is_empty() {
507        return Err(Error::ChunkSetEmpty);
508    }
509
510    let mut corrected_strings: Vec<String> = Vec::with_capacity(strings.len());
511    // Track the post-correction 5-bit symbol vector of the first string so the
512    // single-string detection pre-pass below can inspect bit 0 of the first
513    // symbol (the chunked-flag per SPEC v0.30 §2.3) without re-parsing the
514    // wrapped string.
515    let mut first_corrected_symbols: Option<Vec<u8>> = None;
516    let mut all_details: Vec<CorrectionDetail> = Vec::new();
517
518    for (chunk_index, chunk) in strings.iter().enumerate() {
519        let symbols = parse_chunk_symbols(chunk, chunk_index)?;
520
521        // cycle-4 M4: reject any chunk longer than the codex32 regular code's
522        // 93-symbol codeword BEFORE the residue/correction logic. β has order
523        // 93, so degrees d and d+93 alias in chien_search for an over-93-symbol
524        // word — the correcting decoder would otherwise mis-correct at an
525        // aliased root. This precedes the residue==0 pass-through, so a clean
526        // over-length md1 is rejected on `repair` too (the correct domain gate;
527        // composes with H6's encode cap). Fail-closed.
528        if symbols.len() > REGULAR_CODE_SYMBOLS_MAX {
529            return Err(Error::ChunkSymbolCountOutOfRange {
530                chunk_index,
531                symbols: symbols.len(),
532                max: REGULAR_CODE_SYMBOLS_MAX,
533            });
534        }
535
536        // Polymod residue against md1's target constant.
537        let mut input = crate::bch::hrp_expand("md");
538        input.extend_from_slice(&symbols);
539        let residue = crate::bch::polymod_run(&input) ^ crate::bch::MD_REGULAR_CONST;
540
541        if residue == 0 {
542            // Already valid — pass through unchanged.
543            corrected_strings.push((*chunk).to_string());
544            if chunk_index == 0 {
545                first_corrected_symbols = Some(symbols);
546            }
547            continue;
548        }
549
550        // Attempt BCH correction.
551        let (positions, magnitudes) =
552            crate::bch_decode::decode_regular_errors(residue, symbols.len()).ok_or(
553                Error::TooManyErrors {
554                    chunk_index,
555                    bound: 8,
556                },
557            )?;
558
559        // Apply corrections; record (was, now) chars per position.
560        let mut corrected = symbols.clone();
561        let mut details: Vec<CorrectionDetail> = Vec::with_capacity(positions.len());
562        for (&pos, &mag) in positions.iter().zip(&magnitudes) {
563            if pos >= corrected.len() {
564                // Defensive: chien_search bounded pos to [0, L); but a
565                // pathological 5+-error pattern could in principle skirt
566                // that. Treat as uncorrectable per Q2 absorption rules.
567                return Err(Error::TooManyErrors {
568                    chunk_index,
569                    bound: 8,
570                });
571            }
572            let was_byte = corrected[pos];
573            let now_byte = was_byte ^ mag;
574            let was = CODEX32_ALPHABET[(was_byte & 0x1F) as usize] as char;
575            let now = CODEX32_ALPHABET[(now_byte & 0x1F) as usize] as char;
576            details.push(CorrectionDetail {
577                chunk_index,
578                position: pos,
579                was,
580                now,
581            });
582            corrected[pos] = now_byte;
583        }
584
585        // Defensive re-verify (catches pathological 5+-error patterns
586        // that happen to produce a degree-≤4 locator with 4 valid roots).
587        let mut verify_input = crate::bch::hrp_expand("md");
588        verify_input.extend_from_slice(&corrected);
589        let verify_residue = crate::bch::polymod_run(&verify_input) ^ crate::bch::MD_REGULAR_CONST;
590        if verify_residue != 0 {
591            return Err(Error::TooManyErrors {
592                chunk_index,
593                bound: 8,
594            });
595        }
596
597        corrected_strings.push(encode_chunk_string(&corrected));
598        if chunk_index == 0 {
599            first_corrected_symbols = Some(corrected);
600        }
601        all_details.extend(details);
602    }
603
604    // v0.35.0: single-string auto-dispatch per SPEC v0.30 §2.3. The first
605    // 5-bit symbol of the corrected payload carries the chunked-flag in
606    // bit 0 (0 = single-payload, 1 = chunked). When the sole input string
607    // decodes (post-BCH correction) as non-chunked, route it through the
608    // single-payload decode path rather than `reassemble`. When it
609    // decodes as chunked, fall through to the existing `reassemble`
610    // path — which naturally surfaces `ChunkSetIncomplete { got: 1,
611    // expected: count }` for any `count > 1` (the "chunked-bit set but
612    // only one chunk supplied" ambiguity edge per plan §2.D.1) while
613    // preserving the legitimate count==1 chunked-of-1 case shipped in
614    // v0.34.0.
615    if strings.len() == 1 {
616        // `first_corrected_symbols` is populated by the loop above (both
617        // the residue==0 pass-through and the correction-applied paths
618        // populate it for `chunk_index == 0`).
619        let symbols = first_corrected_symbols
620            .as_ref()
621            .expect("loop populates first_corrected_symbols when strings.len() >= 1");
622        let chunked_flag = symbols.first().map(|s| s & 0x01).unwrap_or(1);
623        if chunked_flag == 0 {
624            // Non-chunked: decode via the single-payload path. The
625            // corrected string passes BCH-verify (proven by the defensive
626            // re-verify above; or by residue == 0 in the pass-through
627            // branch), so `decode_md1_string` will not re-fail at the
628            // codex32 layer.
629            let descriptor = crate::decode::decode_md1_string(&corrected_strings[0])?;
630            return Ok((descriptor, all_details));
631        }
632        // chunked_flag == 1: fall through to `reassemble` below.
633    }
634
635    // Hand corrected strings to the existing reassembly path.
636    let corrected_refs: Vec<&str> = corrected_strings.iter().map(|s| s.as_str()).collect();
637    let descriptor = reassemble(&corrected_refs)?;
638    Ok((descriptor, all_details))
639}