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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! Ledger Bitcoin application commands, wallet policies, and delegated data requests.
//!
//! Common signing requires Ledger device context even when its HMAC is absent.
//! Common descriptor display also requires that context; management and backup
//! commands are unsupported, and opening an application requires a network.

pub mod command;
mod merkle;
pub mod store;

pub mod apdu;
pub mod error;
pub mod psbt;
pub mod wallet;

use std::str::FromStr;

use apdu::{ApduCommand, ApduError, ApduResponse, StatusWord};
use bitcoin::Network;
use bitcoin::bip32::{DerivationPath, Fingerprint, Xpub};
use bitcoin::consensus::encode::deserialize_partial;
use bitcoin::psbt::Psbt;
use bitcoin::secp256k1::ecdsa::Signature;
use store::{DelegatedStore, StoreError};
pub use wallet::{AddressType, LedgerWalletPolicy, Version, WalletError, singlesig_wallet_policy};

use crate::Interpreter;
use crate::device::DeviceId;

/// Ledger USB vendor and firmware usage page, with the default Speculos endpoint.
pub const LEDGER_DEVICE_ID: DeviceId = DeviceId::new(0x2c97)
    .with_usage_page(0xffa0)
    .with_emulator_path("tcp:127.0.0.1:9999");

/// Errors in Ledger command preparation and interpretation.
#[derive(Debug, thiserror::Error)]
pub enum LedgerError {
    /// Missing command context or an unsupported common operation.
    #[error("missing command info: {0}")]
    MissingCommandInfo(
        /// Missing context or unsupported-operation description.
        &'static str,
    ),

    /// An operation ended without a result.
    #[error("no error or result returned")]
    NoErrorOrResult,

    /// APDU decoding failure.
    #[error("APDU error")]
    Apdu(
        /// APDU decoder error.
        #[from]
        ApduError,
    ),

    /// Failure answering a delegated data request.
    #[error("store error")]
    Store(
        /// Delegated-store error.
        #[from]
        StoreError,
    ),

    /// Wallet policy encoding failure.
    #[error("wallet error: {0}")]
    Wallet(
        /// Wallet policy error.
        #[from]
        WalletError,
    ),

    /// A command interrupted without usable delegated state.
    #[error("operation interrupted")]
    Interrupted,

    /// Unexpected response bytes and their operation context.
    #[error("unexpected result for {1}: {0:x?}")]
    UnexpectedResult(
        /// Unexpected response bytes.
        Vec<u8>,
        /// Operation context.
        String,
    ),

    /// An unsupported address-display request.
    #[error("unsupported display address: {0}")]
    UnsupportedDisplayAddress(
        /// Unsupported-display description.
        String,
    ),

    /// Failure opening the selected Bitcoin application, with response bytes.
    #[error("failed to open app: {0:x?}")]
    FailedToOpenApp(
        /// Application-open response bytes.
        Vec<u8>,
    ),

    /// A failing status word and the operation it answered.
    #[error("{1} failed: status {0:?} ({:#06x})", *.0 as u16)]
    Status(StatusWord, &'static str),

    /// A status word saying the Bitcoin app is not open or ready.
    #[error("{1} failed, the Bitcoin app is not ready: status {0:?} ({:#06x})", *.0 as u16)]
    AppNotReady(StatusWord, &'static str),

    /// Invalid PSBT data or yielded signing result.
    #[error("invalid psbt: {0}")]
    InvalidPsbt(
        /// Invalid PSBT or signature description.
        String,
    ),

    /// User cancellation reported by the application.
    #[error("action canceled by the user")]
    UserCancelled(StatusWord),
}

/// Upstream HWI's Ledger `cancels` list: 0x6982 and 0x6985 are user
/// cancellations rather than protocol failures.
fn is_cancel(status_word: StatusWord) -> bool {
    matches!(
        status_word,
        StatusWord::Deny | StatusWord::SecurityStatusNotSatisfied | StatusWord::UserRefusedOnDevice
    )
}

impl LedgerError {
    /// Creates an error retaining response bytes and operation context.
    pub fn unexpected_result(data: Vec<u8>, context: impl Into<String>) -> Self {
        LedgerError::UnexpectedResult(data, context.into())
    }
}

/// A Ledger Bitcoin application command interpreted without transport I/O.
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum LedgerCommand {
    /// Opens `Bitcoin` for mainnet or `Bitcoin Test` for any other network.
    OpenApp(
        /// Network selecting the mainnet or test application.
        Network,
    ),
    /// Requests the running application's name, version, and flags.
    GetAppInfo,
    /// Requests the active wallet's master fingerprint.
    GetMasterFingerprint,
    /// Requests an extended public key.
    GetXpub {
        /// Key derivation path.
        path: DerivationPath,
        /// Whether to ask for confirmation on the device.
        display: bool,
    },
    /// Requests or displays a wallet address.
    GetWalletAddress {
        /// Path-derived or explicit wallet-policy address request.
        address: LedgerDisplayAddress,
    },
    /// Signs a message at the given key path.
    SignMessage {
        /// Message bytes to sign.
        message: Vec<u8>,
        /// Signing key derivation path.
        path: DerivationPath,
    },
    /// Registers a wallet policy and returns its authentication HMAC.
    RegisterWallet {
        /// Named policy to register.
        policy: LedgerWalletPolicy,
    },
    /// Signs a PSBT under an explicit wallet policy.
    SignPsbt {
        /// PSBT to sign.
        psbt: Psbt,
        /// Policy describing the signing wallet.
        policy: LedgerWalletPolicy,
        /// Registration HMAC, or `None` to send a zero HMAC for a standard policy.
        hmac: Option<[u8; 32]>,
    },
}

/// Ledger-native address request consumed by the interpreter.
///
/// A path request derives the corresponding singlesig wallet policy through
/// Ledger API calls. A policy request carries the exact inputs required by the
/// device's `GET_WALLET_ADDRESS` command.
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum LedgerDisplayAddress {
    /// A single-key policy inferred from an address path and queried device keys.
    ByPath {
        /// Purpose/coin/account/change/index path, at least five levels deep.
        path: DerivationPath,
        /// Whether to display the address on the device.
        display: bool,
    },
    /// An address derived from an explicit policy and optional registration HMAC.
    ByWalletPolicy {
        /// Wallet policy to use.
        policy: LedgerWalletPolicy,
        /// Registration HMAC, or `None` for a zero HMAC.
        hmac: Option<[u8; 32]>,
        /// Whether to use the change branch.
        change: bool,
        /// Address index within the branch.
        address_index: u32,
        /// Whether to display the address on the device.
        display: bool,
    },
}

/// Parsed response from the `GetAppInfo` APDU command.
///
/// The raw response format from the device is:
/// - 1 byte: version tag (0x01)
/// - length-prefixed string: app name
/// - length-prefixed string: app version
/// - length-prefixed bytes: state flags
#[derive(Debug, Clone)]
pub struct GetAppInfoResponse {
    /// Running application name.
    pub app_name: String,
    /// Application version string.
    pub version: String,
    /// Application state flag bytes.
    pub flags: Vec<u8>,
}

impl GetAppInfoResponse {
    /// Returns mainnet for the `Bitcoin` application, and testnet for every other name.
    pub fn network(&self) -> Network {
        if self.app_name == "Bitcoin" {
            Network::Bitcoin
        } else {
            Network::Testnet
        }
    }
}

impl TryFrom<Vec<u8>> for GetAppInfoResponse {
    type Error = String;

    fn try_from(data: Vec<u8>) -> Result<Self, Self::Error> {
        if data.is_empty() || data[0] != 0x01 {
            return Err(format!(
                "invalid version response header: expected 0x01, got {:02x}",
                data.first().map_or(0, |b| *b)
            ));
        }
        let (app_name, i): (String, usize) = deserialize_partial(&data[1..])
            .map_err(|e| format!("failed to parse app name: {e}"))?;
        let (version, j): (String, usize) = deserialize_partial(&data[1 + i..])
            .map_err(|e| format!("failed to parse version: {e}"))?;
        let (flags, _): (Vec<u8>, usize) = deserialize_partial(&data[1 + i + j..])
            .map_err(|e| format!("failed to parse flags: {e}"))?;
        Ok(GetAppInfoResponse {
            app_name,
            version,
            flags,
        })
    }
}

/// A completed Ledger command result.
pub enum LedgerResponse {
    /// Running application information.
    AppInfo(
        /// Running application information.
        GetAppInfoResponse,
    ),
    /// Master fingerprint of the active wallet.
    MasterFingerprint(
        /// Active wallet master fingerprint.
        Fingerprint,
    ),
    /// Message-signature header byte and ECDSA signature.
    Signature(
        /// Device-returned compact signature header.
        u8,
        /// Message signature.
        Signature,
    ),
    /// A terminal outcome without a returned value.
    ///
    /// Signing also returns this for [`StatusWord::SignatureFail`] or
    /// [`StatusWord::ClaNotSupported`]; it does not guarantee success.
    TaskDone,
    /// Extended public key of the requested path.
    Xpub(
        /// Requested extended public key.
        Xpub,
    ),
    /// Encoded Bitcoin address.
    Address(
        /// Encoded address text.
        String,
    ),
    /// Authentication HMAC returned by wallet registration.
    WalletHmac(
        /// Registration authentication token.
        [u8; 32],
    ),
    /// PSBT containing returned signatures.
    SignedPsbt(
        /// Updated PSBT.
        Psbt,
    ),
}

#[derive(Default)]
#[allow(clippy::large_enum_variant)]
enum State {
    #[default]
    New,
    Running {
        command: LedgerCommand,
        store: Option<DelegatedStore>,
    },
    GetWalletAddress(GetWalletAddressStep),
    Finished(LedgerResponse),
}

enum GetWalletAddressStep {
    Fingerprint {
        path: DerivationPath,
        display: bool,
    },
    Xpub {
        path: DerivationPath,
        fingerprint: Fingerprint,
        display: bool,
    },
    WalletAddress {
        store: Option<DelegatedStore>,
    },
}

/// A sans-I/O Ledger interpreter answering application data requests from a delegated store.
///
/// # Panics
///
/// Exchanging a successful message-signing response panics if its payload is empty.
pub struct LedgerInterpreter<C, T, R, E> {
    state: State,
    _marker: std::marker::PhantomData<(C, T, R, E)>,
}

impl<C, T, R, E> Default for LedgerInterpreter<C, T, R, E> {
    fn default() -> Self {
        Self {
            state: State::default(),
            _marker: std::marker::PhantomData,
        }
    }
}

fn apply_psbt_signature(psbt: &mut Psbt, yielded: &[u8]) -> Result<(), LedgerError> {
    let (input_index, yielded_object) = parse_sign_psbt_yielded(yielded)?;
    let input = psbt
        .inputs
        .get_mut(input_index)
        .ok_or_else(|| LedgerError::InvalidPsbt(format!("invalid input index {input_index}")))?;

    let SignPsbtYieldedObject::Partial(partial_signature) = yielded_object else {
        return Ok(());
    };

    match partial_signature {
        psbt::PartialSignature::Sig(pubkey, sig) => {
            input.partial_sigs.insert(pubkey, sig);
        }
        psbt::PartialSignature::TapScriptSig(pubkey, Some(leaf_hash), sig) => {
            input.tap_script_sigs.insert((pubkey, leaf_hash), sig);
        }
        psbt::PartialSignature::TapScriptSig(_, None, sig) => {
            input.tap_key_sig = Some(sig);
        }
    }
    Ok(())
}

enum SignPsbtYieldedObject {
    Partial(psbt::PartialSignature),
    Ignored,
}

fn parse_sign_psbt_yielded(data: &[u8]) -> Result<(usize, SignPsbtYieldedObject), LedgerError> {
    let (tag, read) = deserialize_unchecked_varint(data)?;
    match tag {
        // TODO: Parse and store MuSig2 yields once rust-bitcoin exposes the
        // corresponding PSBT fields.
        tag if tag >= 0x80000000 => {
            let (input_index, _) = deserialize_unchecked_varint(&data[read..])?;
            Ok((
                input_index_to_usize(input_index)?,
                SignPsbtYieldedObject::Ignored,
            ))
        }
        input_index => {
            let partial_signature =
                psbt::PartialSignature::from_slice(&data[read..]).map_err(|_| {
                    LedgerError::InvalidPsbt("invalid partial signature yield".to_string())
                })?;
            Ok((
                input_index_to_usize(input_index)?,
                SignPsbtYieldedObject::Partial(partial_signature),
            ))
        }
    }
}

fn input_index_to_usize(input_index: u64) -> Result<usize, LedgerError> {
    usize::try_from(input_index).map_err(|_| {
        LedgerError::InvalidPsbt(format!("input index does not fit usize: {input_index}"))
    })
}

fn deserialize_unchecked_varint(data: &[u8]) -> Result<(u64, usize), LedgerError> {
    let first = data
        .first()
        .ok_or_else(|| LedgerError::InvalidPsbt("missing sign_psbt yield tag".to_string()))?;
    match first {
        0x00..=0xFC => Ok((*first as u64, 1)),
        0xFD => {
            let bytes = data.get(1..3).ok_or_else(|| {
                LedgerError::InvalidPsbt("truncated sign_psbt yield varint".to_string())
            })?;
            let value = u16::from_le_bytes(bytes.try_into().expect("slice length checked")) as u64;
            if value < 0xFD {
                return Err(LedgerError::InvalidPsbt(
                    "non-minimal sign_psbt yield varint".to_string(),
                ));
            }
            Ok((value, 3))
        }
        0xFE => {
            let bytes = data.get(1..5).ok_or_else(|| {
                LedgerError::InvalidPsbt("truncated sign_psbt yield varint".to_string())
            })?;
            let value = u32::from_le_bytes(bytes.try_into().expect("slice length checked")) as u64;
            if value < 0x10000 {
                return Err(LedgerError::InvalidPsbt(
                    "non-minimal sign_psbt yield varint".to_string(),
                ));
            }
            Ok((value, 5))
        }
        0xFF => {
            let bytes = data.get(1..9).ok_or_else(|| {
                LedgerError::InvalidPsbt("truncated sign_psbt yield varint".to_string())
            })?;
            let value = u64::from_le_bytes(bytes.try_into().expect("slice length checked"));
            if value < 0x1_0000_0000 {
                return Err(LedgerError::InvalidPsbt(
                    "non-minimal sign_psbt yield varint".to_string(),
                ));
            }
            Ok((value, 9))
        }
    }
}

impl<C, T, R, E> Interpreter for LedgerInterpreter<C, T, R, E>
where
    C: TryInto<LedgerCommand, Error = LedgerError>,
    T: From<ApduCommand>,
    R: From<LedgerResponse>,
    E: From<LedgerError>,
{
    type Command = C;
    type Transmit = T;
    type Response = R;
    type Error = E;

    fn start(&mut self, command: Self::Command) -> Result<Self::Transmit, Self::Error> {
        let command: LedgerCommand = command.try_into()?;
        let (transmit, store) = match command {
            LedgerCommand::GetAppInfo => (Self::Transmit::from(command::get_version()), None),
            LedgerCommand::GetMasterFingerprint => (
                Self::Transmit::from(command::get_master_fingerprint()),
                None,
            ),
            LedgerCommand::GetXpub { ref path, display } => (
                Self::Transmit::from(command::get_extended_pubkey(path, display)),
                None,
            ),
            LedgerCommand::OpenApp(network) => {
                (Self::Transmit::from(command::open_app(network)), None)
            }
            LedgerCommand::SignMessage {
                ref message,
                ref path,
            } => {
                let message_length = message.len();
                let chunks = message.chunks(64).collect::<Vec<&[u8]>>();
                let mut store = DelegatedStore::new();
                let message_commitment_root = store.add_known_list(&chunks);
                (
                    Self::Transmit::from(command::sign_message(
                        message_length,
                        &message_commitment_root,
                        path,
                    )),
                    Some(store),
                )
            }
            LedgerCommand::GetWalletAddress { ref address } => match address {
                LedgerDisplayAddress::ByPath { path, display } => {
                    self.state = State::GetWalletAddress(GetWalletAddressStep::Fingerprint {
                        path: path.clone(),
                        display: *display,
                    });
                    return Ok(Self::Transmit::from(command::get_master_fingerprint()));
                }
                LedgerDisplayAddress::ByWalletPolicy {
                    policy,
                    hmac,
                    change,
                    address_index,
                    display,
                } => (
                    Self::Transmit::from(
                        command::get_wallet_address(
                            policy,
                            hmac.as_ref(),
                            *change,
                            *address_index,
                            *display,
                        )
                        .map_err(LedgerError::from)?,
                    ),
                    Some(policy.to_store().map_err(LedgerError::from)?),
                ),
            },
            LedgerCommand::RegisterWallet { ref policy } => (
                Self::Transmit::from(command::register_wallet(policy).map_err(LedgerError::from)?),
                Some(policy.to_store().map_err(LedgerError::from)?),
            ),
            LedgerCommand::SignPsbt {
                ref psbt,
                ref policy,
                ref hmac,
            } => {
                if psbt.inputs.len() != psbt.unsigned_tx.input.len() {
                    return Err(LedgerError::InvalidPsbt(
                        "psbt input count does not match unsigned transaction".to_string(),
                    )
                    .into());
                }
                if psbt.outputs.len() != psbt.unsigned_tx.output.len() {
                    return Err(LedgerError::InvalidPsbt(
                        "psbt output count does not match unsigned transaction".to_string(),
                    )
                    .into());
                }

                let global_map = psbt::get_v2_global_pairs(psbt)
                    .into_iter()
                    .map(psbt::deserialize_pair)
                    .collect::<Vec<_>>();
                let input_maps = psbt
                    .inputs
                    .iter()
                    .zip(&psbt.unsigned_tx.input)
                    .map(|(input, txin)| {
                        psbt::get_v2_input_pairs(input, txin)
                            .into_iter()
                            .map(psbt::deserialize_pair)
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>();
                let output_maps = psbt
                    .outputs
                    .iter()
                    .zip(&psbt.unsigned_tx.output)
                    .map(|(output, txout)| {
                        psbt::get_v2_output_pairs(output, txout)
                            .into_iter()
                            .map(psbt::deserialize_pair)
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>();

                let global_commitment = store::get_merkleized_map_commitment(&global_map);
                let input_commitments = input_maps
                    .iter()
                    .map(|map| store::get_merkleized_map_commitment(map))
                    .collect::<Vec<_>>();
                let output_commitments = output_maps
                    .iter()
                    .map(|map| store::get_merkleized_map_commitment(map))
                    .collect::<Vec<_>>();

                let mut store = policy.to_store().map_err(LedgerError::from)?;
                store.add_known_mapping(&global_map);
                for map in &input_maps {
                    store.add_known_mapping(map);
                }
                for map in &output_maps {
                    store.add_known_mapping(map);
                }
                let input_commitments_root = store.add_known_list(&input_commitments);
                let output_commitments_root = store.add_known_list(&output_commitments);

                (
                    Self::Transmit::from(
                        command::sign_psbt(
                            &global_commitment,
                            psbt.inputs.len(),
                            &input_commitments_root,
                            psbt.outputs.len(),
                            &output_commitments_root,
                            policy,
                            hmac.as_ref(),
                        )
                        .map_err(LedgerError::from)?,
                    ),
                    Some(store),
                )
            }
        };
        self.state = State::Running { command, store };
        Ok(transmit)
    }

    fn exchange(&mut self, data: Vec<u8>) -> Result<Option<Self::Transmit>, Self::Error> {
        let res = ApduResponse::try_from(data).map_err(LedgerError::from)?;
        let state = std::mem::take(&mut self.state);
        let (next_state, result) = match state {
            State::GetWalletAddress(GetWalletAddressStep::Fingerprint { path, display }) => {
                if res.status_word != StatusWord::OK {
                    return Err(LedgerError::Status(
                        res.status_word,
                        "display address: master fingerprint",
                    )
                    .into());
                }
                if res.data.len() < 4 {
                    return Err(LedgerError::unexpected_result(
                        res.data,
                        "display address: master fingerprint",
                    )
                    .into());
                }
                let mut fg = [0x00; 4];
                fg.copy_from_slice(&res.data[0..4]);
                let fingerprint = Fingerprint::from(fg);
                let children: Vec<_> = path.as_ref().to_vec();
                if children.len() < 5 {
                    return Err(LedgerError::UnsupportedDisplayAddress(
                        "Ledger requires a full 5-level derivation path (e.g. m/84'/0'/0'/0/0)"
                            .into(),
                    )
                    .into());
                }
                let account_path = DerivationPath::from(children[..3].to_vec());
                let cmd = Self::Transmit::from(command::get_extended_pubkey(&account_path, false));
                (
                    State::GetWalletAddress(GetWalletAddressStep::Xpub {
                        path,
                        fingerprint,
                        display,
                    }),
                    Some(cmd),
                )
            }
            State::GetWalletAddress(GetWalletAddressStep::Xpub {
                path,
                fingerprint,
                display,
            }) => {
                if res.status_word != StatusWord::OK {
                    return Err(
                        LedgerError::Status(res.status_word, "display address: xpub").into(),
                    );
                }
                let xpub = Xpub::from_str(&String::from_utf8_lossy(&res.data)).map_err(|_| {
                    LedgerError::unexpected_result(res.data, "display address: xpub")
                })?;
                let children: Vec<_> = path.as_ref().to_vec();
                let change =
                    children[3] == bitcoin::bip32::ChildNumber::from_normal_idx(1).unwrap();
                let address_index = u32::from(children[4]);
                let policy =
                    singlesig_wallet_policy(&path, fingerprint, xpub).map_err(LedgerError::from)?;
                let ledger_policy = LedgerWalletPolicy::new(String::new(), Version::V2, policy);
                let store = Some(ledger_policy.to_store().map_err(LedgerError::from)?);
                let cmd = Self::Transmit::from(
                    command::get_wallet_address(
                        &ledger_policy,
                        None,
                        change,
                        address_index,
                        display,
                    )
                    .map_err(LedgerError::from)?,
                );
                (
                    State::GetWalletAddress(GetWalletAddressStep::WalletAddress { store }),
                    Some(cmd),
                )
            }
            State::GetWalletAddress(GetWalletAddressStep::WalletAddress { mut store }) => {
                if is_cancel(res.status_word) {
                    return Err(LedgerError::UserCancelled(res.status_word).into());
                } else if res.status_word == StatusWord::InterruptedExecution {
                    if let Some(ref mut s) = store {
                        let transmit = s.execute(res.data).map_err(LedgerError::from)?;
                        let cmd = Self::Transmit::from(command::continue_interrupted(transmit));
                        self.state =
                            State::GetWalletAddress(GetWalletAddressStep::WalletAddress { store });
                        return Ok(Some(cmd));
                    } else {
                        return Err(LedgerError::Interrupted.into());
                    }
                } else if res.status_word != StatusWord::OK {
                    return Err(LedgerError::Status(res.status_word, "display address").into());
                } else {
                    let address = String::from_utf8(res.data)
                        .map_err(|e| LedgerError::unexpected_result(vec![], e.to_string()))?;
                    (State::Finished(LedgerResponse::Address(address)), None)
                }
            }
            State::Running { mut store, command } => {
                if res.status_word == StatusWord::InterruptedExecution {
                    if let Some(ref mut s) = store {
                        let transmit = s.execute(res.data).map_err(LedgerError::from)?;
                        let cmd = Self::Transmit::from(command::continue_interrupted(transmit));
                        self.state = State::Running { store, command };
                        return Ok(Some(cmd));
                    } else {
                        return Err(LedgerError::Interrupted.into());
                    }
                }
                match command {
                    LedgerCommand::GetAppInfo => {
                        if res.status_word != StatusWord::OK {
                            return Err(
                                LedgerError::AppNotReady(res.status_word, "get version").into()
                            );
                        }
                        let response = GetAppInfoResponse::try_from(res.data.clone())
                            .map_err(|e| LedgerError::unexpected_result(res.data, e))?;
                        (State::Finished(LedgerResponse::AppInfo(response)), None)
                    }
                    LedgerCommand::GetMasterFingerprint => {
                        if res.status_word != StatusWord::OK {
                            return Err(
                                LedgerError::Status(res.status_word, "master fingerprint").into()
                            );
                        }
                        if res.data.len() < 4 {
                            return Err(LedgerError::unexpected_result(
                                res.data,
                                "master fingerprint response",
                            )
                            .into());
                        } else {
                            let mut fg = [0x00; 4];
                            fg.copy_from_slice(&res.data[0..4]);
                            (
                                State::Finished(LedgerResponse::MasterFingerprint(
                                    Fingerprint::from(fg),
                                )),
                                None,
                            )
                        }
                    }
                    LedgerCommand::GetXpub {
                        ref path,
                        display: false,
                    } if res.status_word == StatusWord::NotSupported => {
                        // Ledger rejects non-standard derivation paths when the xpub is
                        // requested silently. As in Python HWI's `get_pubkey_at_path`, retry
                        // with display enabled so the user can approve the unusual path.
                        let retry = LedgerCommand::GetXpub {
                            path: path.clone(),
                            display: true,
                        };
                        let transmit =
                            Self::Transmit::from(command::get_extended_pubkey(path, true));
                        self.state = State::Running {
                            store: None,
                            command: retry,
                        };
                        return Ok(Some(transmit));
                    }
                    LedgerCommand::GetXpub { display, .. } => {
                        if display && is_cancel(res.status_word) {
                            return Err(LedgerError::UserCancelled(res.status_word).into());
                        }
                        if res.status_word != StatusWord::OK {
                            return Err(LedgerError::Status(
                                res.status_word,
                                "get extended pubkey",
                            )
                            .into());
                        }
                        let xpub = Xpub::from_str(&String::from_utf8_lossy(&res.data))
                            .map_err(|_| LedgerError::unexpected_result(res.data, "xpub string"))?;
                        (State::Finished(LedgerResponse::Xpub(xpub)), None)
                    }
                    LedgerCommand::OpenApp(..) => {
                        if is_cancel(res.status_word) {
                            return Err(LedgerError::UserCancelled(res.status_word).into());
                        }
                        if matches!(
                            res.status_word,
                            StatusWord::OK | StatusWord::ClaNotSupported
                        ) {
                            (State::Finished(LedgerResponse::TaskDone), None)
                        } else {
                            return Err(
                                LedgerError::AppNotReady(res.status_word, "open app").into()
                            );
                        }
                    }
                    LedgerCommand::SignMessage { .. } => match res.status_word {
                        status if is_cancel(status) => {
                            return Err(LedgerError::UserCancelled(status).into());
                        }
                        StatusWord::ClaNotSupported | StatusWord::SignatureFail => {
                            (State::Finished(LedgerResponse::TaskDone), None)
                        }
                        StatusWord::OK => {
                            let header = res.data[0];
                            let sig = Signature::from_compact(&res.data[1..]).map_err(|_| {
                                LedgerError::unexpected_result(res.data, "signature compact data")
                            })?;
                            (
                                State::Finished(LedgerResponse::Signature(header, sig)),
                                None,
                            )
                        }
                        status => {
                            return Err(LedgerError::Status(status, "sign message").into());
                        }
                    },
                    LedgerCommand::GetWalletAddress { .. } => {
                        if is_cancel(res.status_word) {
                            return Err(LedgerError::UserCancelled(res.status_word).into());
                        } else if res.status_word == StatusWord::OK {
                            let address = String::from_utf8(res.data).map_err(|e| {
                                LedgerError::unexpected_result(vec![], e.to_string())
                            })?;
                            (State::Finished(LedgerResponse::Address(address)), None)
                        } else {
                            return Err(
                                LedgerError::Status(res.status_word, "display address").into()
                            );
                        }
                    }
                    LedgerCommand::RegisterWallet { .. } => {
                        if is_cancel(res.status_word) {
                            return Err(LedgerError::UserCancelled(res.status_word).into());
                        }
                        if res.status_word != StatusWord::OK {
                            return Err(
                                LedgerError::Status(res.status_word, "register wallet").into()
                            );
                        }
                        if res.data.len() < 64 {
                            return Err(LedgerError::unexpected_result(
                                res.data,
                                "register wallet: response too short",
                            )
                            .into());
                        }
                        let mut hmac = [0u8; 32];
                        hmac.copy_from_slice(&res.data[32..64]);
                        (State::Finished(LedgerResponse::WalletHmac(hmac)), None)
                    }
                    LedgerCommand::SignPsbt { mut psbt, .. } => match res.status_word {
                        status if is_cancel(status) => {
                            return Err(LedgerError::UserCancelled(status).into());
                        }
                        StatusWord::ClaNotSupported | StatusWord::SignatureFail => {
                            (State::Finished(LedgerResponse::TaskDone), None)
                        }
                        StatusWord::OK => {
                            let store = store.ok_or(LedgerError::Interrupted)?;
                            for yielded in store.yielded() {
                                apply_psbt_signature(&mut psbt, &yielded)?;
                            }
                            (State::Finished(LedgerResponse::SignedPsbt(psbt)), None)
                        }
                        status => {
                            return Err(LedgerError::Status(status, "sign psbt").into());
                        }
                    },
                }
            }
            State::New => (State::New, None),
            State::Finished(_) => (state, None),
        };
        self.state = next_state;
        Ok(result)
    }

    fn end(self) -> Result<Self::Response, Self::Error> {
        if let State::Finished(res) = self.state {
            Ok(Self::Response::from(res))
        } else {
            Err(LedgerError::NoErrorOrResult.into())
        }
    }
}

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

    const XONLY: [u8; 32] = [
        0x4f, 0x35, 0x5b, 0xdc, 0xb7, 0xcc, 0x0a, 0xf7, 0x28, 0xef, 0x3c, 0xce, 0xb9, 0x61, 0x5d,
        0x90, 0x68, 0x4b, 0xb5, 0xb2, 0xca, 0x5f, 0x85, 0x9a, 0xb0, 0xf0, 0xb7, 0x04, 0x07, 0x58,
        0x71, 0xaa,
    ];

    fn encode_unchecked_varint(value: u64) -> Vec<u8> {
        match value {
            0..=0xFC => vec![value as u8],
            0xFD..=0xFFFF => {
                let mut out = vec![0xFD];
                out.extend_from_slice(&(value as u16).to_le_bytes());
                out
            }
            0x1_0000..=0xFFFF_FFFF => {
                let mut out = vec![0xFE];
                out.extend_from_slice(&(value as u32).to_le_bytes());
                out
            }
            _ => {
                let mut out = vec![0xFF];
                out.extend_from_slice(&value.to_le_bytes());
                out
            }
        }
    }

    fn assert_ignored(payload: &[u8], expected_input_index: usize) {
        let (input_index, object) = parse_sign_psbt_yielded(payload).expect("payload should parse");
        assert_eq!(input_index, expected_input_index);
        assert!(matches!(object, SignPsbtYieldedObject::Ignored));
    }

    #[test]
    fn parse_legacy_partial_taproot_without_tapleaf() {
        let mut payload = encode_unchecked_varint(3);
        payload.push(32);
        payload.extend_from_slice(&XONLY);
        payload.extend_from_slice(&[0xaa; 64]);

        let (input_index, object) =
            parse_sign_psbt_yielded(&payload).expect("payload should parse");
        assert_eq!(input_index, 3);
        assert!(matches!(
            object,
            SignPsbtYieldedObject::Partial(psbt::PartialSignature::TapScriptSig(_, None, _))
        ));
    }

    #[test]
    fn parse_reserved_musig_pubnonce_tag_is_ignored() {
        let mut payload = encode_unchecked_varint(0xFFFF_FFFF);
        payload.extend(encode_unchecked_varint(7));
        payload.extend_from_slice(&[0xaa; 164]);

        assert_ignored(&payload, 7);
    }

    #[test]
    fn parse_reserved_musig_partial_signature_tag_is_ignored() {
        let mut payload = encode_unchecked_varint(0xFFFF_FFFE);
        payload.extend(encode_unchecked_varint(2));
        payload.extend_from_slice(&[0xbb; 98]);

        assert_ignored(&payload, 2);
    }

    #[test]
    fn parse_unknown_reserved_tag_is_ignored() {
        let mut payload = encode_unchecked_varint(0x89AB_CDEF);
        payload.extend(encode_unchecked_varint(11));
        payload.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]);

        assert_ignored(&payload, 11);
    }
}