Merge rust-bitcoin/rust-bitcoin#2097: Add `Witness::p2tr_key_spend` function

6715e93e89 Add Witness::p2tr_key_spend function (Tobin C. Harding)

Pull request description:

  Add a function for creating the witness when doing a key path spend for a P2TR output.

  This mirrors what we did for P2WPKH when adding `Witness::p2wpkh`.

  Includes update to the taproot signing example to use the new constructor.

ACKs for top commit:
  Kixunil:
    ACK 6715e93e89
  apoelstra:
    ACK 6715e93e89

Tree-SHA512: aab51329e8fda471442bb9cebd6327636548dd157bb9842fe66993fcdd211bb04b2b829aa9d5962dd619f5c0b73d19644a44529c1a5958df1a6bc892147b44f5
This commit is contained in:
Andrew Poelstra 2024-01-24 22:28:16 +00:00
commit 2de220ec6a
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
2 changed files with 9 additions and 2 deletions

View File

@ -76,7 +76,7 @@ fn main() {
// Update the witness stack.
let signature = bitcoin::taproot::Signature { signature, sighash_type };
sighasher.witness_mut(input_index).unwrap().push(&signature.to_vec());
*sighasher.witness_mut(input_index).unwrap() = Witness::p2tr_key_spend(&signature);
// Get the signed transaction.
let tx = sighasher.into_transaction();

View File

@ -14,7 +14,7 @@ use crate::consensus::encode::{Error, MAX_VEC_SIZE};
use crate::consensus::{Decodable, Encodable, WriteExt};
use crate::crypto::ecdsa;
use crate::prelude::*;
use crate::taproot::TAPROOT_ANNEX_PREFIX;
use crate::taproot::{self, TAPROOT_ANNEX_PREFIX};
use crate::{Script, VarInt};
/// The Witness is the data used to unlock bitcoin since the [segwit upgrade].
@ -248,6 +248,13 @@ impl Witness {
witness
}
/// Creates a witness required to do a key path spend of a P2TR output.
pub fn p2tr_key_spend(signature: &taproot::Signature) -> Witness {
let mut witness = Witness::new();
witness.push_slice(&signature.serialize());
witness
}
/// Creates a [`Witness`] object from a slice of bytes slices where each slice is a witness item.
pub fn from_slice<T: AsRef<[u8]>>(slice: &[T]) -> Self {
let witness_elements = slice.len();