Add Witness::p2tr_key_spend function

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.
This commit is contained in:
Tobin C. Harding 2023-09-30 05:53:44 +10:00
parent d08d3efdfa
commit 6715e93e89
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
2 changed files with 9 additions and 2 deletions

View File

@ -76,7 +76,7 @@ fn main() {
// Update the witness stack. // Update the witness stack.
let signature = bitcoin::taproot::Signature { signature, sighash_type }; 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. // Get the signed transaction.
let tx = sighasher.into_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::consensus::{Decodable, Encodable, WriteExt};
use crate::crypto::ecdsa; use crate::crypto::ecdsa;
use crate::prelude::*; use crate::prelude::*;
use crate::taproot::TAPROOT_ANNEX_PREFIX; use crate::taproot::{self, TAPROOT_ANNEX_PREFIX};
use crate::{Script, VarInt}; use crate::{Script, VarInt};
/// The Witness is the data used to unlock bitcoin since the [segwit upgrade]. /// The Witness is the data used to unlock bitcoin since the [segwit upgrade].
@ -248,6 +248,13 @@ impl Witness {
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. /// 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 { pub fn from_slice<T: AsRef<[u8]>>(slice: &[T]) -> Self {
let witness_elements = slice.len(); let witness_elements = slice.len();