Merge rust-bitcoin/rust-bitcoin#2082: example: Modify `taproot-psbt.rs` to make the use of prevouts clearer.

3b60ad5567 example: Modify `taproot-psbt.rs` to make the use of prevouts clearer. (S. Santos)

Pull request description:

  The `taroot-psbt.rs` example uses only one input, and therefore the current code may not make it clear that the number of prevout items must correspond to the number of transaction inputs, since the prevout slice is built within a loop.

  This PR aims to make this clear to any user who wants to reuse the logic from the example code.

ACKs for top commit:
  tcharding:
    ACK 3b60ad5567
  apoelstra:
    ACK 3b60ad5567

Tree-SHA512: afad63782b0e8a459de6cf69712d31fdab860c0d4cf9f3a51c3d85544a067bd50f4febc10ec4046e3a37d9ca518bbf2460c2599f1569549701c07f8a267dfd05
This commit is contained in:
Andrew Poelstra 2023-10-01 14:53:40 +00:00
commit bd9c4125cf
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 12 additions and 4 deletions

View File

@ -218,6 +218,7 @@ struct P2trUtxo<'a> {
derivation_path: &'a str,
}
#[allow(clippy::single_element_loop)]
fn generate_bip86_key_spend_tx(
secp: &secp256k1::Secp256k1<secp256k1::All>,
master_xpriv: Xpriv,
@ -267,6 +268,16 @@ fn generate_bip86_key_spend_tx(
input.tap_internal_key = Some(input_pubkey);
psbt.inputs = vec![input];
// The `Prevouts::All` array is used to create the sighash to sign for each input in the
// `psbt.inputs` array, as such it must be the same length and in the same order as the inputs.
let mut input_txouts = Vec::<TxOut>::new();
for input in [&input_utxo].iter() {
input_txouts.push(TxOut {
value: input.amount_in_sats,
script_pubkey: ScriptBuf::from_hex(input.script_pubkey)?,
});
}
// SIGNER
let unsigned_tx = psbt.unsigned_tx.clone();
psbt.inputs.iter_mut().enumerate().try_for_each::<_, Result<(), Box<dyn std::error::Error>>>(
@ -277,10 +288,7 @@ fn generate_bip86_key_spend_tx(
.unwrap_or(TapSighashType::All);
let hash = SighashCache::new(&unsigned_tx).taproot_key_spend_signature_hash(
vout,
&sighash::Prevouts::All(&[TxOut {
value: from_amount,
script_pubkey: ScriptBuf::from_hex(input_utxo.script_pubkey)?,
}]),
&sighash::Prevouts::All(input_txouts.as_slice()),
hash_ty,
)?;