bhwi-async 0.1.0

Async HWI trait over the bhwi sans-IO Bitcoin hardware wallet interpreters
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
use core::fmt;
use std::rc::Rc;
use std::sync::Arc;

use async_trait::async_trait;
use bhwi::bitcoin::{Network, bip32::Fingerprint};
use bhwi::common::{self, ErrorKind};
#[cfg(any(feature = "trezor", feature = "keepkey"))]
use bhwi::passphrase::HostPassphrase;

use crate::{ErrorKindOf, HWIDevice, HWIDeviceError, Info};

/// A supported hardware-wallet family, independent of enabled backend features.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DeviceType {
    /// A BitBox02.
    BitBox02,
    /// A Coldcard.
    Coldcard,
    /// A Blockstream Jade.
    Jade,
    /// A KeepKey.
    KeepKey,
    /// A Ledger running the Bitcoin application.
    Ledger,
    /// A Specter-DIY.
    Specter,
    /// A Trezor.
    Trezor,
}

impl DeviceType {
    /// All recognized wallet families, including backends not compiled in.
    pub const ALL: [DeviceType; 7] = [
        DeviceType::BitBox02,
        DeviceType::Coldcard,
        DeviceType::Jade,
        DeviceType::KeepKey,
        DeviceType::Ledger,
        DeviceType::Specter,
        DeviceType::Trezor,
    ];

    /// Returns the lowercase device-family identifier.
    pub fn as_str(self) -> &'static str {
        match self {
            DeviceType::BitBox02 => "bitbox02",
            DeviceType::Coldcard => "coldcard",
            DeviceType::Jade => "jade",
            DeviceType::KeepKey => "keepkey",
            DeviceType::Ledger => "ledger",
            DeviceType::Specter => "specter",
            DeviceType::Trezor => "trezor",
        }
    }
}

impl fmt::Display for DeviceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Returns whether the family accepts multisig descriptors directly at display time.
pub fn supports_multisig_display_address(device_type: DeviceType) -> bool {
    matches!(
        device_type,
        DeviceType::Coldcard | DeviceType::Jade | DeviceType::KeepKey | DeviceType::Trezor
    )
}

/// Returns the known Taproot-signing capability for a family and model string.
pub fn can_sign_taproot(device_type: DeviceType, model: &str) -> bool {
    match device_type {
        DeviceType::BitBox02 => false,
        DeviceType::Ledger => true,
        DeviceType::Jade => false,
        DeviceType::KeepKey => false,
        DeviceType::Coldcard => model.contains("edge"),
        DeviceType::Specter => false,
        DeviceType::Trezor => model != "trezor_one",
    }
}

/// Returns whether the family reports the management metadata used by discovery.
pub fn reports_device_info(device_type: DeviceType) -> bool {
    matches!(device_type, DeviceType::KeepKey | DeviceType::Trezor)
}

/// Filters discovery candidates and optionally selects a wallet by fingerprint.
#[derive(Debug, Clone)]
pub struct DeviceSelector {
    /// The network used when opening a device and running its unlock handshake.
    pub network: Network,
    /// A wallet fingerprint to query after the unlock handshake; `None` accepts any.
    pub fingerprint: Option<Fingerprint>,
    /// A device-family filter; `None` accepts any family.
    pub device_type: Option<DeviceType>,
    /// An exact discovery-path filter; `None` accepts any path.
    pub device_path: Option<String>,
    /// Whether discovery should include emulator candidates.
    pub include_emulators: bool,
    /// An optional host passphrase, supported only by Trezor and KeepKey.
    #[cfg(any(feature = "trezor", feature = "keepkey"))]
    pub passphrase: Option<HostPassphrase>,
}

impl Default for DeviceSelector {
    fn default() -> Self {
        Self {
            network: Network::Bitcoin,
            fingerprint: None,
            device_type: None,
            device_path: None,
            include_emulators: false,
            #[cfg(any(feature = "trezor", feature = "keepkey"))]
            passphrase: None,
        }
    }
}

impl DeviceSelector {
    /// Returns whether the family and path match, without probing a fingerprint.
    ///
    /// This does not check emulator inclusion, the network, or the passphrase.
    pub fn matches(&self, device_type: DeviceType, path: &str) -> bool {
        self.device_type.is_none_or(|target| target == device_type)
            && self
                .device_path
                .as_ref()
                .is_none_or(|target| target == path)
    }
}

/// A callback that presents a BitBox02 pairing code to the user.
pub type PairingCodePrompt = Arc<dyn Fn(&str) + Send + Sync>;

/// A device found on a bus but not yet opened.
#[derive(Debug, Clone)]
pub struct DeviceCandidate {
    /// The device family.
    pub device_type: DeviceType,
    /// The discovery source's display name.
    pub name: String,
    /// The discovery source's model identifier.
    pub model: String,
    /// The source-specific path used to open this candidate.
    pub path: String,
    /// Whether this candidate represents an emulator.
    pub is_emulated: bool,
}

/// Creates host-input handlers before a device is boxed, including mid-command prompts.
pub type HostInteractionFactory = Rc<dyn Fn() -> Box<dyn crate::HostInteraction>>;

/// Discovers and opens devices using source-specific I/O.
///
/// Futures need not be `Send`; implementations choose their I/O runtime.
#[async_trait(?Send)]
pub trait DeviceSource {
    /// A discovery or device-opening failure.
    type Error: std::error::Error + ErrorKindOf + 'static;

    /// Lists matching candidates, potentially probing emulators with I/O.
    async fn list(&self, selector: &DeviceSelector) -> Result<Vec<DeviceCandidate>, Self::Error>;

    /// Opens a candidate and attaches the supplied pairing and host-input callbacks.
    ///
    /// Opening may perform I/O, but does not by itself promise an unlocked wallet.
    async fn open(
        &self,
        candidate: &DeviceCandidate,
        selector: &DeviceSelector,
        pairing_code: Option<&PairingCodePrompt>,
        host_interaction: Option<&HostInteractionFactory>,
    ) -> Result<Device, Self::Error>;
}

/// A discovery, opening, or wallet-selection failure.
#[derive(Debug, thiserror::Error)]
pub enum SelectError<E> {
    /// The source could not list candidates.
    #[error(transparent)]
    Source(
        /// The source error.
        E,
    ),

    /// A wallet operation failed or was cancelled.
    #[error(transparent)]
    Device(
        /// The wallet-operation error.
        #[from]
        HWIDeviceError,
    ),

    /// Candidates were found but none could be used.
    #[error(transparent)]
    NoUsableDevice(
        /// The rejected candidates and their errors.
        #[from]
        NoUsableDevice,
    ),

    /// A host passphrase was supplied for a BitBox02.
    #[cfg(feature = "bitbox")]
    #[error("{}", crate::bitbox::HOST_PASSPHRASE_REJECTED)]
    HostPassphraseRejected,
}

/// Discovers, opens, and selects wallets through a [`DeviceSource`].
pub struct DeviceManager<S> {
    /// The discovery filters and wallet-selection requirements.
    pub selector: DeviceSelector,
    source: S,
    pairing_code: Option<PairingCodePrompt>,
    host_interaction: Option<HostInteractionFactory>,
}

impl<S: DeviceSource> DeviceManager<S> {
    /// Creates a manager with no pairing or host-input callbacks.
    pub fn new(source: S, selector: DeviceSelector) -> Self {
        Self {
            selector,
            source,
            pairing_code: None,
            host_interaction: None,
        }
    }

    /// Sets the callback used to present BitBox02 pairing codes.
    pub fn with_pairing_code_prompt(mut self, prompt: PairingCodePrompt) -> Self {
        self.pairing_code = Some(prompt);
        self
    }

    /// Sets the factory used to attach host-input handlers to opened devices.
    pub fn with_host_interaction(mut self, factory: HostInteractionFactory) -> Self {
        self.host_interaction = Some(factory);
        self
    }

    /// Lists candidates using the selector, potentially probing emulators.
    pub async fn list(&self) -> Result<Vec<DeviceCandidate>, S::Error> {
        self.source.list(&self.selector).await
    }

    /// Opens a candidate using the selector and configured callbacks.
    pub async fn open(&self, candidate: &DeviceCandidate) -> Result<Device, S::Error> {
        self.source
            .open(
                candidate,
                &self.selector,
                self.pairing_code.as_ref(),
                self.host_interaction.as_ref(),
            )
            .await
    }

    /// Opens listed candidates without additional unlock or metadata requests.
    ///
    /// Source-specific opening may still send wallet commands, such as native
    /// Specter's fingerprint probe. Opening errors are collected in
    /// [`DeviceScan::skipped`].
    pub async fn enumerate(&self) -> Result<DeviceScan, S::Error> {
        let mut scan = DeviceScan::default();
        for candidate in self.list().await? {
            match self.open(&candidate).await {
                Ok(device) => scan.devices.push(device),
                Err(err) => scan.skipped.push(unopened_candidate(&candidate, &err)),
            }
        }
        Ok(scan)
    }

    /// Opens candidates and runs their unlock handshake until the optional fingerprint matches.
    ///
    /// Successful Trezor or KeepKey initialization can leave the wallet PIN-locked.
    /// A common [`bhwi::common::ErrorKind::UserCancelled`] from unlock or fingerprint
    /// queries aborts selection. Without a fingerprint filter, any unlock failure
    /// is returned rather than silently selecting another wallet. Other failures
    /// are collected as skipped devices. Trezor and KeepKey device-side cancellations
    /// become authentication refusals and may be skipped when filtering by fingerprint.
    pub async fn select(
        &self,
    ) -> Result<(Option<Device>, Vec<SkippedDevice>), SelectError<S::Error>> {
        let candidates = self.list().await.map_err(SelectError::Source)?;
        let mut skipped = Vec::new();
        let mut target_dev = None;
        for candidate in candidates {
            let mut d = match self.open(&candidate).await {
                Ok(device) => device,
                Err(err) => {
                    skipped.push(unopened_candidate(&candidate, &err));
                    continue;
                }
            };

            if let Err(err) = d.device().unlock(self.selector.network).await {
                // Without a fingerprint, skipping would hand back the next wallet instead.
                if err.kind() == Some(ErrorKind::UserCancelled)
                    || self.selector.fingerprint.is_none()
                {
                    return Err(err.into());
                }
                skipped.push(skipped_candidate(&candidate, &err));
                continue;
            }

            let Some(fingerprint) = self.selector.fingerprint else {
                target_dev = Some(d);
                break;
            };
            match d.fingerprint().await {
                Ok(found) if found == fingerprint => {
                    target_dev = Some(d);
                    break;
                }
                Ok(_) => {}
                Err(err) => {
                    if err.kind() == Some(ErrorKind::UserCancelled) {
                        return Err(err.into());
                    }
                    skipped.push(skipped_candidate(&candidate, &err));
                }
            }
        }
        let Some(dev) = target_dev else {
            return Ok((None, skipped));
        };
        #[cfg(all(feature = "bitbox", any(feature = "trezor", feature = "keepkey")))]
        if self.selector.passphrase.is_some() && dev.device_type() == DeviceType::BitBox02 {
            return Err(SelectError::HostPassphraseRejected);
        }
        Ok((Some(dev), skipped))
    }

    /// Opens and probes candidates, caching information and initialized-wallet fingerprints.
    ///
    /// A common [`bhwi::common::ErrorKind::UserCancelled`] from unlock or probe commands
    /// aborts the scan. Other per-device failures, including Trezor and KeepKey
    /// device-side cancellations mapped to authentication refusals, are collected
    /// as skipped devices.
    pub async fn scan(&self) -> Result<DeviceScan, SelectError<S::Error>> {
        let candidates = self.list().await.map_err(SelectError::Source)?;
        let mut scan = DeviceScan::default();
        for candidate in candidates {
            let mut device = match self.open(&candidate).await {
                Ok(device) => device,
                Err(err) => {
                    scan.skipped.push(unopened_candidate(&candidate, &err));
                    continue;
                }
            };
            match probe(&mut device, self.selector.network).await {
                Ok(()) => scan.devices.push(device),
                Err(err) if err.kind() == Some(ErrorKind::UserCancelled) => return Err(err.into()),
                Err(err) => scan.skipped.push(skipped_candidate(&candidate, &err)),
            }
        }
        Ok(scan)
    }

    /// Selects a wallet, returning an error if all candidates were skipped.
    ///
    /// With no fingerprint filter, the first successful unlock handshake is accepted;
    /// Trezor and KeepKey may still require a PIN. Uses the rules of [`Self::select`].
    pub async fn get_device_with_fingerprint(
        &self,
    ) -> Result<Option<Device>, SelectError<S::Error>> {
        let (device, skipped) = self.select().await?;
        match device {
            Some(device) => Ok(Some(device)),
            None => Ok(no_device(skipped)?),
        }
    }

    /// Returns the first usable candidate from [`Self::enumerate`].
    ///
    /// The manager makes no additional unlock or metadata request. Discovery and
    /// source-specific opening may still perform protocol I/O, including native
    /// Specter's fingerprint probe.
    pub async fn get_device_without_contacting(
        &self,
    ) -> Result<Option<Device>, SelectError<S::Error>> {
        let scan = self.enumerate().await.map_err(SelectError::Source)?;
        match scan.devices.into_iter().next() {
            Some(device) => Ok(Some(device)),
            None => Ok(no_device(scan.skipped)?),
        }
    }
}

/// A scan in which every candidate was rejected.
#[derive(Debug)]
pub struct NoUsableDevice {
    /// The rejected candidates and their classified errors.
    pub skipped: Vec<SkippedDevice>,
}

impl fmt::Display for NoUsableDevice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let reasons = self
            .skipped
            .iter()
            .map(|s| format!("{} at {}: {}", s.device_type, s.path, s.error))
            .collect::<Vec<_>>()
            .join("; ");
        write!(f, "no usable device found, could not open: {reasons}")
    }
}

impl std::error::Error for NoUsableDevice {}

fn skipped_candidate(
    candidate: &DeviceCandidate,
    error: &(dyn std::error::Error + 'static),
) -> SkippedDevice {
    SkippedDevice::new(
        candidate.device_type,
        &candidate.model,
        &candidate.path,
        error,
    )
}

fn unopened_candidate<E>(candidate: &DeviceCandidate, error: &E) -> SkippedDevice
where
    E: std::error::Error + ErrorKindOf + 'static,
{
    SkippedDevice {
        device_type: candidate.device_type,
        model: candidate.model.clone(),
        path: candidate.path.clone(),
        error: classify(error, Some(error.error_kind())),
    }
}

async fn probe(device: &mut Device, network: Network) -> Result<(), HWIDeviceError> {
    // XXX: Coldcard always needs unlocking
    device.device().unlock(network).await?;
    let info = device.info().await?;
    if info.initialized != Some(false) {
        device.fingerprint().await?;
    }
    Ok(())
}

/// Returns `None` for an empty scan or an error containing rejected candidates.
pub fn no_device(skipped: Vec<SkippedDevice>) -> Result<Option<Device>, NoUsableDevice> {
    if skipped.is_empty() {
        return Ok(None);
    }
    Err(NoUsableDevice { skipped })
}

/// Returns whether an error chain contains a common user-cancellation error.
pub fn is_user_cancelled(err: &(dyn std::error::Error + 'static)) -> bool {
    classify_error(err).kind() == ErrorKind::UserCancelled
}

/// Classifies an error chain into a common error, keeping its kind, code, and message.
pub fn classify_error(err: &(dyn std::error::Error + 'static)) -> common::Error {
    classify(err, None)
}

fn classify(err: &(dyn std::error::Error + 'static), kind: Option<ErrorKind>) -> common::Error {
    let message = err.to_string();
    let mut kind = kind;
    let mut source = Some(err);
    while let Some(current) = source {
        if let Some(error) = current.downcast_ref::<common::Error>() {
            return reworded(error, message);
        }
        kind = kind.or_else(|| {
            current
                .downcast_ref::<HWIDeviceError>()
                .and_then(HWIDeviceError::kind)
        });
        source = current.source();
    }
    common::Error::new(kind.unwrap_or(ErrorKind::Other), message)
}

fn reworded(error: &common::Error, message: String) -> common::Error {
    if error.to_string() == message {
        return error.clone();
    }
    let inner = error.to_string();
    let message = if message.contains(&inner) {
        message
            .replace(&inner, error.message())
            .trim_end_matches(": ")
            .to_owned()
    } else if message.contains(error.message()) {
        message
    } else {
        format!("{message}: {}", error.message())
    };
    let mut outer = common::Error::new(error.kind(), message);
    if let Some(code) = error.device_code() {
        outer = outer.with_device_code(code);
    }
    if let Some(data) = error.data() {
        outer = outer.with_data(data.to_vec());
    }
    outer
}

/// A candidate rejected during opening, selection, or probing.
#[derive(Debug, Clone)]
pub struct SkippedDevice {
    /// The rejected device family.
    pub device_type: DeviceType,
    /// The discovery model identifier.
    pub model: String,
    /// The discovery path.
    pub path: String,
    /// The classified error.
    pub error: common::Error,
}

/// A successfully opened device or a rejected candidate.
pub enum ScanEntry {
    /// An opened device.
    Found(
        /// The opened device.
        Device,
    ),
    /// A rejected candidate.
    Skipped(
        /// The candidate and its classified error.
        SkippedDevice,
    ),
}

impl SkippedDevice {
    /// Creates a rejected-candidate record by classifying an error.
    pub fn new(
        device_type: DeviceType,
        model: impl Into<String>,
        path: impl Into<String>,
        error: &(dyn std::error::Error + 'static),
    ) -> Self {
        Self {
            device_type,
            model: model.into(),
            path: path.into(),
            error: classify_error(error),
        }
    }
}

impl ScanEntry {
    /// Creates a skipped scan entry from candidate metadata and an error.
    pub fn skipped(
        device_type: DeviceType,
        model: impl Into<String>,
        path: impl Into<String>,
        error: &(dyn std::error::Error + 'static),
    ) -> Self {
        Self::Skipped(SkippedDevice::new(device_type, model, path, error))
    }
}

/// Opened devices and rejected candidates collected by a scan.
#[derive(Default)]
pub struct DeviceScan {
    /// Successfully opened devices; metadata availability depends on the scan operation.
    pub devices: Vec<Device>,
    /// Candidates rejected during the scan.
    pub skipped: Vec<SkippedDevice>,
}

impl Extend<ScanEntry> for DeviceScan {
    fn extend<I: IntoIterator<Item = ScanEntry>>(&mut self, iter: I) {
        for entry in iter {
            match entry {
                ScanEntry::Found(device) => self.devices.push(device),
                ScanEntry::Skipped(skipped) => self.skipped.push(skipped),
            }
        }
    }
}

/// A requested network absent from the device's nonempty reported network list.
#[derive(Debug, Clone)]
pub struct NetworkMismatch {
    /// The requested network.
    pub expected: Network,
    /// The networks reported by the device.
    pub reported: Vec<Network>,
}

/// Formats network names as a comma-separated string.
pub fn networks_string(networks: &[Network]) -> String {
    networks
        .iter()
        .map(|n| n.to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

/// An opened wallet with discovery metadata and cached successful query results.
///
/// Cached information and fingerprints are not automatically invalidated when
/// callers change the wallet or session through [`Self::device`].
pub struct Device {
    name: String,
    device_type: DeviceType,
    path: String,
    model: String,
    device: Box<dyn HWIDevice>,
    is_emulated: bool,
    fingerprint: Option<Fingerprint>,
    info: Option<Info>,
}

impl Device {
    /// Wraps an opened wallet with discovery metadata and empty query caches.
    pub fn new(
        name: &str,
        device_type: DeviceType,
        path: impl Into<String>,
        model: impl Into<String>,
        device: Box<dyn HWIDevice>,
        is_emulated: bool,
    ) -> Self {
        Self {
            name: name.into(),
            device_type,
            path: path.into(),
            model: model.into(),
            device,
            is_emulated,
            fingerprint: None,
            info: None,
        }
    }

    /// Returns the discovery display name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the device family.
    pub fn device_type(&self) -> DeviceType {
        self.device_type
    }

    /// Returns the source-specific discovery path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the discovery model identifier.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Returns the underlying wallet interface without invalidating query caches.
    pub fn device(&mut self) -> &mut Box<dyn HWIDevice> {
        &mut self.device
    }

    /// Returns whether discovery identified this device as an emulator.
    pub fn is_emulated(&self) -> bool {
        self.is_emulated
    }

    /// Returns the last successfully queried fingerprint, without performing I/O.
    pub fn cached_fingerprint(&self) -> Option<Fingerprint> {
        self.fingerprint
    }

    /// Returns cached information, without performing I/O.
    pub fn cached_info(&self) -> Option<&Info> {
        self.info.as_ref()
    }

    /// Returns the cached fingerprint or queries the wallet and caches success.
    pub async fn fingerprint(&mut self) -> Result<Fingerprint, HWIDeviceError> {
        if let Some(fingerprint) = self.fingerprint {
            Ok(fingerprint)
        } else {
            let fingerprint = self.device.get_master_fingerprint().await?;
            self.fingerprint = Some(fingerprint);
            Ok(fingerprint)
        }
    }

    /// Returns a mismatch when nonempty reported networks exclude `expected`.
    ///
    /// This may query information; an empty network list is treated as unknown.
    pub async fn network_mismatch(
        &mut self,
        expected: Network,
    ) -> Result<Option<NetworkMismatch>, HWIDeviceError> {
        let info = self.info().await?;
        if info.networks.is_empty() || info.networks.contains(&expected) {
            return Ok(None);
        }
        Ok(Some(NetworkMismatch {
            expected,
            reported: info.networks,
        }))
    }

    /// Returns cached information or queries the device and caches success.
    ///
    /// Specter-DIY instead receives synthetic default information with version
    /// `"unavailable"`, because it has no version command.
    pub async fn info(&mut self) -> Result<Info, HWIDeviceError> {
        if let Some(ref info) = self.info {
            Ok(info.clone())
        } else if self.device_type == DeviceType::Specter {
            // Specter-DIY has no version command, so asking would fail the call.
            let info = Info {
                version: "unavailable".into(),
                ..Info::default()
            };
            self.info = Some(info.clone());
            Ok(info)
        } else {
            let info = self.device.get_info().await?;
            self.info = Some(info.clone());
            Ok(info)
        }
    }
}

#[cfg(test)]
mod tests {
    use bhwi::bitcoin::{
        bip32::{DerivationPath, Xpub},
        psbt::Psbt,
        secp256k1::ecdsa::Signature,
    };
    use futures::executor::block_on;

    use super::*;
    use crate::{
        DeviceBackup, DeviceContext, DisplayAddress, RestoreOptions, SetupOptions,
        WalletRegistration,
    };

    /// Answers only what `select` asks: unlock and the master fingerprint.
    struct Wallet {
        fingerprint: Fingerprint,
        refuses_unlock: bool,
    }

    #[async_trait(?Send)]
    impl HWIDevice for Wallet {
        async fn backup_device(&mut self) -> Result<DeviceBackup, HWIDeviceError> {
            unimplemented!()
        }
        async fn setup_device(
            &mut self,
            _: SetupOptions,
            _: Option<DeviceContext>,
        ) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn wipe_device(&mut self) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn restore_device(
            &mut self,
            _: RestoreOptions,
            _: Option<DeviceContext>,
        ) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn toggle_passphrase(&mut self) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn prompt_pin(&mut self) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn send_pin(&mut self, _: Option<DeviceContext>) -> Result<bool, HWIDeviceError> {
            unimplemented!()
        }
        async fn unlock(&mut self, _: Network) -> Result<(), HWIDeviceError> {
            if self.refuses_unlock {
                let refusal: Box<dyn std::error::Error + Send + Sync> =
                    "authentication refused".into();
                return Err(refusal.into());
            }
            Ok(())
        }
        async fn get_info(&mut self) -> Result<Info, HWIDeviceError> {
            unimplemented!()
        }
        async fn get_master_fingerprint(&mut self) -> Result<Fingerprint, HWIDeviceError> {
            Ok(self.fingerprint)
        }
        async fn get_extended_pubkey(
            &mut self,
            _: DerivationPath,
            _: bool,
        ) -> Result<Xpub, HWIDeviceError> {
            unimplemented!()
        }
        async fn sign_message(
            &mut self,
            _: &[u8],
            _: DerivationPath,
        ) -> Result<(u8, Signature), HWIDeviceError> {
            unimplemented!()
        }
        async fn display_address(
            &mut self,
            _: DisplayAddress,
            _: Option<DeviceContext>,
        ) -> Result<String, HWIDeviceError> {
            unimplemented!()
        }
        async fn register_wallet(
            &mut self,
            _: &str,
            _: &str,
        ) -> Result<WalletRegistration, HWIDeviceError> {
            unimplemented!()
        }
        async fn sign_tx(
            &mut self,
            _: Psbt,
            _: Option<DeviceContext>,
        ) -> Result<Psbt, HWIDeviceError> {
            unimplemented!()
        }
    }

    const REFUSING: [u8; 4] = [0xaa; 4];
    const UNLOCKED: [u8; 4] = [0xbb; 4];

    #[derive(Debug, thiserror::Error)]
    #[error("device went away")]
    struct Unplugged;

    impl ErrorKindOf for Unplugged {
        fn error_kind(&self) -> ErrorKind {
            ErrorKind::Disconnected
        }
    }

    /// A wallet that refuses authentication, then one that unlocks.
    struct Wallets(DeviceType);

    #[async_trait(?Send)]
    impl DeviceSource for Wallets {
        type Error = Unplugged;

        async fn list(&self, _: &DeviceSelector) -> Result<Vec<DeviceCandidate>, Self::Error> {
            Ok(["refusing", "unlocked"]
                .into_iter()
                .map(|path| DeviceCandidate {
                    device_type: self.0,
                    name: "wallet".to_owned(),
                    model: "wallet".to_owned(),
                    path: path.to_owned(),
                    is_emulated: true,
                })
                .collect())
        }

        async fn open(
            &self,
            candidate: &DeviceCandidate,
            _: &DeviceSelector,
            _: Option<&PairingCodePrompt>,
            _: Option<&HostInteractionFactory>,
        ) -> Result<Device, Self::Error> {
            let refuses_unlock = candidate.path == "refusing";
            let wallet = Wallet {
                fingerprint: Fingerprint::from(if refuses_unlock { REFUSING } else { UNLOCKED }),
                refuses_unlock,
            };
            Ok(Device::new(
                &candidate.name,
                candidate.device_type,
                &candidate.path,
                &candidate.model,
                Box::new(wallet),
                candidate.is_emulated,
            ))
        }
    }

    fn manager(fingerprint: Option<Fingerprint>) -> DeviceManager<Wallets> {
        let selector = DeviceSelector {
            fingerprint,
            ..DeviceSelector::default()
        };
        DeviceManager::new(Wallets(DeviceType::Trezor), selector)
    }

    #[cfg(all(feature = "bitbox", any(feature = "trezor", feature = "keepkey")))]
    #[test]
    fn a_bitbox02_refuses_any_supplied_passphrase() {
        for passphrase in [Some("secret"), Some(""), None] {
            let selector = DeviceSelector {
                fingerprint: Some(Fingerprint::from(UNLOCKED)),
                passphrase: passphrase.map(|p| HostPassphrase::new(p.to_owned())),
                ..DeviceSelector::default()
            };
            let result =
                block_on(DeviceManager::new(Wallets(DeviceType::BitBox02), selector).select());
            assert_eq!(
                matches!(result, Err(SelectError::HostPassphraseRejected)),
                passphrase.is_some()
            );
        }
    }

    #[test]
    fn a_refused_unlock_ends_selection_when_no_fingerprint_was_named() {
        let err = block_on(manager(None).select())
            .err()
            .expect("the refusal is reported");
        assert!(matches!(err, SelectError::Device(_)));
    }

    #[test]
    fn a_refused_unlock_is_skipped_while_looking_for_a_named_fingerprint() {
        let unlocked = Fingerprint::from(UNLOCKED);
        let (device, skipped) =
            block_on(manager(Some(unlocked)).select()).expect("the named wallet is found");
        assert_eq!(
            device.expect("a wallet").cached_fingerprint(),
            Some(unlocked)
        );
        assert_eq!(skipped.len(), 1);
    }

    #[test]
    fn taproot_support_matches_python_hwi() {
        assert!(can_sign_taproot(
            DeviceType::Ledger,
            "ledger_nano_s_simulator"
        ));
        assert!(!can_sign_taproot(
            DeviceType::BitBox02,
            "bitbox02_simulator"
        ));
        assert!(!can_sign_taproot(DeviceType::Jade, "jade_simulator"));
        assert!(can_sign_taproot(
            DeviceType::Coldcard,
            "coldcard_simulator_edge"
        ));
        assert!(!can_sign_taproot(
            DeviceType::Coldcard,
            "coldcard_simulator"
        ));
        assert!(can_sign_taproot(DeviceType::Trezor, "trezor_t"));
        assert!(!can_sign_taproot(DeviceType::Trezor, "trezor_one"));
    }

    #[test]
    fn an_interpreter_error_reads_as_its_cause() {
        let wrapped: crate::Error<std::io::Error, std::io::Error> = crate::Error::Interpreter(
            bhwi::common::Error::new(ErrorKind::InvalidInput, "Passphrase too long"),
        );
        assert_eq!(wrapped.to_string(), "[InvalidInput] Passphrase too long");
        assert_eq!(
            std::error::Error::source(&wrapped)
                .expect("the cause is kept")
                .to_string(),
            "[InvalidInput] Passphrase too long"
        );

        let skipped = SkippedDevice::new(DeviceType::KeepKey, "keepkey", "udp:11044", &wrapped);
        assert_eq!(
            skipped.error,
            bhwi::common::Error::new(ErrorKind::InvalidInput, "Passphrase too long")
        );
        assert_eq!(
            skipped.error.to_string(),
            "[InvalidInput] Passphrase too long"
        );
    }

    #[test]
    fn a_transport_error_keeps_the_layer_that_carries_its_meaning() {
        let wrapped = HWIDeviceError::with_kind(
            crate::Error::<std::io::Error, std::io::Error>::Transport {
                kind: ErrorKind::Transport,
                error: std::io::Error::other("Broken pipe"),
            },
            ErrorKind::Transport,
        );

        let skipped = SkippedDevice::new(DeviceType::KeepKey, "keepkey", "udp:11044", &wrapped);
        assert_eq!(skipped.error.kind(), ErrorKind::Transport);
        assert_eq!(
            skipped.error.to_string(),
            "[Transport] transport error: Broken pipe"
        );
    }

    #[cfg(feature = "trezor")]
    struct Replies(std::collections::VecDeque<Result<Vec<u8>, std::io::Error>>);

    #[cfg(feature = "trezor")]
    impl Replies {
        fn new(replies: impl IntoIterator<Item = Result<Vec<u8>, std::io::Error>>) -> Self {
            Self(replies.into_iter().collect())
        }
    }

    #[cfg(feature = "trezor")]
    #[async_trait(?Send)]
    impl crate::Transport for Replies {
        type Error = std::io::Error;

        async fn exchange(&mut self, _: &[u8], _: bool) -> Result<Vec<u8>, Self::Error> {
            self.0.pop_front().expect("a scripted reply")
        }

        fn error_kind(&self, error: &Self::Error) -> ErrorKind {
            crate::transport::io_error_kind(error)
        }
    }

    #[cfg(feature = "trezor")]
    fn raised<F>(error: &HWIDeviceError) -> common::Error
    where
        F: std::error::Error + 'static,
    {
        match std::error::Error::source(error)
            .and_then(|source| source.downcast_ref::<crate::Error<std::io::Error, F>>())
        {
            Some(crate::Error::Interpreter(error)) => error.clone(),
            other => panic!("expected an interpreter error, got {other:?}"),
        }
    }

    #[cfg(feature = "trezor")]
    fn assert_kept_whole(error: &HWIDeviceError, raised: &common::Error) {
        assert_eq!(classify_error(error), *raised);
        let skipped = SkippedDevice::new(DeviceType::Trezor, "trezor_one", "udp:21324", error);
        assert_eq!(skipped.error, *raised);
        assert_eq!(skipped.error.to_string(), error.to_string());
    }

    #[cfg(feature = "trezor")]
    fn trezor_reply(
        message_type: bhwi::trezor::api::MessageType,
        payload: &[u8],
    ) -> Result<Vec<u8>, std::io::Error> {
        Ok(bhwi::trezor::api::frame(message_type as u16, payload))
    }

    #[cfg(feature = "trezor")]
    #[test]
    fn a_trezor_failure_keeps_its_kind_code_and_message() {
        use bhwi::trezor::{TrezorError, api::MessageType};

        // `Failure`: field 1 is the code (7, PIN invalid), field 2 the message.
        let mut failure = vec![0x08, 0x07, 0x12, 0x0b];
        failure.extend_from_slice(b"PIN invalid");
        let mut trezor =
            crate::Trezor::new(Replies::new([trezor_reply(MessageType::Failure, &failure)]));

        let error = block_on(HWIDevice::get_master_fingerprint(&mut trezor))
            .expect_err("the device reports a failure");

        let raised = raised::<TrezorError>(&error);
        assert_eq!(raised.kind(), ErrorKind::WrongPin);
        assert_eq!(raised.device_code(), Some(common::DeviceCode::Trezor(7)));
        assert_eq!(raised.message(), "PIN invalid");
        assert_kept_whole(&error, &raised);

        #[derive(Debug, thiserror::Error)]
        #[error("getting fingerprint failed")]
        struct Context(#[source] crate::HWIDeviceError);
        let classified = classify_error(&Context(error));
        assert_eq!(classified.kind(), ErrorKind::WrongPin);
        assert_eq!(
            classified.message(),
            "getting fingerprint failed: PIN invalid"
        );

        #[derive(Debug, thiserror::Error)]
        #[error("getting fingerprint failed: {0}")]
        struct Quoting(#[source] common::Error);
        let quoted = classify_error(&Quoting(common::Error::new(
            ErrorKind::WrongPin,
            "PIN invalid",
        )));
        assert_eq!(
            quoted.to_string(),
            "[WrongPin] getting fingerprint failed: PIN invalid"
        );
    }

    #[cfg(feature = "trezor")]
    #[test]
    fn a_disconnect_keeps_the_kind_recorded_by_the_device_error() {
        let mut trezor = crate::Trezor::new(Replies::new([Err(std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "device went away",
        ))]));

        let error = block_on(HWIDevice::get_master_fingerprint(&mut trezor))
            .expect_err("the transport fails");

        let classified = classify_error(&error);
        assert_eq!(classified.kind(), ErrorKind::Disconnected);
        assert_eq!(classified.device_code(), None);
        assert_eq!(classified.data(), None);
        assert_eq!(
            classified.to_string(),
            "[Disconnected] transport error: device went away"
        );
        let skipped = SkippedDevice::new(DeviceType::Trezor, "trezor_one", "udp:21324", &error);
        assert_eq!(skipped.error, classified);
        assert!(!is_user_cancelled(&error));
    }

    #[cfg(feature = "trezor")]
    struct CancellingTrezor;

    #[cfg(feature = "trezor")]
    #[async_trait(?Send)]
    impl DeviceSource for CancellingTrezor {
        type Error = Unplugged;

        async fn list(&self, _: &DeviceSelector) -> Result<Vec<DeviceCandidate>, Self::Error> {
            Ok(vec![DeviceCandidate {
                device_type: DeviceType::Trezor,
                name: "trezor".to_owned(),
                model: "trezor_one".to_owned(),
                path: "udp:21324".to_owned(),
                is_emulated: true,
            }])
        }

        async fn open(
            &self,
            candidate: &DeviceCandidate,
            _: &DeviceSelector,
            _: Option<&PairingCodePrompt>,
            _: Option<&HostInteractionFactory>,
        ) -> Result<Device, Self::Error> {
            use bhwi::trezor::api::MessageType;
            // `Failure`: field 1 is the code (4, action cancelled), field 2 the message.
            let mut failure = vec![0x08, 0x04, 0x12, 0x18];
            failure.extend_from_slice(b"Action cancelled by user");
            let replies = Replies::new([
                trezor_reply(MessageType::Features, &[]),
                trezor_reply(MessageType::Failure, &failure),
            ]);
            Ok(Device::new(
                &candidate.name,
                candidate.device_type,
                &candidate.path,
                &candidate.model,
                Box::new(crate::Trezor::new(replies)),
                candidate.is_emulated,
            ))
        }
    }

    #[cfg(feature = "trezor")]
    #[test]
    fn a_cancel_on_the_device_ends_selection_instead_of_skipping_it() {
        let selector = DeviceSelector {
            fingerprint: Some(Fingerprint::from(UNLOCKED)),
            ..DeviceSelector::default()
        };
        let err = block_on(DeviceManager::new(CancellingTrezor, selector).select())
            .err()
            .expect("the cancel is reported");

        let SelectError::Device(err) = err else {
            panic!("expected the device error, got {err:?}");
        };
        assert_eq!(err.kind(), Some(ErrorKind::UserCancelled));
        let raised = raised::<bhwi::trezor::TrezorError>(&err);
        assert_eq!(raised.device_code(), Some(common::DeviceCode::Trezor(4)));

        let built = crate::HWIDeviceError::new(common::Error::new(
            ErrorKind::UserCancelled,
            "action canceled by the user",
        ));
        assert_eq!(built.kind(), Some(ErrorKind::UserCancelled));
        let boxed: Box<dyn std::error::Error + Send + Sync> = Box::new(common::Error::new(
            ErrorKind::UserCancelled,
            "action canceled by the user",
        ));
        let converted = crate::HWIDeviceError::from(boxed);
        assert_eq!(converted.kind(), Some(ErrorKind::UserCancelled));
    }

    #[test]
    fn multisig_display_address_needs_a_descriptor_capable_device() {
        for device_type in DeviceType::ALL {
            assert_eq!(
                supports_multisig_display_address(device_type),
                matches!(
                    device_type,
                    DeviceType::Coldcard
                        | DeviceType::Jade
                        | DeviceType::KeepKey
                        | DeviceType::Trezor
                ),
                "{device_type}"
            );
        }
    }
}