diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index ef9946c1..8e6b7591 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -7,6 +7,7 @@ jobs: name: Tests runs-on: ubuntu-latest strategy: + fail-fast: false matrix: include: - rust: stable diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index 616597df..d0aa9a19 100644 --- a/src/blockdata/script.rs +++ b/src/blockdata/script.rs @@ -41,6 +41,9 @@ use policy::DUST_RELAY_TX_FEE; use util::ecdsa::PublicKey; use util::address::WitnessVersion; +use util::taproot::{LeafVersion, TapBranchHash, TapLeafHash}; +use secp256k1::{Secp256k1, Verification}; +use schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey}; /// A Bitcoin script. #[derive(Clone, Default, PartialOrd, Ord, PartialEq, Eq, Hash)] @@ -312,13 +315,40 @@ impl Script { } /// Generates P2WPKH-type of scriptPubkey + #[deprecated(since = "0.28.0", note = "use Script::new_v0_p2wpkh method instead")] pub fn new_v0_wpkh(pubkey_hash: &WPubkeyHash) -> Script { - Script::new_witness_program(WitnessVersion::V0, &pubkey_hash.to_vec()) + Script::new_v0_p2wpkh(pubkey_hash) + } + + /// Generates P2WPKH-type of scriptPubkey + pub fn new_v0_p2wpkh(pubkey_hash: &WPubkeyHash) -> Script { + Script::new_witness_program(WitnessVersion::V0, &pubkey_hash[..]) } /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script + #[deprecated(since = "0.28.0", note = "use Script::new_v0_p2wsh method instead")] pub fn new_v0_wsh(script_hash: &WScriptHash) -> Script { - Script::new_witness_program(WitnessVersion::V0, &script_hash.to_vec()) + Script::new_v0_p2wsh(script_hash) + } + + /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script + pub fn new_v0_p2wsh(script_hash: &WScriptHash) -> Script { + Script::new_witness_program(WitnessVersion::V0, &script_hash[..]) + } + + /// Generates P2TR for script spending path using an internal public key and some optional + /// script tree merkle root. + pub fn new_v1_p2tr(secp: &Secp256k1, internal_key: UntweakedPublicKey, merkle_root: Option) -> Script { + let (output_key, _) = internal_key.tap_tweak(secp, merkle_root); + Script::new_witness_program(WitnessVersion::V1, &output_key.serialize()) + } + + /// Generates P2TR for key spending path for a known [`TweakedPublicKey`]. + /// + /// NB: Make sure that the used key is indeed tweaked (for instance, it comes from `rawtr` + /// descriptor content); otherwise please use [`Script::new_v1_p2tr`] method. + pub fn new_v1_p2tr_tweaked(output_key: TweakedPublicKey) -> Script { + Script::new_witness_program(WitnessVersion::V1, &output_key.serialize()) } /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script @@ -370,7 +400,21 @@ impl Script { /// Compute the P2WSH output corresponding to this witnessScript (aka the "witness redeem /// script") pub fn to_v0_p2wsh(&self) -> Script { - Script::new_v0_wsh(&self.wscript_hash()) + Script::new_v0_p2wsh(&self.wscript_hash()) + } + + /// Compute P2TR output with a given internal key and a single script spending path equal to the + /// current script, assuming that the script is a Tapscript + #[inline] + pub fn to_v1_p2tr(&self, secp: &Secp256k1, internal_key: UntweakedPublicKey) -> Script { + let leaf_hash = TapLeafHash::from_script(&self, LeafVersion::TapScript); + let merkle_root = TapBranchHash::from_inner(leaf_hash.into_inner()); + Script::new_v1_p2tr(&secp, internal_key, Some(merkle_root)) + } + + #[inline] + fn witness_version(&self) -> Option { + WitnessVersion::from_opcode(self.0[0].into()).ok() } /// Checks whether a script pubkey is a p2sh output @@ -428,18 +472,26 @@ impl Script { #[inline] pub fn is_v0_p2wsh(&self) -> bool { self.0.len() == 34 && - self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() && - self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() + self.witness_version() == Some(WitnessVersion::V0) && + self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() } /// Checks whether a script pubkey is a p2wpkh output #[inline] pub fn is_v0_p2wpkh(&self) -> bool { self.0.len() == 22 && - self.0[0] == opcodes::all::OP_PUSHBYTES_0.into_u8() && + self.witness_version() == Some(WitnessVersion::V0) && self.0[1] == opcodes::all::OP_PUSHBYTES_20.into_u8() } + /// Checks whether a script pubkey is a P2TR output + #[inline] + pub fn is_v1_p2tr(&self) -> bool { + self.0.len() == 34 && + self.witness_version() == Some(WitnessVersion::V1) && + self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() + } + /// Check if this is an OP_RETURN output pub fn is_op_return (&self) -> bool { !self.0.is_empty() && (opcodes::All::from(self.0[0]) == opcodes::all::OP_RETURN) @@ -1042,7 +1094,7 @@ mod test { assert!(Script::new_p2pkh(&pubkey_hash).is_p2pkh()); let wpubkey_hash = WPubkeyHash::hash(&pubkey.inner.serialize()); - assert!(Script::new_v0_wpkh(&wpubkey_hash).is_v0_p2wpkh()); + assert!(Script::new_v0_p2wpkh(&wpubkey_hash).is_v0_p2wpkh()); let script = Builder::new().push_opcode(opcodes::all::OP_NUMEQUAL) .push_verify() @@ -1053,7 +1105,7 @@ mod test { assert_eq!(script.to_p2sh(), p2sh); let wscript_hash = WScriptHash::hash(&script.serialize()); - let p2wsh = Script::new_v0_wsh(&wscript_hash); + let p2wsh = Script::new_v0_p2wsh(&wscript_hash); assert!(p2wsh.is_v0_p2wsh()); assert_eq!(script.to_v0_p2wsh(), p2wsh); diff --git a/src/util/misc.rs b/src/util/misc.rs index 5bcfb3fa..0c3ef086 100644 --- a/src/util/misc.rs +++ b/src/util/misc.rs @@ -320,7 +320,7 @@ mod tests { let msg = secp256k1::Message::from_slice(&msg_hash).unwrap(); let privkey = secp256k1::SecretKey::new(&mut secp256k1::rand::thread_rng()); - let secp_sig = secp.sign_recoverable(&msg, &privkey); + let secp_sig = secp.sign_ecdsa_recoverable(&msg, &privkey); let signature = super::MessageSignature { signature: secp_sig, compressed: true, diff --git a/src/util/schnorr.rs b/src/util/schnorr.rs index d8d6820e..8a1d8f9a 100644 --- a/src/util/schnorr.rs +++ b/src/util/schnorr.rs @@ -26,10 +26,10 @@ use hashes::Hash; use util::taproot::{TapBranchHash, TapTweakHash}; use SchnorrSigHashType; -/// Untweaked Schnorr public key +/// Untweaked BIP-340 X-coord-only public key pub type UntweakedPublicKey = XOnlyPublicKey; -/// Tweaked Schnorr public key +/// Tweaked BIP-340 X-coord-only public key #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TweakedPublicKey(XOnlyPublicKey); @@ -45,29 +45,59 @@ impl fmt::Display for TweakedPublicKey { } } -/// A trait for tweaking Schnorr public keys +/// Untweaked BIP-340 key pair +pub type UntweakedKeyPair = KeyPair; + +/// Tweaked BIP-340 key pair +#[derive(Clone)] +#[cfg_attr(feature = "std", derive(Debug))] +// TODO: Add other derives once secp256k1 v0.21.3 released +pub struct TweakedKeyPair(KeyPair); + +/// A trait for tweaking BIP340 key types (x-only public keys and key pairs). pub trait TapTweak { - /// Tweaks an untweaked public key given an untweaked key and optional script tree merkle root. + /// Tweaked key type with optional auxiliary information + type TweakedAux; + /// Tweaked key type + type TweakedKey; + + /// Tweaks an untweaked key with corresponding public key value and optional script tree merkle + /// root. For the [`KeyPair`] type this also tweaks the private key in the pair. /// /// This is done by using the equation Q = P + H(P|c)G, where - /// * Q is the tweaked key - /// * P is the internal key + /// * Q is the tweaked public key + /// * P is the internal public key /// * H is the hash function /// * c is the commitment data /// * G is the generator point /// /// # Returns /// The tweaked key and its parity. - fn tap_tweak(self, secp: &Secp256k1, merkle_root: Option) -> (TweakedPublicKey, secp256k1::Parity); + fn tap_tweak(self, secp: &Secp256k1, merkle_root: Option) -> Self::TweakedAux; /// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`] /// /// This method is dangerous and can lead to loss of funds if used incorrectly. /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal. - fn dangerous_assume_tweaked(self) -> TweakedPublicKey; + fn dangerous_assume_tweaked(self) -> Self::TweakedKey; } impl TapTweak for UntweakedPublicKey { + type TweakedAux = (TweakedPublicKey, secp256k1::Parity); + type TweakedKey = TweakedPublicKey; + + /// Tweaks an untweaked public key with corresponding public key value and optional script tree + /// merkle root. + /// + /// This is done by using the equation Q = P + H(P|c)G, where + /// * Q is the tweaked public key + /// * P is the internal public key + /// * H is the hash function + /// * c is the commitment data + /// * G is the generator point + /// + /// # Returns + /// The tweaked key and its parity. fn tap_tweak(self, secp: &Secp256k1, merkle_root: Option) -> (TweakedPublicKey, secp256k1::Parity) { let tweak_value = TapTweakHash::from_key_and_tweak(self, merkle_root).into_inner(); let mut output_key = self.clone(); @@ -82,9 +112,42 @@ impl TapTweak for UntweakedPublicKey { } } +impl TapTweak for UntweakedKeyPair { + type TweakedAux = TweakedKeyPair; + type TweakedKey = TweakedKeyPair; + + /// Tweaks private and public keys within an untweaked [`KeyPair`] with corresponding public key + /// value and optional script tree merkle root. + /// + /// This is done by tweaking private key within the pair using the equation q = p + H(P|c), where + /// * q is the tweaked private key + /// * p is the internal private key + /// * H is the hash function + /// * c is the commitment data + /// The public key is generated from a private key by multiplying with generator point, Q = qG. + /// + /// # Returns + /// The tweaked key and its parity. + fn tap_tweak(self, secp: &Secp256k1, merkle_root: Option) -> TweakedKeyPair { + let pubkey = XOnlyPublicKey::from_keypair(&self); + let tweak_value = TapTweakHash::from_key_and_tweak(pubkey, merkle_root).into_inner(); + let mut output_key = self.clone(); + output_key.tweak_add_assign(&secp, &tweak_value).expect("Tap tweak failed"); + TweakedKeyPair(output_key) + } + + fn dangerous_assume_tweaked(self) -> TweakedKeyPair { + TweakedKeyPair(self) + } +} + impl TweakedPublicKey { /// Creates a new [`TweakedPublicKey`] from a [`XOnlyPublicKey`]. No tweak is applied, consider /// calling `tap_tweak` on an [`UntweakedPublicKey`] instead of using this constructor. + /// + /// This method is dangerous and can lead to loss of funds if used incorrectly. + /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal. + #[inline] pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> TweakedPublicKey { TweakedPublicKey(key) } @@ -108,6 +171,24 @@ impl TweakedPublicKey { } } +impl TweakedKeyPair { + /// Creates a new [`TweakedKeyPair`] from a [`KeyPair`]. No tweak is applied, consider + /// calling `tap_tweak` on an [`UntweakedKeyPair`] instead of using this constructor. + /// + /// This method is dangerous and can lead to loss of funds if used incorrectly. + /// Specifically, in multi-party protocols a peer can provide a value that allows them to steal. + #[inline] + pub fn dangerous_assume_tweaked(pair: KeyPair) -> TweakedKeyPair { + TweakedKeyPair(pair) + } + + /// Returns the underlying key pair + #[inline] + pub fn into_inner(self) -> KeyPair { + self.0 + } +} + /// A BIP340-341 serialized schnorr signature with the corresponding hash type. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] @@ -119,7 +200,6 @@ pub struct SchnorrSig { } impl SchnorrSig { - /// Deserialize from slice pub fn from_slice(sl: &[u8]) -> Result { match sl.len() {