From 599c5f9488d7d9a6b6eb0b95f64d0cf2e61d13fb Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Tue, 11 Jan 2022 13:10:54 +0100 Subject: [PATCH 1/5] Generalizing taproot key tweaking for KeyPairs --- src/util/schnorr.rs | 98 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 89 insertions(+), 9 deletions(-) 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() { From 91b68a468d945cf32dadbb24d74463e0ecd4013b Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Fri, 12 Nov 2021 23:55:28 +0100 Subject: [PATCH 2/5] Taproot-related methods for Script type --- src/blockdata/script.rs | 48 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index 616597df..b9e3d64b 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)] @@ -313,12 +316,27 @@ impl Script { /// Generates P2WPKH-type of scriptPubkey pub fn new_v0_wpkh(pubkey_hash: &WPubkeyHash) -> Script { - Script::new_witness_program(WitnessVersion::V0, &pubkey_hash.to_vec()) + Script::new_witness_program(WitnessVersion::V0, &pubkey_hash[..]) } /// Generates P2WSH-type of scriptPubkey with a given hash of the redeem script pub fn new_v0_wsh(script_hash: &WScriptHash) -> Script { - Script::new_witness_program(WitnessVersion::V0, &script_hash.to_vec()) + 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 @@ -373,6 +391,20 @@ impl Script { Script::new_v0_wsh(&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 #[inline] pub fn is_p2sh(&self) -> bool { @@ -428,7 +460,7 @@ 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.witness_version() == Some(WitnessVersion::V0) && self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() } @@ -436,10 +468,18 @@ impl Script { #[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) From f77c57195a671a5735c694b6f0e9ff7dbae692c1 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Sat, 8 Jan 2022 23:52:21 +0100 Subject: [PATCH 3/5] Making Script method new_* names more consistent --- src/blockdata/script.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index b9e3d64b..d0aa9a19 100644 --- a/src/blockdata/script.rs +++ b/src/blockdata/script.rs @@ -315,12 +315,24 @@ 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_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_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[..]) } @@ -388,7 +400,7 @@ 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 @@ -461,7 +473,7 @@ impl Script { pub fn is_v0_p2wsh(&self) -> bool { self.0.len() == 34 && self.witness_version() == Some(WitnessVersion::V0) && - self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() + self.0[1] == opcodes::all::OP_PUSHBYTES_32.into_u8() } /// Checks whether a script pubkey is a p2wpkh output @@ -1082,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() @@ -1093,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); From f39b1300faaa5edfc49b98c5e234f8b9774985dd Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Fri, 12 Nov 2021 23:55:52 +0100 Subject: [PATCH 4/5] CI: do not fail fast --- .github/workflows/rust.yml | 1 + 1 file changed, 1 insertion(+) 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 From 7405836411130255a4148b31789f95e50c19c3b4 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Fri, 7 Jan 2022 21:44:57 +0100 Subject: [PATCH 5/5] Fix warning about deprecated method use --- src/util/misc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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,