Skip to main content

vector_core/transfer/
code.rs

1//! The transfer code, `<nameplate>-<word>-<word>-<word>`. The nameplate picks the meeting room
2//! and is public; the words are the secret the two devices prove to each other.
3
4use bip39::Language;
5use rand::Rng;
6use zeroize::Zeroizing;
7
8/// Secret words per code: 11 bits each from the BIP-39 English list.
9pub const WORDS: usize = 3;
10/// Nameplates run 1..=NAMEPLATE_MAX. Short to type, and only codes in use at once can meet.
11pub const NAMEPLATE_MAX: u16 = 999;
12/// What the QR carries ahead of the code. Plain text, not a link: no camera app or link handler
13/// can open it, and someone scanning it elsewhere reads a code they can type.
14pub const QR_PREFIX: &str = "Vector transfer code: ";
15
16/// Words a generated code never uses: nothing violent, intimate, insulting, or that pairs with
17/// another into something worse. A typed code still accepts every BIP-39 word.
18const AVOIDED: &[&str] = &[
19    "abuse", "accident", "accuse", "acid", "addict", "adult", "affair", "alcohol", "anger",
20    "angry", "anxiety", "armed", "arrest", "assault", "asthma", "attack", "awful", "baby", "ball",
21    "banana", "battle", "betray", "blade", "blast", "blind", "blood", "blush", "body", "bomb",
22    "bone", "bottom", "boy", "bullet", "cannon", "casino", "cherry", "chest", "child", "chronic",
23    "cigar", "crash", "crazy", "cream", "crime", "cruel", "damage", "danger", "demise", "despair",
24    "destroy", "disease", "disorder", "divorce", "dose", "drink", "dumb", "dutch", "enemy", "evil",
25    "execute", "exotic", "expose", "fat", "fatal", "female", "fever", "flush", "fury", "girl",
26    "goddess", "gorilla", "gospel", "grief", "guilt", "gun", "hazard", "hip", "hole", "horn",
27    "horror", "hurt", "husband", "illegal", "illness", "infant", "inflict", "inhale", "inject",
28    "injury", "inmate", "insane", "jealous", "kid", "kiss", "knife", "lady", "latin", "lazy",
29    "liar", "load", "lonely", "mad", "maid", "man", "meat", "misery", "monkey", "nasty", "nut",
30    "orphan", "panic", "pill", "pistol", "pole", "poverty", "prison", "punch", "ride", "rifle",
31    "riot", "romance", "rude", "sad", "sadness", "sausage", "shaft", "shoot", "sick", "siege",
32    "skin", "skull", "smoke", "sniff", "squeeze", "suffer", "suspect", "swallow", "swear", "sword",
33    "symptom", "tobacco", "toddler", "toilet", "tongue", "tragic", "trap", "trigger", "ugly",
34    "useless", "vicious", "virus", "warfare", "weapon", "weird", "wet", "whip", "wife", "wine",
35    "wink", "woman", "wreck",
36];
37/// Nameplates with a reading of their own.
38const AVOIDED_NAMEPLATES: &[u16] = &[14, 69, 88, 420, 666, 911];
39
40/// A transfer code. Debug never prints the words.
41#[derive(Clone, PartialEq, Eq)]
42pub struct Code {
43    nameplate: u16,
44    words: [u16; WORDS],
45}
46
47impl std::fmt::Debug for Code {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(f, "Code({}-…)", self.nameplate)
50    }
51}
52
53impl Code {
54    pub fn generate() -> Self {
55        let mut rng = rand::rngs::OsRng;
56        let list = Language::English.word_list();
57        // Redraw an avoided word: still uniform over the rest, and nothing kept in memory.
58        let words = std::array::from_fn(|_| loop {
59            let i = rng.gen_range(0..2048u16);
60            if !AVOIDED.contains(&list[i as usize]) {
61                break i;
62            }
63        });
64        let nameplate = loop {
65            let n = rng.gen_range(1..=NAMEPLATE_MAX);
66            if !AVOIDED_NAMEPLATES.contains(&n) {
67                break n;
68            }
69        };
70        Self { nameplate, words }
71    }
72
73    /// Read a typed or scanned code. Case and separators are forgiven, and a word may be cut to
74    /// its first four letters, which are unique in the BIP-39 list.
75    pub fn parse(input: &str) -> Result<Self, String> {
76        const BAD: &str = "That code doesn't look right. It's a number and three words, like 7-orbit-lemon-stage.";
77        let lower = input.trim().to_lowercase();
78        let body = lower.strip_prefix(&QR_PREFIX.to_lowercase()).unwrap_or(&lower);
79        let mut parts = body.split(|c: char| !c.is_alphanumeric()).filter(|p| !p.is_empty());
80        let nameplate = parts
81            .next()
82            .and_then(|p| p.parse::<u16>().ok())
83            .filter(|n| (1..=NAMEPLATE_MAX).contains(n))
84            .ok_or(BAD)?;
85        let mut words = [0u16; WORDS];
86        for slot in words.iter_mut() {
87            let part = parts.next().ok_or(BAD)?;
88            *slot = word_index(part).ok_or_else(|| format!("\"{part}\" isn't one of the code words. Check the spelling."))?;
89        }
90        if parts.next().is_some() {
91            return Err(BAD.to_string());
92        }
93        Ok(Self { nameplate, words })
94    }
95
96    pub fn nameplate(&self) -> u16 {
97        self.nameplate
98    }
99
100    /// Lowercase, full words, `-` joined: what both devices feed the PAKE.
101    pub fn canonical(&self) -> Zeroizing<String> {
102        let list = Language::English.word_list();
103        let mut out = Zeroizing::new(self.nameplate.to_string());
104        for w in self.words {
105            out.push('-');
106            out.push_str(list[w as usize]);
107        }
108        out
109    }
110
111    /// The QR payload.
112    pub fn qr(&self) -> Zeroizing<String> {
113        Zeroizing::new(format!("{QR_PREFIX}{}", self.canonical().as_str()))
114    }
115}
116
117fn word_index(part: &str) -> Option<u16> {
118    let lang = Language::English;
119    if let Some(i) = lang.find_word(part) {
120        return Some(i);
121    }
122    if part.len() < 4 {
123        return None;
124    }
125    match lang.words_by_prefix(part) {
126        [only] => lang.find_word(only),
127        _ => None,
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn a_code_reads_back_however_it_is_typed() {
137        for _ in 0..200 {
138            let code = Code::generate();
139            let canon = code.canonical();
140            assert_eq!(Code::parse(&canon).unwrap(), code);
141            assert_eq!(Code::parse(&code.qr()).unwrap(), code);
142            assert_eq!(Code::parse(&canon.replace('-', "\u{2013}")).unwrap(), code, "en dashes");
143            assert_eq!(Code::parse(&canon.replace('-', "\u{a0}")).unwrap(), code, "no-break spaces");
144            assert_eq!(Code::parse(&format!("  {}  ", canon.to_uppercase().replace('-', "  "))).unwrap(), code);
145            let short: Vec<String> = canon.split('-').map(|p| p.chars().take(4).collect()).collect();
146            assert_eq!(Code::parse(&short.join("-")).unwrap(), code, "four-letter prefixes are unique");
147        }
148    }
149
150    #[test]
151    fn a_malformed_code_is_refused() {
152        for bad in ["", "7", "7-orbit-lemon", "7-orbit-lemon-stage-vivid", "0-orbit-lemon-stage", "000-orbit-lemon-stage",
153                    "1000-orbit-lemon-stage", "x-orbit-lemon-stage", "7-orbit-lemon-notaword", "7-orb-lemon-stage",
154                    "vector://transfer#7-orbit-lemon-stage", "7-orbit-lemon-stage"] {
155            assert!(Code::parse(bad).is_err(), "{bad:?} parsed");
156        }
157    }
158
159    #[test]
160    fn a_leading_zero_or_a_word_that_prefixes_others_reads_the_same() {
161        assert_eq!(Code::parse("007-orbit-lemon-stage").unwrap().canonical().as_str(), "7-orbit-lemon-stage");
162        // "act" is a word and also begins "action": the whole word wins.
163        assert_eq!(Code::parse("7-act-act-act").unwrap().canonical().as_str(), "7-act-act-act");
164        assert_eq!(Code::parse("7-acti-lemon-stage").unwrap().canonical().as_str(), "7-action-lemon-stage");
165    }
166
167    #[test]
168    fn a_generated_code_never_uses_an_avoided_word_or_number() {
169        for w in AVOIDED {
170            assert!(Language::English.find_word(w).is_some(), "{w} isn't a BIP-39 word");
171        }
172        let usable = Language::English.word_list().iter().filter(|w| !AVOIDED.contains(w)).count();
173        assert!(usable >= 1850, "enough words left for ~32.6 bits");
174        for _ in 0..20_000 {
175            let code = Code::generate();
176            let canon = code.canonical();
177            let mut parts = canon.split('-');
178            let nameplate: u16 = parts.next().unwrap().parse().unwrap();
179            assert!(!AVOIDED_NAMEPLATES.contains(&nameplate), "{nameplate}");
180            for w in parts {
181                assert!(!AVOIDED.contains(&w), "{w}");
182            }
183        }
184        // Typing still accepts them, so a code from anywhere reads back.
185        assert!(Code::parse("7-wine-knife-gun").is_ok());
186    }
187
188    #[test]
189    fn debug_hides_the_words() {
190        let code = Code::parse("7-orbit-lemon-stage").unwrap();
191        let shown = format!("{code:?}");
192        assert!(!shown.contains("orbit") && shown.contains('7'));
193    }
194}