Skip to main content

ms_codec/
decode.rs

1//! Public decoder. Applies SPEC §4 validity rules in order.
2//!
3//! v0.2.0: also hosts [`decode_with_correction`] — the BCH-error-correcting
4//! decode entry point per plan §1 D22 + §2.B.2. Parse → polymod-residue →
5//! (if non-zero) call [`crate::bch_decode::decode_regular_errors`] → apply
6//! corrections → run the existing [`decode`] path → return
7//! `(Tag, Payload, Vec<CorrectionDetail>)`. ms1 is single-chunk per codex32
8//! spec, so there is no atomic-multi-chunk variant (cf. md-codec's
9//! per-chunk-set version).
10
11use crate::consts::{RESERVED_NOT_EMITTED_V01, TAG_ENTR, VALID_MNEM_STR_LENGTHS, VALID_STR_LENGTHS};
12use crate::envelope;
13use crate::error::{Error, Result};
14use crate::payload::{Payload, PayloadKind};
15use crate::tag::Tag;
16use codex32::Codex32String;
17
18/// Union of all emittable string lengths (entr ∪ mnem). Used as the
19/// pre-dispatch gate in `decode` before kind-specific binding.
20fn is_known_length(len: usize) -> bool {
21    VALID_STR_LENGTHS.contains(&len) || VALID_MNEM_STR_LENGTHS.contains(&len)
22}
23
24/// Return the kind-appropriate allowed-length set for error reporting.
25fn allowed_for_kind(kind: PayloadKind) -> &'static [usize] {
26    match kind {
27        PayloadKind::Entr => VALID_STR_LENGTHS,
28        PayloadKind::Mnem => VALID_MNEM_STR_LENGTHS,
29    }
30}
31
32/// Decode an ms1 string into `(Tag, Payload)`.
33///
34/// Rejects per SPEC §4 rules 1-10 (extended for v0.2 mnem):
35///
36/// - Rule 1: upstream codex32 parse failure (Codex32 variant).
37/// - Rules 2-4, 8: wire-invariant violations (delegated to envelope::discriminate).
38/// - Rules 5-7: tag-table membership rules (here).
39/// - Rule 9: total string length not in the union {entr lengths} ∪ {mnem lengths}
40///   (here, before parse); then bound to the discriminated kind post-dispatch.
41/// - Rule 10: payload byte length mismatch for the tag (here, via Payload::validate()).
42pub fn decode(s: &str) -> Result<(Tag, Payload)> {
43    // §4 rule 9 (pre-dispatch): total string length must be in the union set.
44    if !is_known_length(s.len()) {
45        return Err(Error::UnexpectedStringLength {
46            got: s.len(),
47            allowed: VALID_STR_LENGTHS, // report the entr set as the primary allowed set
48        });
49    }
50
51    // §4 rule 1: delegate parse + checksum to rust-codex32.
52    let c = Codex32String::from_string(s.to_string())?;
53
54    // §4 rules 2, 3, 4, 8 + tag-alphabet rule 5: envelope (returns typed Payload).
55    let (tag, payload) = envelope::discriminate(&c)?;
56
57    // §4 rule 9 (post-dispatch, bind to kind): length must be in the kind-appropriate set.
58    let kind_allowed = allowed_for_kind(payload.kind());
59    if !kind_allowed.contains(&s.len()) {
60        return Err(Error::UnexpectedStringLength {
61            got: s.len(),
62            allowed: kind_allowed,
63        });
64    }
65
66    // §4 rule 7: reserved-not-emitted tags.
67    if RESERVED_NOT_EMITTED_V01.contains(tag.as_bytes()) {
68        return Err(Error::ReservedTagNotEmittedInV01 {
69            got: *tag.as_bytes(),
70        });
71    }
72
73    // §4 rule 6: tag must be in the v0.2 accept set (currently {entr}).
74    // SPEC v0.9.0 §1 item 2 — wrap the OWNED entropy buffer in `Zeroizing`
75    // so the intermediate scrub runs on function exit. The public Payload
76    // boundary is unwrapped per SPEC §3 OOS-2; caller wraps — see payload.rs.
77    use zeroize::Zeroizing;
78    let payload = match *tag.as_bytes() {
79        x if x == TAG_ENTR => {
80            match payload {
81                Payload::Entr(data) => {
82                    let scrubbed: Zeroizing<Vec<u8>> = Zeroizing::new(data);
83                    let p = Payload::Entr((*scrubbed).clone());
84                    // §4 rule 10: validate payload length.
85                    p.validate()?;
86                    p
87                }
88                Payload::Mnem { language, entropy } => {
89                    let scrubbed: Zeroizing<Vec<u8>> = Zeroizing::new(entropy);
90                    let p = Payload::Mnem { language, entropy: (*scrubbed).clone() };
91                    // §4 rule 10: validate (language range + entropy length).
92                    p.validate()?;
93                    p
94                }
95            }
96        }
97        _ => {
98            return Err(Error::UnknownTag {
99                got: *tag.as_bytes(),
100            });
101        }
102    };
103
104    Ok((tag, payload))
105}
106
107// ---------------------------------------------------------------------------
108// v0.2.0: BCH-error-correcting decode (plan §1 D22 + §2.B.2).
109// ---------------------------------------------------------------------------
110
111/// Per-correction report emitted by [`decode_with_correction`]. One entry
112/// per repaired character. `position` is 0-indexed into the codex32
113/// data-part (i.e. the characters following the `ms1` HRP + separator);
114/// `was` is the original (corrupted) char from the input; `now` is the
115/// corrected char.
116///
117/// ms1 is single-chunk per codex32 spec, so there is no `chunk_index`
118/// field (cf. md-codec's `CorrectionDetail`).
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct CorrectionDetail {
121    /// 0-indexed position of the corrected character within the codex32
122    /// data-part (post-HRP-and-separator).
123    pub position: usize,
124    /// The original (corrupted) character at this position.
125    pub was: char,
126    /// The corrected character at this position.
127    pub now: char,
128}
129
130/// Local codex32 alphabet (BIP 173 lowercase). Each char = one 5-bit
131/// symbol. Mirrors md-codec's `chunk.rs` local copy — kept private here so
132/// this module doesn't widen the codex32 public surface.
133const CODEX32_ALPHABET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
134
135/// BIP 173 HRP for ms1 strings (HRP + separator).
136const HRP_PREFIX: &str = "ms1";
137
138/// Parse an ms1 string into its 5-bit data-part symbol vector. Returns
139/// the data-with-checksum symbols (i.e. all symbols after `ms1`). The
140/// returned symbol count includes the 13-symbol BCH checksum tail.
141///
142/// Returns [`Error::WrongHrp`] if the string does not start with `ms1`,
143/// or [`Error::Codex32`] (via a `codex32::Error::InvalidChar`) if any
144/// data-part character is not in the codex32 alphabet.
145fn parse_ms1_symbols(s: &str) -> Result<Vec<u8>> {
146    let lower = s.to_ascii_lowercase();
147    if !lower.starts_with(HRP_PREFIX) {
148        // Report the observed HRP (everything before the last '1' separator)
149        // so the error is actionable. '1' is ASCII, so `rfind('1')` always
150        // returns a char boundary — slicing there is safe regardless of any
151        // multi-byte content elsewhere. When there is NO separator, the whole
152        // (malformed) string is the observed HRP; never slice at `len-1`,
153        // which can land inside a multi-byte char and panic (found by
154        // stress-Cycle-C fuzzing on a no-`'1'` lossy-UTF8 input). Leak-neutral:
155        // the WrongHrp.got echo vector is the unchanged WITH-`'1'` path;
156        // bounding it is the separate `ms-codec-error-display-echoes-input`
157        // FOLLOWUP's job.
158        let got = match lower.rfind('1') {
159            Some(i) => lower[..i].to_string(),
160            None => lower.clone(),
161        };
162        return Err(Error::WrongHrp { got });
163    }
164    let rest = &lower[HRP_PREFIX.len()..];
165    let mut symbols: Vec<u8> = Vec::with_capacity(rest.len());
166    // Non-alphabet characters can't appear in a valid v0.1 string. We
167    // can't fabricate a `codex32::Error` value here (the upstream crate
168    // doesn't expose a constructor for `InvalidChar`), so we use
169    // `UnexpectedStringLength` as a stand-in: the existing `decode` path
170    // would have rejected the string for the same reason on a different
171    // axis. Toolkit-side helper at B.7 absorbs into `UnparseableInput`
172    // per plan §2.B.4 D29 error-mapping table.
173    for c in rest.chars() {
174        let lc = c as u8;
175        let sym = CODEX32_ALPHABET
176            .iter()
177            .position(|&b| b == lc)
178            .ok_or(Error::UnexpectedStringLength {
179                got: s.len(),
180                allowed: VALID_STR_LENGTHS,
181            })? as u8;
182        symbols.push(sym);
183    }
184    Ok(symbols)
185}
186
187/// Re-encode a 5-bit data-part symbol vector as a complete ms1 string.
188fn encode_ms1_string(data_with_checksum: &[u8]) -> String {
189    let mut out = String::with_capacity(HRP_PREFIX.len() + data_with_checksum.len());
190    out.push_str(HRP_PREFIX);
191    for &v in data_with_checksum {
192        out.push(CODEX32_ALPHABET[(v & 0x1F) as usize] as char);
193    }
194    out
195}
196
197/// BCH-error-correcting decode for a single ms1 string.
198///
199/// Per plan §1 Q1 lock — full-decode semantics: this is the single entry
200/// point that callers needing both "did anything get repaired?" AND "the
201/// fully-decoded `(Tag, Payload)`" should use.
202///
203/// Algorithm:
204/// 1. Parse the input as ms1 (`ms1` HRP + codex32 data-part) into a
205///    5-bit symbol vector.
206/// 2. Compute the BCH polymod residue
207///    (`hrp_expand("ms") || data_with_checksum`) XOR'd against
208///    [`crate::bch::MS_REGULAR_CONST`].
209/// 3. Residue `== 0` ⇒ clean codeword; pass through to the existing
210///    [`decode`] entry point unchanged.
211/// 4. Residue `!= 0` ⇒ invoke
212///    [`crate::bch_decode::decode_regular_errors`]. If `None`, return
213///    `Err(Error::TooManyErrors { bound: 8 })` per plan §2.B.4 D29
214///    error-mapping table.
215/// 5. Apply corrections to the symbol vector, re-verify via polymod (a
216///    defensive catch for pathological 5+-error patterns that fool BM
217///    into returning a degree-≤4 locator with 4 valid roots), and record
218///    one [`CorrectionDetail`] per repaired character.
219/// 6. Re-encode the corrected symbol vector as an ms1 string and forward
220///    it to the existing [`decode`] entry point.
221///
222/// Per Q1 lock + D29 error-mapping table, any §4-rule error from the
223/// full decode (orphan variants like `ThresholdNotZero`,
224/// `ReservedTagNotEmittedInV01`, etc.) surfaces directly; toolkit-side
225/// `repair_via_ms_codec` (B.7) absorbs these into
226/// `RepairError::PostCorrectionDecodeFailed`.
227///
228/// Returns `(Tag, Payload, Vec<CorrectionDetail>)` on success. The
229/// correction-detail vector is in ascending `position` order; an empty
230/// vector means the input was already a valid codeword.
231pub fn decode_with_correction(s: &str) -> Result<(Tag, Payload, Vec<CorrectionDetail>)> {
232    // Parse data-part symbols. Length checks live in `decode` proper
233    // (rule 9 is enforced there after we've potentially corrected, since
234    // BCH correction does not change the string length).
235    let symbols = parse_ms1_symbols(s)?;
236
237    // Polymod residue against ms1's target constant.
238    let mut input = crate::bch::hrp_expand("ms");
239    input.extend_from_slice(&symbols);
240    let residue = crate::bch::polymod_run(&input) ^ crate::bch::MS_REGULAR_CONST;
241
242    if residue == 0 {
243        // Already a valid codeword; pass through to the existing decoder.
244        let (tag, payload) = decode(s)?;
245        return Ok((tag, payload, Vec::new()));
246    }
247
248    // Attempt BCH correction.
249    let (positions, magnitudes) = crate::bch_decode::decode_regular_errors(residue, symbols.len())
250        .ok_or(Error::TooManyErrors { bound: 8 })?;
251
252    // Apply corrections; record (was, now) chars per position.
253    let mut corrected = symbols.clone();
254    let mut details: Vec<CorrectionDetail> = Vec::with_capacity(positions.len());
255    for (&pos, &mag) in positions.iter().zip(&magnitudes) {
256        if pos >= corrected.len() {
257            // Defensive: chien_search bounded pos to [0, L); but a
258            // pathological 5+-error pattern could in principle skirt
259            // that.
260            return Err(Error::TooManyErrors { bound: 8 });
261        }
262        let was_byte = corrected[pos];
263        let now_byte = was_byte ^ mag;
264        let was = CODEX32_ALPHABET[(was_byte & 0x1F) as usize] as char;
265        let now = CODEX32_ALPHABET[(now_byte & 0x1F) as usize] as char;
266        details.push(CorrectionDetail {
267            position: pos,
268            was,
269            now,
270        });
271        corrected[pos] = now_byte;
272    }
273
274    // Defensive re-verify (catches pathological 5+-error patterns that
275    // happen to produce a degree-≤4 locator with 4 valid roots).
276    let mut verify_input = crate::bch::hrp_expand("ms");
277    verify_input.extend_from_slice(&corrected);
278    let verify_residue =
279        crate::bch::polymod_run(&verify_input) ^ crate::bch::MS_REGULAR_CONST;
280    if verify_residue != 0 {
281        return Err(Error::TooManyErrors { bound: 8 });
282    }
283
284    // Hand the corrected string to the existing decoder. Any §4-rule
285    // error surfaces directly per Q1 lock; toolkit helper at B.7 absorbs.
286    let corrected_str = encode_ms1_string(&corrected);
287    let (tag, payload) = decode(&corrected_str)?;
288    Ok((tag, payload, details))
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use crate::encode;
295
296    #[test]
297    fn round_trip_entr_all_lengths() {
298        for len in [16usize, 20, 24, 28, 32] {
299            let entropy = (0..len as u8)
300                .map(|i| i.wrapping_mul(7))
301                .collect::<Vec<_>>();
302            let p = Payload::Entr(entropy.clone());
303            let s = encode::encode(Tag::ENTR, &p).unwrap();
304            let (tag, recovered) = decode(&s).unwrap();
305            assert_eq!(tag, Tag::ENTR);
306            assert_eq!(recovered, p);
307        }
308    }
309
310    #[test]
311    fn decode_rejects_unexpected_length() {
312        // 52 chars is outside both the entr set [50,56,62,69,75]
313        // and the mnem set [51,58,64,70,77].
314        let s = "ms10entrsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
315        assert_eq!(s.len(), 52, "test string must be 52 chars");
316        assert!(matches!(
317            decode(s),
318            Err(Error::UnexpectedStringLength { .. })
319        ));
320    }
321
322    #[test]
323    fn decode_routes_share_to_is_share_not_single_string() {
324        // A distributed share of an entr-16 secret is a 50-char string (same
325        // length as a v0.1 entr-16 single — disambiguated by the threshold char,
326        // not length). It passes the length gate, parses, then discriminate must
327        // route it → IsShareNotSingleString (NOT ThresholdNotZero).
328        use crate::shares::{encode_shares, Threshold};
329        let p = Payload::Entr(vec![0xAAu8; 16]);
330        let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
331        let s = &shares[0];
332        assert_eq!(s.len(), 50, "threshold=2 entr-16 share must be 50 chars");
333        match decode(s) {
334            Err(Error::IsShareNotSingleString { threshold, .. }) => {
335                assert_eq!(threshold, '2');
336            }
337            other => panic!("expected IsShareNotSingleString, got {other:?}"),
338        }
339    }
340
341    #[test]
342    fn decode_v01_single_strings_still_ok() {
343        // v0.1 entr single + v0.2 mnem single both decode unchanged.
344        let entr = encode::encode(Tag::ENTR, &Payload::Entr(vec![0x11u8; 16])).unwrap();
345        assert!(decode(&entr).is_ok(), "v0.1 entr single must still decode");
346        let mnem = encode::encode(
347            Tag::ENTR,
348            &Payload::Mnem { language: 1, entropy: vec![0x22u8; 16] },
349        )
350        .unwrap();
351        assert!(decode(&mnem).is_ok(), "mnem single must still decode");
352    }
353
354    #[test]
355    fn decode_rejects_short_seed_string_with_reserved_tag() {
356        // Hand-build a 50-char string with id="seed" — 16-B entropy worth.
357        // The string-length check passes; tag-rule 7 fails.
358        let mut data = vec![0x00u8];
359        data.extend_from_slice(&[0xAAu8; 16]);
360        let c = Codex32String::from_seed("ms", 0, "seed", codex32::Fe::S, &data).unwrap();
361        let s = c.to_string();
362        assert_eq!(s.len(), 50, "expected str.len 50 for 16-B + prefix");
363        assert!(matches!(
364            decode(&s),
365            Err(Error::ReservedTagNotEmittedInV01 { .. })
366        ));
367    }
368
369    // Regression: `decode_with_correction` must NOT panic on a non-`ms1`
370    // input with no `'1'` separator. Found by stress-Cycle-C fuzzing
371    // (`ms1_decode`): `parse_ms1_symbols` sliced `lower[..len-1]`, which lands
372    // inside a multi-byte char when there is no separator → char-boundary
373    // panic. The minimized reproducer is a single `0xaa` byte, which
374    // `String::from_utf8_lossy` turns into the 3-byte U+FFFD.
375    #[test]
376    fn decode_with_correction_no_separator_multibyte_does_not_panic() {
377        // Each input has no `'1'`, and `len-1` lands inside a multi-byte
378        // char at a different offset (1-, 2-, 3-, 4-byte chars + a long run).
379        let cases = [
380            String::from_utf8_lossy(&[0xaa]).into_owned(), // U+FFFD, 3 bytes — the fuzz reproducer
381            "é".to_string(),                               // 2-byte
382            "añ".to_string(),                              // ascii + 2-byte
383            "€".to_string(),                               // 3-byte
384            "😀".to_string(),                              // 4-byte
385            "é".repeat(25),                                // 50-byte multi-byte run
386            "İ".to_string(),                               // dotted-capital-I (case-fold edge)
387        ];
388        for s in &cases {
389            // Must return cleanly, never panic. No `'1'` ⇒ WrongHrp, with the
390            // whole (lowercased) input echoed as the observed HRP.
391            match decode_with_correction(s) {
392                Err(Error::WrongHrp { got }) => {
393                    assert_eq!(
394                        got,
395                        s.to_ascii_lowercase(),
396                        "got echoes the whole no-separator input"
397                    );
398                }
399                other => panic!("expected WrongHrp for {s:?}, got {other:?}"),
400            }
401        }
402    }
403
404    // Preservation: an input WITH a `'1'` but a wrong HRP still reports the
405    // pre-separator part as `got` (byte-identical to pre-fix behavior).
406    #[test]
407    fn decode_with_correction_wrong_hrp_with_separator_unchanged() {
408        match decode_with_correction("xy1qqq") {
409            Err(Error::WrongHrp { got }) => assert_eq!(got, "xy"),
410            other => panic!("expected WrongHrp {{ got: \"xy\" }}, got {other:?}"),
411        }
412        // A `'1'` deep in a multi-byte string still slices at the (ASCII) '1'
413        // boundary, never inside the preceding char.
414        match decode_with_correction("ñ1zzz") {
415            Err(Error::WrongHrp { got }) => assert_eq!(got, "ñ"),
416            other => panic!("expected WrongHrp {{ got: \"ñ\" }}, got {other:?}"),
417        }
418    }
419}