Skip to main content

keep_bitcoin/
psbt.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3use crate::error::{BitcoinError, Result};
4use bitcoin::psbt::Psbt;
5use bitcoin::secp256k1::{Keypair, Message, Secp256k1};
6use bitcoin::sighash::{Prevouts, SighashCache, TapSighashType};
7use bitcoin::taproot::Signature as TaprootSignature;
8use bitcoin::{Address, Network, TxOut, XOnlyPublicKey};
9use keep_core::crypto::MlockedBox;
10
11#[derive(Debug, Clone)]
12pub struct PsbtAnalysis {
13    pub num_inputs: usize,
14    pub num_outputs: usize,
15    pub total_input_sats: u64,
16    pub total_output_sats: u64,
17    pub fee_sats: u64,
18    pub outputs: Vec<OutputInfo>,
19    pub signable_inputs: Vec<usize>,
20}
21
22#[derive(Debug, Clone)]
23pub struct OutputInfo {
24    pub index: usize,
25    pub address: Option<String>,
26    pub amount_sats: u64,
27    pub is_change: bool,
28}
29
30// NOTE: `Keypair` (from secp256k1) does not implement `Zeroize` and cannot be reliably
31// zeroed. A single `Keypair` is created per `sign()` call to minimize stack copies.
32// The canonical secret key is held in `MlockedBox` which provides mlock + madvise +
33// zeroize-on-drop, so the authoritative copy is protected at rest.
34pub struct PsbtSigner {
35    secret: MlockedBox<32>,
36    x_only_pubkey: XOnlyPublicKey,
37    secp: Secp256k1<bitcoin::secp256k1::All>,
38    network: Network,
39}
40
41impl PsbtSigner {
42    pub fn new(secret: &mut [u8; 32], network: Network) -> Result<Self> {
43        let secp = Secp256k1::new();
44
45        let keypair = Keypair::from_seckey_slice(&secp, secret)
46            .map_err(|e| BitcoinError::InvalidSecretKey(e.to_string()))?;
47
48        let (x_only_pubkey, _parity) = keypair.x_only_public_key();
49
50        Ok(Self {
51            secret: MlockedBox::new(secret),
52            x_only_pubkey,
53            secp,
54            network,
55        })
56    }
57
58    pub fn x_only_public_key(&self) -> XOnlyPublicKey {
59        self.x_only_pubkey
60    }
61
62    fn keypair(&self) -> Result<Keypair> {
63        Keypair::from_seckey_slice(&self.secp, &*self.secret)
64            .map_err(|e| BitcoinError::InvalidSecretKey(e.to_string()))
65    }
66
67    pub fn analyze(&self, psbt: &Psbt) -> Result<PsbtAnalysis> {
68        let mut total_input_sats = 0u64;
69        let mut signable_inputs = Vec::new();
70
71        for (i, input) in psbt.inputs.iter().enumerate() {
72            let utxo = input.witness_utxo.as_ref().ok_or_else(|| {
73                BitcoinError::InvalidPsbt(format!("input {i} missing witness_utxo"))
74            })?;
75            total_input_sats = total_input_sats
76                .checked_add(utxo.value.to_sat())
77                .ok_or_else(|| BitcoinError::InvalidPsbt("input value overflow".into()))?;
78
79            if self.should_sign_input(psbt, i)? {
80                signable_inputs.push(i);
81            }
82        }
83
84        let mut outputs = Vec::new();
85        let mut total_output_sats = 0u64;
86
87        for (i, output) in psbt.unsigned_tx.output.iter().enumerate() {
88            total_output_sats = total_output_sats
89                .checked_add(output.value.to_sat())
90                .ok_or_else(|| BitcoinError::InvalidPsbt("output value overflow".into()))?;
91
92            let address = Address::from_script(&output.script_pubkey, self.network)
93                .ok()
94                .map(|a| a.to_string());
95
96            let is_change = self.is_change_output(psbt, i);
97
98            outputs.push(OutputInfo {
99                index: i,
100                address,
101                amount_sats: output.value.to_sat(),
102                is_change,
103            });
104        }
105
106        let fee_sats = total_input_sats
107            .checked_sub(total_output_sats)
108            .ok_or_else(|| BitcoinError::InvalidPsbt("outputs exceed inputs".into()))?;
109
110        Ok(PsbtAnalysis {
111            num_inputs: psbt.inputs.len(),
112            num_outputs: psbt.unsigned_tx.output.len(),
113            total_input_sats,
114            total_output_sats,
115            fee_sats,
116            outputs,
117            signable_inputs,
118        })
119    }
120
121    pub fn sign(&self, psbt: &mut Psbt) -> Result<usize> {
122        let mut signed_count = 0;
123
124        let prevouts: Vec<TxOut> = psbt
125            .inputs
126            .iter()
127            .enumerate()
128            .map(|(i, input)| {
129                input
130                    .witness_utxo
131                    .clone()
132                    .ok_or(BitcoinError::MissingWitnessUtxo(i))
133            })
134            .collect::<Result<Vec<_>>>()?;
135
136        let prevouts_ref = Prevouts::All(&prevouts);
137
138        let keypair = self.keypair()?;
139
140        for i in 0..psbt.inputs.len() {
141            if !self.should_sign_input(psbt, i)? {
142                continue;
143            }
144
145            self.sign_taproot_keypath(psbt, i, &prevouts_ref, &keypair)?;
146            signed_count += 1;
147        }
148
149        Ok(signed_count)
150    }
151
152    fn should_sign_input(&self, psbt: &Psbt, index: usize) -> Result<bool> {
153        let input = &psbt.inputs[index];
154
155        if let Some(tap_internal_key) = &input.tap_internal_key {
156            if tap_internal_key == &self.x_only_pubkey {
157                return Ok(true);
158            }
159        }
160
161        for pubkey in input.tap_key_origins.keys() {
162            if pubkey == &self.x_only_pubkey {
163                return Ok(true);
164            }
165        }
166
167        if let Some(utxo) = &input.witness_utxo {
168            let our_address = Address::p2tr(&self.secp, self.x_only_pubkey, None, self.network);
169            if utxo.script_pubkey == our_address.script_pubkey() {
170                return Ok(true);
171            }
172        }
173
174        Ok(false)
175    }
176
177    fn sign_taproot_keypath(
178        &self,
179        psbt: &mut Psbt,
180        index: usize,
181        prevouts: &Prevouts<TxOut>,
182        keypair: &Keypair,
183    ) -> Result<()> {
184        let mut sighash_cache = SighashCache::new(&psbt.unsigned_tx);
185
186        let sighash = sighash_cache
187            .taproot_key_spend_signature_hash(index, prevouts, TapSighashType::Default)
188            .map_err(|e| BitcoinError::Sighash(e.to_string()))?;
189
190        let msg = Message::from_digest_slice(sighash.as_ref())
191            .map_err(|e| BitcoinError::Signing(e.to_string()))?;
192
193        let aux_rand = crate::aux_rand()?;
194        let sig = self
195            .secp
196            .sign_schnorr_with_aux_rand(&msg, keypair, &aux_rand);
197
198        let taproot_sig = TaprootSignature {
199            signature: sig,
200            sighash_type: TapSighashType::Default,
201        };
202
203        psbt.inputs[index].tap_key_sig = Some(taproot_sig);
204
205        Ok(())
206    }
207
208    fn is_change_output(&self, psbt: &Psbt, index: usize) -> bool {
209        if let Some(output) = psbt.outputs.get(index) {
210            for pubkey in output.tap_key_origins.keys() {
211                if pubkey == &self.x_only_pubkey {
212                    return true;
213                }
214            }
215
216            if let Some(internal_key) = &output.tap_internal_key {
217                if internal_key == &self.x_only_pubkey {
218                    return true;
219                }
220            }
221        }
222        false
223    }
224}
225
226pub fn parse_psbt(data: &[u8]) -> Result<Psbt> {
227    Psbt::deserialize(data).map_err(|e| BitcoinError::InvalidPsbt(e.to_string()))
228}
229
230pub fn parse_psbt_base64(base64: &str) -> Result<Psbt> {
231    use bitcoin::base64::{engine::general_purpose::STANDARD, Engine};
232    let bytes = STANDARD
233        .decode(base64)
234        .map_err(|e| BitcoinError::InvalidPsbt(format!("Invalid base64: {e}")))?;
235    parse_psbt(&bytes)
236}
237
238pub fn serialize_psbt(psbt: &Psbt) -> Vec<u8> {
239    psbt.serialize()
240}
241
242pub fn serialize_psbt_base64(psbt: &Psbt) -> String {
243    use bitcoin::base64::{engine::general_purpose::STANDARD, Engine};
244    STANDARD.encode(psbt.serialize())
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use bitcoin::hashes::Hash;
251
252    #[test]
253    fn test_psbt_signer_creation() {
254        let mut secret = [1u8; 32];
255        let signer = PsbtSigner::new(&mut secret, Network::Testnet).unwrap();
256
257        let pubkey = signer.x_only_public_key();
258        assert_eq!(pubkey.serialize().len(), 32);
259    }
260
261    // === #417 round 4a: targeted unit tests killing the surviving mutations ===
262
263    fn fixture_psbt_to(spk: bitcoin::ScriptBuf, value: u64) -> Psbt {
264        use bitcoin::{
265            absolute::LockTime, transaction::Version, OutPoint, Sequence, Transaction, TxIn, TxOut,
266            Witness,
267        };
268        let tx = Transaction {
269            version: Version(2),
270            lock_time: LockTime::ZERO,
271            input: vec![TxIn {
272                previous_output: OutPoint {
273                    txid: bitcoin::Txid::all_zeros(),
274                    vout: 0,
275                },
276                script_sig: bitcoin::ScriptBuf::new(),
277                sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
278                witness: Witness::default(),
279            }],
280            output: vec![TxOut {
281                value: bitcoin::Amount::from_sat(50_000),
282                script_pubkey: bitcoin::ScriptBuf::new(),
283            }],
284        };
285        let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
286        psbt.inputs[0].witness_utxo = Some(TxOut {
287            value: bitcoin::Amount::from_sat(value),
288            script_pubkey: spk,
289        });
290        psbt
291    }
292
293    fn own_address(signer: &PsbtSigner) -> Address {
294        Address::p2tr(
295            &Secp256k1::new(),
296            signer.x_only_public_key(),
297            None,
298            Network::Testnet,
299        )
300    }
301
302    fn other_address(secret: &mut [u8; 32]) -> Address {
303        own_address(&PsbtSigner::new(secret, Network::Testnet).unwrap())
304    }
305
306    /// `parse_psbt(serialize_psbt(p)) == p`. The `serialize_psbt → vec![]`
307    /// and `vec![0]` / `vec![1]` regressions all produce non-PSBT bytes
308    /// that `parse_psbt` rejects, so this roundtrip catches every constant-
309    /// return mutation on `serialize_psbt`. A `serialize_psbt_base64` →
310    /// `"xyzzy"` regression is caught the same way through `parse_psbt_base64`.
311    #[test]
312    fn psbt_serialization_roundtrip() {
313        let psbt = fixture_psbt_to(bitcoin::ScriptBuf::new(), 60_000);
314
315        // Binary roundtrip.
316        let bytes = serialize_psbt(&psbt);
317        assert!(!bytes.is_empty(), "serialize_psbt must not return empty");
318        let parsed = parse_psbt(&bytes).expect("must roundtrip through binary");
319        assert_eq!(parsed.unsigned_tx, psbt.unsigned_tx);
320
321        // Base64 roundtrip.
322        let b64 = serialize_psbt_base64(&psbt);
323        assert!(
324            !b64.is_empty(),
325            "serialize_psbt_base64 must not return empty"
326        );
327        let parsed = parse_psbt_base64(&b64).expect("must roundtrip through base64");
328        assert_eq!(parsed.unsigned_tx, psbt.unsigned_tx);
329    }
330
331    /// `should_sign_input` returns false for an input whose witness_utxo
332    /// belongs to a different taproot key. A constant `Ok(true)`
333    /// regression would have us sign an input whose UTXO we don't control.
334    #[test]
335    fn should_sign_input_returns_false_for_unrelated_input() {
336        let mut our_secret = [1u8; 32];
337        let signer = PsbtSigner::new(&mut our_secret, Network::Testnet).unwrap();
338
339        let mut other_secret = [2u8; 32];
340        let other_addr = other_address(&mut other_secret);
341        let psbt = fixture_psbt_to(other_addr.script_pubkey(), 60_000);
342
343        assert!(!signer.should_sign_input(&psbt, 0).unwrap());
344    }
345
346    /// `should_sign_input` returns true when the input's witness_utxo
347    /// script_pubkey is the signer's own p2tr address (the script_pubkey
348    /// match arm). A constant `Ok(false)` regression would refuse to sign
349    /// an input we actually control.
350    #[test]
351    fn should_sign_input_returns_true_for_our_own_p2tr_input() {
352        let mut our_secret = [1u8; 32];
353        let signer = PsbtSigner::new(&mut our_secret, Network::Testnet).unwrap();
354        let our_addr = own_address(&signer);
355        let psbt = fixture_psbt_to(our_addr.script_pubkey(), 60_000);
356
357        assert!(signer.should_sign_input(&psbt, 0).unwrap());
358    }
359
360    /// `sign` returns 0 when no input matches our key and writes no
361    /// signature. A constant `Ok(1)` regression would report a phantom
362    /// signed input.
363    #[test]
364    fn sign_returns_zero_when_no_inputs_match_our_key() {
365        let mut our_secret = [1u8; 32];
366        let signer = PsbtSigner::new(&mut our_secret, Network::Testnet).unwrap();
367
368        let mut other_secret = [2u8; 32];
369        let other_addr = other_address(&mut other_secret);
370        let mut psbt = fixture_psbt_to(other_addr.script_pubkey(), 60_000);
371
372        let signed = signer.sign(&mut psbt).unwrap();
373        assert_eq!(signed, 0, "sign must report zero when no inputs match");
374        assert!(
375            psbt.inputs[0].tap_key_sig.is_none(),
376            "no signature should be written for an unrelated input"
377        );
378    }
379
380    /// `sign` signs an input addressed to our own key, writes the taproot
381    /// key-spend signature, and reports the count. This drives
382    /// `sign_taproot_keypath`; a constant `Ok(0)` regression would leave
383    /// `tap_key_sig` unset while reporting nothing signed.
384    #[test]
385    fn sign_signs_our_own_input_and_reports_count() {
386        let mut our_secret = [1u8; 32];
387        let signer = PsbtSigner::new(&mut our_secret, Network::Testnet).unwrap();
388        let our_addr = own_address(&signer);
389        let mut psbt = fixture_psbt_to(our_addr.script_pubkey(), 60_000);
390
391        let signed = signer.sign(&mut psbt).unwrap();
392        assert_eq!(signed, 1, "sign must report one signed input");
393        assert!(
394            psbt.inputs[0].tap_key_sig.is_some(),
395            "a signature must be written for our own input"
396        );
397    }
398}