Skip to main content

ms_codec/
inspect.rs

1//! Structural inspection of an ms1 string for debugging / future ms-cli.
2
3use crate::consts::MNEM_PREFIX;
4use crate::envelope;
5use crate::error::Result;
6use crate::tag::Tag;
7use codex32::Codex32String;
8
9/// Payload kind as decoded by `inspect()`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum InspectKind {
12    /// `entr` — raw BIP-39 entropy (0x00 prefix byte, v0.1).
13    Entr,
14    /// `mnem` — BIP-39 mnemonic entropy with language tag (0x02 prefix byte, v0.2).
15    Mnem,
16    /// Any other prefix byte — future or invalid.
17    Unknown,
18}
19
20impl InspectKind {
21    /// Kebab-case name for text/JSON output.
22    pub fn as_str(self) -> &'static str {
23        match self {
24            InspectKind::Entr => "entr",
25            InspectKind::Mnem => "mnem",
26            InspectKind::Unknown => "unknown",
27        }
28    }
29}
30
31/// Structural dump of a parsed ms1 string. `#[non_exhaustive]` per SPEC §10
32/// — v0.2+ may add fields (share-index detail, threshold-layer hints,
33/// derivation metadata).
34#[derive(Debug, Clone)]
35#[non_exhaustive]
36pub struct InspectReport {
37    /// Expected "ms" in v0.1.
38    pub hrp: String,
39    /// Expected 0 in v0.1.
40    pub threshold: u8,
41    /// The parsed type tag (id field).
42    pub tag: Tag,
43    /// Expected 's' in v0.1.
44    pub share_index: char,
45    /// 0x00 in v0.1 (reserved); becomes type discriminator in v0.2+.
46    pub prefix_byte: u8,
47    /// Payload bytes after the prefix byte.
48    pub payload_bytes: Vec<u8>,
49    /// BCH verification result. True if the upstream codex32 parser accepted.
50    pub checksum_valid: bool,
51    /// Payload kind derived from the prefix byte.
52    pub kind: InspectKind,
53    /// For `kind == Mnem`: the language byte (index into `MNEM_LANGUAGE_NAMES`).
54    /// `None` for all other kinds.
55    pub language: Option<u8>,
56}
57
58/// Inspect an ms1 string. Less strict than `decode()`: returns a report even
59/// for strings that would fail decoder validity rules (e.g., wrong threshold,
60/// reserved-not-emitted tag, non-zero prefix byte) — caller can examine the
61/// fields to diagnose what's wrong. Still requires a valid BIP-93 parse.
62pub fn inspect(s: &str) -> Result<InspectReport> {
63    // `?` leverages From<codex32::Error> for Error.
64    let c = Codex32String::from_string(s.to_string())?;
65    let s_owned = c.to_string();
66    let fields = envelope::extract_wire_fields(&s_owned)?;
67
68    // For tag construction in inspect we accept whatever bytes were on the wire
69    // (alphabet-valid or not) — surfacing the raw observation is the point.
70    let tag = match std::str::from_utf8(&fields.id_bytes) {
71        Ok(t) => Tag::try_new(t).unwrap_or_else(|_| Tag::from_raw_bytes(fields.id_bytes)),
72        Err(_) => Tag::from_raw_bytes(fields.id_bytes),
73    };
74
75    let payload_with_prefix = c.parts().data();
76    let (prefix_byte, payload_bytes) = if payload_with_prefix.is_empty() {
77        (0u8, Vec::new())
78    } else {
79        (payload_with_prefix[0], payload_with_prefix[1..].to_vec())
80    };
81
82    // Classify the payload kind and extract the language byte for mnem payloads.
83    let (kind, language) = match prefix_byte {
84        0x00 => (InspectKind::Entr, None),
85        MNEM_PREFIX => {
86            // payload_bytes = [lang_byte, entropy...]; language is the first byte.
87            let lang = payload_bytes.first().copied();
88            (InspectKind::Mnem, lang)
89        }
90        _ => (InspectKind::Unknown, None),
91    };
92
93    Ok(InspectReport {
94        hrp: fields.hrp.to_string(),
95        threshold: fields.threshold_byte - b'0', // ASCII to digit
96        tag,
97        share_index: fields.share_index_byte as char,
98        prefix_byte,
99        payload_bytes,
100        checksum_valid: true, // if from_string accepted, BCH was valid
101        kind,
102        language,
103    })
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::{encode, payload::Payload};
110
111    #[test]
112    fn inspect_v01_entr_returns_expected_fields() {
113        let entropy = vec![0xAAu8; 16];
114        let s = encode::encode(Tag::ENTR, &Payload::Entr(entropy.clone())).unwrap();
115        let r = inspect(&s).unwrap();
116        assert_eq!(r.hrp, "ms");
117        assert_eq!(r.threshold, 0);
118        assert_eq!(r.tag, Tag::ENTR);
119        assert_eq!(r.share_index, 's');
120        assert_eq!(r.prefix_byte, 0x00);
121        assert_eq!(r.payload_bytes, entropy);
122        assert!(r.checksum_valid);
123    }
124
125    #[test]
126    fn inspect_returns_report_for_decoder_rejects() {
127        // A non-zero-prefix string: decode() rejects, inspect() returns the report.
128        let mut data = vec![0x01u8];
129        data.extend_from_slice(&[0xAAu8; 16]);
130        let c = Codex32String::from_seed("ms", 0, "entr", codex32::Fe::S, &data).unwrap();
131        let r = inspect(&c.to_string()).unwrap();
132        assert_eq!(r.prefix_byte, 0x01); // would fail decode rule 8, inspect surfaces it
133    }
134}