2022-06-29 04:05:31 +00:00
|
|
|
// Written in 2014 by Andrew Poelstra <apoelstra@wpsoftware.net>
|
|
|
|
// SPDX-License-Identifier: CC0-1.0
|
2021-04-12 11:24:25 +00:00
|
|
|
|
2021-11-05 21:58:18 +00:00
|
|
|
//! Schnorr Bitcoin keys.
|
2021-04-12 11:24:25 +00:00
|
|
|
//!
|
2021-11-05 21:58:18 +00:00
|
|
|
//! This module provides Schnorr keys used in Bitcoin, reexporting Secp256k1
|
|
|
|
//! Schnorr key types.
|
2021-04-12 11:24:25 +00:00
|
|
|
//!
|
|
|
|
|
2021-11-16 00:00:12 +00:00
|
|
|
use core::fmt;
|
2022-06-24 02:01:53 +00:00
|
|
|
|
2022-09-05 02:19:28 +00:00
|
|
|
use bitcoin_internals::write_err;
|
|
|
|
|
2022-09-15 02:14:52 +00:00
|
|
|
pub use secp256k1::{self, constants, Secp256k1, KeyPair, XOnlyPublicKey, Verification};
|
|
|
|
|
2022-05-02 22:13:57 +00:00
|
|
|
use crate::prelude::*;
|
2021-11-16 00:00:12 +00:00
|
|
|
|
2022-05-02 22:13:57 +00:00
|
|
|
use crate::util::taproot::{TapBranchHash, TapTweakHash};
|
2022-09-15 02:59:36 +00:00
|
|
|
use crate::sighash::SchnorrSighashType;
|
2021-11-07 06:11:43 +00:00
|
|
|
|
2022-01-11 12:10:54 +00:00
|
|
|
/// Untweaked BIP-340 X-coord-only public key
|
2022-09-15 02:14:52 +00:00
|
|
|
pub type UntweakedPublicKey = XOnlyPublicKey;
|
2021-11-07 06:11:43 +00:00
|
|
|
|
2022-01-11 12:10:54 +00:00
|
|
|
/// Tweaked BIP-340 X-coord-only public key
|
2021-11-29 02:18:22 +00:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
2022-03-24 21:15:41 +00:00
|
|
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
2022-05-25 06:41:59 +00:00
|
|
|
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
|
2022-03-24 21:15:41 +00:00
|
|
|
#[cfg_attr(feature = "serde", serde(transparent))]
|
2022-09-15 02:14:52 +00:00
|
|
|
pub struct TweakedPublicKey(XOnlyPublicKey);
|
2021-11-07 06:11:43 +00:00
|
|
|
|
2021-12-12 14:23:57 +00:00
|
|
|
impl fmt::LowerHex for TweakedPublicKey {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
fmt::LowerHex::fmt(&self.0, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for TweakedPublicKey {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
fmt::Display::fmt(&self.0, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-11 12:10:54 +00:00
|
|
|
/// Untweaked BIP-340 key pair
|
2022-09-15 02:14:52 +00:00
|
|
|
pub type UntweakedKeyPair = KeyPair;
|
2022-01-11 12:10:54 +00:00
|
|
|
|
|
|
|
/// Tweaked BIP-340 key pair
|
2022-03-28 19:29:04 +00:00
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
|
|
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
2022-05-25 06:41:59 +00:00
|
|
|
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
|
2022-03-28 19:29:04 +00:00
|
|
|
#[cfg_attr(feature = "serde", serde(transparent))]
|
2022-09-15 02:14:52 +00:00
|
|
|
pub struct TweakedKeyPair(KeyPair);
|
2022-01-11 12:10:54 +00:00
|
|
|
|
|
|
|
/// A trait for tweaking BIP340 key types (x-only public keys and key pairs).
|
2021-11-07 06:11:43 +00:00
|
|
|
pub trait TapTweak {
|
2022-01-11 12:10:54 +00:00
|
|
|
/// 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.
|
2021-11-12 21:36:31 +00:00
|
|
|
///
|
|
|
|
/// This is done by using the equation Q = P + H(P|c)G, where
|
2022-01-11 12:10:54 +00:00
|
|
|
/// * Q is the tweaked public key
|
|
|
|
/// * P is the internal public key
|
2021-11-07 06:11:43 +00:00
|
|
|
/// * H is the hash function
|
|
|
|
/// * c is the commitment data
|
|
|
|
/// * G is the generator point
|
2021-12-02 03:43:38 +00:00
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
/// The tweaked key and its parity.
|
2022-01-11 12:10:54 +00:00
|
|
|
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> Self::TweakedAux;
|
2021-11-07 06:11:43 +00:00
|
|
|
|
2021-12-10 00:42:43 +00:00
|
|
|
/// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`]
|
2021-11-12 21:36:31 +00:00
|
|
|
///
|
2021-11-07 06:11:43 +00:00
|
|
|
/// 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.
|
2022-01-11 12:10:54 +00:00
|
|
|
fn dangerous_assume_tweaked(self) -> Self::TweakedKey;
|
2021-11-07 06:11:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TapTweak for UntweakedPublicKey {
|
2022-01-11 12:10:54 +00:00
|
|
|
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.
|
2022-01-03 02:52:44 +00:00
|
|
|
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> (TweakedPublicKey, secp256k1::Parity) {
|
2022-06-28 02:47:29 +00:00
|
|
|
let tweak = TapTweakHash::from_key_and_tweak(self, merkle_root).to_scalar();
|
|
|
|
let (output_key, parity) = self.add_tweak(secp, &tweak).expect("Tap tweak failed");
|
2021-12-02 03:13:33 +00:00
|
|
|
|
2022-06-28 02:47:29 +00:00
|
|
|
debug_assert!(self.tweak_add_check(secp, &output_key, parity, tweak));
|
2021-12-02 03:43:38 +00:00
|
|
|
(TweakedPublicKey(output_key), parity)
|
2021-11-07 06:11:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn dangerous_assume_tweaked(self) -> TweakedPublicKey {
|
|
|
|
TweakedPublicKey(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-11 12:10:54 +00:00
|
|
|
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.
|
2022-06-28 02:47:29 +00:00
|
|
|
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> TweakedKeyPair {
|
2022-09-15 02:14:52 +00:00
|
|
|
let (pubkey, _parity) = XOnlyPublicKey::from_keypair(&self);
|
2022-06-28 02:47:29 +00:00
|
|
|
let tweak = TapTweakHash::from_key_and_tweak(pubkey, merkle_root).to_scalar();
|
|
|
|
let tweaked = self.add_xonly_tweak(secp, &tweak).expect("Tap tweak failed");
|
|
|
|
TweakedKeyPair(tweaked)
|
2022-01-11 12:10:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn dangerous_assume_tweaked(self) -> TweakedKeyPair {
|
|
|
|
TweakedKeyPair(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 06:11:43 +00:00
|
|
|
impl TweakedPublicKey {
|
2022-01-03 02:52:44 +00:00
|
|
|
/// Creates a new [`TweakedPublicKey`] from a [`XOnlyPublicKey`]. No tweak is applied, consider
|
2021-12-02 03:40:24 +00:00
|
|
|
/// calling `tap_tweak` on an [`UntweakedPublicKey`] instead of using this constructor.
|
2022-01-11 12:10:54 +00:00
|
|
|
///
|
|
|
|
/// 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]
|
2022-09-15 02:14:52 +00:00
|
|
|
pub fn dangerous_assume_tweaked(key: XOnlyPublicKey) -> TweakedPublicKey {
|
2021-11-07 06:11:43 +00:00
|
|
|
TweakedPublicKey(key)
|
|
|
|
}
|
2021-11-12 21:36:31 +00:00
|
|
|
|
2021-12-10 00:42:43 +00:00
|
|
|
/// Returns the underlying public key.
|
2022-09-15 02:14:52 +00:00
|
|
|
pub fn to_inner(self) -> XOnlyPublicKey {
|
2021-11-07 06:11:43 +00:00
|
|
|
self.0
|
|
|
|
}
|
2021-11-12 21:36:31 +00:00
|
|
|
|
2021-12-12 14:24:31 +00:00
|
|
|
/// Serialize the key as a byte-encoded pair of values. In compressed form
|
|
|
|
/// the y-coordinate is represented by only a single bit, as x determines
|
|
|
|
/// it up to one bit.
|
|
|
|
#[inline]
|
2022-03-10 22:41:32 +00:00
|
|
|
pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
|
2021-12-12 14:24:31 +00:00
|
|
|
self.0.serialize()
|
|
|
|
}
|
2021-11-29 02:17:16 +00:00
|
|
|
}
|
2021-11-16 00:00:12 +00:00
|
|
|
|
2022-01-11 12:10:54 +00:00
|
|
|
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]
|
2022-09-15 02:14:52 +00:00
|
|
|
pub fn dangerous_assume_tweaked(pair: KeyPair) -> TweakedKeyPair {
|
2022-01-11 12:10:54 +00:00
|
|
|
TweakedKeyPair(pair)
|
|
|
|
}
|
|
|
|
|
2022-01-19 02:41:45 +00:00
|
|
|
/// Returns the underlying key pair.
|
|
|
|
#[inline]
|
2022-09-15 02:14:52 +00:00
|
|
|
pub fn to_inner(self) -> KeyPair {
|
2022-01-19 02:41:45 +00:00
|
|
|
self.0
|
|
|
|
}
|
2022-01-11 12:10:54 +00:00
|
|
|
}
|
|
|
|
|
2022-09-15 02:14:52 +00:00
|
|
|
impl From<TweakedPublicKey> for XOnlyPublicKey {
|
2022-01-13 16:40:27 +00:00
|
|
|
#[inline]
|
|
|
|
fn from(pair: TweakedPublicKey) -> Self {
|
|
|
|
pair.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-15 02:14:52 +00:00
|
|
|
impl From<TweakedKeyPair> for KeyPair {
|
2022-01-13 16:40:27 +00:00
|
|
|
#[inline]
|
|
|
|
fn from(pair: TweakedKeyPair) -> Self {
|
|
|
|
pair.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-16 00:00:12 +00:00
|
|
|
/// A BIP340-341 serialized schnorr signature with the corresponding hash type.
|
2022-05-06 03:37:24 +00:00
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
2021-10-28 07:43:02 +00:00
|
|
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
2022-05-25 06:41:59 +00:00
|
|
|
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
|
2021-11-16 00:00:12 +00:00
|
|
|
pub struct SchnorrSig {
|
|
|
|
/// The underlying schnorr signature
|
2022-01-03 02:52:44 +00:00
|
|
|
pub sig: secp256k1::schnorr::Signature,
|
2021-11-16 00:00:12 +00:00
|
|
|
/// The corresponding hash type
|
2022-03-28 21:52:33 +00:00
|
|
|
pub hash_ty: SchnorrSighashType,
|
2021-11-16 00:00:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl SchnorrSig {
|
|
|
|
/// Deserialize from slice
|
|
|
|
pub fn from_slice(sl: &[u8]) -> Result<Self, SchnorrSigError> {
|
|
|
|
match sl.len() {
|
|
|
|
64 => {
|
|
|
|
// default type
|
2022-01-03 02:52:44 +00:00
|
|
|
let sig = secp256k1::schnorr::Signature::from_slice(sl)
|
2021-11-16 00:00:12 +00:00
|
|
|
.map_err(SchnorrSigError::Secp256k1)?;
|
2022-05-25 03:32:42 +00:00
|
|
|
Ok(SchnorrSig { sig, hash_ty: SchnorrSighashType::Default })
|
2021-11-16 00:00:12 +00:00
|
|
|
},
|
|
|
|
65 => {
|
|
|
|
let (hash_ty, sig) = sl.split_last().expect("Slice len checked == 65");
|
2022-06-24 02:01:53 +00:00
|
|
|
let hash_ty = SchnorrSighashType::from_consensus_u8(*hash_ty)
|
2021-11-16 00:00:12 +00:00
|
|
|
.map_err(|_| SchnorrSigError::InvalidSighashType(*hash_ty))?;
|
2022-01-03 02:52:44 +00:00
|
|
|
let sig = secp256k1::schnorr::Signature::from_slice(sig)
|
2021-11-16 00:00:12 +00:00
|
|
|
.map_err(SchnorrSigError::Secp256k1)?;
|
|
|
|
Ok(SchnorrSig { sig, hash_ty })
|
|
|
|
}
|
|
|
|
len => {
|
|
|
|
Err(SchnorrSigError::InvalidSchnorrSigSize(len))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Serialize SchnorrSig
|
2022-08-01 22:33:22 +00:00
|
|
|
pub fn to_vec(self) -> Vec<u8> {
|
2021-11-16 00:00:12 +00:00
|
|
|
// TODO: add support to serialize to a writer to SerializedSig
|
|
|
|
let mut ser_sig = self.sig.as_ref().to_vec();
|
2022-03-28 21:52:33 +00:00
|
|
|
if self.hash_ty == SchnorrSighashType::Default {
|
2021-11-16 00:00:12 +00:00
|
|
|
// default sighash type, don't add extra sighash byte
|
|
|
|
} else {
|
|
|
|
ser_sig.push(self.hash_ty as u8);
|
|
|
|
}
|
|
|
|
ser_sig
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A schnorr sig related error.
|
|
|
|
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
2022-05-31 04:29:50 +00:00
|
|
|
#[non_exhaustive]
|
2021-11-16 00:00:12 +00:00
|
|
|
pub enum SchnorrSigError {
|
|
|
|
/// Base58 encoding error
|
|
|
|
InvalidSighashType(u8),
|
|
|
|
/// Signature has valid size but does not parse correctly
|
|
|
|
Secp256k1(secp256k1::Error),
|
|
|
|
/// Invalid schnorr signature size
|
|
|
|
InvalidSchnorrSigSize(usize),
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl fmt::Display for SchnorrSigError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match *self {
|
|
|
|
SchnorrSigError::InvalidSighashType(hash_ty) =>
|
|
|
|
write!(f, "Invalid signature hash type {}", hash_ty),
|
|
|
|
SchnorrSigError::Secp256k1(ref e) =>
|
2022-05-25 02:56:51 +00:00
|
|
|
write_err!(f, "Schnorr signature has correct len but is malformed"; e),
|
2021-11-16 00:00:12 +00:00
|
|
|
SchnorrSigError::InvalidSchnorrSigSize(sz) =>
|
|
|
|
write!(f, "Invalid Schnorr signature size: {}", sz),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature = "std")]
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
|
2022-05-04 05:56:24 +00:00
|
|
|
impl std::error::Error for SchnorrSigError {
|
|
|
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
|
|
use self::SchnorrSigError::*;
|
|
|
|
|
|
|
|
match self {
|
|
|
|
Secp256k1(e) => Some(e),
|
|
|
|
InvalidSighashType(_) | InvalidSchnorrSigSize(_) => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-11-16 00:00:12 +00:00
|
|
|
|
|
|
|
impl From<secp256k1::Error> for SchnorrSigError {
|
|
|
|
|
|
|
|
fn from(e: secp256k1::Error) -> SchnorrSigError {
|
|
|
|
SchnorrSigError::Secp256k1(e)
|
|
|
|
}
|
|
|
|
}
|