-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbtc.rs
1235 lines (1150 loc) · 45.3 KB
/
btc.rs
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
//! Functions and methods related to Bitcoin.
use crate::runtime::Runtime;
use crate::error::Error;
use crate::pb::{self, request::Request, response::Response};
use crate::Keypath;
use crate::PairedBitBox;
pub use bitcoin::{
bip32::{Fingerprint, Xpub},
blockdata::script::witness_version::WitnessVersion,
Script,
};
#[cfg(feature = "wasm")]
use enum_assoc::Assoc;
#[cfg(feature = "wasm")]
pub(crate) fn serde_deserialize_simple_type<'de, D>(deserializer: D) -> Result<i32, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
Ok(pb::btc_script_config::SimpleType::deserialize(deserializer)?.into())
}
#[cfg(feature = "wasm")]
pub(crate) fn serde_deserialize_multisig<'de, D>(
deserializer: D,
) -> Result<pb::btc_script_config::Multisig, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
use std::str::FromStr;
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct Multisig {
threshold: u32,
xpubs: Vec<String>,
our_xpub_index: u32,
script_type: pb::btc_script_config::multisig::ScriptType,
}
let ms = Multisig::deserialize(deserializer)?;
let xpubs = ms
.xpubs
.iter()
.map(|s| Xpub::from_str(s.as_str()))
.collect::<Result<Vec<Xpub>, _>>()
.map_err(serde::de::Error::custom)?;
Ok(pb::btc_script_config::Multisig {
threshold: ms.threshold,
xpubs: xpubs.iter().map(convert_xpub).collect(),
our_xpub_index: ms.our_xpub_index,
script_type: ms.script_type.into(),
})
}
#[cfg(feature = "wasm")]
#[derive(serde::Deserialize)]
pub(crate) struct SerdeScriptConfig(pb::btc_script_config::Config);
#[cfg(feature = "wasm")]
impl From<SerdeScriptConfig> for pb::BtcScriptConfig {
fn from(value: SerdeScriptConfig) -> Self {
pb::BtcScriptConfig {
config: Some(value.0),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PrevTxInput {
pub prev_out_hash: Vec<u8>,
pub prev_out_index: u32,
pub signature_script: Vec<u8>,
pub sequence: u32,
}
impl From<&bitcoin::TxIn> for PrevTxInput {
fn from(value: &bitcoin::TxIn) -> Self {
PrevTxInput {
prev_out_hash: (value.previous_output.txid.as_ref() as &[u8]).to_vec(),
prev_out_index: value.previous_output.vout,
signature_script: value.script_sig.as_bytes().to_vec(),
sequence: value.sequence.to_consensus_u32(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PrevTxOutput {
pub value: u64,
pub pubkey_script: Vec<u8>,
}
impl From<&bitcoin::TxOut> for PrevTxOutput {
fn from(value: &bitcoin::TxOut) -> Self {
PrevTxOutput {
value: value.value.to_sat(),
pubkey_script: value.script_pubkey.as_bytes().to_vec(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PrevTx {
pub version: u32,
pub inputs: Vec<PrevTxInput>,
pub outputs: Vec<PrevTxOutput>,
pub locktime: u32,
}
impl From<&bitcoin::Transaction> for PrevTx {
fn from(value: &bitcoin::Transaction) -> Self {
PrevTx {
version: value.version.0 as _,
inputs: value.input.iter().map(PrevTxInput::from).collect(),
outputs: value.output.iter().map(PrevTxOutput::from).collect(),
locktime: value.lock_time.to_consensus_u32(),
}
}
}
#[derive(Debug, PartialEq)]
pub struct TxInput {
pub prev_out_hash: Vec<u8>,
pub prev_out_index: u32,
pub prev_out_value: u64,
pub sequence: u32,
pub keypath: Keypath,
pub script_config_index: u32,
// Can be None if all transaction inputs are Taproot.
pub prev_tx: Option<PrevTx>,
}
impl TxInput {
fn get_prev_tx(&self) -> Result<&PrevTx, Error> {
self.prev_tx.as_ref().ok_or(Error::BtcSign(
"input's previous transaction required but missing".into(),
))
}
}
#[derive(Debug, PartialEq)]
pub struct TxInternalOutput {
pub keypath: Keypath,
pub value: u64,
pub script_config_index: u32,
}
#[derive(Debug, PartialEq)]
pub struct Payload {
pub data: Vec<u8>,
pub output_type: pb::BtcOutputType,
}
#[derive(thiserror::Error, Debug)]
pub enum PayloadError {
#[error("unrecognized pubkey script")]
Unrecognized,
}
impl Payload {
pub fn from_pkscript(pkscript: &[u8]) -> Result<Payload, PayloadError> {
let script = Script::from_bytes(pkscript);
if script.is_p2pkh() {
Ok(Payload {
data: pkscript[3..23].to_vec(),
output_type: pb::BtcOutputType::P2pkh,
})
} else if script.is_p2sh() {
Ok(Payload {
data: pkscript[2..22].to_vec(),
output_type: pb::BtcOutputType::P2sh,
})
} else if script.is_p2wpkh() {
Ok(Payload {
data: pkscript[2..].to_vec(),
output_type: pb::BtcOutputType::P2wpkh,
})
} else if script.is_p2wsh() {
Ok(Payload {
data: pkscript[2..].to_vec(),
output_type: pb::BtcOutputType::P2wsh,
})
} else if script.is_p2tr() {
Ok(Payload {
data: pkscript[2..].to_vec(),
output_type: pb::BtcOutputType::P2tr,
})
} else {
Err(PayloadError::Unrecognized)
}
}
}
#[derive(Debug, PartialEq)]
pub struct TxExternalOutput {
pub payload: Payload,
pub value: u64,
}
impl TryFrom<&bitcoin::TxOut> for TxExternalOutput {
type Error = PsbtError;
fn try_from(value: &bitcoin::TxOut) -> Result<Self, Self::Error> {
Ok(TxExternalOutput {
payload: Payload::from_pkscript(value.script_pubkey.as_bytes())
.map_err(|_| PsbtError::UnknownOutputType)?,
value: value.value.to_sat(),
})
}
}
#[derive(Debug, PartialEq)]
pub enum TxOutput {
Internal(TxInternalOutput),
External(TxExternalOutput),
}
#[derive(Debug, PartialEq)]
pub struct Transaction {
pub script_configs: Vec<pb::BtcScriptConfigWithKeypath>,
pub version: u32,
pub inputs: Vec<TxInput>,
pub outputs: Vec<TxOutput>,
pub locktime: u32,
}
// See https://github.com/spesmilo/electrum/blob/84dc181b6e7bb20e88ef6b98fb8925c5f645a765/electrum/ecc.py#L521-L523
#[derive(Debug, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SignMessageSignature {
pub sig: Vec<u8>,
pub recid: u8,
pub electrum_sig65: Vec<u8>,
}
#[derive(thiserror::Error, Debug)]
#[cfg_attr(feature = "wasm", derive(Assoc), func(pub const fn js_code(&self) -> &'static str))]
pub enum PsbtError {
#[error("{0}")]
#[cfg_attr(feature = "wasm", assoc(js_code = "sign-error"))]
SignError(#[from] bitcoin::psbt::SignError),
#[error("Taproot pubkeys must be unique across the internal key and all leaf scripts.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "key-not-unique"))]
KeyNotUnique,
#[error("Could not find our key in an input.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "key-not-found"))]
KeyNotFound,
#[error("Unrecognized/unsupported output type.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "unknown-output-type"))]
UnknownOutputType,
}
enum OurKey {
Segwit(bitcoin::secp256k1::PublicKey, Keypath),
TaprootInternal(Keypath),
TaprootScript(
bitcoin::secp256k1::XOnlyPublicKey,
bitcoin::taproot::TapLeafHash,
Keypath,
),
}
impl OurKey {
fn keypath(&self) -> Keypath {
match self {
OurKey::Segwit(_, kp) => kp.clone(),
OurKey::TaprootInternal(kp) => kp.clone(),
OurKey::TaprootScript(_, _, kp) => kp.clone(),
}
}
}
trait PsbtOutputInfo {
fn get_bip32_derivation(
&self,
) -> &std::collections::BTreeMap<bitcoin::secp256k1::PublicKey, bitcoin::bip32::KeySource>;
fn get_tap_internal_key(&self) -> Option<&bitcoin::secp256k1::XOnlyPublicKey>;
fn get_tap_key_origins(
&self,
) -> &std::collections::BTreeMap<
bitcoin::secp256k1::XOnlyPublicKey,
(
Vec<bitcoin::taproot::TapLeafHash>,
bitcoin::bip32::KeySource,
),
>;
}
impl PsbtOutputInfo for &bitcoin::psbt::Input {
fn get_bip32_derivation(
&self,
) -> &std::collections::BTreeMap<bitcoin::secp256k1::PublicKey, bitcoin::bip32::KeySource> {
&self.bip32_derivation
}
fn get_tap_internal_key(&self) -> Option<&bitcoin::secp256k1::XOnlyPublicKey> {
self.tap_internal_key.as_ref()
}
fn get_tap_key_origins(
&self,
) -> &std::collections::BTreeMap<
bitcoin::secp256k1::XOnlyPublicKey,
(
Vec<bitcoin::taproot::TapLeafHash>,
bitcoin::bip32::KeySource,
),
> {
&self.tap_key_origins
}
}
impl PsbtOutputInfo for &bitcoin::psbt::Output {
fn get_bip32_derivation(
&self,
) -> &std::collections::BTreeMap<bitcoin::secp256k1::PublicKey, bitcoin::bip32::KeySource> {
&self.bip32_derivation
}
fn get_tap_internal_key(&self) -> Option<&bitcoin::secp256k1::XOnlyPublicKey> {
self.tap_internal_key.as_ref()
}
fn get_tap_key_origins(
&self,
) -> &std::collections::BTreeMap<
bitcoin::secp256k1::XOnlyPublicKey,
(
Vec<bitcoin::taproot::TapLeafHash>,
bitcoin::bip32::KeySource,
),
> {
&self.tap_key_origins
}
}
fn find_our_key<T: PsbtOutputInfo>(
our_root_fingerprint: &[u8],
output_info: T,
) -> Result<OurKey, PsbtError> {
for (xonly, (leaf_hashes, (fingerprint, derivation_path))) in
output_info.get_tap_key_origins().iter()
{
if &fingerprint[..] == our_root_fingerprint {
// TODO: check for fingerprint collision
if let Some(tap_internal_key) = output_info.get_tap_internal_key() {
if tap_internal_key == xonly {
if !leaf_hashes.is_empty() {
// TODO change err msg, we don't support the
// same key as internal key and also in a leaf
// script.
return Err(PsbtError::KeyNotUnique);
}
return Ok(OurKey::TaprootInternal(derivation_path.into()));
}
}
if leaf_hashes.len() != 1 {
// TODO change err msg, per BIP-388 all pubkeys are
// unique, so it can't be in multiple leafs.
return Err(PsbtError::KeyNotUnique);
}
return Ok(OurKey::TaprootScript(
*xonly,
leaf_hashes[0],
derivation_path.into(),
));
}
}
for (pubkey, (fingerprint, derivation_path)) in output_info.get_bip32_derivation().iter() {
if &fingerprint[..] == our_root_fingerprint {
// TODO: check for fingerprint collision
return Ok(OurKey::Segwit(*pubkey, derivation_path.into()));
}
}
Err(PsbtError::KeyNotFound)
}
fn script_config_from_utxo(
output: &bitcoin::TxOut,
keypath: Keypath,
redeem_script: Option<&bitcoin::ScriptBuf>,
_witness_script: Option<&bitcoin::ScriptBuf>,
) -> Result<pb::BtcScriptConfigWithKeypath, PsbtError> {
let keypath = keypath.hardened_prefix();
if output.script_pubkey.is_p2wpkh() {
return Ok(pb::BtcScriptConfigWithKeypath {
script_config: Some(make_script_config_simple(
pb::btc_script_config::SimpleType::P2wpkh,
)),
keypath: keypath.to_vec(),
});
}
let redeem_script_is_p2wpkh = redeem_script.map(|s| s.is_p2wpkh()).unwrap_or(false);
if output.script_pubkey.is_p2sh() && redeem_script_is_p2wpkh {
return Ok(pb::BtcScriptConfigWithKeypath {
script_config: Some(make_script_config_simple(
pb::btc_script_config::SimpleType::P2wpkhP2sh,
)),
keypath: keypath.to_vec(),
});
}
if output.script_pubkey.is_p2tr() {
return Ok(pb::BtcScriptConfigWithKeypath {
script_config: Some(make_script_config_simple(
pb::btc_script_config::SimpleType::P2tr,
)),
keypath: keypath.to_vec(),
});
}
// Check for segwit multisig (p2wsh or p2wsh-p2sh).
let redeem_script_is_p2wsh = redeem_script.map(|s| s.is_p2wsh()).unwrap_or(false);
let is_p2wsh_p2sh = output.script_pubkey.is_p2sh() && redeem_script_is_p2wsh;
if output.script_pubkey.is_p2wsh() || is_p2wsh_p2sh {
todo!();
}
Err(PsbtError::UnknownOutputType)
}
impl Transaction {
fn from_psbt(
our_root_fingerprint: &[u8],
psbt: &bitcoin::psbt::Psbt,
force_script_config: Option<pb::BtcScriptConfigWithKeypath>,
) -> Result<(Self, Vec<OurKey>), PsbtError> {
let mut script_configs: Vec<pb::BtcScriptConfigWithKeypath> = Vec::new();
let mut is_script_config_forced = false;
if let Some(cfg) = force_script_config {
script_configs.push(cfg);
is_script_config_forced = true;
}
let mut our_keys: Vec<OurKey> = Vec::new();
let mut inputs: Vec<TxInput> = Vec::new();
let mut add_script_config = |script_config: pb::BtcScriptConfigWithKeypath| -> usize {
match script_configs.iter().position(|el| el == &script_config) {
Some(pos) => pos,
None => {
script_configs.push(script_config);
script_configs.len() - 1
}
}
};
for (input_index, (tx_input, psbt_input)) in
psbt.unsigned_tx.input.iter().zip(&psbt.inputs).enumerate()
{
let utxo = psbt.spend_utxo(input_index)?;
let our_key = find_our_key(our_root_fingerprint, psbt_input)?;
let script_config_index = if is_script_config_forced {
0
} else {
add_script_config(script_config_from_utxo(
utxo,
our_key.keypath(),
psbt_input.redeem_script.as_ref(),
psbt_input.witness_script.as_ref(),
)?)
};
inputs.push(TxInput {
prev_out_hash: (tx_input.previous_output.txid.as_ref() as &[u8]).to_vec(),
prev_out_index: tx_input.previous_output.vout,
prev_out_value: utxo.value.to_sat(),
sequence: tx_input.sequence.to_consensus_u32(),
keypath: our_key.keypath(),
script_config_index: script_config_index as _,
prev_tx: psbt_input.non_witness_utxo.as_ref().map(PrevTx::from),
});
our_keys.push(our_key);
}
let mut outputs: Vec<TxOutput> = Vec::new();
for (tx_output, psbt_output) in psbt.unsigned_tx.output.iter().zip(&psbt.outputs) {
let our_key = find_our_key(our_root_fingerprint, psbt_output);
// Either change output or a non-change output owned by the BitBox.
match our_key {
Ok(our_key) => {
let script_config_index = if is_script_config_forced {
0
} else {
add_script_config(script_config_from_utxo(
tx_output,
our_key.keypath(),
psbt_output.redeem_script.as_ref(),
psbt_output.witness_script.as_ref(),
)?)
};
outputs.push(TxOutput::Internal(TxInternalOutput {
keypath: our_key.keypath(),
value: tx_output.value.to_sat(),
script_config_index: script_config_index as _,
}));
}
Err(_) => {
outputs.push(TxOutput::External(tx_output.try_into()?));
}
}
}
Ok((
Transaction {
script_configs,
version: psbt.unsigned_tx.version.0 as _,
inputs,
outputs,
locktime: psbt.unsigned_tx.lock_time.to_consensus_u32(),
},
our_keys,
))
}
}
/// Create a single-sig script config.
pub fn make_script_config_simple(
simple_type: pb::btc_script_config::SimpleType,
) -> pb::BtcScriptConfig {
pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::SimpleType(
simple_type.into(),
)),
}
}
#[derive(Clone)]
#[cfg_attr(
feature = "wasm",
derive(serde::Deserialize),
serde(rename_all = "camelCase")
)]
#[derive(PartialEq)]
pub struct KeyOriginInfo {
pub root_fingerprint: Option<bitcoin::bip32::Fingerprint>,
pub keypath: Option<Keypath>,
pub xpub: bitcoin::bip32::Xpub,
}
fn convert_xpub(xpub: &bitcoin::bip32::Xpub) -> pb::XPub {
pb::XPub {
depth: vec![xpub.depth],
parent_fingerprint: xpub.parent_fingerprint[..].to_vec(),
child_num: xpub.child_number.into(),
chain_code: xpub.chain_code[..].to_vec(),
public_key: xpub.public_key.serialize().to_vec(),
}
}
impl From<KeyOriginInfo> for pb::KeyOriginInfo {
fn from(value: KeyOriginInfo) -> Self {
pb::KeyOriginInfo {
root_fingerprint: value
.root_fingerprint
.map_or(vec![], |fp| fp.as_bytes().to_vec()),
keypath: value.keypath.map_or(vec![], |kp| kp.to_vec()),
xpub: Some(convert_xpub(&value.xpub)),
}
}
}
/// Create a multi-sig script config.
pub fn make_script_config_multisig(
threshold: u32,
xpubs: &[bitcoin::bip32::Xpub],
our_xpub_index: u32,
script_type: pb::btc_script_config::multisig::ScriptType,
) -> pb::BtcScriptConfig {
pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::Multisig(
pb::btc_script_config::Multisig {
threshold,
xpubs: xpubs.iter().map(convert_xpub).collect(),
our_xpub_index,
script_type: script_type as _,
},
)),
}
}
/// Create a wallet policy script config according to the wallet policies BIP:
/// <https://github.com/bitcoin/bips/pull/1389>
///
/// At least one of the keys must be ours, i.e. contain our root fingerprint and a keypath to one of
/// our xpubs.
pub fn make_script_config_policy(policy: &str, keys: &[KeyOriginInfo]) -> pb::BtcScriptConfig {
pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::Policy(
pb::btc_script_config::Policy {
policy: policy.into(),
keys: keys.iter().cloned().map(pb::KeyOriginInfo::from).collect(),
},
)),
}
}
fn is_taproot_simple(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
matches!(
script_config.script_config.as_ref(),
Some(pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::SimpleType(simple_type)),
}) if *simple_type == pb::btc_script_config::SimpleType::P2tr as i32
)
}
fn is_taproot_policy(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
matches!(
script_config.script_config.as_ref(),
Some(pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::Policy(policy)),
}) if policy.policy.as_str().starts_with("tr("),
)
}
fn is_schnorr(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
is_taproot_simple(script_config) | is_taproot_policy(script_config)
}
impl<R: Runtime> PairedBitBox<R> {
/// Retrieves an xpub. For non-standard keypaths, a warning is displayed on the BitBox even if
/// `display` is false.
pub async fn btc_xpub(
&self,
coin: pb::BtcCoin,
keypath: &Keypath,
xpub_type: pb::btc_pub_request::XPubType,
display: bool,
) -> Result<String, Error> {
match self
.query_proto(Request::BtcPub(pb::BtcPubRequest {
coin: coin as _,
keypath: keypath.to_vec(),
display,
output: Some(pb::btc_pub_request::Output::XpubType(xpub_type as _)),
}))
.await?
{
Response::Pub(pb::PubResponse { r#pub }) => Ok(r#pub),
_ => Err(Error::UnexpectedResponse),
}
}
/// Retrieves a Bitcoin address at the provided keypath.
///
/// For the simple script configs (single-sig), the keypath must follow the
/// BIP44/BIP49/BIP84/BIP86 conventions.
pub async fn btc_address(
&self,
coin: pb::BtcCoin,
keypath: &Keypath,
script_config: &pb::BtcScriptConfig,
display: bool,
) -> Result<String, Error> {
match self
.query_proto(Request::BtcPub(pb::BtcPubRequest {
coin: coin as _,
keypath: keypath.to_vec(),
display,
output: Some(pb::btc_pub_request::Output::ScriptConfig(
script_config.clone(),
)),
}))
.await?
{
Response::Pub(pb::PubResponse { r#pub }) => Ok(r#pub),
_ => Err(Error::UnexpectedResponse),
}
}
async fn query_proto_btc(
&self,
request: pb::btc_request::Request,
) -> Result<pb::btc_response::Response, Error> {
match self
.query_proto(Request::Btc(pb::BtcRequest {
request: Some(request),
}))
.await?
{
Response::Btc(pb::BtcResponse {
response: Some(response),
}) => Ok(response),
_ => Err(Error::UnexpectedResponse),
}
}
async fn get_next_response(&self, request: Request) -> Result<pb::BtcSignNextResponse, Error> {
match self.query_proto(request).await? {
Response::BtcSignNext(next_response) => Ok(next_response),
_ => Err(Error::UnexpectedResponse),
}
}
async fn get_next_response_nested(
&self,
request: pb::btc_request::Request,
) -> Result<pb::BtcSignNextResponse, Error> {
match self.query_proto_btc(request).await? {
pb::btc_response::Response::SignNext(next_response) => Ok(next_response),
_ => Err(Error::UnexpectedResponse),
}
}
/// Sign a Bitcoin transaction. Returns one 64 byte signature (compact serlization of the R and
/// S values) per input.
pub async fn btc_sign(
&self,
coin: pb::BtcCoin,
transaction: &Transaction,
format_unit: pb::btc_sign_init_request::FormatUnit,
) -> Result<Vec<Vec<u8>>, Error> {
self.validate_version(">=9.4.0")?; // anti-klepto since 9.4.0
if transaction.script_configs.iter().any(is_taproot_simple) {
self.validate_version(">=9.10.0")?; // taproot since 9.10.0
}
let mut sigs: Vec<Vec<u8>> = Vec::new();
let mut next_response = self
.get_next_response(Request::BtcSignInit(pb::BtcSignInitRequest {
coin: coin as _,
script_configs: transaction.script_configs.clone(),
output_script_configs: vec![],
version: transaction.version,
num_inputs: transaction.inputs.len() as _,
num_outputs: transaction.outputs.len() as _,
locktime: transaction.locktime,
format_unit: format_unit as _,
contains_silent_payment_outputs: false,
}))
.await?;
let mut is_inputs_pass2 = false;
loop {
match pb::btc_sign_next_response::Type::try_from(next_response.r#type)
.map_err(|_| Error::UnexpectedResponse)?
{
pb::btc_sign_next_response::Type::Input => {
let input_index: usize = next_response.index as _;
let tx_input: &TxInput = &transaction.inputs[input_index];
let input_is_schnorr = is_schnorr(
&transaction.script_configs[tx_input.script_config_index as usize],
);
let perform_antiklepto = is_inputs_pass2 && !input_is_schnorr;
let host_nonce = if perform_antiklepto {
Some(crate::antiklepto::gen_host_nonce()?)
} else {
None
};
next_response = self
.get_next_response(Request::BtcSignInput(pb::BtcSignInputRequest {
prev_out_hash: tx_input.prev_out_hash.clone(),
prev_out_index: tx_input.prev_out_index,
prev_out_value: tx_input.prev_out_value,
sequence: tx_input.sequence,
keypath: tx_input.keypath.to_vec(),
script_config_index: tx_input.script_config_index,
host_nonce_commitment: host_nonce.as_ref().map(|host_nonce| {
pb::AntiKleptoHostNonceCommitment {
commitment: crate::antiklepto::host_commit(host_nonce).to_vec(),
}
}),
}))
.await?;
if let Some(host_nonce) = host_nonce {
if next_response.r#type
!= pb::btc_sign_next_response::Type::HostNonce as i32
{
return Err(Error::UnexpectedResponse);
}
if let Some(pb::AntiKleptoSignerCommitment { commitment }) =
next_response.anti_klepto_signer_commitment
{
next_response = self
.get_next_response_nested(
pb::btc_request::Request::AntikleptoSignature(
pb::AntiKleptoSignatureRequest {
host_nonce: host_nonce.to_vec(),
},
),
)
.await?;
if !next_response.has_signature {
return Err(Error::UnexpectedResponse);
}
crate::antiklepto::verify_ecdsa(
&host_nonce,
&commitment,
&next_response.signature,
)?
} else {
return Err(Error::UnexpectedResponse);
}
}
if is_inputs_pass2 {
if !next_response.has_signature {
return Err(Error::UnexpectedResponse);
}
sigs.push(next_response.signature.clone());
}
if input_index == transaction.inputs.len() - 1 {
is_inputs_pass2 = true
}
}
pb::btc_sign_next_response::Type::PrevtxInit => {
let prevtx: &PrevTx =
transaction.inputs[next_response.index as usize].get_prev_tx()?;
next_response = self
.get_next_response_nested(pb::btc_request::Request::PrevtxInit(
pb::BtcPrevTxInitRequest {
version: prevtx.version,
num_inputs: prevtx.inputs.len() as _,
num_outputs: prevtx.outputs.len() as _,
locktime: prevtx.locktime,
},
))
.await?;
}
pb::btc_sign_next_response::Type::PrevtxInput => {
let prevtx: &PrevTx =
transaction.inputs[next_response.index as usize].get_prev_tx()?;
let prevtx_input: &PrevTxInput =
&prevtx.inputs[next_response.prev_index as usize];
next_response = self
.get_next_response_nested(pb::btc_request::Request::PrevtxInput(
pb::BtcPrevTxInputRequest {
prev_out_hash: prevtx_input.prev_out_hash.clone(),
prev_out_index: prevtx_input.prev_out_index,
signature_script: prevtx_input.signature_script.clone(),
sequence: prevtx_input.sequence,
},
))
.await?;
}
pb::btc_sign_next_response::Type::PrevtxOutput => {
let prevtx: &PrevTx =
transaction.inputs[next_response.index as usize].get_prev_tx()?;
let prevtx_output: &PrevTxOutput =
&prevtx.outputs[next_response.prev_index as usize];
next_response = self
.get_next_response_nested(pb::btc_request::Request::PrevtxOutput(
pb::BtcPrevTxOutputRequest {
value: prevtx_output.value,
pubkey_script: prevtx_output.pubkey_script.clone(),
},
))
.await?;
}
pb::btc_sign_next_response::Type::Output => {
let tx_output: &TxOutput = &transaction.outputs[next_response.index as usize];
let request: Request = match tx_output {
TxOutput::Internal(output) => {
Request::BtcSignOutput(pb::BtcSignOutputRequest {
ours: true,
value: output.value,
keypath: output.keypath.to_vec(),
script_config_index: output.script_config_index,
..Default::default()
})
}
TxOutput::External(output) => {
Request::BtcSignOutput(pb::BtcSignOutputRequest {
ours: false,
value: output.value,
r#type: output.payload.output_type as _,
payload: output.payload.data.clone(),
..Default::default()
})
}
};
next_response = self.get_next_response(request).await?;
}
pb::btc_sign_next_response::Type::Done => break,
pb::btc_sign_next_response::Type::HostNonce => {
return Err(Error::UnexpectedResponse);
}
_ => return Err(Error::UnexpectedResponse),
}
}
Ok(sigs)
}
/// Sign a PSBT.
///
/// If `force_script_config` is None, we attempt to infer the involved script configs. For the
/// simple script config (single sig), we infer the script config from the involved redeem
/// scripts and provided derviation paths.
///
/// Multisig and policy configs are currently not inferred and must be provided using
/// `force_script_config`.
pub async fn btc_sign_psbt(
&self,
coin: pb::BtcCoin,
psbt: &mut bitcoin::psbt::Psbt,
force_script_config: Option<pb::BtcScriptConfigWithKeypath>,
format_unit: pb::btc_sign_init_request::FormatUnit,
) -> Result<(), Error> {
// since v9.15.0, the BitBox02 accepts "internal" outputs (ones sent to the BitBox02 with
// the keypath) even if the keypath is not a change keypath. PSBTs often contain the key
// origin info in outputs even in regular send-to-self outputs.
self.validate_version(">=9.15.0")?;
let our_root_fingerprint = hex::decode(self.root_fingerprint().await?).unwrap();
let (transaction, our_keys) =
Transaction::from_psbt(&our_root_fingerprint, psbt, force_script_config)?;
let signatures = self.btc_sign(coin, &transaction, format_unit).await?;
for (psbt_input, (signature, our_key)) in
psbt.inputs.iter_mut().zip(signatures.iter().zip(our_keys))
{
match our_key {
OurKey::Segwit(pubkey, _) => {
psbt_input.partial_sigs.insert(
bitcoin::PublicKey::new(pubkey),
bitcoin::ecdsa::Signature {
signature: bitcoin::secp256k1::ecdsa::Signature::from_compact(
signature,
)
.map_err(|_| Error::InvalidSignature)?,
sighash_type: bitcoin::sighash::EcdsaSighashType::All,
},
);
}
OurKey::TaprootInternal(_) => {
psbt_input.tap_key_sig = Some(
bitcoin::taproot::Signature::from_slice(signature)
.map_err(|_| Error::InvalidSignature)?,
);
}
OurKey::TaprootScript(xonly, leaf_hash, _) => {
let sig = bitcoin::taproot::Signature::from_slice(signature)
.map_err(|_| Error::InvalidSignature)?;
psbt_input.tap_script_sigs.insert((xonly, leaf_hash), sig);
}
}
}
Ok(())
}
/// Sign a message.
pub async fn btc_sign_message(
&self,
coin: pb::BtcCoin,
script_config: pb::BtcScriptConfigWithKeypath,
msg: &[u8],
) -> Result<SignMessageSignature, Error> {
self.validate_version(">=9.5.0")?;
let host_nonce = crate::antiklepto::gen_host_nonce()?;
let request = pb::BtcSignMessageRequest {
coin: coin as _,
script_config: Some(script_config),
msg: msg.to_vec(),
host_nonce_commitment: Some(pb::AntiKleptoHostNonceCommitment {
commitment: crate::antiklepto::host_commit(&host_nonce).to_vec(),
}),
};
let response = self
.query_proto_btc(pb::btc_request::Request::SignMessage(request))
.await?;
let signer_commitment = match response {
pb::btc_response::Response::AntikleptoSignerCommitment(
pb::AntiKleptoSignerCommitment { commitment },
) => commitment,
_ => return Err(Error::UnexpectedResponse),
};
let request = pb::AntiKleptoSignatureRequest {
host_nonce: host_nonce.to_vec(),
};
let response = self
.query_proto_btc(pb::btc_request::Request::AntikleptoSignature(request))
.await?;
let signature = match response {
pb::btc_response::Response::SignMessage(pb::BtcSignMessageResponse { signature }) => {
signature
}
_ => return Err(Error::UnexpectedResponse),
};
crate::antiklepto::verify_ecdsa(&host_nonce, &signer_commitment, &signature)?;
let sig = signature[..64].to_vec();
let recid = signature[64];
let compressed: u8 = 4; // BitBox02 uses only compressed pubkeys
let sig65: u8 = 27 + compressed + recid;
let mut electrum_sig65 = vec![sig65];
electrum_sig65.extend_from_slice(&sig);
Ok(SignMessageSignature {
sig,
recid,
electrum_sig65,
})
}