Skip to main content

vector_core/
secrets.rs

1//! Secrets a message should never carry: a Nostr private key, a wallet's seed phrase or a
2//! wallet private key. Clients ask before sending one; only a checksum that verifies
3//! counts, so ordinary words and ids never trip it.
4
5use bip39::{Language, Mnemonic};
6use nostr_sdk::prelude::{FromBech32, SecretKey};
7use serde::Serialize;
8use sha2::{Digest, Sha256};
9
10#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
11#[serde(rename_all = "snake_case")]
12pub enum SecretKind {
13    /// An `nsec`, or the password-wrapped `ncryptsec`: the keys to a Nostr account.
14    NostrKey,
15    /// A BIP-39 recovery phrase whose checksum holds.
16    SeedPhrase,
17    /// A WIF private key or an extended private key (`xprv` and kin), checksum intact.
18    WalletKey,
19}
20
21/// Seed phrases are 12 to 24 words, in steps of three.
22const PHRASE_LENGTHS: [usize; 5] = [24, 21, 18, 15, 12];
23/// Plenty for any phrase; bounds the work on a long run of wordlist words.
24const MAX_RUN: usize = 64;
25
26/// The most sensitive secret in `text`, if any.
27pub fn detect(text: &str) -> Option<SecretKind> {
28    if has_nostr_key(text) {
29        return Some(SecretKind::NostrKey);
30    }
31    if has_wallet_key(text) {
32        return Some(SecretKind::WalletKey);
33    }
34    has_seed_phrase(text).then_some(SecretKind::SeedPhrase)
35}
36
37fn has_nostr_key(text: &str) -> bool {
38    tokens(text, |c| c.is_ascii_alphanumeric()).any(|t| {
39        let lower = t.to_ascii_lowercase();
40        (lower.starts_with("nsec1") && SecretKey::from_bech32(&lower).is_ok())
41            // Its checksum is bech32's own: length and alphabet are enough for a warning.
42            || (lower.starts_with("ncryptsec1") && lower.len() > 100 && lower[10..].bytes().all(is_bech32))
43    })
44}
45
46fn is_bech32(b: u8) -> bool {
47    matches!(b, b'0' | b'2'..=b'9' | b'a' | b'c'..=b'h' | b'j'..=b'n' | b'p'..=b'z')
48}
49
50fn has_wallet_key(text: &str) -> bool {
51    tokens(text, |c| c.is_ascii_alphanumeric()).any(|t| {
52        let n = t.len();
53        // WIF: a version byte, 32 key bytes and an optional compression flag. Extended
54        // private keys: 78 bytes, named by their prefix (xprv, yprv, zprv, tprv…).
55        let wif = (51..=52).contains(&n);
56        let extended = (110..=112).contains(&n) && t.get(1..4) == Some("prv");
57        if !wif && !extended {
58            return false;
59        }
60        match base58check(t) {
61            Some(payload) if wif => payload.len() == 33 || (payload.len() == 34 && payload[33] == 0x01),
62            Some(payload) => payload.len() == 78,
63            None => false,
64        }
65    })
66}
67
68fn has_seed_phrase(text: &str) -> bool {
69    let lang = Language::English;
70    let words: Vec<String> = tokens(text, |c| c.is_ascii_alphabetic()).map(|w| w.to_ascii_lowercase()).collect();
71    let mut run: Vec<&str> = Vec::new();
72    // A run of wordlist words long enough to hold a phrase is tried at every length and offset.
73    let check = |run: &[&str]| {
74        PHRASE_LENGTHS.iter().filter(|&&len| run.len() >= len).any(|&len| {
75            run.windows(len).any(|w| Mnemonic::parse_in_normalized(lang, &w.join(" ")).is_ok())
76        })
77    };
78    for w in &words {
79        if lang.find_word(w).is_some() && run.len() < MAX_RUN {
80            run.push(w);
81            continue;
82        }
83        if check(&run) {
84            return true;
85        }
86        run.clear();
87        if lang.find_word(w).is_some() {
88            run.push(w);
89        }
90    }
91    check(&run)
92}
93
94/// The maximal runs of characters `keep` accepts.
95fn tokens(text: &str, keep: impl Fn(char) -> bool + Copy) -> impl Iterator<Item = &str> {
96    text.split(move |c: char| !keep(c)).filter(|t| !t.is_empty())
97}
98
99const BASE58: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
100
101/// Base58 with a four-byte double-SHA256 checksum: the payload when it verifies.
102fn base58check(s: &str) -> Option<Vec<u8>> {
103    let mut bytes: Vec<u8> = Vec::with_capacity(s.len());
104    for c in s.bytes() {
105        let mut carry = BASE58.iter().position(|&b| b == c)? as u32;
106        for b in bytes.iter_mut().rev() {
107            carry += (*b as u32) * 58;
108            *b = (carry & 0xff) as u8;
109            carry >>= 8;
110        }
111        while carry > 0 {
112            bytes.insert(0, (carry & 0xff) as u8);
113            carry >>= 8;
114        }
115    }
116    let zeros = s.bytes().take_while(|&b| b == b'1').count();
117    let mut full = vec![0u8; zeros];
118    full.extend(bytes);
119    if full.len() < 5 {
120        return None;
121    }
122    let (payload, sum) = full.split_at(full.len() - 4);
123    let digest = Sha256::digest(Sha256::digest(payload));
124    (digest[..4] == *sum).then(|| payload.to_vec())
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn nostr_keys_are_found_and_lookalikes_are_not() {
133        let keys = nostr_sdk::prelude::Keys::generate();
134        let nsec = nostr_sdk::prelude::ToBech32::to_bech32(keys.secret_key()).unwrap();
135        assert_eq!(detect(&format!("here you go: {nsec} thanks")), Some(SecretKind::NostrKey));
136        assert_eq!(detect(&nsec.to_uppercase()), Some(SecretKind::NostrKey));
137        let npub = nostr_sdk::prelude::ToBech32::to_bech32(&keys.public_key()).unwrap();
138        assert_eq!(detect(&format!("my npub is {npub}")), None);
139        let mut broken = nsec.clone();
140        broken.replace_range(10..11, if &nsec[10..11] == "q" { "p" } else { "q" });
141        assert_eq!(detect(&broken), None, "a checksum that fails is not a key");
142    }
143
144    #[test]
145    fn seed_phrases_need_a_valid_checksum() {
146        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
147        assert_eq!(detect(phrase), Some(SecretKind::SeedPhrase));
148        assert_eq!(detect(&format!("backup:\n1. {}", phrase.replace(' ', "\n2. "))), Some(SecretKind::SeedPhrase));
149        assert_eq!(detect(&format!("Pls check my wallet {} ok?", phrase.to_uppercase())), Some(SecretKind::SeedPhrase));
150        let mnemonic = Mnemonic::generate_in(Language::English, 24).unwrap().to_string();
151        assert_eq!(detect(&mnemonic), Some(SecretKind::SeedPhrase));
152        // Twelve wordlist words whose checksum fails: everyday English, not a wallet.
153        assert_eq!(detect("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"), None);
154        assert_eq!(detect("we should all go to the beach this summer and have a great time with family"), None);
155    }
156
157    #[test]
158    fn wallet_keys_need_a_valid_checksum() {
159        // Well-known test vectors (mastering bitcoin): uncompressed and compressed WIF.
160        assert_eq!(detect("5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ"), Some(SecretKind::WalletKey));
161        assert_eq!(detect("key KwdMAjGmerYanjeui5SHS7JkmpZvVipYvB2LJGU1ZxJwYvP98617 there"), Some(SecretKind::WalletKey));
162        assert_eq!(detect("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"), Some(SecretKind::WalletKey));
163        // A bitcoin address is base58check too, but not a key.
164        assert_eq!(detect("send to 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"), None);
165        assert_eq!(detect("5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTX"), None, "checksum fails");
166    }
167}