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
//! Coldcard wire request encoding and response parsing.
//!
// See https://github.com/Coldcard/ckcc-protocol for implementation details.
/// Encoders for Coldcard requests.
pub mod request {
    use bitcoin::bip32::{ChildNumber, DerivationPath, Fingerprint};

    /// Maximum upload chunk size in bytes.
    pub const MAX_UPLOAD_CHUNK_LEN: usize = 2048;

    /// Encodes key agreement with an unprefixed host public key and version defaulting to 1.
    pub fn start_encryption(version: Option<u32>, key: &[u8; 64]) -> Vec<u8> {
        let mut data = "ncry".as_bytes().to_owned();
        data.extend(version.unwrap_or(1).to_le_bytes());
        data.extend(key);
        data
    }

    /// Encodes a request to create an encrypted backup.
    pub fn start_backup() -> Vec<u8> {
        b"back".to_vec()
    }

    /// Encodes an extended-public-key request for a derivation path.
    pub fn get_xpub(path: &DerivationPath) -> Vec<u8> {
        if path.is_master() {
            "xpubm".as_bytes().to_vec()
        } else {
            format!("xpubm/{}", path).as_bytes().to_vec()
        }
    }

    /// Coldcard address-format bitmask constants.
    pub mod addr_fmt {
        /// Flag selecting a public-key script.
        pub const AFC_PUBKEY: u32 = 0x01;
        /// Flag selecting SegWit.
        pub const AFC_SEGWIT: u32 = 0x02;
        /// Flag selecting Bech32 encoding.
        pub const AFC_BECH32: u32 = 0x04;
        /// Flag selecting a script-hash address.
        pub const AFC_SCRIPT: u32 = 0x08;
        /// Flag selecting wrapped SegWit.
        pub const AFC_WRAPPED: u32 = 0x10;
        /// Flag selecting Bech32m encoding.
        pub const AFC_BECH32M: u32 = 0x20;

        /// Legacy P2PKH address format.
        pub const AF_P2PKH: u32 = AFC_PUBKEY;
        /// Native SegWit P2WPKH address format.
        pub const AF_P2WPKH: u32 = AFC_PUBKEY | AFC_SEGWIT | AFC_BECH32;
        /// Wrapped SegWit P2SH-P2WPKH address format.
        pub const AF_P2WPKH_P2SH: u32 = AFC_PUBKEY | AFC_SEGWIT | AFC_WRAPPED;
        /// Taproot P2TR address format.
        pub const AF_P2TR: u32 = AFC_PUBKEY | AFC_SEGWIT | AFC_BECH32M;
        /// Legacy P2SH address format.
        pub const AF_P2SH: u32 = AFC_SCRIPT;
        /// Native SegWit P2WSH address format.
        pub const AF_P2WSH: u32 = AFC_SCRIPT | AFC_SEGWIT | AFC_BECH32;
        /// Wrapped SegWit P2SH-P2WSH address format.
        pub const AF_P2WSH_P2SH: u32 = AFC_SCRIPT | AFC_SEGWIT | AFC_WRAPPED;

        /// Maps a Bitcoin address type, treating P2SH as wrapped P2WPKH.
        ///
        /// Unrecognized types use P2WPKH.
        pub fn from_address_type(addr_type: bitcoin::address::AddressType) -> u32 {
            match addr_type {
                bitcoin::address::AddressType::P2pkh => AF_P2PKH,
                bitcoin::address::AddressType::P2sh => AF_P2WPKH_P2SH,
                bitcoin::address::AddressType::P2wpkh => AF_P2WPKH,
                bitcoin::address::AddressType::P2wsh => AF_P2WSH,
                bitcoin::address::AddressType::P2tr => AF_P2TR,
                _ => AF_P2WPKH,
            }
        }
    }

    /// Encodes an address-display request for a path and address-format bitmask.
    pub fn show_address(path: &DerivationPath, addr_fmt: u32) -> Vec<u8> {
        let mut data = b"show".to_vec();
        data.extend(addr_fmt.to_le_bytes());
        data.extend(path.to_string().as_bytes());
        data
    }

    /// Encodes a multisig address request with key origins and a concrete redeem script.
    ///
    /// Counts and lengths are cast to their wire widths without range validation.
    pub fn show_p2sh_address(
        threshold: u8,
        key_paths: &[(Fingerprint, DerivationPath)],
        redeem_script: &[u8],
        addr_fmt: u32,
    ) -> Vec<u8> {
        let mut data = b"p2sh".to_vec();
        data.extend(addr_fmt.to_le_bytes());
        data.push(threshold);
        data.push(key_paths.len() as u8);
        data.extend((redeem_script.len() as u16).to_le_bytes());
        data.extend(redeem_script);
        for (fingerprint, derivation_path) in key_paths {
            let path = coldcard_xfp_path(*fingerprint, derivation_path);
            data.push(path.len() as u8);
            for child in path {
                data.extend(child.to_le_bytes());
            }
        }
        data
    }

    fn coldcard_xfp_path(fingerprint: Fingerprint, path: &DerivationPath) -> Vec<u32> {
        let mut result = vec![u32::from_le_bytes(fingerprint.to_bytes())];
        result.extend(path.as_ref().iter().copied().map(child_number_u32));
        result
    }

    fn child_number_u32(child: ChildNumber) -> u32 {
        u32::from(child)
    }

    /// Encodes a registered-descriptor address request for a branch and index.
    pub fn miniscript_address(name: &str, change: bool, index: u32) -> Vec<u8> {
        let mut data = b"msas".to_vec();
        data.extend((change as u32).to_le_bytes());
        data.extend(index.to_le_bytes());
        data.extend(name.as_bytes());
        data
    }

    /// Encodes message signing using the P2WPKH format.
    pub fn sign_message(message: &[u8], path: &DerivationPath) -> Vec<u8> {
        let mut data = b"smsg".to_vec();
        // coldcard can support a few different address types:
        // https://github.com/Coldcard/ckcc-protocol/blob/0bd92d4d6d01872e41ffc1e7d9a1e2f153130061/ckcc/constants.py#L75-L90
        data.extend((0x01u32 | 0x02 | 0x04).to_le_bytes()); // hardcoding to P2WPKH
        let path_string = path.to_string();
        data.extend((path_string.len() as u32).to_le_bytes());
        data.extend((message.len() as u32).to_le_bytes());
        data.extend(path_string.as_bytes());
        data.extend_from_slice(message);
        data
    }

    /// Encodes a poll for the current message-signing result.
    pub fn get_signed_message() -> Vec<u8> {
        b"smok".to_vec()
    }

    /// Encodes a file upload chunk with byte offset and total byte size.
    ///
    /// # Panics
    ///
    /// Panics if `data` exceeds [`MAX_UPLOAD_CHUNK_LEN`] (2048 bytes).
    pub fn upload(offset: u32, total_size: u32, data: &[u8]) -> Vec<u8> {
        assert!(data.len() <= MAX_UPLOAD_CHUNK_LEN);
        let mut rv = b"upld".to_vec();
        rv.extend(offset.to_le_bytes());
        rv.extend(total_size.to_le_bytes());
        rv.extend(data);
        rv
    }

    /// Encodes a request for the SHA-256 digest of the uploaded file.
    pub fn sha256() -> Vec<u8> {
        b"sha2".to_vec()
    }

    /// Encodes signing of an uploaded PSBT identified by byte length and SHA-256 digest.
    pub fn sign_transaction(length: u32, file_sha: &[u8; 32]) -> Vec<u8> {
        let mut rv = b"stxn".to_vec();
        rv.extend(length.to_le_bytes());
        rv.extend(0u32.to_le_bytes());
        rv.extend(file_sha);
        rv
    }

    /// Encodes wallet enrollment using the uploaded file's byte length and SHA-256 digest.
    pub fn multisig_enroll(length: u32, file_sha: &[u8; 32]) -> Vec<u8> {
        let mut data = b"enrl".to_vec();
        data.extend(length.to_le_bytes());
        data.extend(file_sha);
        data
    }

    /// Encodes a poll for the current transaction-signing result.
    pub fn get_signed_transaction() -> Vec<u8> {
        b"stok".to_vec()
    }

    /// Encodes a poll for the current backup file.
    pub fn get_backup_file() -> Vec<u8> {
        b"bkok".to_vec()
    }

    /// Encodes a file download request with byte offset, byte length, and file number.
    pub fn download(offset: u32, length: u32, file_number: u32) -> Vec<u8> {
        let mut rv = b"dwld".to_vec();
        rv.extend(offset.to_le_bytes());
        rv.extend(length.to_le_bytes());
        rv.extend(file_number.to_le_bytes());
        rv
    }

    /// Encodes a firmware-version request.
    pub fn get_version() -> Vec<u8> {
        b"vers".to_vec()
    }
}

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

    use bitcoin::bip32::DerivationPath;

    #[test]
    fn test_derivation_path() {
        let path = DerivationPath::from_str("m/48'/1'/0'/2'").unwrap();
        assert_eq!("48'/1'/0'/2'", path.to_string());
    }

    #[test]
    fn upload_request_encodes_offset_total_and_data() {
        let req = super::request::upload(7, 11, b"psbt");
        assert_eq!(&req[..4], b"upld");
        assert_eq!(u32::from_le_bytes(req[4..8].try_into().unwrap()), 7);
        assert_eq!(u32::from_le_bytes(req[8..12].try_into().unwrap()), 11);
        assert_eq!(&req[12..], b"psbt");
    }

    #[test]
    fn sign_transaction_request_encodes_length_flags_and_hash() {
        let hash = [3u8; 32];
        let req = super::request::sign_transaction(99, &hash);
        assert_eq!(&req[..4], b"stxn");
        assert_eq!(u32::from_le_bytes(req[4..8].try_into().unwrap()), 99);
        assert_eq!(u32::from_le_bytes(req[8..12].try_into().unwrap()), 0);
        assert_eq!(&req[12..], &hash);
    }

    #[test]
    fn multisig_enroll_request_encodes_length_and_hash() {
        let hash = [4u8; 32];
        let req = super::request::multisig_enroll(321, &hash);
        assert_eq!(&req[..4], b"enrl");
        assert_eq!(u32::from_le_bytes(req[4..8].try_into().unwrap()), 321);
        assert_eq!(&req[8..], &hash);
    }

    #[test]
    fn p2sh_address_type_maps_to_nested_segwit_for_path_display() {
        assert_eq!(
            super::request::addr_fmt::from_address_type(bitcoin::address::AddressType::P2sh),
            super::request::addr_fmt::AF_P2WPKH_P2SH
        );
    }

    #[test]
    fn backup_requests_encode_command_names() {
        assert_eq!(super::request::start_backup(), b"back");
        assert_eq!(super::request::get_backup_file(), b"bkok");
    }

    #[test]
    fn upload_response_decodes_acknowledged_offset() {
        let mut res = b"int1".to_vec();
        res.extend(42u32.to_le_bytes());
        assert_eq!(super::response::upload(&res).unwrap(), 42);
    }

    #[test]
    fn signed_transaction_response_decodes_length_and_hash() {
        let mut res = b"strx".to_vec();
        res.extend(123u32.to_le_bytes());
        res.extend([9u8; 32]);
        match super::response::signed_transaction(&res).unwrap() {
            super::response::SignedTransactionStatus::Complete { length, sha } => {
                assert_eq!(length, 123);
                assert_eq!(sha, [9u8; 32]);
            }
            super::response::SignedTransactionStatus::Pending => {
                panic!("expected complete transaction")
            }
        }
    }

    #[test]
    fn signed_transaction_response_treats_busy_as_pending() {
        assert!(matches!(
            super::response::signed_transaction(b"busy").unwrap(),
            super::response::SignedTransactionStatus::Pending
        ));
    }

    #[test]
    fn refu_frames_are_user_cancelled_errors() {
        use crate::coldcard::ColdcardError;

        assert!(matches!(
            super::response::show_address(b"refu"),
            Err(ColdcardError::UserCancelled)
        ));
        assert!(matches!(
            super::response::miniscript_address(b"refu"),
            Err(ColdcardError::UserCancelled)
        ));
        assert!(matches!(
            super::response::sign_message(b"refu"),
            Err(ColdcardError::UserCancelled)
        ));
        assert!(matches!(
            super::response::sign_transaction(b"refu"),
            Err(ColdcardError::UserCancelled)
        ));
        assert!(matches!(
            super::response::signed_transaction(b"refu"),
            Err(ColdcardError::UserCancelled)
        ));
    }

    #[test]
    fn err_frames_during_signing_polls_are_device_errors() {
        use crate::coldcard::ColdcardError;

        for result in [
            super::response::sign_transaction(b"err_No active request").map(|_| ()),
            super::response::signed_transaction(b"err_No active request").map(|_| ()),
            super::response::sign_message(b"err_No active request").map(|_| ()),
        ] {
            match result {
                Err(ColdcardError::Device(message)) => assert_eq!(message, "No active request"),
                other => panic!("expected a device error, got {other:?}"),
            }
        }
    }

    #[test]
    fn err_frames_keep_the_device_error_prefix() {
        let error = match super::response::show_address(b"err_boom") {
            Err(error) => error,
            Ok(_) => panic!("expected a device error"),
        };
        assert_eq!(error.to_string(), "Coldcard Error: boom");
    }

    #[test]
    fn every_parser_reports_refu_and_err_frames() {
        use super::response;
        use crate::coldcard::ColdcardError;

        type Parser = fn(&[u8]) -> Result<(), ColdcardError>;
        let parsers: [(&str, Parser); 8] = [
            ("get_xpub", |res| response::get_xpub(res).map(|_| ())),
            ("master_fingerprint", |res| {
                response::master_fingerprint(res).map(|_| ())
            }),
            ("upload", |res| response::upload(res).map(|_| ())),
            ("sha256", |res| response::sha256(res).map(|_| ())),
            ("okay", response::okay),
            ("download", |res| response::download(res).map(|_| ())),
            ("version", |res| response::version(res).map(|_| ())),
            ("mypub", |res| response::mypub(res).map(|_| ())),
        ];
        for (name, parse) in parsers {
            assert!(
                matches!(parse(b"refu"), Err(ColdcardError::UserCancelled)),
                "{name}"
            );
            assert!(
                matches!(parse(b"err_boom"), Err(ColdcardError::Device(text)) if text == "boom"),
                "{name}"
            );
        }
    }
}

/// Parsers for Coldcard response tags and payloads.
pub mod response {
    use std::fmt::Display;
    use std::str::FromStr;

    use bitcoin::bip32::Xpub;
    use bitcoin::secp256k1::ecdsa::Signature;

    use crate::coldcard::{ColdcardError, ColdcardResponse};

    /// Completion status of a transaction-signing poll.
    pub enum SignedTransactionStatus {
        /// The device has not returned the signed file yet.
        Pending,
        /// The signed file is ready to download.
        Complete {
            /// File size in bytes.
            length: u32,
            /// SHA-256 digest of the file.
            sha: [u8; 32],
        },
    }

    /// Four-byte Coldcard response tags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ResponseMessage {
        /// Successful acknowledgement without content.
        Okay,
        /// Framing error.
        Fram,
        /// Device error.
        Err_,
        /// User refusal.
        Refu,
        /// Pending user approval or completion.
        Busy,
        /// Binary response payload.
        Biny,
        /// One little-endian `u32`.
        Int1,
        /// Two little-endian `u32` values.
        Int2,
        /// Three little-endian `u32` values.
        Int3,
        /// Key-agreement public key and wallet identity response.
        MyPb,
        /// ASCII string response.
        Asci,
        /// Message-signing result.
        Smrx,
        /// Transaction-signing result.
        Strx,
    }

    struct ResponseHandler<'a> {
        message: ResponseMessage,
        data: &'a [u8],
    }

    impl<'a> ResponseHandler<'a> {
        /// Parse a response message and data from the raw device response
        fn parse_response(res: &[u8]) -> Result<(ResponseMessage, &[u8]), ColdcardError> {
            ResponseHandler::try_from(res).map(|ResponseHandler { message, data }| (message, data))
        }

        /// Parse data from the raw device response given an expected response
        /// message.
        fn expect_response(res: &[u8], expected: ResponseMessage) -> Result<&[u8], ColdcardError> {
            match ResponseHandler::parse_response(res)? {
                (msg, data) if msg == expected => Ok(data),
                (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
                (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                    String::from_utf8_lossy(data).into_owned(),
                )),
                (msg, _) => Err(ColdcardError::unexpected_response_message(msg, &[expected])),
            }
        }
    }

    impl Display for ResponseMessage {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let response_str = match self {
                ResponseMessage::Okay => "okay",
                ResponseMessage::Fram => "fram",
                ResponseMessage::Err_ => "err_",
                ResponseMessage::Refu => "refu",
                ResponseMessage::Busy => "busy",
                ResponseMessage::Biny => "biny",
                ResponseMessage::Int1 => "int1",
                ResponseMessage::Int2 => "int2",
                ResponseMessage::Int3 => "int3",
                ResponseMessage::MyPb => "mypb",
                ResponseMessage::Asci => "asci",
                ResponseMessage::Smrx => "smrx",
                ResponseMessage::Strx => "strx",
            };

            write!(f, "{}", response_str)
        }
    }

    impl<'a> TryFrom<&'a [u8]> for ResponseHandler<'a> {
        type Error = ColdcardError;

        fn try_from(res: &'a [u8]) -> Result<Self, Self::Error> {
            let (msg, data) = split(res, 4)?;
            let message = match msg {
                b"okay" => ResponseMessage::Okay,
                b"fram" => ResponseMessage::Fram,
                b"err_" => ResponseMessage::Err_,
                b"refu" => ResponseMessage::Refu,
                b"busy" => ResponseMessage::Busy,
                b"biny" => ResponseMessage::Biny,
                b"int1" => ResponseMessage::Int1,
                b"int2" => ResponseMessage::Int2,
                b"int3" => ResponseMessage::Int3,
                b"mypb" => ResponseMessage::MyPb,
                b"asci" => ResponseMessage::Asci,
                b"smrx" => ResponseMessage::Smrx,
                b"strx" => ResponseMessage::Strx,
                _ => {
                    return Err(ColdcardError::Serialization(format!(
                        "unknown device response message: {:?}, data: {}",
                        String::from_utf8_lossy(msg),
                        String::from_utf8_lossy(data),
                    )));
                }
            };
            Ok(ResponseHandler { message, data })
        }
    }

    fn xpub(res: &[u8]) -> Result<Xpub, ColdcardError> {
        let data = ResponseHandler::expect_response(res, ResponseMessage::Asci)?;
        let s =
            std::str::from_utf8(data).map_err(|e| ColdcardError::Serialization(e.to_string()))?;
        Xpub::from_str(s).map_err(|e| ColdcardError::Serialization(e.to_string()))
    }

    /// Parses an address response or a device refusal or error.
    pub fn show_address(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        match ResponseHandler::parse_response(res)? {
            (ResponseMessage::Asci, data) => {
                let address = String::from_utf8(data.to_owned())?;
                Ok(ColdcardResponse::Address(address))
            }
            (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
            (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                String::from_utf8_lossy(data).into_owned(),
            )),
            (msg, _) => Err(ColdcardError::unexpected_response_message(
                msg,
                &[ResponseMessage::Asci, ResponseMessage::Refu],
            )),
        }
    }

    /// Parses a registered-descriptor address response or device error.
    pub fn miniscript_address(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        match ResponseHandler::parse_response(res)? {
            (ResponseMessage::Asci, data) => {
                let address = String::from_utf8(data.to_owned())?;
                Ok(ColdcardResponse::Address(address))
            }
            (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
            (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                String::from_utf8_lossy(data).into_owned(),
            )),
            (msg, _) => Err(ColdcardError::unexpected_response_message(
                msg,
                &[ResponseMessage::Asci, ResponseMessage::Refu],
            )),
        }
    }

    /// Parses a master xpub response and returns its fingerprint.
    pub fn master_fingerprint(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        Ok(ColdcardResponse::MasterFingerprint(
            xpub(res)?.fingerprint(),
        ))
    }

    /// Parses an extended public key response.
    pub fn get_xpub(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        Ok(ColdcardResponse::Xpub(xpub(res)?))
    }

    /// Parses the acknowledged upload byte offset.
    pub fn upload(res: &[u8]) -> Result<u32, ColdcardError> {
        let data = ResponseHandler::expect_response(res, ResponseMessage::Int1)?;
        decode_u32(Some(data))
    }

    /// Parses a 32-byte SHA-256 digest response.
    pub fn sha256(res: &[u8]) -> Result<[u8; 32], ColdcardError> {
        let data = ResponseHandler::expect_response(res, ResponseMessage::Biny)?;
        data.try_into()
            .map_err(|_| ColdcardError::Serialization("sha256".to_string()))
    }

    /// Parses the acknowledgement or pending status of a signing request.
    pub fn sign_transaction(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        match ResponseHandler::parse_response(res)? {
            (ResponseMessage::Okay, _) => Ok(ColdcardResponse::Ok),
            (ResponseMessage::Busy, _) => Ok(ColdcardResponse::Busy),
            (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
            (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                String::from_utf8_lossy(data).into_owned(),
            )),
            (msg, _) => Err(ColdcardError::unexpected_response_message(
                msg,
                &[ResponseMessage::Okay, ResponseMessage::Busy],
            )),
        }
    }

    /// Requires a successful acknowledgement response.
    pub fn okay(res: &[u8]) -> Result<(), ColdcardError> {
        ResponseHandler::expect_response(res, ResponseMessage::Okay).map(|_| ())
    }

    /// Parses a transaction-signing poll into pending status or downloadable file metadata.
    pub fn signed_transaction(res: &[u8]) -> Result<SignedTransactionStatus, ColdcardError> {
        match ResponseHandler::parse_response(res)? {
            (ResponseMessage::Okay, _) | (ResponseMessage::Busy, _) => {
                Ok(SignedTransactionStatus::Pending)
            }
            (ResponseMessage::Strx, data) => {
                let (len, sha) = split(data, 4)?;
                let length = decode_u32(Some(len))?;
                let sha = sha
                    .try_into()
                    .map_err(|_| ColdcardError::Serialization("signed transaction sha".into()))?;
                Ok(SignedTransactionStatus::Complete { length, sha })
            }
            (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
            // A refused signing request is cleared on the device; the poll then
            // reports `err_ No active request`, which upstream surfaces as a
            // device error rather than a cancellation.
            (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                String::from_utf8_lossy(data).into_owned(),
            )),
            (msg, _) => Err(ColdcardError::unexpected_response_message(
                msg,
                &[
                    ResponseMessage::Okay,
                    ResponseMessage::Busy,
                    ResponseMessage::Strx,
                ],
            )),
        }
    }

    /// Parses binary file-download bytes.
    pub fn download(res: &[u8]) -> Result<Vec<u8>, ColdcardError> {
        Ok(ResponseHandler::expect_response(res, ResponseMessage::Biny)?.to_vec())
    }

    /// Parses firmware-version text into a version and model string.
    pub fn version(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        let data = ResponseHandler::expect_response(res, ResponseMessage::Asci)?;
        let version_string =
            std::str::from_utf8(data).map_err(|e| ColdcardError::Serialization(e.to_string()))?;
        let lines = version_string.lines().collect::<Vec<&str>>();
        let version = lines.get(1).unwrap_or(&version_string).to_string();
        let device_model = lines.last().cloned().unwrap_or_default().to_string();
        Ok(ColdcardResponse::Version {
            version,
            device_model,
        })
    }

    /// Parses the device's key-agreement public key and optional master xpub.
    pub fn mypub(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        let data = ResponseHandler::expect_response(res, ResponseMessage::MyPb)?;
        let (dev_pubkey, data) = split(data, 64)?;
        let encryption_key = dev_pubkey
            .try_into()
            .map_err(|_| ColdcardError::Serialization("encryption_key".to_string()))?;
        let xpub_fingerprint = data
            .get(0..4)
            .ok_or(ColdcardError::Serialization(
                "xfp wants 4 bytes".to_string(),
            ))?
            .try_into()
            .expect("infallible");
        let xpub_len = decode_u32(data.get(4..8))? as usize;
        let xpub = if xpub_len > 0 {
            if let Some(s) = data
                .get(8..8 + xpub_len)
                .map(|d| String::from_utf8(d.to_owned()))
                .transpose()
                .map_err(|e| ColdcardError::Serialization(e.to_string()))?
            {
                Some(Xpub::from_str(&s).map_err(|e| ColdcardError::Serialization(e.to_string()))?)
            } else {
                None
            }
        } else {
            None
        };
        Ok(ColdcardResponse::MyPub {
            encryption_key,
            xpub_fingerprint,
            xpub,
        })
    }

    /// Parses a message-signing acknowledgement, pending status, or compact signature.
    ///
    /// # Panics
    ///
    /// Panics for a signing-result payload shorter than its four-byte address
    /// length, or containing no signature header after the address.
    pub fn sign_message(res: &[u8]) -> Result<ColdcardResponse, ColdcardError> {
        match ResponseHandler::parse_response(res)? {
            (ResponseMessage::Okay, _) => Ok(ColdcardResponse::Ok),
            (ResponseMessage::Refu, _) => Err(ColdcardError::UserCancelled),
            (ResponseMessage::Err_, data) => Err(ColdcardError::Device(
                String::from_utf8_lossy(data).into_owned(),
            )),
            (ResponseMessage::Smrx, data) => {
                let addr_len = u32::from_le_bytes(data[..4].try_into().map_err(|_| {
                    ColdcardError::Serialization("couldn't parse address length into u32".into())
                })?);
                let (_addr, sig_bytes) = split(
                    &data[4..],
                    addr_len.try_into().map_err(|_| {
                        ColdcardError::Serialization("address length can't fit into usize".into())
                    })?,
                )?;
                let sig = Signature::from_compact(&sig_bytes[1..])
                    .map_err(|e| ColdcardError::Serialization(e.to_string()))?;
                Ok(ColdcardResponse::Signature(sig_bytes[0], sig))
            }
            (ResponseMessage::Busy, _) => Ok(ColdcardResponse::Busy),
            (msg, _) => Err(ColdcardError::unexpected_response_message(
                msg,
                &[
                    ResponseMessage::Okay,
                    ResponseMessage::Busy,
                    ResponseMessage::Smrx,
                ],
            )),
        }
    }

    /// Safely splits a slice at `mid`. Returns an error if `bytes.len() < mid`.
    fn split(bytes: &[u8], mid: usize) -> Result<(&[u8], &[u8]), ColdcardError> {
        match bytes.len().cmp(&mid) {
            std::cmp::Ordering::Less => Err(ColdcardError::Serialization(
                "unexpected slice length".to_string(),
            )),
            _ => Ok(bytes.split_at(mid)),
        }
    }

    /// Safely decodes a possible 4 byte slice into an `u32`.
    fn decode_u32(bytes: Option<&[u8]>) -> Result<u32, ColdcardError> {
        match bytes {
            Some(bytes) if bytes.len() == 4 => {
                Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| {
                    ColdcardError::Serialization("u32".to_string())
                })?))
            }
            _ => Err(ColdcardError::Serialization("u32".to_string())),
        }
    }
}