pubport 0.4.0

A library for parsing hardware wallet export formats
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Parse a key expression string into a KeyExpression, we only support KeyExpressions that contain
//! an XPub, we do not support KeyExpressions that contain a private key or bare compressed or uncompressed public keys.

use bitcoin::bip32::{DerivationPath, Fingerprint, Xpub};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Clone, Serialize, Deserialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
/// A parsed key expression
pub struct KeyExpression {
    /// the public key in xpub format
    pub xpub: Xpub,

    /// the master fingerprint if present in the origin
    pub master_fingerprint: Option<Fingerprint>,

    /// the derivation path if present in the origin
    pub origin_derivation_path: Option<DerivationPath>,

    /// the derivation path if present after the xpub
    /// string to allow representing wildcard paths
    pub xpub_derivation_path: Option<String>,
}

/// Errors that can occur when parsing a key expression
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("A valid key expression must contain only ASCII digits")]
    NotAsciiDigits,

    #[error("Invalid key origin format")]
    InvalidKeyOrigin,

    #[error("Children indicator not allowed in key origin: {0}")]
    ChildrenIndicatorInKeyOrigin(String),

    #[error("Trailing slash in key origin")]
    TrailingSlashInKeyOrigin,

    #[error("Invalid fingerprint length (must be 8 characters), was {0}")]
    InvalidFingerprintLength(usize),

    #[error("Invalid hardened indicator, must be 'h' or \"'\" found {0}")]
    InvalidHardenedIndicator(char),

    #[error("Negative indices are not allowed")]
    NegativeIndices,

    #[error("Multiple key origins are not allowed")]
    MultipleKeyOrigins(String),

    #[error("Missing key origin start bracket: {0}")]
    MissingKeyOriginStart(String),

    #[error("Non-hexadecimal fingerprint: {0}")]
    NonHexFingerprint(String),

    #[error("Key origin with no public key: {0}")]
    KeyOriginWithNoPublicKey(String),

    #[error("Failed to parse Xpub: {0}")]
    XpubParseError(#[from] bitcoin::bip32::Error),

    #[error("Failed to parse derivation path: {0}")]
    DerivationPathParseError(bitcoin::bip32::Error),
}

impl KeyExpression {
    /// Parse a key expression string into a KeyExpression struct using winnow
    pub fn try_from_str(input_str: &str) -> Result<Self, Error> {
        let input_str = input_str.trim();

        if !input_str.is_ascii() {
            return Err(Error::NotAsciiDigits);
        }

        let mut parser = Parser::new(input_str);

        let (master_fingerprint, origin_path) =
            parser.parse_optional_fingerprint_and_origin_path()?;

        // check for multiple key origins
        if parser.contains('[') && parser.contains(']') {
            return Err(Error::MultipleKeyOrigins(
                parser.remaining_input.to_string(),
            ));
        }

        // check if there's a derivation path after the xpub
        let (xpub_str, derivation_path) = parser.parse_xpub_and_derivation()?;

        let xpub = Xpub::from_str(xpub_str).map_err(Error::XpubParseError)?;

        Ok(KeyExpression {
            xpub,
            master_fingerprint,
            origin_derivation_path: origin_path,
            xpub_derivation_path: derivation_path,
        })
    }
}

struct Parser<'a> {
    remaining_input: &'a str,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        Self {
            remaining_input: input,
        }
    }

    fn starts_with(&self, char: char) -> bool {
        self.remaining_input.starts_with(char)
    }

    fn contains(&self, byte: impl ToByte) -> bool {
        self.find(byte).is_some()
    }

    fn find(&self, byte: impl ToByte) -> Option<usize> {
        memchr::memchr(byte.to_byte(), self.remaining_input.as_bytes())
    }

    /// Parse the optional xpub and derivation path at the end
    fn parse_xpub_and_derivation(&mut self) -> Result<(&'a str, Option<String>), Error> {
        // check if there's a slash in the remaining input
        if let Some(slash_pos) = self.find('/') {
            // split at the slash
            let xpub_part = &self.remaining_input[..slash_pos];
            let path_part = &self.remaining_input[slash_pos + 1..];

            // process the derivation path
            // first validate it doesn't contain invalid characters
            if path_part.contains('-') {
                return Err(Error::NegativeIndices);
            }

            // for empty string, return no derivation
            if path_part.is_empty() {
                return Err(Error::TrailingSlashInKeyOrigin);
            }

            // Handle the path - we need to strip any wildcard before parsing
            let cleaned_path = path_part.replace("*h", "0h").replace("*", "0");
            let path_str = format!("m/{}", cleaned_path);

            // verify the derivation path is valid
            DerivationPath::from_str(&path_str).map_err(Error::DerivationPathParseError)?;

            let path_string = path_part.to_string();

            // update remaining input (cleared since we parsed everything)
            self.remaining_input = "";
            return Ok((xpub_part, Some(path_string)));
        }

        // no slash, so the entire remaining input is the xpub
        let xpub_part = self.remaining_input;

        // update remaining input (cleared since we parsed everything)
        self.remaining_input = "";

        Ok((xpub_part, None))
    }

    fn parse_optional_fingerprint_and_origin_path(
        &mut self,
    ) -> Result<(Option<Fingerprint>, Option<DerivationPath>), Error> {
        if !self.starts_with('[') && self.contains(']') {
            return Err(Error::MissingKeyOriginStart(
                self.remaining_input.to_string(),
            ));
        }

        if !self.remaining_input.starts_with('[') {
            return Ok((None, None));
        }

        // extract content within brackets
        let origin_content = {
            // find closing bracket
            let closing_bracket_pos = self.find(']').ok_or(Error::InvalidKeyOrigin)?;

            let inside_bracket_content = &self.remaining_input[1..closing_bracket_pos];

            // change input to the remaining content
            self.remaining_input = &self.remaining_input[closing_bracket_pos + 1..];

            // the origin is the content inside the brackets
            inside_bracket_content
        };

        // If we only have a key origin with no xpub
        if self.remaining_input.is_empty() {
            return Err(Error::KeyOriginWithNoPublicKey(origin_content.to_string()));
        }

        // split by first slash to separate fingerprint from path
        let parts: Vec<&str> = origin_content.splitn(2, '/').collect();
        let fingerprint_str = parts[0];

        // validate fingerprint
        if fingerprint_str.len() != 8 {
            return Err(Error::InvalidFingerprintLength(fingerprint_str.len()));
        }

        if !fingerprint_str.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(Error::NonHexFingerprint(fingerprint_str.to_string()));
        }

        // parse the fingerprint
        let fingerprint = Fingerprint::from_str(fingerprint_str)
            .map_err(|_| Error::NonHexFingerprint(fingerprint_str.to_string()))?;

        // no origin derivation path
        if parts.len() == 1 {
            return Ok((Some(fingerprint), None));
        }

        let path_str = parts[1];

        // validation checks
        if path_str.ends_with('/') {
            return Err(Error::TrailingSlashInKeyOrigin);
        }

        if path_str.contains('*') {
            return Err(Error::ChildrenIndicatorInKeyOrigin(path_str.to_string()));
        }

        if path_str.contains('-') {
            return Err(Error::NegativeIndices);
        }

        // check hardened indicators - allow both h and ' for hardened derivation
        for segment in path_str.split('/') {
            if !segment.is_empty() {
                let last_char = segment.chars().last().unwrap_or_default();

                // allow digits for non-hardened, or h/' for hardened
                if !last_char.is_ascii_digit() && last_char != 'h' && last_char != '\'' {
                    return Err(Error::InvalidHardenedIndicator(last_char));
                }
            }
        }

        // parse the path with m/ prefix
        let full_path_str = format!("m/{}", path_str);
        let derivation_path =
            DerivationPath::from_str(&full_path_str).map_err(Error::DerivationPathParseError)?;

        Ok((Some(fingerprint), Some(derivation_path)))
    }
}

trait ToByte {
    fn to_byte(self) -> u8;
}

impl ToByte for char {
    fn to_byte(self) -> u8 {
        self as u8
    }
}

impl ToByte for u8 {
    fn to_byte(self) -> u8 {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extended_public_key() {
        let input = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(result, KeyExpression { xpub: _, .. }));
    }

    #[test]
    fn test_extended_public_key_with_key_origin() {
        let input = "[deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                master_fingerprint: Some(_),
                origin_derivation_path: Some(_),
                xpub_derivation_path: None,
            }
        ));
    }

    #[test]
    fn test_extended_public_key_with_derivation() {
        let input = "[deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/4/5";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                master_fingerprint: Some(_),
                origin_derivation_path: Some(_),
                xpub_derivation_path: Some(_),
            }
        ));
    }

    #[test]
    fn test_extended_public_key_with_derivation_and_children() {
        let input = "[deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/4/5/*";
        let fingerprint = Fingerprint::from_str("deadbeef").unwrap();
        let derivation_path = DerivationPath::from_str("0h/1h/2h").unwrap();
        let xpub = Xpub::from_str("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL").unwrap();
        let path = "3/4/5/*".to_string();
        let result = KeyExpression::try_from_str(input).unwrap();

        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                master_fingerprint: Some(_),
                origin_derivation_path: Some(_),
                xpub_derivation_path: Some(_),
            }
        ));

        assert_eq!(result.xpub, xpub);
        assert_eq!(result.origin_derivation_path, Some(derivation_path));
        assert_eq!(result.xpub_derivation_path, Some(path));
        assert_eq!(result.master_fingerprint, Some(fingerprint));
    }

    #[test]
    fn test_extended_public_key_with_hardened_derivation_and_unhardened_children() {
        let input = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                xpub_derivation_path: Some(_),
                ..
            }
        ));
    }

    #[test]
    fn test_extended_public_key_with_hardened_derivation_and_hardened_children() {
        let input = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*h";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                xpub_derivation_path: Some(_),
                ..
            }
        ));
    }

    #[test]
    fn test_extended_public_key_with_key_origin_hardened_derivation_and_children() {
        let input = "[deadbeef/0h/1h/2]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*h";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert!(matches!(
            result,
            KeyExpression {
                xpub: _,
                master_fingerprint: Some(_),
                origin_derivation_path: Some(_),
                xpub_derivation_path: Some(_),
            }
        ));
    }

    #[test]
    fn test_invalid_children_indicator_in_key_origin() {
        let input = "[deadbeef/0h/0h/0h/*]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(
            result,
            Err(Error::ChildrenIndicatorInKeyOrigin(_))
        ));
    }

    #[test]
    fn test_invalid_trailing_slash_in_key_origin() {
        let input = "[deadbeef/0h/0h/0h/]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::TrailingSlashInKeyOrigin)));
    }

    #[test]
    fn test_invalid_too_short_fingerprint() {
        let input =
            "[deadbef/0h/0h/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::InvalidFingerprintLength(_))));
    }

    #[test]
    fn test_invalid_too_long_fingerprint() {
        let input = "[deadbeeef/0h/0h/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::InvalidFingerprintLength(_))));
    }

    #[test]
    fn test_invalid_hardened_indicators_other_letter() {
        let input =
            "[deadbeef/0z/0d/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::InvalidHardenedIndicator(_))));
    }

    #[test]
    fn test_invalid_hardened_indicators_f() {
        let input =
            "[deadbeef/0f/0f/0f]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::InvalidHardenedIndicator(_))));
    }

    #[test]
    fn test_invalid_hardened_indicators_capital_h() {
        let input =
            "[deadbeef/0H/0H/0H]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::InvalidHardenedIndicator(_))));
    }

    #[test]
    fn test_invalid_negative_indices() {
        let input =
            "[deadbeef/-0/-0/-0]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::NegativeIndices)));
    }

    #[test]
    fn test_invalid_derivation_index_out_of_range() {
        let input = "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483648";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::DerivationPathParseError(_))));
    }

    #[test]
    fn test_invalid_derivation_index_non_numeric() {
        let input = "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/1aa";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::DerivationPathParseError(_))));
    }

    #[test]
    fn test_invalid_multiple_key_origins() {
        let input = "[aaaaaaaa][aaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::MultipleKeyOrigins(_))));
    }

    #[test]
    fn test_invalid_missing_key_origin_start() {
        let input = "aaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::MissingKeyOriginStart(_))));
    }

    #[test]
    fn test_invalid_non_hex_fingerprint() {
        let input = "[gaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::NonHexFingerprint(_))));
    }

    #[test]
    fn test_invalid_key_origin_with_no_public_key() {
        let input = "[deadbeef]";
        let result = KeyExpression::try_from_str(input);
        assert!(matches!(result, Err(Error::KeyOriginWithNoPublicKey(_))));
    }

    #[test]
    fn test_correct_derivation_path() {
        let input = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/4/5";
        let result = KeyExpression::try_from_str(input).unwrap();
        assert_eq!(result.xpub_derivation_path, Some("3/4/5".to_string()));
    }

    #[test]
    fn test_nothing_after_slash() {
        let input = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/";
        assert!(matches!(
            KeyExpression::try_from_str(input),
            Err(Error::TrailingSlashInKeyOrigin)
        ));
    }

    #[test]
    fn test_correct_origin_path() {
        let input = "[deadbeef/84h/0h/0h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL";
        let result = KeyExpression::try_from_str(input).unwrap();

        let derv_path = DerivationPath::from_str("84'/0'/0'").unwrap();

        assert_eq!(result.origin_derivation_path, Some(derv_path));
        assert_eq!(result.xpub_derivation_path, None);

        let children_as_u32 = result.origin_derivation_path.unwrap().to_u32_vec();
        assert_eq!(children_as_u32, vec![84 ^ (1 << 31), (1 << 31), (1 << 31)]);
    }
}