bhwi 0.1.0

Sans-IO Bitcoin hardware wallet interpreters and their common command model
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use crate::common::{
    Command, DeviceCode, DeviceContext, DisplayAddress, Error, ErrorKind, Info, Recipient,
    Response, Transmit, WalletRegistration,
};
use crate::ledger::apdu::{ApduCommand, ApduError, StatusWord};
use crate::ledger::store::StoreError;
use crate::ledger::{
    LedgerCommand, LedgerDisplayAddress, LedgerError, LedgerResponse, LedgerWalletPolicy, Version,
};

impl TryFrom<Command> for LedgerCommand {
    type Error = LedgerError;

    fn try_from(command: Command) -> Result<Self, Self::Error> {
        match command {
            Command::Setup(..) => Err(LedgerError::MissingCommandInfo(
                "Setup not supported by Ledger",
            )),
            Command::Wipe => Err(LedgerError::MissingCommandInfo(
                "Wipe not supported by Ledger",
            )),
            Command::Restore(..) => Err(LedgerError::MissingCommandInfo(
                "Restore not supported by Ledger",
            )),
            Command::TogglePassphrase => Err(LedgerError::MissingCommandInfo(
                "Toggle passphrase not supported by Ledger",
            )),
            Command::PromptPin | Command::SendPin(_) => Err(LedgerError::MissingCommandInfo(
                "PIN entry from the host not needed by Ledger",
            )),
            Command::Backup => Err(LedgerError::MissingCommandInfo(
                "Backup not supported by Ledger",
            )),
            Command::Unlock { options } => options
                .network
                .map(Self::OpenApp)
                .ok_or(LedgerError::MissingCommandInfo("network")),
            Command::GetMasterFingerprint => Ok(Self::GetMasterFingerprint),
            Command::GetXpub { path, display } => Ok(Self::GetXpub { path, display }),
            Command::DisplayAddress(address, context) => {
                let address = match address {
                    DisplayAddress::ByPath { path, display, .. } => {
                        LedgerDisplayAddress::ByPath { path, display }
                    }
                    DisplayAddress::ByDescriptor {
                        index,
                        change,
                        display,
                        ..
                    } => {
                        // Extract via let-else so no cfg-gated wildcard arm is needed
                        // when other device context variants are feature-gated off.
                        let Some(DeviceContext::Ledger {
                            wallet_policy: policy,
                            wallet_hmac: hmac,
                        }) = context
                        else {
                            return Err(LedgerError::MissingCommandInfo(
                                "Ledger requires DeviceContext::Ledger for descriptor-based address display",
                            ));
                        };
                        LedgerDisplayAddress::ByWalletPolicy {
                            policy,
                            hmac,
                            change,
                            address_index: index,
                            display,
                        }
                    }
                    DisplayAddress::ByMultisig(_) => {
                        return Err(LedgerError::UnsupportedDisplayAddress(
                            "Ledger raw multisig display is not implemented".into(),
                        ));
                    }
                };
                Ok(Self::GetWalletAddress { address })
            }
            Command::SignMessage { message, path } => Ok(Self::SignMessage { message, path }),
            Command::GetVersion => Ok(Self::GetAppInfo),
            Command::RegisterWallet { name, policy } => Ok(Self::RegisterWallet {
                policy: LedgerWalletPolicy::new(name, Version::V2, policy),
            }),
            Command::SignTx(psbt, context) => {
                let Some(DeviceContext::Ledger {
                    wallet_policy: policy,
                    wallet_hmac: hmac,
                }) = context
                else {
                    return Err(LedgerError::MissingCommandInfo("ledger sign tx context"));
                };
                Ok(Self::SignPsbt { psbt, policy, hmac })
            }
        }
    }
}

impl From<LedgerResponse> for Response {
    fn from(response: LedgerResponse) -> Self {
        match response {
            LedgerResponse::AppInfo(response) => {
                let network = response.network();
                Self::Info(Info {
                    version: response.version,
                    networks: vec![network],
                    firmware: Some(response.app_name),
                    initialized: None,
                    label: None,
                    on_device_passphrase_entry: None,
                    needs_pin_sent: None,
                    needs_passphrase_sent: None,
                })
            }
            LedgerResponse::Signature(header, signature) => Self::Signature(header, signature),
            LedgerResponse::TaskDone => Self::TaskDone,
            LedgerResponse::Xpub(xpub) => Self::Xpub(xpub),
            LedgerResponse::MasterFingerprint(fingerprint) => Self::MasterFingerprint(fingerprint),
            LedgerResponse::Address(address) => Self::Address(address),
            LedgerResponse::WalletHmac(hmac) => {
                Self::WalletRegistration(WalletRegistration::Complete { hmac: Some(hmac) })
            }
            LedgerResponse::SignedPsbt(psbt) => Self::SignedPsbt(psbt),
        }
    }
}

impl From<LedgerError> for Error {
    fn from(error: LedgerError) -> Self {
        match error {
            LedgerError::MissingCommandInfo(error) => Self::new(ErrorKind::Unsupported, error),
            LedgerError::NoErrorOrResult => {
                Self::new(ErrorKind::UnexpectedResponse, "no error or result returned")
            }
            LedgerError::Apdu(ApduError::StatusWordUnknown(status)) => unknown_status(status),
            LedgerError::Apdu(error) => Self::new(ErrorKind::Serialization, error.to_string()),
            LedgerError::Store(error) => Self::new(
                ErrorKind::Protocol,
                match error {
                    StoreError::EmptyInput => "Store operation failed: empty request",
                    StoreError::UnknownCommand(_) => "Store operation failed: unknown command",
                    StoreError::UnsupportedRequest(_) => {
                        "Store operation failed: unsupported request"
                    }
                    StoreError::InvalidIndexOrSize => {
                        "Store operation failed: invalid Merkle index or size"
                    }
                    StoreError::UnknownHash => "Store operation failed: unknown hash",
                    StoreError::UnknownMerkleRoot => "Store operation failed: unknown Merkle root",
                    StoreError::UnexpectedQueue => "Store operation failed: unexpected queue state",
                },
            ),
            LedgerError::Wallet(_) => Self::new(ErrorKind::Protocol, "Wallet operation failed"),
            LedgerError::Interrupted => Self::new(ErrorKind::Protocol, "Operation interrupted"),
            LedgerError::UnexpectedResult(data, context) => Self::new(
                ErrorKind::UnexpectedResponse,
                format!("unexpected response to {context}"),
            )
            .with_data(data),
            LedgerError::UnsupportedDisplayAddress(context) => {
                Self::new(ErrorKind::UnsupportedDisplayAddress, context)
            }
            LedgerError::FailedToOpenApp(_) => {
                Self::new(ErrorKind::NotReady, "Bitcoin app could not be opened")
            }
            LedgerError::Status(status, context) => Self::new(
                status_kind(status),
                LedgerError::Status(status, context).to_string(),
            )
            .with_device_code(DeviceCode::Ledger(status as u16)),
            LedgerError::AppNotReady(status, context) => Self::new(
                ErrorKind::NotReady,
                LedgerError::AppNotReady(status, context).to_string(),
            )
            .with_device_code(DeviceCode::Ledger(status as u16)),
            LedgerError::InvalidPsbt(error) => Self::new(ErrorKind::Serialization, error),
            LedgerError::UserCancelled(status) => Self::new(ErrorKind::UserCancelled, "")
                .with_device_code(DeviceCode::Ledger(status as u16)),
        }
    }
}

/// A refusal reaches here only from a command that never asks the user, so it is not a cancel.
fn status_kind(status: StatusWord) -> ErrorKind {
    match status {
        StatusWord::IncorrectData => ErrorKind::InvalidInput,
        StatusWord::NotSupported | StatusWord::InsNotSupported => ErrorKind::Unsupported,
        StatusWord::WrongP1P2 | StatusWord::WrongDataLength | StatusWord::BadState => {
            ErrorKind::Protocol
        }
        StatusWord::ClaNotSupported => ErrorKind::NotReady,
        StatusWord::SignatureFail => ErrorKind::DeviceFailure,
        StatusWord::Deny
        | StatusWord::SecurityStatusNotSatisfied
        | StatusWord::UserRefusedOnDevice
        | StatusWord::CommandNotAllowed => ErrorKind::Rejected,
        StatusWord::OK | StatusWord::InterruptedExecution => ErrorKind::Protocol,
    }
}

/// Status words from the Ledger OS rather than the Bitcoin app, so absent from its table.
fn unknown_status(status: u16) -> Error {
    let (kind, message) = match status {
        0x5515 => (ErrorKind::Locked, "Ledger device is locked".to_owned()),
        0x6511 | 0x6D02 | 0x6E01 => (ErrorKind::NotReady, "Bitcoin app is not open".to_owned()),
        0x6807 => (
            ErrorKind::NotReady,
            "Bitcoin app is not installed".to_owned(),
        ),
        _ => (
            ErrorKind::Other,
            format!("unknown status word 0x{status:04x}"),
        ),
    };
    Error::new(kind, message).with_device_code(DeviceCode::Ledger(status))
}

impl From<ApduCommand> for Transmit {
    fn from(command: ApduCommand) -> Self {
        Self {
            recipient: Recipient::Device,
            payload: command.encode(),
            encrypted: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use bitcoin::Network;
    use bitcoin::bip32::DerivationPath;
    use miniscript::descriptor::{KeyInfo, WalletPolicy};

    use super::*;
    use crate::Interpreter;
    use crate::common::LedgerInterpreter;

    const KEY: &str = "[f5acc2fd/84'/1'/0']tpubDCbK3Ysvk8HjcF6mPyrgMu3KgLiaaP19RjKpNezd8GrbAbNg6v5BtWLaCt8FNm6QkLseopKLf5MNYQFtochDTKHdfgG6iqJ8cqnLNAwtXuP";

    #[test]
    fn path_display_maps_to_ledger_native_address() {
        let path = DerivationPath::from_str("m/84'/1'/0'/0/7").unwrap();
        let command = LedgerCommand::try_from(Command::DisplayAddress(
            DisplayAddress::ByPath {
                path: path.clone(),
                display: true,
                address_format: None,
            },
            None,
        ))
        .unwrap();

        assert!(matches!(
            command,
            LedgerCommand::GetWalletAddress {
                address: LedgerDisplayAddress::ByPath {
                    path: mapped,
                    display: true,
                },
            } if mapped == path
        ));
    }

    #[test]
    fn descriptor_display_maps_context_to_wallet_policy_request() {
        let policy = LedgerWalletPolicy::new("wallet".into(), Version::V2, wallet_policy());
        let command = LedgerCommand::try_from(Command::DisplayAddress(
            DisplayAddress::ByDescriptor {
                index: 3,
                change: true,
                display: true,
                descriptor_name: "ignored-by-ledger".into(),
            },
            Some(DeviceContext::Ledger {
                wallet_policy: policy,
                wallet_hmac: Some([42; 32]),
            }),
        ))
        .unwrap();

        assert!(matches!(
            command,
            LedgerCommand::GetWalletAddress {
                address: LedgerDisplayAddress::ByWalletPolicy {
                    hmac: Some(hmac),
                    change: true,
                    address_index: 3,
                    display: true,
                    ..
                },
            } if hmac == [42; 32]
        ));
    }

    #[test]
    fn descriptor_display_requires_ledger_context() {
        let result = LedgerCommand::try_from(Command::DisplayAddress(
            DisplayAddress::ByDescriptor {
                index: 0,
                change: false,
                display: true,
                descriptor_name: "wallet".into(),
            },
            None,
        ));

        assert!(matches!(result, Err(LedgerError::MissingCommandInfo(_))));
    }

    #[test]
    fn policy_display_starts_with_wallet_address_apdu() {
        let policy = LedgerWalletPolicy::new("wallet".into(), Version::V2, wallet_policy());
        let mut interpreter = LedgerInterpreter::default();
        let transmit = interpreter
            .start(Command::DisplayAddress(
                DisplayAddress::ByDescriptor {
                    index: 0,
                    change: false,
                    display: true,
                    descriptor_name: "wallet".into(),
                },
                Some(DeviceContext::Ledger {
                    wallet_policy: policy,
                    wallet_hmac: None,
                }),
            ))
            .unwrap();

        assert_eq!(
            transmit.payload[1],
            crate::ledger::apdu::BitcoinCommandCode::GetWalletAddress as u8
        );
    }

    #[test]
    fn sign_message_refusal_status_words_map_to_user_cancelled() {
        for status in [[0x69u8, 0x85], [0x69, 0x82]] {
            let mut interpreter = LedgerInterpreter::default();
            interpreter
                .start(Command::SignMessage {
                    message: b"hello".to_vec(),
                    path: DerivationPath::from_str("m/84'/1'/0'/0/0").unwrap(),
                })
                .unwrap();
            let err = match interpreter.exchange(status.to_vec()) {
                Err(err) => err,
                Ok(_) => panic!("expected an error"),
            };
            assert_eq!(err.kind(), ErrorKind::UserCancelled, "{err:?}");
            assert_eq!(
                err.device_code(),
                Some(DeviceCode::Ledger(u16::from_be_bytes(status)))
            );
        }
    }

    fn status_error(command: Command, replies: &[Vec<u8>], status: u16) -> Error {
        let mut interpreter = LedgerInterpreter::default();
        interpreter.start(command).unwrap();
        for reply in replies {
            interpreter.exchange(reply.clone()).unwrap();
        }
        match interpreter.exchange(status.to_be_bytes().to_vec()) {
            Err(err) => err,
            Ok(_) => panic!("{status:#06x}: expected an error"),
        }
    }

    #[test]
    fn every_failed_status_keeps_its_word_and_kind() {
        let path = |s: &str| DerivationPath::from_str(s).unwrap();
        let by_path = move || {
            Command::DisplayAddress(
                DisplayAddress::ByPath {
                    path: path("m/84'/1'/0'/0/0"),
                    display: true,
                    address_format: None,
                },
                None,
            )
        };
        let fingerprint = vec![0xf5, 0xac, 0xc2, 0xfd, 0x90, 0x00];
        let mut xpub = KEY.split(']').nth(1).unwrap().as_bytes().to_vec();
        xpub.extend([0x90, 0x00]);
        type Case = (&'static str, Box<dyn Fn() -> Command>, Vec<Vec<u8>>);
        let commands: Vec<Case> = vec![
            (
                "fingerprint",
                Box::new(|| Command::GetMasterFingerprint),
                vec![],
            ),
            (
                "silent xpub",
                Box::new(move || Command::GetXpub {
                    path: path("m/84'/1'/0'"),
                    display: false,
                }),
                vec![],
            ),
            ("address fingerprint step", Box::new(by_path), vec![]),
            (
                "address xpub step",
                Box::new(by_path),
                vec![fingerprint.clone()],
            ),
            ("address step", Box::new(by_path), vec![fingerprint, xpub]),
            (
                "sign message",
                Box::new(move || Command::SignMessage {
                    message: b"hello".to_vec(),
                    path: path("m/84'/1'/0'/0/0"),
                }),
                vec![],
            ),
            (
                "register",
                Box::new(|| Command::RegisterWallet {
                    name: "wallet".into(),
                    policy: wallet_policy(),
                }),
                vec![],
            ),
        ];
        for (name, command, replies) in commands {
            for (status, kind) in [
                (0x6A80, ErrorKind::InvalidInput),
                (0x6A82, ErrorKind::Unsupported),
                (0x6A86, ErrorKind::Protocol),
                (0x6A87, ErrorKind::Protocol),
                (0x6D00, ErrorKind::Unsupported),
                (0xB007, ErrorKind::Protocol),
                (0x6901, ErrorKind::Rejected),
            ] {
                if name == "silent xpub" && status == 0x6A82 {
                    continue;
                }
                let err = status_error(command(), &replies, status);
                assert_eq!(err.kind(), kind, "{name} {status:#06x}: {err:?}");
                assert_eq!(err.device_code(), Some(DeviceCode::Ledger(status)));
                assert!(err.message().contains(&format!("{status:#06x}")), "{err}");
            }
        }
    }

    #[test]
    fn policy_display_refusal_maps_to_user_cancelled() {
        let policy = LedgerWalletPolicy::new("wallet".into(), Version::V2, wallet_policy());
        let mut interpreter = LedgerInterpreter::default();
        interpreter
            .start(Command::DisplayAddress(
                DisplayAddress::ByDescriptor {
                    index: 0,
                    change: false,
                    display: true,
                    descriptor_name: "wallet".into(),
                },
                Some(DeviceContext::Ledger {
                    wallet_policy: policy,
                    wallet_hmac: None,
                }),
            ))
            .unwrap();
        let err = match interpreter.exchange(vec![0x69, 0x85]) {
            Err(err) => err,
            Ok(_) => panic!("expected an error"),
        };
        assert_eq!(err.kind(), ErrorKind::UserCancelled, "{err:?}");
    }

    #[test]
    fn sign_psbt_refusal_maps_to_user_cancelled() {
        use bitcoin::psbt::Psbt;
        use bitcoin::{
            Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness,
            absolute::LockTime, transaction::Version as TxVersion,
        };

        let psbt = Psbt::from_unsigned_tx(Transaction {
            version: TxVersion::TWO,
            lock_time: LockTime::ZERO,
            input: vec![TxIn {
                previous_output: OutPoint::null(),
                script_sig: ScriptBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            }],
            output: vec![TxOut {
                value: Amount::from_sat(0),
                script_pubkey: ScriptBuf::new(),
            }],
        })
        .unwrap();
        let policy = LedgerWalletPolicy::new("wallet".into(), Version::V2, wallet_policy());
        let mut interpreter = LedgerInterpreter::default();
        interpreter
            .start(Command::SignTx(
                psbt,
                Some(DeviceContext::Ledger {
                    wallet_policy: policy,
                    wallet_hmac: None,
                }),
            ))
            .unwrap();
        let err = match interpreter.exchange(vec![0x69, 0x82]) {
            Err(err) => err,
            Ok(_) => panic!("expected an error"),
        };
        assert_eq!(err.kind(), ErrorKind::UserCancelled, "{err:?}");
    }

    #[test]
    fn nonstandard_xpub_path_retries_with_display() {
        let path = DerivationPath::from_str("m/0h/0h/4h").unwrap();
        let mut interpreter = LedgerInterpreter::default();

        let initial = interpreter
            .start(Command::GetXpub {
                path,
                display: false,
            })
            .unwrap();
        assert_eq!(initial.payload[5], 0);

        let retry = interpreter
            .exchange(vec![0x6a, 0x82])
            .unwrap()
            .expect("non-standard path should be retried");
        assert_eq!(retry.payload[5], 1);
    }

    fn wallet_policy() -> WalletPolicy {
        let mut policy = WalletPolicy::from_str("wpkh(@0/**)").unwrap();
        let key = KeyInfo::from_str(KEY).unwrap();
        policy.set_key_info(vec![key]).unwrap();
        policy
    }

    #[test]
    fn unlock_preserves_network_mapping() {
        assert!(matches!(
            LedgerCommand::try_from(Command::Unlock {
                options: crate::common::UnlockOptions {
                    network: Some(Network::Testnet),
                },
            }),
            Ok(LedgerCommand::OpenApp(Network::Testnet))
        ));
    }
}