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).
155        //
156        // SECRET-LEAK BOUND (ms-codec-error-display-echoes-input, 0.4.4): a
157        // data-char→`'1'` mutation can stretch the "observed HRP" into a long
158        // secret prefix. Cap the stored `got` to the first 4 CHARS (not bytes —
159        // multibyte chars like "ñ"/"é"/"😀" would re-introduce the v0.4.3 panic
160        // on a byte slice). 4 < the 8-char leak window and still carries the
161        // "you typed mk1/lnbc not ms1" diagnostic. Construction-time bound so
162        // downstream re-echoers (ms-cli, toolkit) inherit it for free.
163        let observed = match lower.rfind('1') {
164            Some(i) => &lower[..i],
165            None => &lower,
166        };
167        let got = observed.chars().take(4).collect::<String>();
168        return Err(Error::WrongHrp { got });
169    }
170    let rest = &lower[HRP_PREFIX.len()..];
171    let mut symbols: Vec<u8> = Vec::with_capacity(rest.len());
172    // Non-alphabet characters can't appear in a valid v0.1 string. We
173    // can't fabricate a `codex32::Error` value here (the upstream crate
174    // doesn't expose a constructor for `InvalidChar`), so we use
175    // `UnexpectedStringLength` as a stand-in: the existing `decode` path
176    // would have rejected the string for the same reason on a different
177    // axis. Toolkit-side helper at B.7 absorbs into `UnparseableInput`
178    // per plan §2.B.4 D29 error-mapping table.
179    for c in rest.chars() {
180        let lc = c as u8;
181        let sym = CODEX32_ALPHABET
182            .iter()
183            .position(|&b| b == lc)
184            .ok_or(Error::UnexpectedStringLength {
185                got: s.len(),
186                allowed: VALID_STR_LENGTHS,
187            })? as u8;
188        symbols.push(sym);
189    }
190    Ok(symbols)
191}
192
193/// Re-encode a 5-bit data-part symbol vector as a complete ms1 string.
194fn encode_ms1_string(data_with_checksum: &[u8]) -> String {
195    let mut out = String::with_capacity(HRP_PREFIX.len() + data_with_checksum.len());
196    out.push_str(HRP_PREFIX);
197    for &v in data_with_checksum {
198        out.push(CODEX32_ALPHABET[(v & 0x1F) as usize] as char);
199    }
200    out
201}
202
203/// BCH-error-correcting decode for a single ms1 string.
204///
205/// Per plan §1 Q1 lock — full-decode semantics: this is the single entry
206/// point that callers needing both "did anything get repaired?" AND "the
207/// fully-decoded `(Tag, Payload)`" should use.
208///
209/// Algorithm:
210/// 1. Parse the input as ms1 (`ms1` HRP + codex32 data-part) into a
211///    5-bit symbol vector.
212/// 2. Compute the BCH polymod residue
213///    (`hrp_expand("ms") || data_with_checksum`) XOR'd against
214///    [`crate::bch::MS_REGULAR_CONST`].
215/// 3. Residue `== 0` ⇒ clean codeword; pass through to the existing
216///    [`decode`] entry point unchanged.
217/// 4. Residue `!= 0` ⇒ invoke
218///    [`crate::bch_decode::decode_regular_errors`]. If `None`, return
219///    `Err(Error::TooManyErrors { bound: 8 })` per plan §2.B.4 D29
220///    error-mapping table.
221/// 5. Apply corrections to the symbol vector, re-verify via polymod (a
222///    defensive catch for pathological 5+-error patterns that fool BM
223///    into returning a degree-≤4 locator with 4 valid roots), and record
224///    one [`CorrectionDetail`] per repaired character.
225/// 6. Re-encode the corrected symbol vector as an ms1 string and forward
226///    it to the existing [`decode`] entry point.
227///
228/// Per Q1 lock + D29 error-mapping table, any §4-rule error from the
229/// full decode (orphan variants like `ThresholdNotZero`,
230/// `ReservedTagNotEmittedInV01`, etc.) surfaces directly; toolkit-side
231/// `repair_via_ms_codec` (B.7) absorbs these into
232/// `RepairError::PostCorrectionDecodeFailed`.
233///
234/// Returns `(Tag, Payload, Vec<CorrectionDetail>)` on success. The
235/// correction-detail vector is in ascending `position` order; an empty
236/// vector means the input was already a valid codeword.
237pub fn decode_with_correction(s: &str) -> Result<(Tag, Payload, Vec<CorrectionDetail>)> {
238    // Parse data-part symbols. Length checks live in `decode` proper
239    // (rule 9 is enforced there after we've potentially corrected, since
240    // BCH correction does not change the string length).
241    let symbols = parse_ms1_symbols(s)?;
242
243    // Polymod residue against ms1's target constant.
244    let mut input = crate::bch::hrp_expand("ms");
245    input.extend_from_slice(&symbols);
246    let residue = crate::bch::polymod_run(&input) ^ crate::bch::MS_REGULAR_CONST;
247
248    if residue == 0 {
249        // Already a valid codeword; pass through to the existing decoder.
250        let (tag, payload) = decode(s)?;
251        return Ok((tag, payload, Vec::new()));
252    }
253
254    // Attempt BCH correction.
255    let (positions, magnitudes) = crate::bch_decode::decode_regular_errors(residue, symbols.len())
256        .ok_or(Error::TooManyErrors { bound: 8 })?;
257
258    // Apply corrections; record (was, now) chars per position.
259    let mut corrected = symbols.clone();
260    let mut details: Vec<CorrectionDetail> = Vec::with_capacity(positions.len());
261    for (&pos, &mag) in positions.iter().zip(&magnitudes) {
262        if pos >= corrected.len() {
263            // Defensive: chien_search bounded pos to [0, L); but a
264            // pathological 5+-error pattern could in principle skirt
265            // that.
266            return Err(Error::TooManyErrors { bound: 8 });
267        }
268        let was_byte = corrected[pos];
269        let now_byte = was_byte ^ mag;
270        let was = CODEX32_ALPHABET[(was_byte & 0x1F) as usize] as char;
271        let now = CODEX32_ALPHABET[(now_byte & 0x1F) as usize] as char;
272        details.push(CorrectionDetail {
273            position: pos,
274            was,
275            now,
276        });
277        corrected[pos] = now_byte;
278    }
279
280    // Defensive re-verify (catches pathological 5+-error patterns that
281    // happen to produce a degree-≤4 locator with 4 valid roots).
282    let mut verify_input = crate::bch::hrp_expand("ms");
283    verify_input.extend_from_slice(&corrected);
284    let verify_residue =
285        crate::bch::polymod_run(&verify_input) ^ crate::bch::MS_REGULAR_CONST;
286    if verify_residue != 0 {
287        return Err(Error::TooManyErrors { bound: 8 });
288    }
289
290    // Hand the corrected string to the existing decoder. Any §4-rule
291    // error surfaces directly per Q1 lock; toolkit helper at B.7 absorbs.
292    let corrected_str = encode_ms1_string(&corrected);
293    let (tag, payload) = decode(&corrected_str)?;
294    Ok((tag, payload, details))
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::encode;
301
302    #[test]
303    fn round_trip_entr_all_lengths() {
304        for len in [16usize, 20, 24, 28, 32] {
305            let entropy = (0..len as u8)
306                .map(|i| i.wrapping_mul(7))
307                .collect::<Vec<_>>();
308            let p = Payload::Entr(entropy.clone());
309            let s = encode::encode(Tag::ENTR, &p).unwrap();
310            let (tag, recovered) = decode(&s).unwrap();
311            assert_eq!(tag, Tag::ENTR);
312            assert_eq!(recovered, p);
313        }
314    }
315
316    #[test]
317    fn decode_rejects_unexpected_length() {
318        // 52 chars is outside both the entr set [50,56,62,69,75]
319        // and the mnem set [51,58,64,70,77].
320        let s = "ms10entrsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
321        assert_eq!(s.len(), 52, "test string must be 52 chars");
322        assert!(matches!(
323            decode(s),
324            Err(Error::UnexpectedStringLength { .. })
325        ));
326    }
327
328    #[test]
329    fn decode_routes_share_to_is_share_not_single_string() {
330        // A distributed share of an entr-16 secret is a 50-char string (same
331        // length as a v0.1 entr-16 single — disambiguated by the threshold char,
332        // not length). It passes the length gate, parses, then discriminate must
333        // route it → IsShareNotSingleString (NOT ThresholdNotZero).
334        use crate::shares::{encode_shares, Threshold};
335        let p = Payload::Entr(vec![0xAAu8; 16]);
336        let shares = encode_shares(Tag::ENTR, Threshold::new(2).unwrap(), 3, &p).unwrap();
337        let s = &shares[0];
338        assert_eq!(s.len(), 50, "threshold=2 entr-16 share must be 50 chars");
339        match decode(s) {
340            Err(Error::IsShareNotSingleString { threshold, .. }) => {
341                assert_eq!(threshold, '2');
342            }
343            other => panic!("expected IsShareNotSingleString, got {other:?}"),
344        }
345    }
346
347    #[test]
348    fn decode_v01_single_strings_still_ok() {
349        // v0.1 entr single + v0.2 mnem single both decode unchanged.
350        let entr = encode::encode(Tag::ENTR, &Payload::Entr(vec![0x11u8; 16])).unwrap();
351        assert!(decode(&entr).is_ok(), "v0.1 entr single must still decode");
352        let mnem = encode::encode(
353            Tag::ENTR,
354            &Payload::Mnem { language: 1, entropy: vec![0x22u8; 16] },
355        )
356        .unwrap();
357        assert!(decode(&mnem).is_ok(), "mnem single must still decode");
358    }
359
360    #[test]
361    fn decode_rejects_short_seed_string_with_reserved_tag() {
362        // Hand-build a 50-char string with id="seed" — 16-B entropy worth.
363        // The string-length check passes; tag-rule 7 fails.
364        let mut data = vec![0x00u8];
365        data.extend_from_slice(&[0xAAu8; 16]);
366        let c = Codex32String::from_seed("ms", 0, "seed", codex32::Fe::S, &data).unwrap();
367        let s = c.to_string();
368        assert_eq!(s.len(), 50, "expected str.len 50 for 16-B + prefix");
369        assert!(matches!(
370            decode(&s),
371            Err(Error::ReservedTagNotEmittedInV01 { .. })
372        ));
373    }
374
375    // Regression: `decode_with_correction` must NOT panic on a non-`ms1`
376    // input with no `'1'` separator. Found by stress-Cycle-C fuzzing
377    // (`ms1_decode`): `parse_ms1_symbols` sliced `lower[..len-1]`, which lands
378    // inside a multi-byte char when there is no separator → char-boundary
379    // panic. The minimized reproducer is a single `0xaa` byte, which
380    // `String::from_utf8_lossy` turns into the 3-byte U+FFFD.
381    #[test]
382    fn decode_with_correction_no_separator_multibyte_does_not_panic() {
383        // Each input has no `'1'`, and `len-1` lands inside a multi-byte
384        // char at a different offset (1-, 2-, 3-, 4-byte chars + a long run).
385        let cases = [
386            String::from_utf8_lossy(&[0xaa]).into_owned(), // U+FFFD, 3 bytes — the fuzz reproducer
387            "é".to_string(),                               // 2-byte
388            "añ".to_string(),                              // ascii + 2-byte
389            "€".to_string(),                               // 3-byte
390            "😀".to_string(),                              // 4-byte
391            "é".repeat(25),                                // 50-byte multi-byte run
392            "İ".to_string(),                               // dotted-capital-I (case-fold edge)
393        ];
394        for s in &cases {
395            // Must return cleanly, never panic. No `'1'` ⇒ WrongHrp, with the
396            // observed HRP CAPPED to the first 4 chars (the 0.4.4
397            // secret-leak bound; char-counted so multibyte cases don't panic).
398            match decode_with_correction(s) {
399                Err(Error::WrongHrp { got }) => {
400                    assert_eq!(
401                        got,
402                        s.chars().take(4).collect::<String>().to_ascii_lowercase(),
403                        "got is the first 4 chars of the no-separator input (capped)"
404                    );
405                }
406                other => panic!("expected WrongHrp for {s:?}, got {other:?}"),
407            }
408        }
409    }
410
411    // Preservation: an input WITH a `'1'` but a wrong HRP still reports the
412    // pre-separator part as `got` (byte-identical to pre-fix behavior).
413    #[test]
414    fn decode_with_correction_wrong_hrp_with_separator_unchanged() {
415        match decode_with_correction("xy1qqq") {
416            Err(Error::WrongHrp { got }) => assert_eq!(got, "xy"),
417            other => panic!("expected WrongHrp {{ got: \"xy\" }}, got {other:?}"),
418        }
419        // A `'1'` deep in a multi-byte string still slices at the (ASCII) '1'
420        // boundary, never inside the preceding char.
421        match decode_with_correction("ñ1zzz") {
422            Err(Error::WrongHrp { got }) => assert_eq!(got, "ñ"),
423            other => panic!("expected WrongHrp {{ got: \"ñ\" }}, got {other:?}"),
424        }
425    }
426}