Coverage Report

Created: 2024-10-10 10:38

/home/darosior/projects/bdk/crates/wallet/tests/psbt.rs
Line
Count
Source (jump to first uncovered line)
1
use bdk_wallet::bitcoin::{Amount, FeeRate, Psbt, TxIn};
2
use bdk_wallet::{psbt, KeychainKind, SignOptions};
3
use core::str::FromStr;
4
mod common;
5
use common::*;
6
7
// from bip 174
8
const PSBT_STR: &str = "cHNidP8BAKACAAAAAqsJSaCMWvfEm4IS9Bfi8Vqz9cM9zxU4IagTn4d6W3vkAAAAAAD+////qwlJoIxa98SbghL0F+LxWrP1wz3PFTghqBOfh3pbe+QBAAAAAP7///8CYDvqCwAAAAAZdqkUdopAu9dAy+gdmI5x3ipNXHE5ax2IrI4kAAAAAAAAGXapFG9GILVT+glechue4O/p+gOcykWXiKwAAAAAAAEHakcwRAIgR1lmF5fAGwNrJZKJSGhiGDR9iYZLcZ4ff89X0eURZYcCIFMJ6r9Wqk2Ikf/REf3xM286KdqGbX+EhtdVRs7tr5MZASEDXNxh/HupccC1AaZGoqg7ECy0OIEhfKaC3Ibi1z+ogpIAAQEgAOH1BQAAAAAXqRQ1RebjO4MsRwUPJNPuuTycA5SLx4cBBBYAFIXRNTfy4mVAWjTbr6nj3aAfuCMIAAAA";
9
10
#[test]
11
#[should_panic(expected = "InputIndexOutOfRange")]
12
1
fn test_psbt_malformed_psbt_input_legacy() {
13
1
    let psbt_bip = Psbt::from_str(PSBT_STR).unwrap();
14
1
    let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
15
1
    let send_to = wallet.peek_address(KeychainKind::External, 0);
16
1
    let mut builder = wallet.build_tx();
17
1
    builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
18
1
    let mut psbt = builder.finish().unwrap();
19
1
    psbt.inputs.push(psbt_bip.inputs[0].clone());
20
1
    let options = SignOptions {
21
1
        trust_witness_utxo: true,
22
1
        ..Default::default()
23
1
    };
24
1
    let _ = wallet.sign(&mut psbt, options).unwrap();
25
1
}
26
27
#[test]
28
#[should_panic(expected = "InputIndexOutOfRange")]
29
1
fn test_psbt_malformed_psbt_input_segwit() {
30
1
    let psbt_bip = Psbt::from_str(PSBT_STR).unwrap();
31
1
    let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
32
1
    let send_to = wallet.peek_address(KeychainKind::External, 0);
33
1
    let mut builder = wallet.build_tx();
34
1
    builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
35
1
    let mut psbt = builder.finish().unwrap();
36
1
    psbt.inputs.push(psbt_bip.inputs[1].clone());
37
1
    let options = SignOptions {
38
1
        trust_witness_utxo: true,
39
1
        ..Default::default()
40
1
    };
41
1
    let _ = wallet.sign(&mut psbt, options).unwrap();
42
1
}
43
44
#[test]
45
#[should_panic(expected = "InputIndexOutOfRange")]
46
1
fn test_psbt_malformed_tx_input() {
47
1
    let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
48
1
    let send_to = wallet.peek_address(KeychainKind::External, 0);
49
1
    let mut builder = wallet.build_tx();
50
1
    builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
51
1
    let mut psbt = builder.finish().unwrap();
52
1
    psbt.unsigned_tx.input.push(TxIn::default());
53
1
    let options = SignOptions {
54
1
        trust_witness_utxo: true,
55
1
        ..Default::default()
56
1
    };
57
1
    let _ = wallet.sign(&mut psbt, options).unwrap();
58
1
}
59
60
#[test]
61
1
fn test_psbt_sign_with_finalized() {
62
1
    let psbt_bip = Psbt::from_str(PSBT_STR).unwrap();
63
1
    let (mut wallet, _) = get_funded_wallet(get_test_wpkh());
64
1
    let send_to = wallet.peek_address(KeychainKind::External, 0);
65
1
    let mut builder = wallet.build_tx();
66
1
    builder.add_recipient(send_to.script_pubkey(), Amount::from_sat(10_000));
67
1
    let mut psbt = builder.finish().unwrap();
68
1
69
1
    // add a finalized input
70
1
    psbt.inputs.push(psbt_bip.inputs[0].clone());
71
1
    psbt.unsigned_tx
72
1
        .input
73
1
        .push(psbt_bip.unsigned_tx.input[0].clone());
74
1
75
1
    let _ = wallet.sign(&mut psbt, SignOptions::default()).unwrap();
76
1
}
77
78
#[test]
79
1
fn test_psbt_fee_rate_with_witness_utxo() {
80
1
    use psbt::PsbtUtils;
81
1
82
1
    let expected_fee_rate = FeeRate::from_sat_per_kwu(310);
83
1
84
1
    let (mut wallet, _) = get_funded_wallet("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)");
85
1
    let addr = wallet.peek_address(KeychainKind::External, 0);
86
1
    let mut builder = wallet.build_tx();
87
1
    builder.drain_to(addr.script_pubkey()).drain_wallet();
88
1
    builder.fee_rate(expected_fee_rate);
89
1
    let mut psbt = builder.finish().unwrap();
90
1
    let fee_amount = psbt.fee_amount();
91
1
    assert!(fee_amount.is_some());
92
93
1
    let unfinalized_fee_rate = psbt.fee_rate().unwrap();
94
1
95
1
    let finalized = wallet.sign(&mut psbt, Default::default()).unwrap();
96
1
    assert!(finalized);
97
98
1
    let finalized_fee_rate = psbt.fee_rate().unwrap();
99
1
    assert!(finalized_fee_rate >= expected_fee_rate);
100
1
    assert!(finalized_fee_rate < unfinalized_fee_rate);
101
1
}
102
103
#[test]
104
1
fn test_psbt_fee_rate_with_nonwitness_utxo() {
105
1
    use psbt::PsbtUtils;
106
1
107
1
    let expected_fee_rate = FeeRate::from_sat_per_kwu(310);
108
1
109
1
    let (mut wallet, _) = get_funded_wallet("pkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)");
110
1
    let addr = wallet.peek_address(KeychainKind::External, 0);
111
1
    let mut builder = wallet.build_tx();
112
1
    builder.drain_to(addr.script_pubkey()).drain_wallet();
113
1
    builder.fee_rate(expected_fee_rate);
114
1
    let mut psbt = builder.finish().unwrap();
115
1
    let fee_amount = psbt.fee_amount();
116
1
    assert!(fee_amount.is_some());
117
1
    let unfinalized_fee_rate = psbt.fee_rate().unwrap();
118
1
119
1
    let finalized = wallet.sign(&mut psbt, Default::default()).unwrap();
120
1
    assert!(finalized);
121
122
1
    let finalized_fee_rate = psbt.fee_rate().unwrap();
123
1
    assert!(finalized_fee_rate >= expected_fee_rate);
124
1
    assert!(finalized_fee_rate < unfinalized_fee_rate);
125
1
}
126
127
#[test]
128
1
fn test_psbt_fee_rate_with_missing_txout() {
129
1
    use psbt::PsbtUtils;
130
1
131
1
    let expected_fee_rate = FeeRate::from_sat_per_kwu(310);
132
1
133
1
    let (mut wpkh_wallet,  _) = get_funded_wallet("wpkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/*)");
134
1
    let addr = wpkh_wallet.peek_address(KeychainKind::External, 0);
135
1
    let mut builder = wpkh_wallet.build_tx();
136
1
    builder.drain_to(addr.script_pubkey()).drain_wallet();
137
1
    builder.fee_rate(expected_fee_rate);
138
1
    let mut wpkh_psbt = builder.finish().unwrap();
139
1
140
1
    wpkh_psbt.inputs[0].witness_utxo = None;
141
1
    wpkh_psbt.inputs[0].non_witness_utxo = None;
142
1
    assert!(wpkh_psbt.fee_amount().is_none());
143
1
    assert!(wpkh_psbt.fee_rate().is_none());
144
145
1
    let desc = "pkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/0)";
146
1
    let change_desc = "pkh(tprv8ZgxMBicQKsPd3EupYiPRhaMooHKUHJxNsTfYuScep13go8QFfHdtkG9nRkFGb7busX4isf6X9dURGCoKgitaApQ6MupRhZMcELAxTBRJgS/1)";
147
1
    let (mut pkh_wallet, _) = get_funded_wallet_with_change(desc, change_desc);
148
1
    let addr = pkh_wallet.peek_address(KeychainKind::External, 0);
149
1
    let mut builder = pkh_wallet.build_tx();
150
1
    builder.drain_to(addr.script_pubkey()).drain_wallet();
151
1
    builder.fee_rate(expected_fee_rate);
152
1
    let mut pkh_psbt = builder.finish().unwrap();
153
1
154
1
    pkh_psbt.inputs[0].non_witness_utxo = None;
155
1
    assert!(pkh_psbt.fee_amount().is_none());
156
1
    assert!(pkh_psbt.fee_rate().is_none());
157
1
}
158
159
#[test]
160
1
fn test_psbt_multiple_internalkey_signers() {
161
1
    use bdk_wallet::signer::{SignerContext, SignerOrdering, SignerWrapper};
162
1
    use bdk_wallet::KeychainKind;
163
1
    use bitcoin::key::TapTweak;
164
1
    use bitcoin::secp256k1::{schnorr, Keypair, Message, Secp256k1, XOnlyPublicKey};
165
1
    use bitcoin::sighash::{Prevouts, SighashCache, TapSighashType};
166
1
    use bitcoin::{PrivateKey, TxOut};
167
1
    use std::sync::Arc;
168
1
169
1
    let secp = Secp256k1::new();
170
1
    let wif = "cNJmN3fH9DDbDt131fQNkVakkpzawJBSeybCUNmP1BovpmGQ45xG";
171
1
    let desc = format!("tr({})", wif);
172
1
    let prv = PrivateKey::from_wif(wif).unwrap();
173
1
    let keypair = Keypair::from_secret_key(&secp, &prv.inner);
174
1
175
1
    let change_desc = "tr(cVpPVruEDdmutPzisEsYvtST1usBR3ntr8pXSyt6D2YYqXRyPcFW)";
176
1
    let (mut wallet, _) = get_funded_wallet_with_change(&desc, change_desc);
177
1
    let to_spend = wallet.balance().total();
178
1
    let send_to = wallet.peek_address(KeychainKind::External, 0);
179
1
    let mut builder = wallet.build_tx();
180
1
    builder.drain_to(send_to.script_pubkey()).drain_wallet();
181
1
    let mut psbt = builder.finish().unwrap();
182
1
    let unsigned_tx = psbt.unsigned_tx.clone();
183
1
184
1
    // Adds a signer for the wrong internal key, bdk should not use this key to sign
185
1
    wallet.add_signer(
186
1
        KeychainKind::External,
187
1
        // A signerordering lower than 100, bdk will use this signer first
188
1
        SignerOrdering(0),
189
1
        Arc::new(SignerWrapper::new(
190
1
            PrivateKey::from_wif("5J5PZqvCe1uThJ3FZeUUFLCh2FuK9pZhtEK4MzhNmugqTmxCdwE").unwrap(),
191
1
            SignerContext::Tap {
192
1
                is_internal_key: true,
193
1
            },
194
1
        )),
195
1
    );
196
1
    let finalized = wallet.sign(&mut psbt, SignOptions::default()).unwrap();
197
1
    assert!(finalized);
198
199
    // To verify, we need the signature, message, and pubkey
200
1
    let witness = psbt.inputs[0].final_script_witness.as_ref().unwrap();
201
1
    assert!(!witness.is_empty());
202
1
    let signature = schnorr::Signature::from_slice(witness.iter().next().unwrap()).unwrap();
203
1
204
1
    // the prevout we're spending
205
1
    let prevouts = &[TxOut {
206
1
        script_pubkey: send_to.script_pubkey(),
207
1
        value: to_spend,
208
1
    }];
209
1
    let prevouts = Prevouts::All(prevouts);
210
1
    let input_index = 0;
211
1
    let mut sighash_cache = SighashCache::new(unsigned_tx);
212
1
    let sighash = sighash_cache
213
1
        .taproot_key_spend_signature_hash(input_index, &prevouts, TapSighashType::Default)
214
1
        .unwrap();
215
1
    let message = Message::from(sighash);
216
1
217
1
    // add tweak. this was taken from `signer::sign_psbt_schnorr`
218
1
    let keypair = keypair.tap_tweak(&secp, None).to_inner();
219
1
    let (xonlykey, _parity) = XOnlyPublicKey::from_keypair(&keypair);
220
1
221
1
    // Must verify if we used the correct key to sign
222
1
    let verify_res = secp.verify_schnorr(&signature, &message, &xonlykey);
223
1
    assert!(verify_res.is_ok(), 
"The wrong internal key was used"0
);
224
1
}