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