ms_codec/error.rs
1//! ms-codec error taxonomy. Variants mirror SPEC §4 decoder validity rules
2//! plus the encoder-side validation surface from SPEC §3.5 / §3.5.1.
3
4use std::fmt;
5
6/// ms-codec error type.
7///
8/// `Debug` is hand-implemented (NOT derived) so that neither `Display` nor
9/// `Debug` of this type can echo ≥8 contiguous chars of secret input
10/// (`ms-codec-error-display-echoes-input`, 0.4.4). A derived `Debug` would
11/// print every field — including the raw input carried by the inner
12/// `codex32::Error` (`InvalidChecksum`/`MismatchedHrp`/`MismatchedId`) and the
13/// `WrongHrp.got` HRP — so it is replaced by a delegation to the sanitized
14/// `Display`. This is load-bearing for downstream `#[derive(Debug)]` wrappers
15/// (toolkit `ToolkitError`/`CliError`) whose `{:?}` transitively renders this
16/// type via panics / `expect` / logging. Replacing the derive is NOT a SemVer
17/// break (the `Debug` IMPL is preserved; its exact output is not contractual).
18#[non_exhaustive]
19pub enum Error {
20 /// Upstream codex32 parse / checksum failure (delegated from rust-codex32).
21 Codex32(codex32::Error),
22 /// Mnem wordlist-language byte was not in the valid range 0..=9 (SPEC v0.2 §3).
23 MnemUnknownLanguage(u8),
24 /// HRP was not "ms" (SPEC §4 rule 2).
25 WrongHrp {
26 /// The HRP that was observed.
27 got: String,
28 },
29 /// Threshold was not 0 (SPEC §4 rule 3).
30 ThresholdNotZero {
31 /// The threshold-position byte (ASCII digit) that was observed.
32 got: u8,
33 },
34 /// Share-index was not 's' — BIP-93 requires 's' for threshold=0 (SPEC §4 rule 4).
35 ShareIndexNotSecret {
36 /// The share-index character that was observed.
37 got: char,
38 },
39 /// Tag bytes were not in the codex32 alphabet (SPEC §4 rule 5).
40 TagInvalidAlphabet {
41 /// The 4-byte id-field bytes that failed alphabet validation.
42 got: [u8; 4],
43 },
44 /// Tag was structurally valid but not in RESERVED_TAG_TABLE (SPEC §4 rule 6).
45 UnknownTag {
46 /// The 4-byte tag that was not recognized.
47 got: [u8; 4],
48 },
49 /// Tag was in RESERVED_TAG_TABLE but reserved-not-emitted in v0.1 (SPEC §4 rule 7,
50 /// SPEC §3.5.1 encoder symmetry).
51 ReservedTagNotEmittedInV01 {
52 /// The 4-byte reserved tag (one of seed/xprv/mnem/prvk in v0.1).
53 got: [u8; 4],
54 },
55 /// Reserved-prefix byte was not 0x00 (SPEC §4 rule 8).
56 ReservedPrefixViolation {
57 /// The non-zero prefix byte that was observed.
58 got: u8,
59 },
60 /// Total string length was outside the v0.1 emittable set (SPEC §4 rule 9).
61 UnexpectedStringLength {
62 /// The total string length that was observed.
63 got: usize,
64 /// The set of v0.1-emittable lengths.
65 allowed: &'static [usize],
66 },
67 /// Payload byte length did not match the tag's spec (SPEC §3.5, §4 rule 10).
68 PayloadLengthMismatch {
69 /// The 4-byte tag whose length set was checked against.
70 tag: [u8; 4],
71 /// The set of valid byte lengths for this tag.
72 expected: &'static [usize],
73 /// The observed payload byte length (after stripping the prefix byte).
74 got: usize,
75 },
76 /// BCH error-correction (`bch_decode`) reported the input is uncorrectable
77 /// — the number of symbol errors exceeds the regular code's `t = 4`
78 /// correction capacity (singleton bound `d = 8`). Surfaced by
79 /// [`crate::decode_with_correction`] when `bch_decode::decode_regular_errors`
80 /// returns `None`, or when a post-correction re-verification step fails
81 /// (catches pathological 5+-error patterns that fool the decoder into
82 /// producing a "consistent" but invalid locator). Added v0.2.0 per plan
83 /// §1 D29 + §2.B.2.
84 ///
85 /// `bound = 8` is the BCH(93,80,8) singleton bound. ms1 is single-chunk
86 /// only — no `chunk_index` field (cf. md-codec's `TooManyErrors` which
87 /// carries chunk-set context).
88 TooManyErrors {
89 /// Singleton bound for the BCH regular code (always 8).
90 bound: u8,
91 },
92
93 // --- v0.2 K-of-N share variants (SPEC_ms_v0_2_kofn §2) ---
94 //
95 // Inserted alphabetically AMONG THEMSELVES (the pre-existing v0.1 variants
96 // above are NOT retro-sorted — mirrors the toolkit's
97 // `error-rs-retroactive-alphabetical-sort` deferral). These carry `Display`
98 // arms only: `ms_codec::Error` has no `exit_code`/`kind` methods — the
99 // exit-code/message mapping is ms-cli's `CliError` job.
100 /// Share count `n` was outside the valid range for threshold `k` (need
101 /// `k <= n <= 31`; there are exactly 31 valid non-`s` share indices).
102 InvalidShareCount {
103 /// The threshold `k` that was requested.
104 k: u8,
105 /// The share count `n` that was requested (out of range).
106 n: usize,
107 },
108 /// Threshold `k` was not in the valid share range `2..=9`
109 /// (`Threshold::ZERO` is the unshared single-string sentinel, a const).
110 InvalidThreshold(u8),
111 /// A single-string `decode` was handed one share of a K-of-N share-set
112 /// (threshold char `2..9`). Use `ms combine` to recombine K shares.
113 IsShareNotSingleString {
114 /// The threshold char observed on the wire (`'2'..'9'`).
115 threshold: char,
116 /// The share-index char observed on the wire.
117 index: char,
118 },
119 /// `combine_shares` was handed the secret-at-S (index `s`) as an input.
120 /// The secret-at-S is the recovery target, never a combine input; codex32's
121 /// `interpolate_at` would short-circuit on it and bypass validation (C1).
122 SecretShareSuppliedToCombine,
123}
124
125impl fmt::Display for Error {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 // SECRET-LEAK BOUND (ms-codec-error-display-echoes-input, 0.4.4):
129 // codex32-0.1.0's `Error` is `derive(Debug)`-only (NO `Display`), so
130 // a manual variant match is mandatory. Exactly 3 of its 16 variants
131 // carry the raw input string and MUST be intercepted EXPLICITLY (no
132 // generic `{:?}` fallback for them, so a future codex32 bump can't
133 // silently route a new leaky variant through):
134 // * `InvalidChecksum { checksum, string }` — `string` is the FULL
135 // input; `checksum` is a `&'static "short"/"long"` (safe).
136 // * `MismatchedHrp(String, String)` — both dropped.
137 // * `MismatchedId(String, String)` — both dropped.
138 // (MismatchedHrp/Id are provenance-bounded SAFE for ms1 — from
139 // `interpolate_at` on valid Codex32String, hrp="ms"/id=4 chars — but
140 // dropped for robustness.) The other 13 carry only
141 // `&'static str`/`usize`/`char`/`Case`/`Fe`/`field::Error` (all
142 // ≤1 echoed char < the 8-char window) and are rendered structurally
143 // via `{:?}` on the inner error AFTER the 3 leaky arms are peeled off.
144 Error::Codex32(e) => match e {
145 codex32::Error::InvalidChecksum { checksum, .. } => {
146 write!(f, "invalid {checksum} checksum (input withheld)")
147 }
148 codex32::Error::MismatchedHrp(..) => {
149 write!(f, "mismatched HRP across shares")
150 }
151 codex32::Error::MismatchedId(..) => {
152 write!(f, "mismatched ID across shares")
153 }
154 // Safe variants only reach here (the 3 leaky ones are peeled off
155 // above), so `{:?}` of the inner error echoes no secret window.
156 safe => write!(f, "codex32 parse error: {safe:?}"),
157 },
158 Error::MnemUnknownLanguage(code) => {
159 write!(f, "unknown mnem wordlist-language code: {0}", code)
160 }
161 Error::WrongHrp { got } => write!(f, "wrong HRP: got {:?}, expected \"ms\"", got),
162 Error::ThresholdNotZero { got } => {
163 write!(
164 f,
165 "threshold not 0 (got '{}'); v0.1 is single-string only",
166 *got as char
167 )
168 }
169 Error::ShareIndexNotSecret { got } => {
170 write!(
171 f,
172 "share-index not 's' (got '{}'); BIP-93 requires 's' for threshold=0",
173 got
174 )
175 }
176 Error::TagInvalidAlphabet { got } => {
177 write!(f, "tag bytes not in codex32 alphabet: {:?}", got)
178 }
179 Error::UnknownTag { got } => write!(
180 f,
181 "unknown tag {:?}; not a member of RESERVED_TAG_TABLE",
182 std::str::from_utf8(got).unwrap_or("<non-utf8>")
183 ),
184 Error::ReservedTagNotEmittedInV01 { got } => write!(
185 f,
186 "tag {:?} reserved-not-emitted in v0.1; deferred to v0.2+",
187 std::str::from_utf8(got).unwrap_or("<non-utf8>")
188 ),
189 Error::ReservedPrefixViolation { got } => {
190 write!(f, "reserved-prefix byte was 0x{:02x}, expected 0x00", got)
191 }
192 Error::UnexpectedStringLength { got, allowed } => {
193 write!(f, "string length {} outside v0.1 set {:?}", got, allowed)
194 }
195 Error::PayloadLengthMismatch { tag, expected, got } => write!(
196 f,
197 "tag {:?} payload length {} not in expected set {:?}",
198 std::str::from_utf8(tag).unwrap_or("<non-utf8>"),
199 got,
200 expected
201 ),
202 Error::TooManyErrors { bound } => {
203 write!(f, "more than {} errors; uncorrectable", bound)
204 }
205 Error::InvalidShareCount { k, n } => write!(
206 f,
207 "invalid share count n={} for threshold k={}; require k <= n <= 31",
208 n, k
209 ),
210 Error::InvalidThreshold(k) => write!(
211 f,
212 "invalid threshold {}; K-of-N shares require k in 2..=9",
213 k
214 ),
215 Error::IsShareNotSingleString { threshold, index } => write!(
216 f,
217 "this is one share of a K-of-N set (threshold '{}', index '{}'); \
218 use `ms combine` to recombine K shares",
219 threshold, index
220 ),
221 Error::SecretShareSuppliedToCombine => write!(
222 f,
223 "the secret share (index 's') cannot be supplied to combine; \
224 supply only distributed shares (the secret is the recovery target)"
225 ),
226 }
227 }
228}
229
230impl fmt::Debug for Error {
231 /// Hand-rolled to match `Display`'s sanitization — see the type doc.
232 /// Delegates to the (non-echoing) `Display` so the leaky inner
233 /// `codex32::Error` String fields and the (already construction-bounded)
234 /// `WrongHrp.got` can never reach a derived field dump. Wrapped as
235 /// `Error("…")` so the output still reads as a debug value.
236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
237 write!(f, "Error(\"{self}\")")
238 }
239}
240
241impl std::error::Error for Error {
242 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
243 // codex32::Error doesn't impl std::error::Error in v0.1.0; chain stops here.
244 None
245 }
246}
247
248impl From<codex32::Error> for Error {
249 fn from(e: codex32::Error) -> Self {
250 Error::Codex32(e)
251 }
252}
253
254/// Result alias for ms-codec.
255pub type Result<T> = std::result::Result<T, Error>;
256
257#[cfg(test)]
258mod no_echo_tests {
259 //! Red-first leak tests for the `ms-codec-error-display-echoes-input` fix
260 //! (0.4.4). Neither `Display` NOR `Debug` of `ms_codec::Error` may contain
261 //! any ≥8-char contiguous window of secret input, for ALL reachable inputs.
262 //! These tests construct/trigger the three leaky surfaces (codex32
263 //! `InvalidChecksum`/`MismatchedHrp`/`MismatchedId` + `WrongHrp`) and assert
264 //! the rendered strings carry no 8-char window of the secret.
265 use super::*;
266 use crate::{decode, decode_with_correction};
267
268 /// The contiguous-window length the fuzz oracle scans (8 chars = 40 bits
269 /// over the 32-symbol codex32 alphabet). Mirror it here.
270 const WINDOW: usize = 8;
271
272 /// Does `haystack` contain any ≥WINDOW-char contiguous window of `needle`?
273 fn contains_window(haystack: &str, needle: &str) -> Option<String> {
274 let n: Vec<char> = needle.chars().collect();
275 if n.len() < WINDOW {
276 return None;
277 }
278 for w in n.windows(WINDOW) {
279 let win: String = w.iter().collect();
280 if haystack.contains(&win) {
281 return Some(win);
282 }
283 }
284 None
285 }
286
287 /// Assert neither Display nor Debug of `e` carries an 8-char window of
288 /// `secret`.
289 fn assert_no_leak(e: &Error, secret: &str, label: &str) {
290 let display = format!("{e}");
291 let debug = format!("{e:?}");
292 if let Some(hit) = contains_window(&display, secret) {
293 panic!(
294 "{label}: Display leaked an {WINDOW}-char window of the secret: \
295 hit={hit:?}\n rendered: {display:?}"
296 );
297 }
298 if let Some(hit) = contains_window(&debug, secret) {
299 panic!(
300 "{label}: Debug leaked an {WINDOW}-char window of the secret: \
301 hit={hit:?}\n rendered: {debug:?}"
302 );
303 }
304 }
305
306 /// A 50-char codex32-alphabet "secret" data-part for the constructed cases.
307 const SECRET_50: &str = "qpzry9x8gf2tvdw0s3jn54khce6mua7lqpzry9x8gf2tvdw0s3";
308
309 /// (1) `Codex32(InvalidChecksum)` reached via a real `decode` — take a
310 /// valid 50-char ms1 string and flip one data char so the checksum fails.
311 /// codex32-0.1.0's `InvalidChecksum.string` carries the FULL input, so
312 /// pre-fix this leaks the whole secret data-part.
313 #[test]
314 fn codex32_invalid_checksum_from_decode_does_not_leak() {
315 // Verified-valid 50-char ms1 vector (decodes OK at HEAD).
316 let valid = "ms10entrsqgqqc83yukgh23xkvmp59xf2eldpk4cdrq2y4h82yz";
317 assert!(decode(valid).is_ok(), "fixture must decode: {:?}", decode(valid));
318 let mut chars: Vec<char> = valid.chars().collect();
319 // Flip a data char (well past the `ms10entrs` prefix) → checksum fails.
320 let i = 14;
321 chars[i] = if chars[i] == 'q' { 'p' } else { 'q' };
322 let flipped: String = chars.iter().collect();
323 let e = decode(&flipped).unwrap_err();
324 // Must be the leaky Codex32(InvalidChecksum) arm.
325 assert!(
326 matches!(e, Error::Codex32(codex32::Error::InvalidChecksum { .. })),
327 "expected Codex32(InvalidChecksum), got {e:?}"
328 );
329 // The secret is the data-part of the flipped string (after `ms1`).
330 let secret = flipped.strip_prefix("ms1").unwrap();
331 assert_no_leak(&e, secret, "codex32_invalid_checksum_from_decode");
332 }
333
334 /// (1b) `Codex32(InvalidChecksum)` constructed directly with a 50-char
335 /// secret string — the construction-side red-first cell.
336 #[test]
337 fn codex32_invalid_checksum_constructed_does_not_leak() {
338 let e = Error::Codex32(codex32::Error::InvalidChecksum {
339 checksum: "short",
340 string: format!("ms1{SECRET_50}"),
341 });
342 assert_no_leak(&e, SECRET_50, "codex32_invalid_checksum_constructed");
343 }
344
345 /// (2) `WrongHrp` reached via a real `decode_with_correction` of a
346 /// no-separator 50-char secret-shaped input — pre-fix the whole input
347 /// rides in `got` (this is the path `parse_ms1_symbols` reaches directly;
348 /// `decode`/`inspect` length/codex32-validate first and route a
349 /// codex32-alphabet 50-char string to the checksum path instead).
350 #[test]
351 fn wrong_hrp_no_separator_does_not_leak() {
352 // 50 codex32-alphabet chars, NO `'1'` separator → the whole string is
353 // the observed HRP at the construction site (capped to 4 by the fix).
354 let secret = "qpzry9x8gf2tvdw0s3jn54khce6mua7lqpzry9x8gf2tvdw0s3";
355 assert!(!secret.contains('1'), "fixture must have no '1' separator");
356 let e = decode_with_correction(secret).unwrap_err();
357 assert!(
358 matches!(e, Error::WrongHrp { .. }),
359 "expected WrongHrp, got {e:?}"
360 );
361 assert_no_leak(&e, secret, "wrong_hrp_no_separator");
362 }
363
364 /// (3) `Codex32(MismatchedHrp)` constructed directly with secret strings.
365 #[test]
366 fn codex32_mismatched_hrp_does_not_leak() {
367 let e = Error::Codex32(codex32::Error::MismatchedHrp(
368 SECRET_50.to_string(),
369 SECRET_50.to_string(),
370 ));
371 assert_no_leak(&e, SECRET_50, "codex32_mismatched_hrp");
372 }
373
374 /// (4) `Codex32(MismatchedId)` constructed directly with secret strings.
375 #[test]
376 fn codex32_mismatched_id_does_not_leak() {
377 let e = Error::Codex32(codex32::Error::MismatchedId(
378 SECRET_50.to_string(),
379 SECRET_50.to_string(),
380 ));
381 assert_no_leak(&e, SECRET_50, "codex32_mismatched_id");
382 }
383}