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        // Find the actual HRP (everything up to and including the last '1'
149        // separator) so the error reports the observed HRP instead of "".
150        let hrp_end = lower.rfind('1').map(|i| i + 1).unwrap_or(lower.len());
151        let got = lower[..hrp_end.saturating_sub(1)].to_string();
152        return Err(Error::WrongHrp { got });
153    }
154    let rest = &lower[HRP_PREFIX.len()..];
155    let mut symbols: Vec<u8> = Vec::with_capacity(rest.len());
156    // Non-alphabet characters can't appear in a valid v0.1 string. We
157    // can't fabricate a `codex32::Error` value here (the upstream crate
158    // doesn't expose a constructor for `InvalidChar`), so we use
159    // `UnexpectedStringLength` as a stand-in: the existing `decode` path
160    // would have rejected the string for the same reason on a different
161    // axis. Toolkit-side helper at B.7 absorbs into `UnparseableInput`
162    // per plan §2.B.4 D29 error-mapping table.
163    for c in rest.chars() {
164        let lc = c as u8;
165        let sym = CODEX32_ALPHABET
166            .iter()
167            .position(|&b| b == lc)
168            .ok_or(Error::UnexpectedStringLength {
169                got: s.len(),
170                allowed: VALID_STR_LENGTHS,
171            })? as u8;
172        symbols.push(sym);
173    }
174    Ok(symbols)
175}
176
177/// Re-encode a 5-bit data-part symbol vector as a complete ms1 string.
178fn encode_ms1_string(data_with_checksum: &[u8]) -> String {
179    let mut out = String::with_capacity(HRP_PREFIX.len() + data_with_checksum.len());
180    out.push_str(HRP_PREFIX);
181    for &v in data_with_checksum {
182        out.push(CODEX32_ALPHABET[(v & 0x1F) as usize] as char);
183    }
184    out
185}
186
187/// BCH-error-correcting decode for a single ms1 string.
188///
189/// Per plan §1 Q1 lock — full-decode semantics: this is the single entry
190/// point that callers needing both "did anything get repaired?" AND "the
191/// fully-decoded `(Tag, Payload)`" should use.
192///
193/// Algorithm:
194/// 1. Parse the input as ms1 (`ms1` HRP + codex32 data-part) into a
195///    5-bit symbol vector.
196/// 2. Compute the BCH polymod residue
197///    (`hrp_expand("ms") || data_with_checksum`) XOR'd against
198///    [`crate::bch::MS_REGULAR_CONST`].
199/// 3. Residue `== 0` ⇒ clean codeword; pass through to the existing
200///    [`decode`] entry point unchanged.
201/// 4. Residue `!= 0` ⇒ invoke
202///    [`crate::bch_decode::decode_regular_errors`]. If `None`, return
203///    `Err(Error::TooManyErrors { bound: 8 })` per plan §2.B.4 D29
204///    error-mapping table.
205/// 5. Apply corrections to the symbol vector, re-verify via polymod (a
206///    defensive catch for pathological 5+-error patterns that fool BM
207///    into returning a degree-≤4 locator with 4 valid roots), and record
208///    one [`CorrectionDetail`] per repaired character.
209/// 6. Re-encode the corrected symbol vector as an ms1 string and forward
210///    it to the existing [`decode`] entry point.
211///
212/// Per Q1 lock + D29 error-mapping table, any §4-rule error from the
213/// full decode (orphan variants like `ThresholdNotZero`,
214/// `ReservedTagNotEmittedInV01`, etc.) surfaces directly; toolkit-side
215/// `repair_via_ms_codec` (B.7) absorbs these into
216/// `RepairError::PostCorrectionDecodeFailed`.
217///
218/// Returns `(Tag, Payload, Vec<CorrectionDetail>)` on success. The
219/// correction-detail vector is in ascending `position` order; an empty
220/// vector means the input was already a valid codeword.
221pub fn decode_with_correction(s: &str) -> Result<(Tag, Payload, Vec<CorrectionDetail>)> {
222    // Parse data-part symbols. Length checks live in `decode` proper
223    // (rule 9 is enforced there after we've potentially corrected, since
224    // BCH correction does not change the string length).
225    let symbols = parse_ms1_symbols(s)?;
226
227    // Polymod residue against ms1's target constant.
228    let mut input = crate::bch::hrp_expand("ms");
229    input.extend_from_slice(&symbols);
230    let residue = crate::bch::polymod_run(&input) ^ crate::bch::MS_REGULAR_CONST;
231
232    if residue == 0 {
233        // Already a valid codeword; pass through to the existing decoder.
234        let (tag, payload) = decode(s)?;
235        return Ok((tag, payload, Vec::new()));
236    }
237
238    // Attempt BCH correction.
239    let (positions, magnitudes) = crate::bch_decode::decode_regular_errors(residue, symbols.len())
240        .ok_or(Error::TooManyErrors { bound: 8 })?;
241
242    // Apply corrections; record (was, now) chars per position.
243    let mut corrected = symbols.clone();
244    let mut details: Vec<CorrectionDetail> = Vec::with_capacity(positions.len());
245    for (&pos, &mag) in positions.iter().zip(&magnitudes) {
246        if pos >= corrected.len() {
247            // Defensive: chien_search bounded pos to [0, L); but a
248            // pathological 5+-error pattern could in principle skirt
249            // that.
250            return Err(Error::TooManyErrors { bound: 8 });
251        }
252        let was_byte = corrected[pos];
253        let now_byte = was_byte ^ mag;
254        let was = CODEX32_ALPHABET[(was_byte & 0x1F) as usize] as char;
255        let now = CODEX32_ALPHABET[(now_byte & 0x1F) as usize] as char;
256        details.push(CorrectionDetail {
257            position: pos,
258            was,
259            now,
260        });
261        corrected[pos] = now_byte;
262    }
263
264    // Defensive re-verify (catches pathological 5+-error patterns that
265    // happen to produce a degree-≤4 locator with 4 valid roots).
266    let mut verify_input = crate::bch::hrp_expand("ms");
267    verify_input.extend_from_slice(&corrected);
268    let verify_residue =
269        crate::bch::polymod_run(&verify_input) ^ crate::bch::MS_REGULAR_CONST;
270    if verify_residue != 0 {
271        return Err(Error::TooManyErrors { bound: 8 });
272    }
273
274    // Hand the corrected string to the existing decoder. Any §4-rule
275    // error surfaces directly per Q1 lock; toolkit helper at B.7 absorbs.
276    let corrected_str = encode_ms1_string(&corrected);
277    let (tag, payload) = decode(&corrected_str)?;
278    Ok((tag, payload, details))
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::encode;
285
286    #[test]
287    fn round_trip_entr_all_lengths() {
288        for len in [16usize, 20, 24, 28, 32] {
289            let entropy = (0..len as u8)
290                .map(|i| i.wrapping_mul(7))
291                .collect::<Vec<_>>();
292            let p = Payload::Entr(entropy.clone());
293            let s = encode::encode(Tag::ENTR, &p).unwrap();
294            let (tag, recovered) = decode(&s).unwrap();
295            assert_eq!(tag, Tag::ENTR);
296            assert_eq!(recovered, p);
297        }
298    }
299
300    #[test]
301    fn decode_rejects_unexpected_length() {
302        // 52 chars is outside both the entr set [50,56,62,69,75]
303        // and the mnem set [51,58,64,70,77].
304        let s = "ms10entrsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
305        assert_eq!(s.len(), 52, "test string must be 52 chars");
306        assert!(matches!(
307            decode(s),
308            Err(Error::UnexpectedStringLength { .. })
309        ));
310    }
311
312    #[test]
313    fn decode_rejects_short_seed_string_with_reserved_tag() {
314        // Hand-build a 50-char string with id="seed" — 16-B entropy worth.
315        // The string-length check passes; tag-rule 7 fails.
316        let mut data = vec![0x00u8];
317        data.extend_from_slice(&[0xAAu8; 16]);
318        let c = Codex32String::from_seed("ms", 0, "seed", codex32::Fe::S, &data).unwrap();
319        let s = c.to_string();
320        assert_eq!(s.len(), 50, "expected str.len 50 for 16-B + prefix");
321        assert!(matches!(
322            decode(&s),
323            Err(Error::ReservedTagNotEmittedInV01 { .. })
324        ));
325    }
326}