lb-rs 26.11.25

The rust library for interacting with your lockbook.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use crate::model::pubkey;
use bip39_dict::Language;
use libsecp256k1::{PublicKey, SecretKey};
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::fmt::Write;

use super::errors::{LbErrKind, LbResult};

pub const MAX_USERNAME_LENGTH: usize = 32;
pub const SUB_ACCOUNT_SEPARATOR: char = '+';

/// True when `key` (after stripping whitespace) decodes as a valid v1 or v2 compact account key.
pub fn is_valid_compact_key(key: &str) -> bool {
    let compact: String = key.split_whitespace().collect();
    if compact.is_empty() {
        return false;
    }
    let Ok(bytes) = base64::decode(&compact) else {
        return false;
    };
    bincode::deserialize::<Account>(&bytes).is_ok() || SecretKey::parse_slice(&bytes).is_ok()
}

/// True when `word` (trimmed, ASCII case-insensitive) is in the English BIP-39 word list.
pub fn is_valid_phrase_word(word: &str) -> bool {
    let w = word.trim();
    if w.is_empty() {
        return false;
    }
    if bip39_dict::ENGLISH.lookup_mnemonic(w).is_ok() {
        return true;
    }
    let lower = w.to_ascii_lowercase();
    lower != w && bip39_dict::ENGLISH.lookup_mnemonic(&lower).is_ok()
}

/// How a typed prefix matches the sorted English BIP-39 word list.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PhrasePrefixMatch {
    /// Empty input.
    Empty,
    /// No BIP-39 word starts with this prefix.
    None,
    /// Exactly one BIP-39 word starts with this prefix (`word == prefix` when complete).
    Unique(&'static str),
    /// Two or more BIP-39 words start with this prefix (`exact` is true when the
    /// prefix itself is a valid word, e.g. `"art"` vs `"artist"`).
    Multiple { exact: bool },
}

fn english_bip39_words() -> &'static [&'static str] {
    static WORDS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
    WORDS
        .get_or_init(|| {
            (0..2048u16)
                .map(|i| {
                    bip39_dict::MnemonicIndex::new(i)
                        .expect("0..2048 is valid")
                        .to_word(&bip39_dict::ENGLISH)
                })
                .collect()
        })
        .as_slice()
}

/// Classify a typed prefix against the English BIP-39 word list.
pub fn match_phrase_prefix(prefix: &str) -> PhrasePrefixMatch {
    let lower = prefix.trim().to_ascii_lowercase();
    if lower.is_empty() {
        return PhrasePrefixMatch::Empty;
    }
    let words = english_bip39_words();
    let idx = words.partition_point(|&w| w < lower.as_str());
    let Some(&first) = words.get(idx) else {
        return PhrasePrefixMatch::None;
    };
    if !first.starts_with(lower.as_str()) {
        return PhrasePrefixMatch::None;
    }
    let has_second = words
        .get(idx + 1)
        .is_some_and(|w| w.starts_with(lower.as_str()));
    if has_second {
        PhrasePrefixMatch::Multiple { exact: first == lower }
    } else {
        PhrasePrefixMatch::Unique(first)
    }
}

/// A flag for which users have volunteers as beta testers.
///
/// Beta users are users to which riskier code is enabled first for testing.
/// Beta users are also users who have opted into telemetry by way of approving a PR that adds
/// their name to this list. Certainly telemetry in lockbook will always be opt in but the
/// mechanism of consent may evolve over time.
pub const BETA_USERS: &[&str] = &[
    "parth",
    "travis",
    "smail",
    "adam",
    "krish",
    "aravd",
    "lucaloncar",
    "krishma",
    "steve",
    "rahul",
    "chetna",
    "chefbowyer",
    "raayan",
    "praful",
    "paulhovey",
    "amumu",
    "coreycole",
];

/// Users who get developer-only checks, like panicking when a frame or lock overruns its budget.
pub const DEV_USERS: &[&str] = &["parth", "adam", "travis", "at"];

pub type Username = String;
pub type ApiUrl = String;

#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Account {
    pub username: Username,
    pub api_url: ApiUrl,
    #[serde(with = "secret_key_serializer")]
    pub private_key: SecretKey,
}

impl Account {
    pub fn new(username: String, api_url: String) -> Self {
        let private_key = pubkey::generate_key();
        Self { username, api_url, private_key }
    }

    pub fn public_key(&self) -> PublicKey {
        PublicKey::from_secret_key(&self.private_key)
    }

    pub fn sub_account(&self, username: Username, counter: u32) -> LbResult<Self> {
        let private_key = pubkey::derive_key(&self.private_key, counter)?;
        Ok(Self { username, api_url: self.api_url.clone(), private_key })
    }

    pub fn get_phrase(&self) -> LbResult<[&'static str; 24]> {
        let key = self.private_key.serialize();
        let key_bits = key.iter().fold(String::new(), |mut out, byte| {
            let _ = write!(out, "{byte:08b}");
            out
        });

        let checksum: String =
            sha2::Sha256::digest(&key)
                .into_iter()
                .fold(String::new(), |mut out, byte| {
                    let _ = write!(out, "{byte:08b}");
                    out
                });

        let checksum_last_4_bits = &checksum[..4];
        let combined_bits = format!("{key_bits}{checksum_last_4_bits}");

        let mut phrase: [&str; 24] = Default::default();

        for (i, chunk) in combined_bits
            .chars()
            .collect::<Vec<_>>()
            .chunks(11)
            .enumerate()
        {
            let index =
                u16::from_str_radix(&chunk.iter().collect::<String>(), 2).map_err(|_| {
                    LbErrKind::Unexpected(
                        "could not parse appropriate private key bits into u16".to_string(),
                    )
                })?;
            let word = bip39_dict::ENGLISH.lookup_word(bip39_dict::MnemonicIndex(index));

            phrase[i] = word;
        }

        Ok(phrase)
    }

    pub fn phrase_to_private_key(phrases: [&str; 24]) -> LbResult<SecretKey> {
        let mut combined_bits = phrases
            .iter()
            .map(|word| {
                bip39_dict::ENGLISH
                    .lookup_mnemonic(word)
                    .map(|index| format!("{:011b}", index.0))
            })
            .collect::<Result<String, _>>()
            .map_err(|_| LbErrKind::KeyPhraseInvalid)?;

        if combined_bits.len() != 264 {
            return Err(LbErrKind::Unexpected("the number of bits after translating the phrase does not equal the expected amount (264)".to_string()).into());
        }

        for _ in 0..4 {
            combined_bits.remove(253);
        }

        let key_bits = &combined_bits[..256];
        let checksum_last_4_bits = &combined_bits[256..260];

        let mut key: Vec<u8> = Vec::new();
        for chunk in key_bits.chars().collect::<Vec<_>>().chunks(8) {
            let comp = u8::from_str_radix(&chunk.iter().collect::<String>(), 2).map_err(|_| {
                LbErrKind::Unexpected(
                    "could not parse appropriate phrases bits into u8".to_string(),
                )
            })?;

            key.push(comp);
        }

        let gen_checksum: String =
            sha2::Sha256::digest(&key)
                .iter()
                .fold(String::new(), |mut acc, byte| {
                    acc.push_str(&format!("{byte:08b}"));
                    acc
                });

        let gen_checksum_last_4 = &gen_checksum[..4];

        if gen_checksum_last_4 != checksum_last_4_bits {
            Err(LbErrKind::KeyPhraseInvalid)?;
        }

        Ok(SecretKey::parse_slice(&key).map_err(|e| {
            error!("unexpected secretkey parse error: {e:?}");
            LbErrKind::KeyPhraseInvalid
        })?)
    }

    pub fn is_beta(&self) -> bool {
        BETA_USERS.contains(&self.username.as_str())
    }

    pub fn is_dev(&self) -> bool {
        DEV_USERS.contains(&self.username.as_str())
    }
}

pub mod secret_key_serializer {
    use libsecp256k1::SecretKey;
    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;

    pub fn serialize<S>(sk: &SecretKey, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bytes(&sk.serialize())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<SecretKey, D::Error>
    where
        D: Deserializer<'de>,
    {
        let key = <Vec<u8>>::deserialize(deserializer)?;
        let sk = SecretKey::parse_slice(&key).map_err(serde::de::Error::custom)?;
        Ok(sk)
    }
}

#[cfg(test)]
mod test_account_serialization {
    use libsecp256k1::SecretKey;
    use rand::rngs::OsRng;

    use crate::model::account::Account;

    #[test]
    fn account_serialize_deserialize() {
        let account1 = Account {
            username: "test".to_string(),
            api_url: "test.com".to_string(),
            private_key: SecretKey::random(&mut OsRng),
        };

        let encoded: Vec<u8> = bincode::serialize(&account1).unwrap();
        let account2: Account = bincode::deserialize(&encoded).unwrap();

        assert_eq!(account1, account2);
    }

    #[test]
    fn verify_account_v1() {
        let account1 = Account {
            username: "test1".to_string(),
            api_url: "test1.com".to_string(),
            private_key: SecretKey::parse_slice(&[
                19, 34, 85, 4, 36, 83, 52, 122, 49, 107, 223, 44, 31, 16, 2, 160, 100, 103, 193, 0,
                67, 15, 184, 133, 33, 111, 91, 143, 137, 232, 240, 42,
            ])
            .unwrap(),
        };

        let account2 = bincode::deserialize(
            base64::decode("BQAAAAAAAAB0ZXN0MQkAAAAAAAAAdGVzdDEuY29tIAAAAAAAAAATIlUEJFM0ejFr3ywfEAKgZGfBAEMPuIUhb1uPiejwKg==")
                .unwrap()
                .as_slice()
        ).unwrap();

        assert_eq!(account1, account2);
    }

    #[test]
    fn verify_account_v2() {
        let account1 = Account {
            username: "test1".to_string(),
            api_url: "test1.com".to_string(),
            private_key: SecretKey::parse_slice(&[
                158, 250, 59, 72, 139, 112, 93, 137, 168, 199, 28, 230, 56, 37, 43, 52, 152, 176,
                243, 149, 124, 11, 2, 126, 73, 118, 252, 112, 225, 207, 34, 90,
            ])
            .unwrap(),
        };

        let account2 = Account {
            username: "test1".to_string(),
            api_url: "test1.com".to_string(),
            private_key: SecretKey::parse_slice(
                base64::decode("nvo7SItwXYmoxxzmOCUrNJiw85V8CwJ+SXb8cOHPIlo=")
                    .unwrap()
                    .as_slice(),
            )
            .unwrap(),
        };

        assert_eq!(account1, account2);
    }

    #[test]
    fn verify_account_phrase() {
        let account1 = Account {
            username: "test1".to_string(),
            api_url: "test1.com".to_string(),
            private_key: SecretKey::parse_slice(&[
                234, 169, 139, 200, 30, 42, 176, 229, 16, 101, 229, 85, 125, 47, 182, 24, 154, 8,
                156, 233, 24, 102, 126, 171, 86, 240, 0, 175, 6, 192, 253, 231,
            ])
            .unwrap(),
        };

        let account2 = Account {
            username: "test1".to_string(),
            api_url: "test1.com".to_string(),
            private_key: Account::phrase_to_private_key([
                "turkey", "era", "velvet", "detail", "prison", "income", "dose", "royal", "fever",
                "truly", "unique", "couple", "party", "example", "piece", "art", "leaf", "follow",
                "rose", "access", "vacant", "gather", "wasp", "audit",
            ])
            .unwrap(),
        };

        assert_eq!(account1, account2)
    }
}

#[cfg(test)]
mod test_account_key_and_phrase {
    use libsecp256k1::SecretKey;
    use rand::rngs::OsRng;

    use crate::model::account::Account;

    #[test]
    fn account_key_and_phrase_eq() {
        let account1 = Account {
            username: "test".to_string(),
            api_url: "test.com".to_string(),
            private_key: SecretKey::random(&mut OsRng),
        };

        let phrase = account1.get_phrase().unwrap();

        let reverse = Account::phrase_to_private_key(phrase).unwrap();

        assert!(account1.private_key == reverse);
    }

    #[test]
    fn valid_phrase_word_checks_english_bip39() {
        use crate::model::account::is_valid_phrase_word;
        assert!(is_valid_phrase_word("abandon"));
        assert!(is_valid_phrase_word("turkey"));
        assert!(is_valid_phrase_word("  Audit "));
        assert!(!is_valid_phrase_word(""));
        assert!(!is_valid_phrase_word("   "));
        assert!(!is_valid_phrase_word("notabip39word"));
        assert!(!is_valid_phrase_word("turke"));
    }

    #[test]
    fn match_phrase_prefix_classifies_empty_none_unique_and_multiple() {
        use crate::model::account::{PhrasePrefixMatch, match_phrase_prefix};
        assert_eq!(match_phrase_prefix(""), PhrasePrefixMatch::Empty);
        assert_eq!(match_phrase_prefix("qz"), PhrasePrefixMatch::None);
        assert_eq!(match_phrase_prefix("turk"), PhrasePrefixMatch::Unique("turkey"));
        assert_eq!(match_phrase_prefix("turkey"), PhrasePrefixMatch::Unique("turkey"));
        assert_eq!(match_phrase_prefix("art"), PhrasePrefixMatch::Multiple { exact: true });
        assert_eq!(match_phrase_prefix("ar"), PhrasePrefixMatch::Multiple { exact: false });
        assert_eq!(match_phrase_prefix("artist"), PhrasePrefixMatch::Unique("artist"));
    }

    #[test]
    fn valid_compact_key_accepts_v1_v2_and_rejects_partial_or_phrase() {
        use crate::model::account::is_valid_compact_key;
        let v1 = "BQAAAAAAAAB0ZXN0MQkAAAAAAAAAdGVzdDEuY29tIAAAAAAAAAATIlUEJFM0ejFr3ywfEAKgZGfBAEMPuIUhb1uPiejwKg==";
        let v2 = "nvo7SItwXYmoxxzmOCUrNJiw85V8CwJ+SXb8cOHPIlo=";
        assert!(is_valid_compact_key(v1));
        assert!(is_valid_compact_key(v2));
        assert!(is_valid_compact_key("  nvo7SItwXYmoxxzmOCUr\nNJiw85V8CwJ+SXb8cOHPIlo=  "));
        assert!(!is_valid_compact_key(""));
        assert!(!is_valid_compact_key(&v2[..20]));
        assert!(!is_valid_compact_key("not-a-valid-key!"));
        assert!(!is_valid_compact_key(
            "turkey era velvet detail prison income dose royal fever truly unique couple party example piece art leaf follow rose access vacant gather wasp audit"
        ));
    }
}