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 /// `combine_shares` was handed a same-id (same hrp/id/threshold/length) but
124 /// cross-polynomial share set: the first `k` shares define one polynomial,
125 /// but at least one EXTRA supplied share does not lie on it. Beyond-BIP-93
126 /// defense-in-depth (codex32 K-of-N carries no digest share) — without this
127 /// check the combine would silently return a WRONG secret. The supplied
128 /// shares are not all from the same split.
129 InconsistentShareSet,
130}
131
132impl fmt::Display for Error {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 match self {
135 // SECRET-LEAK BOUND (ms-codec-error-display-echoes-input, 0.4.4):
136 // codex32-0.1.0's `Error` is `derive(Debug)`-only (NO `Display`), so
137 // a manual variant match is mandatory. Exactly 3 of its 16 variants
138 // carry the raw input string and MUST be intercepted EXPLICITLY (no
139 // generic `{:?}` fallback for them, so a future codex32 bump can't
140 // silently route a new leaky variant through):
141 // * `InvalidChecksum { checksum, string }` — `string` is the FULL
142 // input; `checksum` is a `&'static "short"/"long"` (safe).
143 // * `MismatchedHrp(String, String)` — both dropped.
144 // * `MismatchedId(String, String)` — both dropped.
145 // (MismatchedHrp/Id are provenance-bounded SAFE for ms1 — from
146 // `interpolate_at` on valid Codex32String, hrp="ms"/id=4 chars — but
147 // dropped for robustness.) The other 13 carry only
148 // `&'static str`/`usize`/`char`/`Case`/`Fe`/`field::Error` (all
149 // ≤1 echoed char < the 8-char window) and are rendered structurally
150 // via `{:?}` on the inner error AFTER the 3 leaky arms are peeled off.
151 Error::Codex32(e) => match e {
152 codex32::Error::InvalidChecksum { checksum, .. } => {
153 write!(f, "invalid {checksum} checksum (input withheld)")
154 }
155 codex32::Error::MismatchedHrp(..) => {
156 write!(f, "mismatched HRP across shares")
157 }
158 codex32::Error::MismatchedId(..) => {
159 write!(f, "mismatched ID across shares")
160 }
161 // Safe variants only reach here (the 3 leaky ones are peeled off
162 // above), so `{:?}` of the inner error echoes no secret window.
163 safe => write!(f, "codex32 parse error: {safe:?}"),
164 },
165 Error::MnemUnknownLanguage(code) => {
166 write!(f, "unknown mnem wordlist-language code: {0}", code)
167 }
168 Error::WrongHrp { got } => write!(f, "wrong HRP: got {:?}, expected \"ms\"", got),
169 Error::ThresholdNotZero { got } => {
170 write!(
171 f,
172 "threshold not 0 (got '{}'); v0.1 is single-string only",
173 *got as char
174 )
175 }
176 Error::ShareIndexNotSecret { got } => {
177 write!(
178 f,
179 "share-index not 's' (got '{}'); BIP-93 requires 's' for threshold=0",
180 got
181 )
182 }
183 Error::TagInvalidAlphabet { got } => {
184 write!(f, "tag bytes not in codex32 alphabet: {:?}", got)
185 }
186 Error::UnknownTag { got } => write!(
187 f,
188 "unknown tag {:?}; not a member of RESERVED_TAG_TABLE",
189 std::str::from_utf8(got).unwrap_or("<non-utf8>")
190 ),
191 Error::ReservedTagNotEmittedInV01 { got } => write!(
192 f,
193 "tag {:?} reserved-not-emitted in v0.1; deferred to v0.2+",
194 std::str::from_utf8(got).unwrap_or("<non-utf8>")
195 ),
196 Error::ReservedPrefixViolation { got } => {
197 write!(f, "reserved-prefix byte was 0x{:02x}, expected 0x00", got)
198 }
199 Error::UnexpectedStringLength { got, allowed } => {
200 write!(f, "string length {} outside v0.1 set {:?}", got, allowed)
201 }
202 Error::PayloadLengthMismatch { tag, expected, got } => write!(
203 f,
204 "tag {:?} payload length {} not in expected set {:?}",
205 std::str::from_utf8(tag).unwrap_or("<non-utf8>"),
206 got,
207 expected
208 ),
209 Error::TooManyErrors { bound } => {
210 write!(f, "more than {} errors; uncorrectable", bound)
211 }
212 Error::InvalidShareCount { k, n } => write!(
213 f,
214 "invalid share count n={} for threshold k={}; require k <= n <= 31",
215 n, k
216 ),
217 Error::InvalidThreshold(k) => write!(
218 f,
219 "invalid threshold {}; K-of-N shares require k in 2..=9",
220 k
221 ),
222 Error::IsShareNotSingleString { threshold, index } => write!(
223 f,
224 "this is one share of a K-of-N set (threshold '{}', index '{}'); \
225 use `ms combine` to recombine K shares",
226 threshold, index
227 ),
228 Error::SecretShareSuppliedToCombine => write!(
229 f,
230 "the secret share (index 's') cannot be supplied to combine; \
231 supply only distributed shares (the secret is the recovery target)"
232 ),
233 Error::InconsistentShareSet => write!(
234 f,
235 "one or more shares are not from the same split; the supplied \
236 shares do not all lie on a single Shamir polynomial"
237 ),
238 }
239 }
240}
241
242impl fmt::Debug for Error {
243 /// Hand-rolled to match `Display`'s sanitization — see the type doc.
244 /// Delegates to the (non-echoing) `Display` so the leaky inner
245 /// `codex32::Error` String fields and the (already construction-bounded)
246 /// `WrongHrp.got` can never reach a derived field dump. Wrapped as
247 /// `Error("…")` so the output still reads as a debug value.
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 write!(f, "Error(\"{self}\")")
250 }
251}
252
253impl std::error::Error for Error {
254 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
255 // codex32::Error doesn't impl std::error::Error in v0.1.0; chain stops here.
256 None
257 }
258}
259
260impl From<codex32::Error> for Error {
261 fn from(e: codex32::Error) -> Self {
262 Error::Codex32(e)
263 }
264}
265
266/// Result alias for ms-codec.
267pub type Result<T> = std::result::Result<T, Error>;
268
269#[cfg(test)]
270mod no_echo_tests {
271 //! Red-first leak tests for the `ms-codec-error-display-echoes-input` fix
272 //! (0.4.4). Neither `Display` NOR `Debug` of `ms_codec::Error` may contain
273 //! any ≥8-char contiguous window of secret input, for ALL reachable inputs.
274 //! These tests construct/trigger the three leaky surfaces (codex32
275 //! `InvalidChecksum`/`MismatchedHrp`/`MismatchedId` + `WrongHrp`) and assert
276 //! the rendered strings carry no 8-char window of the secret.
277 use super::*;
278 use crate::{decode, decode_with_correction};
279
280 /// The contiguous-window length the fuzz oracle scans (8 chars = 40 bits
281 /// over the 32-symbol codex32 alphabet). Mirror it here.
282 const WINDOW: usize = 8;
283
284 /// Does `haystack` contain any ≥WINDOW-char contiguous window of `needle`?
285 fn contains_window(haystack: &str, needle: &str) -> Option<String> {
286 let n: Vec<char> = needle.chars().collect();
287 if n.len() < WINDOW {
288 return None;
289 }
290 for w in n.windows(WINDOW) {
291 let win: String = w.iter().collect();
292 if haystack.contains(&win) {
293 return Some(win);
294 }
295 }
296 None
297 }
298
299 /// Assert neither Display nor Debug of `e` carries an 8-char window of
300 /// `secret`.
301 fn assert_no_leak(e: &Error, secret: &str, label: &str) {
302 let display = format!("{e}");
303 let debug = format!("{e:?}");
304 if let Some(hit) = contains_window(&display, secret) {
305 panic!(
306 "{label}: Display leaked an {WINDOW}-char window of the secret: \
307 hit={hit:?}\n rendered: {display:?}"
308 );
309 }
310 if let Some(hit) = contains_window(&debug, secret) {
311 panic!(
312 "{label}: Debug leaked an {WINDOW}-char window of the secret: \
313 hit={hit:?}\n rendered: {debug:?}"
314 );
315 }
316 }
317
318 /// A 50-char codex32-alphabet "secret" data-part for the constructed cases.
319 const SECRET_50: &str = "qpzry9x8gf2tvdw0s3jn54khce6mua7lqpzry9x8gf2tvdw0s3";
320
321 /// (1) `Codex32(InvalidChecksum)` reached via a real `decode` — take a
322 /// valid 50-char ms1 string and flip one data char so the checksum fails.
323 /// codex32-0.1.0's `InvalidChecksum.string` carries the FULL input, so
324 /// pre-fix this leaks the whole secret data-part.
325 #[test]
326 fn codex32_invalid_checksum_from_decode_does_not_leak() {
327 // Verified-valid 50-char ms1 vector (decodes OK at HEAD).
328 let valid = "ms10entrsqgqqc83yukgh23xkvmp59xf2eldpk4cdrq2y4h82yz";
329 assert!(decode(valid).is_ok(), "fixture must decode: {:?}", decode(valid));
330 let mut chars: Vec<char> = valid.chars().collect();
331 // Flip a data char (well past the `ms10entrs` prefix) → checksum fails.
332 let i = 14;
333 chars[i] = if chars[i] == 'q' { 'p' } else { 'q' };
334 let flipped: String = chars.iter().collect();
335 let e = decode(&flipped).unwrap_err();
336 // Must be the leaky Codex32(InvalidChecksum) arm.
337 assert!(
338 matches!(e, Error::Codex32(codex32::Error::InvalidChecksum { .. })),
339 "expected Codex32(InvalidChecksum), got {e:?}"
340 );
341 // The secret is the data-part of the flipped string (after `ms1`).
342 let secret = flipped.strip_prefix("ms1").unwrap();
343 assert_no_leak(&e, secret, "codex32_invalid_checksum_from_decode");
344 }
345
346 /// (1b) `Codex32(InvalidChecksum)` constructed directly with a 50-char
347 /// secret string — the construction-side red-first cell.
348 #[test]
349 fn codex32_invalid_checksum_constructed_does_not_leak() {
350 let e = Error::Codex32(codex32::Error::InvalidChecksum {
351 checksum: "short",
352 string: format!("ms1{SECRET_50}"),
353 });
354 assert_no_leak(&e, SECRET_50, "codex32_invalid_checksum_constructed");
355 }
356
357 /// (2) `WrongHrp` reached via a real `decode_with_correction` of a
358 /// no-separator 50-char secret-shaped input — pre-fix the whole input
359 /// rides in `got` (this is the path `parse_ms1_symbols` reaches directly;
360 /// `decode`/`inspect` length/codex32-validate first and route a
361 /// codex32-alphabet 50-char string to the checksum path instead).
362 #[test]
363 fn wrong_hrp_no_separator_does_not_leak() {
364 // 50 codex32-alphabet chars, NO `'1'` separator → the whole string is
365 // the observed HRP at the construction site (capped to 4 by the fix).
366 let secret = "qpzry9x8gf2tvdw0s3jn54khce6mua7lqpzry9x8gf2tvdw0s3";
367 assert!(!secret.contains('1'), "fixture must have no '1' separator");
368 let e = decode_with_correction(secret).unwrap_err();
369 assert!(
370 matches!(e, Error::WrongHrp { .. }),
371 "expected WrongHrp, got {e:?}"
372 );
373 assert_no_leak(&e, secret, "wrong_hrp_no_separator");
374 }
375
376 /// (3) `Codex32(MismatchedHrp)` constructed directly with secret strings.
377 #[test]
378 fn codex32_mismatched_hrp_does_not_leak() {
379 let e = Error::Codex32(codex32::Error::MismatchedHrp(
380 SECRET_50.to_string(),
381 SECRET_50.to_string(),
382 ));
383 assert_no_leak(&e, SECRET_50, "codex32_mismatched_hrp");
384 }
385
386 /// (4) `Codex32(MismatchedId)` constructed directly with secret strings.
387 #[test]
388 fn codex32_mismatched_id_does_not_leak() {
389 let e = Error::Codex32(codex32::Error::MismatchedId(
390 SECRET_50.to_string(),
391 SECRET_50.to_string(),
392 ));
393 assert_no_leak(&e, SECRET_50, "codex32_mismatched_id");
394 }
395}