Skip to main content

mk_codec/string_layer/
bch.rs

1//! BCH primitives for the mk1 string layer: bech32 alphabet conversion and
2//! syndrome-based error correction.
3//!
4//! Forked from `md-codec` v0.4.x (`crates/md-codec/src/encoding.rs`) at the
5//! start of the mk1 v0.1 implementation per `design/DECISIONS.md` D-13. The
6//! BCH polynomials and field arithmetic are shared with the sibling md1
7//! format (both reuse BIP 93's `BCH(93,80,8)` regular code and
8//! `BCH(108,93,8)` long code); the only mk1-specific knobs are the HRP
9//! (`"mk"`) and the NUMS-derived target residues ([`crate::consts::MK_REGULAR_CONST`]
10//! / [`crate::consts::MK_LONG_CONST`]).
11//!
12//! Unlike md-codec's encoding module, this file does **not** expose a
13//! top-level `encode_string` / `decode_string`: mk1's string-layer header
14//! lives at the 5-bit symbol layer (per closure Q-5 — 2 symbols for
15//! `SingleString`, 8 symbols for `Chunked`) rather than the byte-aligned
16//! layer md1 uses. The mk1 `string_layer/mod.rs` builds string-level
17//! encode/decode on top of the BCH primitives here.
18
19use super::bch_decode;
20use crate::consts::{HRP, MK_LONG_CONST, MK_REGULAR_CONST};
21
22/// Which BCH code variant a string uses.
23///
24/// Determined by the total data-part length: regular for ≤93 chars,
25/// long for 96–108 chars. Lengths 94–95 are reserved-invalid.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum BchCode {
28    /// Regular code: BCH(93,80,8). 13-char checksum.
29    Regular,
30    /// Long code: BCH(108,93,8). 15-char checksum.
31    Long,
32}
33
34/// The bech32 32-character alphabet, in 5-bit-value order.
35///
36/// `q=0, p=1, z=2, r=3, y=4, 9=5, x=6, 8=7, g=8, f=9, 2=10, t=11, v=12,
37///  d=13, w=14, 0=15, s=16, 3=17, j=18, n=19, 5=20, 4=21, k=22, h=23,
38///  c=24, e=25, 6=26, m=27, u=28, a=29, 7=30, l=31`.
39pub const ALPHABET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
40
41/// Inverse lookup: char (lowercase ASCII) -> 5-bit value, or 0xFF if not in alphabet.
42const ALPHABET_INV: [u8; 128] = build_alphabet_inv();
43
44const fn build_alphabet_inv() -> [u8; 128] {
45    let mut inv = [0xFFu8; 128];
46    let mut i = 0;
47    while i < 32 {
48        inv[ALPHABET[i] as usize] = i as u8;
49        i += 1;
50    }
51    inv
52}
53
54/// Convert a sequence of 8-bit bytes to a sequence of 5-bit values
55/// (padded with zero bits at the end if the bit count is not a multiple of 5).
56pub fn bytes_to_5bit(bytes: &[u8]) -> Vec<u8> {
57    let mut acc: u32 = 0;
58    let mut bits = 0u32;
59    let mut out = Vec::with_capacity((bytes.len() * 8).div_ceil(5));
60    for &b in bytes {
61        acc = (acc << 8) | b as u32;
62        bits += 8;
63        while bits >= 5 {
64            bits -= 5;
65            out.push(((acc >> bits) & 0x1F) as u8);
66        }
67    }
68    if bits > 0 {
69        out.push(((acc << (5 - bits)) & 0x1F) as u8);
70    }
71    out
72}
73
74/// Convert a sequence of 5-bit values back to 8-bit bytes.
75///
76/// Returns `None` if any value in `values` is ≥ 32 (out of 5-bit range),
77/// or if the trailing padding bits are non-zero.
78pub fn five_bit_to_bytes(values: &[u8]) -> Option<Vec<u8>> {
79    let mut acc: u32 = 0;
80    let mut bits = 0u32;
81    let mut out = Vec::with_capacity(values.len() * 5 / 8);
82    for &v in values {
83        if v >= 32 {
84            return None;
85        }
86        acc = (acc << 5) | v as u32;
87        bits += 5;
88        if bits >= 8 {
89            bits -= 8;
90            out.push(((acc >> bits) & 0xFF) as u8);
91        }
92    }
93    // Any remaining bits must be zero (padding).
94    if bits >= 5 {
95        return None;
96    }
97    if (acc & ((1 << bits) - 1)) != 0 {
98        return None;
99    }
100    Some(out)
101}
102
103/// The bech32 separator character between HRP and data-part (BIP 173 §3).
104///
105/// Re-exported by [`crate::consts::HRP`] is `"mk"`; this module's
106/// BCH-checksum helpers consume the HRP through their `hrp` parameter so
107/// that the same primitives can verify any single-HRP codex32-derived
108/// string. Production callers MUST pass [`crate::consts::HRP`].
109pub const SEPARATOR: char = '1';
110
111/// Determine the BchCode variant from a total data-part length.
112///
113/// Boundaries are from BIP 93 (codex32): regular code `BCH(93,80,8)` caps at 93,
114/// long code `BCH(108,93,8)` runs 96–108, and lengths 94–95 are explicitly
115/// reserved-invalid to prevent ambiguity in code-variant selection. Lengths
116/// below 14 or above 108 are also rejected.
117pub fn bch_code_for_length(data_part_len: usize) -> Option<BchCode> {
118    match data_part_len {
119        14..=93 => Some(BchCode::Regular),
120        94..=95 => None,
121        96..=108 => Some(BchCode::Long),
122        _ => None,
123    }
124}
125
126/// Check whether a string is all-lowercase, all-uppercase, or mixed.
127///
128/// Only ASCII letters are considered; non-ASCII characters (digits, punctuation,
129/// Unicode letters) are treated as neither case. This is appropriate for MD
130/// strings, whose alphabet is a subset of ASCII. An empty string or one with
131/// no ASCII letters returns [`CaseStatus::Lower`].
132pub fn case_check(s: &str) -> CaseStatus {
133    let mut has_lower = false;
134    let mut has_upper = false;
135    for c in s.chars() {
136        if c.is_ascii_lowercase() {
137            has_lower = true;
138        } else if c.is_ascii_uppercase() {
139            has_upper = true;
140        }
141        if has_lower && has_upper {
142            break;
143        }
144    }
145    match (has_lower, has_upper) {
146        (true, true) => CaseStatus::Mixed,
147        (true, false) => CaseStatus::Lower,
148        (false, true) => CaseStatus::Upper,
149        (false, false) => CaseStatus::Lower, // empty / no letters; treat as lower
150    }
151}
152
153/// Result of a case check.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum CaseStatus {
156    /// All-lowercase or no letters.
157    Lower,
158    /// All-uppercase.
159    Upper,
160    /// Both lowercase and uppercase letters present (invalid).
161    Mixed,
162}
163
164/// BCH polymod constants for the regular checksum (BCH(93,80,8)).
165///
166/// Source: BIP 93 (codex32) reference implementation, `ms32_polymod` function.
167/// These five values are XORed into the running residue based on the top 5 bits
168/// of the residue at each step. The polymod operation uses a 65-bit residue
169/// (top 5 bits = current `b`, bottom 60 bits = masked state).
170///
171/// Verified against the canonical reference at
172/// <https://github.com/bitcoin/bips/blob/master/bip-0093.mediawiki>.
173pub const GEN_REGULAR: [u128; 5] = [
174    0x19dc500ce73fde210,
175    0x1bfae00def77fe529,
176    0x1fbd920fffe7bee52,
177    0x1739640bdeee3fdad,
178    0x07729a039cfc75f5a,
179];
180
181/// Initial residue value for both the regular and long polymod algorithms (BIP 93).
182///
183/// Both `ms32_polymod` and `ms32_long_polymod` start with this residue before
184/// processing any input characters.
185pub const POLYMOD_INIT: u128 = 0x23181b3;
186
187/// Right-shift amount to extract the top 5 bits from a 65-bit regular-code residue.
188///
189/// Usage: `b = residue >> REGULAR_SHIFT` gives the 5-bit feedback selector
190/// for the polymod algorithm.
191pub const REGULAR_SHIFT: u32 = 60;
192
193/// Mask preserving the low 60 bits of a 65-bit regular-code residue.
194pub const REGULAR_MASK: u128 = 0x0fffffffffffffff;
195
196/// BCH polymod constants for the long checksum (BCH(108,93,8)).
197///
198/// Source: BIP 93 (codex32) reference implementation, `ms32_long_polymod` function.
199/// The long polymod uses a 75-bit residue (top 5 bits = `b`, bottom 70 bits = masked state).
200///
201/// Verified against the canonical reference at
202/// <https://github.com/bitcoin/bips/blob/master/bip-0093.mediawiki>.
203pub const GEN_LONG: [u128; 5] = [
204    0x3d59d273535ea62d897,
205    0x7a9becb6361c6c51507,
206    0x543f9b7e6c38d8a2a0e,
207    0x0c577eaeccf1990d13c,
208    0x1887f74f8dc71b10651,
209];
210
211/// Right-shift amount to extract the top 5 bits from a 75-bit long-code residue.
212///
213/// Usage: `b = residue >> LONG_SHIFT` gives the 5-bit feedback selector
214/// for the polymod algorithm.
215pub const LONG_SHIFT: u32 = 70;
216
217/// Mask preserving the low 70 bits of a 75-bit long-code residue.
218pub const LONG_MASK: u128 = 0x3fffffffffffffffff;
219
220/// One step of the BCH polymod algorithm from BIP 93.
221///
222/// Updates the running `residue` to incorporate the next 5-bit input `value`
223/// using the polynomial defined by `gen`, shift width `shift`, and mask `mask`.
224/// The same function is used for both the regular and long codes; pass
225/// `(GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK)` for the regular code and
226/// `(GEN_LONG, LONG_SHIFT, LONG_MASK)` for the long code.
227///
228/// Returns the updated residue after incorporating `value`. The top 5 bits of
229/// the returned residue feed the next iteration's `b` selector.
230///
231/// This is a direct port of BIP 93's `ms32_polymod` / `ms32_long_polymod` inner
232/// loop. See <https://github.com/bitcoin/bips/blob/master/bip-0093.mediawiki> .
233fn polymod_step(residue: u128, value: u128, r#gen: &[u128; 5], shift: u32, mask: u128) -> u128 {
234    let b = residue >> shift;
235    let mut new_residue = ((residue & mask) << 5) ^ value;
236    for (i, &g) in r#gen.iter().enumerate() {
237        if (b >> i) & 1 != 0 {
238            new_residue ^= g;
239        }
240    }
241    new_residue
242}
243
244/// BIP 173-style HRP-expansion: produces the 5-bit-symbol prelude that gets
245/// prepended to the data part before running the BCH polymod.
246///
247/// For each HRP character `c`, emits `c >> 5` (high 3 bits); then emits a
248/// single 0 separator; then emits each character's `c & 31` (low 5 bits).
249/// The result has length `2 * hrp.len() + 1` for ASCII HRPs.
250///
251/// For `hrp_expand("md")` this returns `[3, 3, 0, 13, 4]`.
252pub fn hrp_expand(hrp: &str) -> Vec<u8> {
253    let bytes = hrp.as_bytes();
254    let mut out = Vec::with_capacity(bytes.len() * 2 + 1);
255    for &c in bytes {
256        out.push(c >> 5);
257    }
258    out.push(0);
259    for &c in bytes {
260        out.push(c & 31);
261    }
262    out
263}
264
265/// Run polymod over a sequence of 5-bit values using the parameters for
266/// either the regular or long BCH code, starting from POLYMOD_INIT.
267///
268/// v0.3.1: promoted from `pub(in crate::string_layer)` to `pub` so
269/// downstream consumers (toolkit `repair` feature) can compute polymod
270/// residues against ms / md / mk target constants (all 3 share the
271/// BIP-93 BCH(93,80,8) generator). Test-helper-drift concern remains
272/// resolved by the sibling `bch_decode` module using THIS function
273/// directly rather than re-implementing.
274pub fn polymod_run(values: &[u8], r#gen: &[u128; 5], shift: u32, mask: u128) -> u128 {
275    let mut residue = POLYMOD_INIT;
276    for &v in values {
277        residue = polymod_step(residue, v as u128, r#gen, shift, mask);
278    }
279    residue
280}
281
282/// Compute the 13-character BCH checksum for the regular code over the
283/// HRP-expanded preamble plus the data part.
284///
285/// `data` is the sequence of 5-bit values for the data part (header + payload),
286/// not including the checksum. Returns the 13-element checksum array, ready
287/// to append to `data` to form the full data-part-plus-checksum.
288///
289/// The algorithm runs polymod over `hrp_expand(hrp) || data || [0; 13]`,
290/// then XORs the result with [`MK_REGULAR_CONST`] to extract the checksum.
291pub fn bch_create_checksum_regular(hrp: &str, data: &[u8]) -> [u8; 13] {
292    // Regular code: 13-symbol checksum (0..=12), pad/array/extraction all use 13.
293    let mut input = hrp_expand(hrp);
294    input.extend_from_slice(data);
295    input.extend(std::iter::repeat_n(0, 13));
296    let polymod = polymod_run(&input, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK) ^ MK_REGULAR_CONST;
297    let mut out = [0u8; 13];
298    for (i, slot) in out.iter_mut().enumerate() {
299        *slot = ((polymod >> (5 * (12 - i))) & 0x1F) as u8;
300    }
301    out
302}
303
304/// Verify a regular-code BCH checksum.
305///
306/// `data_with_checksum` is the full data part including the trailing 13
307/// checksum characters. Returns `true` iff the polymod over
308/// `hrp_expand(hrp) || data_with_checksum` equals [`MK_REGULAR_CONST`].
309pub fn bch_verify_regular(hrp: &str, data_with_checksum: &[u8]) -> bool {
310    if data_with_checksum.len() < 13 {
311        return false;
312    }
313    let mut input = hrp_expand(hrp);
314    input.extend_from_slice(data_with_checksum);
315    polymod_run(&input, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK) == MK_REGULAR_CONST
316}
317
318/// Compute the 15-character BCH checksum for the long code.
319///
320/// Same algorithm as [`bch_create_checksum_regular`] but uses the long-code
321/// polymod parameters (`GEN_LONG`, `LONG_SHIFT`, `LONG_MASK`) and target
322/// constant ([`MK_LONG_CONST`]). Produces a 15-element checksum array.
323pub fn bch_create_checksum_long(hrp: &str, data: &[u8]) -> [u8; 15] {
324    // Long code: 15-symbol checksum (0..=14), pad/array/extraction all use 15.
325    let mut input = hrp_expand(hrp);
326    input.extend_from_slice(data);
327    input.extend(std::iter::repeat_n(0, 15));
328    let polymod = polymod_run(&input, &GEN_LONG, LONG_SHIFT, LONG_MASK) ^ MK_LONG_CONST;
329    let mut out = [0u8; 15];
330    for (i, slot) in out.iter_mut().enumerate() {
331        *slot = ((polymod >> (5 * (14 - i))) & 0x1F) as u8;
332    }
333    out
334}
335
336/// Verify a long-code BCH checksum.
337///
338/// Same algorithm as [`bch_verify_regular`] with long-code parameters.
339/// Returns false if `data_with_checksum` is shorter than 15 symbols.
340pub fn bch_verify_long(hrp: &str, data_with_checksum: &[u8]) -> bool {
341    if data_with_checksum.len() < 15 {
342        return false;
343    }
344    let mut input = hrp_expand(hrp);
345    input.extend_from_slice(data_with_checksum);
346    polymod_run(&input, &GEN_LONG, LONG_SHIFT, LONG_MASK) == MK_LONG_CONST
347}
348
349/// Result of a successful BCH decode + correct attempt.
350///
351/// Returned by [`bch_correct_regular`] / [`bch_correct_long`] when correction
352/// succeeds. `corrections_applied == 0` means the input was already valid;
353/// `> 0` means substitutions were applied at the indicated positions.
354///
355/// Marked `#[non_exhaustive]` to allow future fields (e.g., confidence
356/// score, syndrome metadata) without breaking downstream struct-literal
357/// construction. Construct via the [`bch_correct_regular`] /
358/// [`bch_correct_long`] APIs.
359#[non_exhaustive]
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub struct CorrectionResult {
362    /// The corrected `data_with_checksum` slice (input may have been modified).
363    pub data: Vec<u8>,
364    /// Number of substitutions applied (0 = clean input).
365    pub corrections_applied: usize,
366    /// Indices into `data` of the substituted positions.
367    pub corrected_positions: Vec<usize>,
368}
369
370/// Attempt to correct a regular-code BCH-checksummed string with up to four
371/// substitutions, the full t = 4 capacity of the BCH(93, 80, 8) code.
372///
373/// Implements the standard syndrome-based BCH decoder pipeline: syndrome
374/// computation in `GF(1024) = GF(32²)`, Berlekamp–Massey for the
375/// error-locator polynomial, Chien search for error positions, Forney's
376/// algorithm for error magnitudes. After applying the proposed corrections,
377/// the result is re-verified via [`bch_verify_regular`]; the decoder rejects
378/// any output that does not produce a valid codeword (defensive guard
379/// against pathological 5+-error inputs whose syndromes happen to factor as
380/// a degree-≤ 4 locator).
381///
382/// Returns `Ok(CorrectionResult)` if the input is clean or up to four
383/// substitutions repair it. Returns `Err(Error::BchUncorrectable)` otherwise.
384///
385/// # Algorithm details
386///
387/// See the private `bch_decode` submodule for the algorithm and the
388/// `GF(1024)` field representation.
389pub fn bch_correct_regular(
390    hrp: &str,
391    data_with_checksum: &[u8],
392) -> Result<CorrectionResult, crate::Error> {
393    if bch_verify_regular(hrp, data_with_checksum) {
394        return Ok(CorrectionResult {
395            data: data_with_checksum.to_vec(),
396            corrections_applied: 0,
397            corrected_positions: vec![],
398        });
399    }
400    // Compute polymod over hrp_expand(hrp) || data_with_checksum, XOR with
401    // the MD target constant. The result is congruent to the error
402    // polynomial E(x) modulo g_regular(x).
403    let mut input = hrp_expand(hrp);
404    input.extend_from_slice(data_with_checksum);
405    let residue = polymod_run(&input, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK) ^ MK_REGULAR_CONST;
406
407    if let Some((positions, magnitudes)) =
408        bch_decode::decode_regular_errors(residue, data_with_checksum.len())
409    {
410        if positions.is_empty() {
411            // Should be unreachable (caller already verified); guard anyway.
412            return Ok(CorrectionResult {
413                data: data_with_checksum.to_vec(),
414                corrections_applied: 0,
415                corrected_positions: vec![],
416            });
417        }
418        let mut corrected = data_with_checksum.to_vec();
419        for (&p, &m) in positions.iter().zip(&magnitudes) {
420            if p >= corrected.len() {
421                return Err(crate::Error::BchUncorrectable(format!(
422                    "decoder reported error position {p} outside data ({} symbols)",
423                    corrected.len()
424                )));
425            }
426            corrected[p] ^= m;
427        }
428        // Defensive: re-verify. Catches the 5+-error edge case.
429        if bch_verify_regular(hrp, &corrected) {
430            return Ok(CorrectionResult {
431                corrections_applied: positions.len(),
432                corrected_positions: positions,
433                data: corrected,
434            });
435        }
436    }
437    Err(crate::Error::BchUncorrectable(
438        "regular code: more than 4 substitutions or pathological pattern".into(),
439    ))
440}
441
442/// Long-code analog of [`bch_correct_regular`].
443///
444/// Implements the same BM/Chien/Forney pipeline against the long-code
445/// generator polynomial, reaching the full t = 4 capacity of
446/// `BCH(108, 93, 8)`.
447pub fn bch_correct_long(
448    hrp: &str,
449    data_with_checksum: &[u8],
450) -> Result<CorrectionResult, crate::Error> {
451    if bch_verify_long(hrp, data_with_checksum) {
452        return Ok(CorrectionResult {
453            data: data_with_checksum.to_vec(),
454            corrections_applied: 0,
455            corrected_positions: vec![],
456        });
457    }
458    let mut input = hrp_expand(hrp);
459    input.extend_from_slice(data_with_checksum);
460    let residue = polymod_run(&input, &GEN_LONG, LONG_SHIFT, LONG_MASK) ^ MK_LONG_CONST;
461
462    if let Some((positions, magnitudes)) =
463        bch_decode::decode_long_errors(residue, data_with_checksum.len())
464    {
465        if positions.is_empty() {
466            return Ok(CorrectionResult {
467                data: data_with_checksum.to_vec(),
468                corrections_applied: 0,
469                corrected_positions: vec![],
470            });
471        }
472        let mut corrected = data_with_checksum.to_vec();
473        for (&p, &m) in positions.iter().zip(&magnitudes) {
474            if p >= corrected.len() {
475                return Err(crate::Error::BchUncorrectable(format!(
476                    "decoder reported error position {p} outside data ({} symbols)",
477                    corrected.len()
478                )));
479            }
480            corrected[p] ^= m;
481        }
482        if bch_verify_long(hrp, &corrected) {
483            return Ok(CorrectionResult {
484                corrections_applied: positions.len(),
485                corrected_positions: positions,
486                data: corrected,
487            });
488        }
489    }
490    Err(crate::Error::BchUncorrectable(
491        "long code: more than 4 substitutions or pathological pattern".into(),
492    ))
493}
494
495/// Encode a 5-bit-symbol data stream as a complete mk1 string.
496///
497/// The data stream is the concatenation `header_symbols || bytes_to_5bit(payload_bytes)`
498/// where `header_symbols` is the 2-symbol single-string header or the
499/// 8-symbol chunked header (closure Q-5). The BCH code variant (regular or
500/// long) is auto-selected from the resulting data-part length per BIP 93:
501/// regular for ≤93-symbol data parts, long for 96–108-symbol data parts.
502/// Lengths in the reserved-invalid 94–95 gap or outside the BIP 93 valid
503/// range return [`Error::InvalidStringLength`].
504///
505/// Per the v0.1 emit policy described in `design/IMPLEMENTATION_PLAN_mk_v0_1.md`
506/// §5.4, callers control fragment sizing so that each chunked fragment lands
507/// within long-code territory. Single-string mk1 may pick regular or long
508/// based on bytecode size.
509///
510/// Returns the full string starting with [`crate::consts::HRP`] and the
511/// BIP 173 separator (`"mk1"`).
512pub fn encode_5bit_to_string(data_5bit: &[u8]) -> Result<String, crate::Error> {
513    use crate::Error;
514
515    // Auto-determine code from the eventual data-part length (data_5bit + checksum).
516    let regular_total = data_5bit.len() + 13;
517    let long_total = data_5bit.len() + 15;
518    let code = match (
519        bch_code_for_length(regular_total),
520        bch_code_for_length(long_total),
521    ) {
522        (Some(BchCode::Regular), _) => BchCode::Regular,
523        (_, Some(BchCode::Long)) => BchCode::Long,
524        // Neither code variant accepts this data-part length: too short, in
525        // the 94–95 reserved-invalid gap, or too long for v0.1.
526        _ => {
527            // Pick the closest length to report — long_total is always larger,
528            // so report that as the "actual length you tried to produce".
529            return Err(Error::InvalidStringLength(long_total));
530        }
531    };
532
533    let checksum: Vec<u8> = match code {
534        BchCode::Regular => bch_create_checksum_regular(HRP, data_5bit).to_vec(),
535        BchCode::Long => bch_create_checksum_long(HRP, data_5bit).to_vec(),
536    };
537
538    let mut full = String::with_capacity(HRP.len() + 1 + data_5bit.len() + checksum.len());
539    full.push_str(HRP);
540    full.push(SEPARATOR);
541    for &v in data_5bit {
542        full.push(ALPHABET[v as usize] as char);
543    }
544    for v in checksum {
545        full.push(ALPHABET[v as usize] as char);
546    }
547    Ok(full)
548}
549
550/// Result of a successful mk1 string decode at the BCH layer.
551///
552/// Use [`Self::data`] to access the data part as 5-bit values (header
553/// symbols + payload, checksum stripped); the string-layer reassembler
554/// in `crate::string_layer` splits header symbols off and feeds the
555/// remaining payload through [`five_bit_to_bytes`] to recover the original
556/// fragment bytes.
557///
558/// The full post-correction 5-bit symbol sequence (data **plus** the trailing
559/// 13- or 15-char checksum) is retained internally as [`Self::data_with_checksum`]
560/// and can be queried by [`Self::corrected_char_at`] for any position in
561/// the data part — including positions that fall inside the checksum region.
562/// The decoder-report layer uses this to surface the real corrected
563/// character when BCH ECC repairs a substitution inside the checksum
564/// (parallels md-codec's `Correction.corrected` field).
565#[non_exhaustive]
566#[derive(Debug, Clone, PartialEq, Eq)]
567pub struct DecodedString {
568    /// Detected BCH code variant.
569    pub code: BchCode,
570    /// Number of substitution errors corrected (0 = clean input, 1 = recovered).
571    pub corrections_applied: usize,
572    /// Indices into the data-part (chars after `"md1"`) of any corrected positions.
573    pub corrected_positions: Vec<usize>,
574    /// Full post-correction 5-bit symbol sequence (data part + checksum), in
575    /// the same coordinate system as [`Self::corrected_positions`].
576    ///
577    /// Length is `data().len() + 13` (regular code) or `data().len() + 15`
578    /// (long code). Indices `0..data().len()` mirror [`Self::data`] symbol-for-symbol;
579    /// indices `data().len()..` are the corrected checksum symbols. Use
580    /// [`Self::corrected_char_at`] for the human-readable bech32 character at
581    /// any position.
582    pub data_with_checksum: Vec<u8>,
583}
584
585impl DecodedString {
586    /// Data part as 5-bit values, with the trailing checksum stripped.
587    ///
588    /// Returns a slice into [`Self::data_with_checksum`] — the data part is
589    /// `data_with_checksum[..len - checksum_len]`, where `checksum_len` is 13
590    /// for [`BchCode::Regular`] and 15 for [`BchCode::Long`].
591    pub fn data(&self) -> &[u8] {
592        let checksum_len = match self.code {
593            BchCode::Regular => 13,
594            BchCode::Long => 15,
595        };
596        &self.data_with_checksum[..self.data_with_checksum.len() - checksum_len]
597    }
598
599    /// Look up the corrected bech32 character at the given position in the
600    /// data part (chars after the `"md1"` HRP+separator).
601    ///
602    /// `char_position` is 0-indexed. Positions `0..data().len()` are in the
603    /// data region; positions `data().len()..data().len() + checksum_len` are
604    /// inside the BCH checksum (13 chars for [`BchCode::Regular`], 15 for
605    /// [`BchCode::Long`]). All positions return the post-correction
606    /// character — i.e., what the symbol *should* be after BCH repair, which
607    /// is exactly what [`Correction.corrected`][crate::Correction::corrected]
608    /// is documented to report.
609    ///
610    /// # Panics
611    ///
612    /// Panics if `char_position >= data_with_checksum.len()`. Callers are
613    /// responsible for clamping the position to a valid range; in the decode
614    /// pipeline this is guaranteed by the BCH layer (it never reports a
615    /// `corrected_position` outside `data_with_checksum`). Note that
616    /// `data_with_checksum` includes the checksum region; "outside the data
617    /// part" elsewhere in this crate excludes the checksum and is a tighter
618    /// bound than what this method requires.
619    pub fn corrected_char_at(&self, char_position: usize) -> char {
620        let v = self.data_with_checksum[char_position];
621        ALPHABET[v as usize] as char
622    }
623}
624
625/// Decode an mk1 string, validating HRP, case, length, and checksum.
626///
627/// Performs full BCH error correction up to four substitutions
628/// (`t = 4` capacity of the BCH(93, 80, 8) regular code and the
629/// BCH(108, 93, 8) long code), via syndrome-based Berlekamp–Massey +
630/// Forney decoding (implemented in the sibling `bch_decode` module).
631///
632/// Errors:
633/// - [`Error::MixedCase`] if the string mixes upper and lower case.
634/// - [`Error::InvalidHrp`] if the HRP is missing or not [`crate::consts::HRP`].
635/// - [`Error::InvalidStringLength`] if the data-part length isn't a valid mk1 length.
636/// - [`Error::InvalidChar`] if the data part contains a non-bech32 character.
637/// - [`Error::BchUncorrectable`] if the checksum can't be repaired within
638///   the BCH `t = 4` correction radius.
639///
640/// [`Error::MixedCase`]: crate::Error::MixedCase
641/// [`Error::InvalidHrp`]: crate::Error::InvalidHrp
642/// [`Error::InvalidStringLength`]: crate::Error::InvalidStringLength
643/// [`Error::InvalidChar`]: crate::Error::InvalidChar
644/// [`Error::BchUncorrectable`]: crate::Error::BchUncorrectable
645pub fn decode_string(s: &str) -> Result<DecodedString, crate::Error> {
646    use crate::Error;
647
648    if matches!(case_check(s), CaseStatus::Mixed) {
649        return Err(Error::MixedCase);
650    }
651    let s_lower = s.to_lowercase();
652
653    let sep_pos = s_lower
654        .rfind(SEPARATOR)
655        .ok_or_else(|| Error::InvalidHrp(s_lower.clone()))?;
656    let (hrp, rest) = s_lower.split_at(sep_pos);
657    let data_part = &rest[1..]; // skip the '1' separator
658
659    if hrp != HRP {
660        return Err(Error::InvalidHrp(hrp.to_string()));
661    }
662
663    let code =
664        bch_code_for_length(data_part.len()).ok_or(Error::InvalidStringLength(data_part.len()))?;
665
666    let mut values: Vec<u8> = Vec::with_capacity(data_part.len());
667    for (i, c) in data_part.chars().enumerate() {
668        if !c.is_ascii() {
669            return Err(Error::InvalidChar { ch: c, position: i });
670        }
671        let v = ALPHABET_INV[c as usize];
672        if v == 0xFF {
673            return Err(Error::InvalidChar { ch: c, position: i });
674        }
675        values.push(v);
676    }
677
678    let correction = match code {
679        BchCode::Regular => bch_correct_regular(hrp, &values),
680        BchCode::Long => bch_correct_long(hrp, &values),
681    };
682    let result = correction?;
683
684    Ok(DecodedString {
685        code,
686        corrections_applied: result.corrections_applied,
687        corrected_positions: result.corrected_positions,
688        data_with_checksum: result.data,
689    })
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695
696    #[test]
697    fn bch_code_equality() {
698        assert_eq!(BchCode::Regular, BchCode::Regular);
699        assert_ne!(BchCode::Regular, BchCode::Long);
700    }
701
702    #[test]
703    fn bch_code_can_be_hashed() {
704        use std::collections::HashSet;
705        let mut set = HashSet::new();
706        set.insert(BchCode::Regular);
707        set.insert(BchCode::Long);
708        set.insert(BchCode::Regular);
709        assert_eq!(set.len(), 2);
710    }
711
712    #[test]
713    fn alphabet_is_32_unique_chars() {
714        let mut seen = std::collections::HashSet::new();
715        for &c in ALPHABET {
716            assert!(seen.insert(c), "duplicate char in alphabet: {}", c as char);
717        }
718        assert_eq!(seen.len(), 32);
719    }
720
721    #[test]
722    fn bytes_to_5bit_round_trip_zero() {
723        let bytes = vec![0x00];
724        let fives = bytes_to_5bit(&bytes);
725        assert_eq!(fives, vec![0, 0]);
726        let back = five_bit_to_bytes(&fives).unwrap();
727        assert_eq!(back, bytes);
728    }
729
730    #[test]
731    fn bytes_to_5bit_round_trip_known_value() {
732        // 0xFF = binary 11111111. Splits as 11111 (=31) and 111 (padded with 00 to 11100=28).
733        let bytes = vec![0xFF];
734        let fives = bytes_to_5bit(&bytes);
735        assert_eq!(fives, vec![31, 28]);
736    }
737
738    #[test]
739    fn bytes_to_5bit_round_trip_multibyte() {
740        // 3 bytes = 24 bits → 5 five-bit groups (25 bits, 1 pad bit).
741        let bytes = vec![0xDE, 0xAD, 0xBE];
742        let back = five_bit_to_bytes(&bytes_to_5bit(&bytes)).unwrap();
743        assert_eq!(back, bytes);
744    }
745
746    #[test]
747    fn five_bit_to_bytes_rejects_nonzero_padding() {
748        // Two 5-bit values = 10 bits, of which 8 form a byte and 2 are padding.
749        // If padding bits are nonzero, decode must fail.
750        // 31 = 11111, 1 = 00001. Last 2 bits (= 01) are nonzero padding.
751        assert!(five_bit_to_bytes(&[31, 1]).is_none());
752    }
753
754    #[test]
755    fn five_bit_to_bytes_rejects_value_out_of_range() {
756        assert!(five_bit_to_bytes(&[32]).is_none());
757    }
758
759    #[test]
760    fn bch_code_for_length_regular() {
761        assert_eq!(bch_code_for_length(14), Some(BchCode::Regular));
762        assert_eq!(bch_code_for_length(93), Some(BchCode::Regular));
763    }
764
765    #[test]
766    fn bch_code_for_length_long() {
767        assert_eq!(bch_code_for_length(96), Some(BchCode::Long));
768        assert_eq!(bch_code_for_length(108), Some(BchCode::Long));
769    }
770
771    #[test]
772    fn bch_code_for_length_rejects_94_and_95() {
773        assert_eq!(bch_code_for_length(94), None);
774        assert_eq!(bch_code_for_length(95), None);
775    }
776
777    #[test]
778    fn bch_code_for_length_rejects_extremes() {
779        assert_eq!(bch_code_for_length(0), None);
780        assert_eq!(bch_code_for_length(13), None);
781        assert_eq!(bch_code_for_length(109), None);
782        assert_eq!(bch_code_for_length(1000), None);
783    }
784
785    #[test]
786    fn case_check_lowercase() {
787        assert_eq!(case_check("md1qq"), CaseStatus::Lower);
788    }
789
790    #[test]
791    fn case_check_uppercase() {
792        assert_eq!(case_check("MD1QQ"), CaseStatus::Upper);
793    }
794
795    #[test]
796    fn case_check_mixed() {
797        assert_eq!(case_check("mD1qq"), CaseStatus::Mixed);
798    }
799
800    #[test]
801    fn case_check_empty_string_is_lower() {
802        assert_eq!(case_check(""), CaseStatus::Lower);
803    }
804
805    #[test]
806    fn case_check_digits_only_is_lower() {
807        // Digits have no case; result must be Lower (BIP 173: no-letter strings are lower).
808        assert_eq!(case_check("1234"), CaseStatus::Lower);
809    }
810
811    #[test]
812    fn gen_regular_has_5_entries() {
813        assert_eq!(GEN_REGULAR.len(), 5);
814    }
815
816    #[test]
817    fn gen_long_has_5_entries() {
818        assert_eq!(GEN_LONG.len(), 5);
819    }
820
821    #[test]
822    fn gen_regular_matches_bip93_canonical_values() {
823        // Cross-checked against https://github.com/bitcoin/bips/blob/master/bip-0093.mediawiki
824        // ms32_polymod GEN array. If this fails, the constants drifted from the BIP.
825        assert_eq!(GEN_REGULAR[0], 0x19dc500ce73fde210);
826        assert_eq!(GEN_REGULAR[1], 0x1bfae00def77fe529);
827        assert_eq!(GEN_REGULAR[2], 0x1fbd920fffe7bee52);
828        assert_eq!(GEN_REGULAR[3], 0x1739640bdeee3fdad);
829        assert_eq!(GEN_REGULAR[4], 0x07729a039cfc75f5a);
830    }
831
832    #[test]
833    fn gen_long_matches_bip93_canonical_values() {
834        // Cross-checked against https://github.com/bitcoin/bips/blob/master/bip-0093.mediawiki
835        // ms32_long_polymod GEN array.
836        assert_eq!(GEN_LONG[0], 0x3d59d273535ea62d897);
837        assert_eq!(GEN_LONG[1], 0x7a9becb6361c6c51507);
838        assert_eq!(GEN_LONG[2], 0x543f9b7e6c38d8a2a0e);
839        assert_eq!(GEN_LONG[3], 0x0c577eaeccf1990d13c);
840        assert_eq!(GEN_LONG[4], 0x1887f74f8dc71b10651);
841    }
842
843    #[test]
844    fn polymod_init_matches_bip93() {
845        // POLYMOD_INIT is unchanged from BIP 93; the GEN_REGULAR / GEN_LONG
846        // constants have their own value-equality tests.
847        assert_eq!(POLYMOD_INIT, 0x23181b3);
848    }
849
850    // (NUMS-derivation reproducer for `MK_REGULAR_CONST` / `MK_LONG_CONST`
851    // lives in `crate::consts::tests::nums_constants_reproduce_from_domain`,
852    // which uses the mk1-specific domain `b"shibbolethnumskey"`. Duplicating
853    // it here would risk drift if either side were updated in isolation.)
854
855    #[test]
856    fn polymod_masks_are_consistent_with_shifts() {
857        // The mask must be (1 << shift) - 1 so that masking preserves bits below
858        // the shift boundary, exactly matching the BIP 93 algorithm.
859        assert_eq!(REGULAR_MASK, (1u128 << REGULAR_SHIFT) - 1);
860        assert_eq!(LONG_MASK, (1u128 << LONG_SHIFT) - 1);
861        assert_eq!(REGULAR_SHIFT, 60);
862        assert_eq!(LONG_SHIFT, 70);
863    }
864
865    #[test]
866    fn polymod_step_zero_residue_zero_value() {
867        // Both residue and value zero, no GEN XORs since b = 0.
868        assert_eq!(
869            polymod_step(0, 0, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
870            0
871        );
872    }
873
874    #[test]
875    fn polymod_step_value_only_xor_when_residue_zero() {
876        // Residue 0, value 7 → result is 7 (XORed into the shifted-zero residue).
877        assert_eq!(
878            polymod_step(0, 7, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
879            7
880        );
881    }
882
883    #[test]
884    fn polymod_step_isolates_each_gen_entry() {
885        // Setting just bit `shift+i` in the residue → b = 1<<i → only GEN[i] is XORed.
886        for i in 0..5 {
887            let r = 1u128 << (REGULAR_SHIFT + i);
888            assert_eq!(
889                polymod_step(r, 0, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
890                GEN_REGULAR[i as usize],
891                "bit {} of b should isolate GEN_REGULAR[{}]",
892                i,
893                i
894            );
895        }
896    }
897
898    #[test]
899    fn polymod_step_xors_multiple_gens_when_multiple_b_bits_set() {
900        // b = 0b00011 → XOR GEN[0] and GEN[1].
901        let r = 0b00011u128 << REGULAR_SHIFT;
902        assert_eq!(
903            polymod_step(r, 0, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
904            GEN_REGULAR[0] ^ GEN_REGULAR[1]
905        );
906        // b = 0b11111 → XOR all 5.
907        let r = 0b11111u128 << REGULAR_SHIFT;
908        let expected =
909            GEN_REGULAR[0] ^ GEN_REGULAR[1] ^ GEN_REGULAR[2] ^ GEN_REGULAR[3] ^ GEN_REGULAR[4];
910        assert_eq!(
911            polymod_step(r, 0, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
912            expected
913        );
914    }
915
916    #[test]
917    fn polymod_step_works_for_long_code() {
918        // Same parameterization works for the long code (shift=70, mask=LONG_MASK).
919        let r = 1u128 << LONG_SHIFT;
920        assert_eq!(
921            polymod_step(r, 0, &GEN_LONG, LONG_SHIFT, LONG_MASK),
922            GEN_LONG[0]
923        );
924        // b = 0b11111 → XOR all 5 long GENs.
925        let r = 0b11111u128 << LONG_SHIFT;
926        let expected = GEN_LONG[0] ^ GEN_LONG[1] ^ GEN_LONG[2] ^ GEN_LONG[3] ^ GEN_LONG[4];
927        assert_eq!(
928            polymod_step(r, 0, &GEN_LONG, LONG_SHIFT, LONG_MASK),
929            expected
930        );
931    }
932
933    #[test]
934    fn polymod_step_init_residue_first_iteration() {
935        // POLYMOD_INIT < 2^60 so b = 0 in the first iteration; only the shift+xor happens.
936        // Verify: polymod_step(POLYMOD_INIT, 0) = POLYMOD_INIT << 5.
937        assert_eq!(
938            polymod_step(POLYMOD_INIT, 0, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
939            POLYMOD_INIT << 5
940        );
941        // And with value=v: polymod_step(POLYMOD_INIT, v) = (POLYMOD_INIT << 5) ^ v.
942        assert_eq!(
943            polymod_step(POLYMOD_INIT, 31, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
944            (POLYMOD_INIT << 5) ^ 31
945        );
946    }
947
948    #[test]
949    fn polymod_step_value_and_gen_xor_combined() {
950        // Both effects active: b = 1 (bit 0 of b set) AND value = 5.
951        // Expected: ((residue & mask) << 5) ^ value ^ GEN[0]
952        //         = (0 << 5) ^ 5 ^ GEN[0]
953        //         = GEN_REGULAR[0] ^ 5
954        let r = 1u128 << REGULAR_SHIFT;
955        assert_eq!(
956            polymod_step(r, 5, &GEN_REGULAR, REGULAR_SHIFT, REGULAR_MASK),
957            GEN_REGULAR[0] ^ 5
958        );
959    }
960
961    #[test]
962    fn hrp_expand_mk_matches_spec() {
963        // BIP 173 hrp_expand for the MK HRP. Each ASCII byte contributes
964        // its high 3 bits then (after the [0] separator) its low 5 bits.
965        // 'm' = 0x6D → high 3 bits = 3, low 5 bits = 13.
966        // 'k' = 0x6B → high 3 bits = 3, low 5 bits = 11.
967        // Result: [3, 3, 0, 13, 11]. Documented in the BIP draft §"Checksum".
968        assert_eq!(hrp_expand(crate::consts::HRP), vec![3, 3, 0, 13, 11]);
969    }
970
971    #[test]
972    fn hrp_expand_empty_returns_just_separator() {
973        // Edge case: empty HRP yields just the [0] separator.
974        assert_eq!(hrp_expand(""), vec![0]);
975    }
976
977    #[test]
978    fn bch_round_trip_regular() {
979        // Encode then verify a small data part. The verify call sees the
980        // full data + checksum, so polymod returns MK_REGULAR_CONST exactly.
981        let hrp = "mk";
982        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
983        let checksum = bch_create_checksum_regular(hrp, &data);
984        assert_eq!(checksum.len(), 13);
985
986        let mut full = data.clone();
987        full.extend_from_slice(&checksum);
988        assert!(bch_verify_regular(hrp, &full));
989    }
990
991    #[test]
992    fn bch_verify_rejects_single_char_tampering_regular() {
993        // Flipping one bit in one symbol breaks verification.
994        // (Spot check; BCH detects all single-symbol errors by construction.)
995        let hrp = "mk";
996        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
997        let checksum = bch_create_checksum_regular(hrp, &data);
998        let mut full = data.clone();
999        full.extend_from_slice(&checksum);
1000        full[5] ^= 0x01;
1001        assert!(!bch_verify_regular(hrp, &full));
1002    }
1003
1004    #[test]
1005    fn bch_verify_rejects_too_short_input_regular() {
1006        // Less than 13 symbols cannot hold a checksum.
1007        assert!(!bch_verify_regular("mk", &[0, 1, 2]));
1008        assert!(!bch_verify_regular("mk", &[]));
1009    }
1010
1011    // (mk1-specific pinned-checksum vectors are deferred to Phase 6 vector
1012    // corpus generation, which writes both regular- and long-code conformance
1013    // points to disk under `crates/mk-codec/src/test_vectors/v0.1.json`.
1014    // Forking md-codec's pinned vectors verbatim would record the wrong
1015    // values: mk1's HRP and target constants both differ.)
1016
1017    #[test]
1018    fn bch_zero_data_does_not_self_validate_regular() {
1019        // The all-zeros data + all-zeros checksum must NOT validate, because
1020        // MK_REGULAR_CONST was chosen NUMS-style to avoid this trivial case.
1021        // Data length 8 is arbitrary; any non-empty zero-fill exhibits the same
1022        // negative result. 8 echoes the regular-code known-vector data length.
1023        let mut zero = vec![0u8; 8];
1024        zero.extend(std::iter::repeat_n(0, 13));
1025        assert!(!bch_verify_regular("mk", &zero));
1026    }
1027
1028    #[test]
1029    fn bch_round_trip_empty_data_regular() {
1030        // Empty data part is a degenerate but valid input: the checksum
1031        // covers only the HRP preamble. encode → verify must round-trip.
1032        let checksum = bch_create_checksum_regular("mk", &[]);
1033        assert!(bch_verify_regular("mk", &checksum));
1034    }
1035
1036    #[test]
1037    fn bch_round_trip_long() {
1038        let hrp = "mk";
1039        let data: Vec<u8> = (0..16).collect();
1040        let checksum = bch_create_checksum_long(hrp, &data);
1041        assert_eq!(checksum.len(), 15);
1042        let mut full = data.clone();
1043        full.extend_from_slice(&checksum);
1044        assert!(bch_verify_long(hrp, &full));
1045    }
1046
1047    #[test]
1048    fn bch_verify_rejects_single_char_tampering_long() {
1049        // Flipping one bit in one symbol breaks verification.
1050        // (Spot check; BCH detects all single-symbol errors by construction.)
1051        let hrp = "mk";
1052        let data: Vec<u8> = (0..16).collect();
1053        let checksum = bch_create_checksum_long(hrp, &data);
1054        let mut full = data.clone();
1055        full.extend_from_slice(&checksum);
1056        full[7] ^= 0x01;
1057        assert!(!bch_verify_long(hrp, &full));
1058    }
1059
1060    #[test]
1061    fn bch_verify_rejects_too_short_input_long() {
1062        // Less than 15 symbols cannot hold a long-code checksum.
1063        assert!(!bch_verify_long("mk", &[0; 14]));
1064        assert!(!bch_verify_long("mk", &[]));
1065    }
1066
1067    #[test]
1068    fn bch_zero_data_does_not_self_validate_long() {
1069        // All-zeros must not validate, by NUMS construction of MK_LONG_CONST.
1070        // Data length 16 is arbitrary; any non-empty zero-fill exhibits the same
1071        // negative result. 16 echoes the long-code known-vector data length.
1072        let mut zero = vec![0u8; 16];
1073        zero.extend(std::iter::repeat_n(0, 15));
1074        assert!(!bch_verify_long("mk", &zero));
1075    }
1076
1077    #[test]
1078    fn bch_round_trip_empty_data_long() {
1079        // Degenerate but valid: checksum covers only the HRP preamble.
1080        let checksum = bch_create_checksum_long("mk", &[]);
1081        assert!(bch_verify_long("mk", &checksum));
1082    }
1083
1084    #[test]
1085    fn bch_correct_regular_clean_input() {
1086        // Clean input → 0 corrections, identity result.
1087        let hrp = "mk";
1088        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1089        let checksum = bch_create_checksum_regular(hrp, &data);
1090        let mut full = data.clone();
1091        full.extend_from_slice(&checksum);
1092        let r = bch_correct_regular(hrp, &full).unwrap();
1093        assert_eq!(r.corrections_applied, 0);
1094        assert!(r.corrected_positions.is_empty());
1095        assert_eq!(r.data, full);
1096    }
1097
1098    #[test]
1099    fn bch_correct_regular_one_error() {
1100        // Single-symbol corruption is recoverable.
1101        let hrp = "mk";
1102        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1103        let checksum = bch_create_checksum_regular(hrp, &data);
1104        let mut full = data.clone();
1105        full.extend_from_slice(&checksum);
1106        let original = full.clone();
1107        full[3] = (full[3] + 1) & 0x1F;
1108        let r = bch_correct_regular(hrp, &full).unwrap();
1109        assert_eq!(r.corrections_applied, 1);
1110        assert_eq!(r.corrected_positions, vec![3]);
1111        assert_eq!(r.data, original);
1112    }
1113
1114    #[test]
1115    fn bch_correct_regular_two_errors_recovered_v0_2() {
1116        // v0.2 BM/Forney decoder reaches the BCH(93,80,8) full t = 4
1117        // capacity. A 2-error pattern is now recoverable. This test was
1118        // `..._uncorrectable_v0_1` in v0.1; flipped sign in v0.2.
1119        let hrp = "mk";
1120        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1121        let checksum = bch_create_checksum_regular(hrp, &data);
1122        let mut full = data.clone();
1123        full.extend_from_slice(&checksum);
1124        let original = full.clone();
1125        full[3] = (full[3] + 1) & 0x1F;
1126        full[7] = (full[7] + 1) & 0x1F;
1127        let r = bch_correct_regular(hrp, &full).unwrap();
1128        assert_eq!(r.corrections_applied, 2);
1129        assert!(r.corrected_positions.contains(&3));
1130        assert!(r.corrected_positions.contains(&7));
1131        assert_eq!(r.data, original);
1132    }
1133
1134    #[test]
1135    fn bch_correct_long_clean_input() {
1136        let hrp = "mk";
1137        let data: Vec<u8> = (0..16).collect();
1138        let checksum = bch_create_checksum_long(hrp, &data);
1139        let mut full = data.clone();
1140        full.extend_from_slice(&checksum);
1141        let r = bch_correct_long(hrp, &full).unwrap();
1142        assert_eq!(r.corrections_applied, 0);
1143    }
1144
1145    #[test]
1146    fn bch_correct_long_one_error() {
1147        let hrp = "mk";
1148        let data: Vec<u8> = (0..16).collect();
1149        let checksum = bch_create_checksum_long(hrp, &data);
1150        let mut full = data.clone();
1151        full.extend_from_slice(&checksum);
1152        let original = full.clone();
1153        full[5] = (full[5] + 1) & 0x1F;
1154        let r = bch_correct_long(hrp, &full).unwrap();
1155        assert_eq!(r.corrections_applied, 1);
1156        assert_eq!(r.corrected_positions, vec![5]);
1157        assert_eq!(r.data, original);
1158    }
1159
1160    #[test]
1161    fn bch_correct_returns_correction_result_with_position() {
1162        // Verify the API contract: a successful 1-error correction reports
1163        // exactly the position that was changed.
1164        let hrp = "mk";
1165        let data: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7];
1166        let checksum = bch_create_checksum_regular(hrp, &data);
1167        let mut full = data.clone();
1168        full.extend_from_slice(&checksum);
1169        // Damage the second checksum byte (position 9 from start).
1170        full[9] = (full[9] + 7) & 0x1F;
1171        let r = bch_correct_regular(hrp, &full).unwrap();
1172        assert_eq!(r.corrected_positions, vec![9]);
1173    }
1174
1175    /// Build a fake mk1 5-bit data stream for round-trip tests:
1176    /// `[v0, v1, ...]` are 2 bech32-symbol single-string-style header
1177    /// symbols; `payload_bytes` is the byte-level fragment.
1178    fn build_5bit_data(header_symbols: &[u8], payload_bytes: &[u8]) -> Vec<u8> {
1179        let mut out = Vec::with_capacity(header_symbols.len() + payload_bytes.len() * 2);
1180        out.extend_from_slice(header_symbols);
1181        out.extend(bytes_to_5bit(payload_bytes));
1182        out
1183    }
1184
1185    #[test]
1186    fn encode_5bit_to_string_round_trip_regular() {
1187        // 2-symbol single-string header + 4-byte payload → 7 5-bit symbols
1188        // (header [v=0, t=0] || bytes_to_5bit(4 bytes) = 2 + 7 = 9 symbols).
1189        // 9 + 13 regular checksum = 22-char data part — well within regular range.
1190        let header_symbols = [0u8, 0u8];
1191        let payload = vec![0xDE, 0xAD, 0xBE, 0xEF];
1192        let data_5bit = build_5bit_data(&header_symbols, &payload);
1193        let s = encode_5bit_to_string(&data_5bit).unwrap();
1194        assert!(s.starts_with("mk1"), "string did not start with mk1: {}", s);
1195
1196        let decoded = decode_string(&s).unwrap();
1197        assert_eq!(decoded.code, BchCode::Regular);
1198        assert_eq!(decoded.corrections_applied, 0);
1199        assert!(decoded.corrected_positions.is_empty());
1200        assert_eq!(decoded.data(), data_5bit.as_slice());
1201
1202        // Recover the payload by stripping the 2-symbol header and byte-decoding.
1203        let payload_5bit = &decoded.data()[2..];
1204        let recovered = five_bit_to_bytes(payload_5bit).unwrap();
1205        assert_eq!(recovered, payload);
1206    }
1207
1208    #[test]
1209    fn encode_5bit_to_string_round_trip_long() {
1210        // Force a long-code path with an 8-symbol chunked-style header +
1211        // a 53-byte fragment: data_5bit.len() = 8 + ceil(53*8/5) = 8 + 85 = 93,
1212        // + 15 long checksum = 108 — exact long-code upper bound.
1213        let header_symbols = [0u8; 8];
1214        let payload = vec![0xA5u8; 53];
1215        let data_5bit = build_5bit_data(&header_symbols, &payload);
1216        assert_eq!(
1217            data_5bit.len(),
1218            93,
1219            "fixture invariant: 8 header + 85 payload symbols"
1220        );
1221        let s = encode_5bit_to_string(&data_5bit).unwrap();
1222        assert!(s.starts_with("mk1"));
1223        let decoded = decode_string(&s).unwrap();
1224        assert_eq!(decoded.code, BchCode::Long);
1225        assert_eq!(decoded.data(), data_5bit.as_slice());
1226
1227        let recovered = five_bit_to_bytes(&decoded.data()[8..]).unwrap();
1228        assert_eq!(recovered, payload);
1229    }
1230
1231    #[test]
1232    fn encode_starts_with_hrp_and_separator() {
1233        // Minimum-shape input: 1 5-bit symbol + 13 regular checksum = 14 — the
1234        // tightest valid regular-code data-part length.
1235        let s = encode_5bit_to_string(&[1u8]).unwrap();
1236        assert!(s.starts_with("mk1"), "string did not start with mk1: {}", s);
1237    }
1238
1239    #[test]
1240    fn decode_rejects_invalid_hrp() {
1241        let s = encode_5bit_to_string(&[0u8; 10]).unwrap();
1242        let bad = s.replacen("mk", "bt", 1);
1243        assert!(matches!(
1244            decode_string(&bad),
1245            Err(crate::Error::InvalidHrp(_))
1246        ));
1247    }
1248
1249    #[test]
1250    fn decode_rejects_mixed_case() {
1251        let s = encode_5bit_to_string(&[0u8; 10]).unwrap();
1252        let bad: String = s
1253            .chars()
1254            .enumerate()
1255            .map(|(i, c)| if i == 5 { c.to_ascii_uppercase() } else { c })
1256            .collect();
1257        assert!(matches!(decode_string(&bad), Err(crate::Error::MixedCase)));
1258    }
1259
1260    #[test]
1261    fn decode_rejects_invalid_char() {
1262        // 'b' is excluded from the bech32 alphabet; substitute one in the data
1263        // part to force a parse-time character rejection.
1264        let s = encode_5bit_to_string(&[0u8; 10]).unwrap();
1265        // s looks like "mk1...". Splice 'b' at index 5 (definitely past "mk1").
1266        let mut chars: Vec<char> = s.chars().collect();
1267        chars[5] = 'b';
1268        let bad: String = chars.into_iter().collect();
1269        assert!(matches!(
1270            decode_string(&bad),
1271            Err(crate::Error::InvalidChar { .. })
1272        ));
1273    }
1274
1275    #[test]
1276    fn decode_rejects_missing_separator() {
1277        // No '1' at all in the string. rfind('1') returns None → InvalidHrp.
1278        let bad = "mknoseparatorhere";
1279        assert!(matches!(
1280            decode_string(bad),
1281            Err(crate::Error::InvalidHrp(_))
1282        ));
1283    }
1284
1285    #[test]
1286    fn decode_recovers_one_error() {
1287        // Encode, corrupt one char in the data part, decode should auto-correct.
1288        let data_5bit = vec![0u8, 0u8, 1, 2, 3, 4, 5];
1289        let s = encode_5bit_to_string(&data_5bit).unwrap();
1290
1291        let mut chars: Vec<char> = s.chars().collect();
1292        // Corrupt position 6 (past "mk1", well within the data part).
1293        let original_char = chars[6];
1294        chars[6] = if original_char == 'q' { 'p' } else { 'q' };
1295        let corrupted: String = chars.into_iter().collect();
1296
1297        let decoded = decode_string(&corrupted).unwrap();
1298        assert_eq!(decoded.corrections_applied, 1);
1299        assert_eq!(decoded.corrected_positions.len(), 1);
1300        assert_eq!(decoded.data(), data_5bit.as_slice());
1301    }
1302
1303    #[test]
1304    fn encode_rejects_data_part_in_reserved_invalid_length_range() {
1305        // For 5-bit data-part lengths 0..=12 (so data_part = 13..=25 with regular
1306        // checksum, or 15..=27 with long), `bch_code_for_length` rejects below 14.
1307        // Empty input → data_5bit.len()=0 → regular_total=13 → None; long_total=15
1308        // → Regular. Wait — regular range starts at 14 not 13.
1309        //
1310        // Actual invariant test: len 0 → regular_total=13 (None, below 14) and
1311        // long_total=15 (Regular). So it falls back to long->regular ladder ...
1312        // Re-checking encode_5bit_to_string: only fails when both miss [14..=93]
1313        // and [96..=108]. For data_5bit.len()=79, regular_total=92 → Regular ✓.
1314        // The provable reserved-invalid case is a length that misses both
1315        // ranges; the BIP 93 BCH ladder leaves no such gap below 109 because
1316        // [14..=93] ∪ [96..=108] only excludes {0..=13, 94..=95, ≥109}. The
1317        // smallest input length that produces invalid data-part lengths in
1318        // BOTH the regular and long branches is therefore data_5bit.len() ≥ 94
1319        // (regular_total ≥ 107 in invalid territory, long_total ≥ 109 too long).
1320        let too_long = vec![0u8; 94];
1321        let result = encode_5bit_to_string(&too_long);
1322        assert!(matches!(result, Err(crate::Error::InvalidStringLength(_))));
1323    }
1324}