Skip to main content

ms_codec/
inspect.rs

1//! Structural inspection of an ms1 string for debugging / future ms-cli.
2
3use crate::codex32::Codex32String;
4use crate::consts::MNEM_PREFIX;
5use crate::envelope;
6use crate::error::Result;
7use crate::tag::Tag;
8use std::fmt;
9use zeroize::Zeroizing;
10
11/// Payload kind as decoded by `inspect()`.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum InspectKind {
14    /// `entr` — raw BIP-39 entropy (0x00 prefix byte, v0.1).
15    Entr,
16    /// `mnem` — BIP-39 mnemonic entropy with language tag (0x02 prefix byte, v0.2).
17    Mnem,
18    /// Any other prefix byte — future or invalid.
19    Unknown,
20}
21
22impl InspectKind {
23    /// Kebab-case name for text/JSON output.
24    pub fn as_str(self) -> &'static str {
25        match self {
26            InspectKind::Entr => "entr",
27            InspectKind::Mnem => "mnem",
28            InspectKind::Unknown => "unknown",
29        }
30    }
31}
32
33/// Structural dump of a parsed ms1 string. `#[non_exhaustive]` per SPEC §10
34/// — v0.2+ may add fields (share-index detail, threshold-layer hints,
35/// derivation metadata).
36///
37/// `Debug` is **hand-rolled** (not derived) to redact `payload_bytes`
38/// (RULE Z-DEBUG, cycle-15 Lane M): `Zeroizing<Vec<u8>>`'s own derived `Debug`
39/// is non-redacting (forwards to `Vec`), so a derived `Debug` here would leak
40/// the raw entropy bytes. The hand-roll surfaces every *structural* field
41/// verbatim and renders the secret bytes as a length-only `[REDACTED; N]`
42/// placeholder. See the `impl fmt::Debug` below.
43#[derive(Clone)]
44#[non_exhaustive]
45pub struct InspectReport {
46    /// Expected "ms" in v0.1.
47    pub hrp: String,
48    /// Expected 0 in v0.1.
49    pub threshold: u8,
50    /// The parsed type tag (id field).
51    pub tag: Tag,
52    /// Expected 's' in v0.1.
53    pub share_index: char,
54    /// 0x00 in v0.1 (reserved); becomes type discriminator in v0.2+.
55    pub prefix_byte: u8,
56    /// Payload bytes after the prefix byte. Wrapped in `Zeroizing` so the
57    /// decoded secret entropy is scrubbed on drop (cycle-15 Lane M). The
58    /// hand-rolled `Debug` (below) redacts it; `Deref<Target=Vec<u8>>` keeps
59    /// read-only consumers (`.len()`, `hex::encode(&field)`) unchanged.
60    pub payload_bytes: Zeroizing<Vec<u8>>,
61    /// BCH verification result. True if the upstream codex32 parser accepted.
62    pub checksum_valid: bool,
63    /// Payload kind derived from the prefix byte.
64    pub kind: InspectKind,
65    /// For `kind == Mnem`: the language byte (index into `MNEM_LANGUAGE_NAMES`).
66    /// `None` for all other kinds.
67    pub language: Option<u8>,
68}
69
70impl fmt::Debug for InspectReport {
71    /// Hand-rolled redacting `Debug` (RULE Z-DEBUG): surfaces every structural
72    /// field verbatim and renders the secret `payload_bytes` as a length-only
73    /// `[REDACTED; N]` placeholder so the raw entropy can never reach a debug
74    /// dump. Mirrors the no-echo precedent on `crate::error::Error` (`error.rs`).
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_struct("InspectReport")
77            .field("hrp", &self.hrp)
78            .field("threshold", &self.threshold)
79            .field("tag", &self.tag)
80            .field("share_index", &self.share_index)
81            .field("prefix_byte", &self.prefix_byte)
82            .field(
83                "payload_bytes",
84                &format_args!("[REDACTED; {} bytes]", self.payload_bytes.len()),
85            )
86            .field("checksum_valid", &self.checksum_valid)
87            .field("kind", &self.kind)
88            .field("language", &self.language)
89            .finish()
90    }
91}
92
93/// Inspect an ms1 string. Less strict than `decode()`: returns a report even
94/// for strings that would fail decoder validity rules (e.g., wrong threshold,
95/// reserved-not-emitted tag, non-zero prefix byte) — caller can examine the
96/// fields to diagnose what's wrong. Still requires a valid BIP-93 parse.
97pub fn inspect(s: &str) -> Result<InspectReport> {
98    // `?` leverages From<crate::codex32::Error> for Error.
99    let c = Codex32String::from_string(s.to_string())?;
100    // Canonical lowercase wire copy (BIP-173 uppercase QR form folds here;
101    // codex32 already rejected mixed case). Lowercasing loses no diagnostic
102    // information — codex32 enforces whole-string uniform case, and the
103    // "surface the raw observation" intent is about non-table tag VALUES.
104    let s_owned = envelope::wire_string(&c);
105    let fields = envelope::extract_wire_fields(&s_owned)?;
106
107    // For tag construction in inspect we accept whatever bytes were on the wire
108    // (alphabet-valid or not) — surfacing the raw observation is the point.
109    let tag = match std::str::from_utf8(&fields.id_bytes) {
110        Ok(t) => Tag::try_new(t).unwrap_or_else(|_| Tag::from_raw_bytes(fields.id_bytes)),
111        Err(_) => Tag::from_raw_bytes(fields.id_bytes),
112    };
113
114    let payload_with_prefix = c.parts().data();
115    let (prefix_byte, payload_bytes) = if payload_with_prefix.is_empty() {
116        (0u8, Vec::new())
117    } else {
118        (payload_with_prefix[0], payload_with_prefix[1..].to_vec())
119    };
120
121    // Classify the payload kind and extract the language byte for mnem payloads.
122    let (kind, language) = match prefix_byte {
123        0x00 => (InspectKind::Entr, None),
124        MNEM_PREFIX => {
125            // payload_bytes = [lang_byte, entropy...]; language is the first byte.
126            let lang = payload_bytes.first().copied();
127            (InspectKind::Mnem, lang)
128        }
129        _ => (InspectKind::Unknown, None),
130    };
131
132    Ok(InspectReport {
133        hrp: fields.hrp.to_string(),
134        threshold: fields.threshold_byte - b'0', // ASCII to digit
135        tag,
136        share_index: fields.share_index_byte as char,
137        prefix_byte,
138        payload_bytes: Zeroizing::new(payload_bytes),
139        checksum_valid: true, // if from_string accepted, BCH was valid
140        kind,
141        language,
142    })
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use crate::{encode, payload::Payload};
149
150    #[test]
151    fn inspect_v01_entr_returns_expected_fields() {
152        let entropy = vec![0xAAu8; 16];
153        let s = encode::encode(Tag::ENTR, &Payload::Entr(entropy.clone())).unwrap();
154        let r = inspect(&s).unwrap();
155        assert_eq!(r.hrp, "ms");
156        assert_eq!(r.threshold, 0);
157        assert_eq!(r.tag, Tag::ENTR);
158        assert_eq!(r.share_index, 's');
159        assert_eq!(r.prefix_byte, 0x00);
160        // I-1 (cycle-15 Lane M): `payload_bytes` is now `Zeroizing<Vec<u8>>`,
161        // which has no `PartialEq<Vec<u8>>` (and `Deref` doesn't bridge `==`),
162        // so deref the field rather than deriving `PartialEq` on the secret-
163        // bearing struct.
164        assert_eq!(*r.payload_bytes, entropy);
165        assert!(r.checksum_valid);
166    }
167
168    #[test]
169    fn inspect_returns_report_for_decoder_rejects() {
170        // A non-zero-prefix string: decode() rejects, inspect() returns the report.
171        let mut data = vec![0x01u8];
172        data.extend_from_slice(&[0xAAu8; 16]);
173        let c = Codex32String::from_seed("ms", 0, "entr", crate::codex32::Fe::S, &data).unwrap();
174        let r = inspect(&c.to_string()).unwrap();
175        assert_eq!(r.prefix_byte, 0x01); // would fail decode rule 8, inspect surfaces it
176    }
177}