use core::fmt;
use crate::prelude::*;
use secp256k1::{self, Secp256k1, Verification, constants};
use crate::util::taproot::{TapBranchHash, TapTweakHash};
use crate::SchnorrSighashType;
use crate::internal_macros::write_err;
#[deprecated(since = "0.28.0", note = "Please use `util::key::XOnlyPublicKey` instead")]
pub type XOnlyPublicKey = secp256k1::XOnlyPublicKey;
#[deprecated(since = "0.28.0", note = "Please use `util::key::KeyPair` instead")]
pub type KeyPair = secp256k1::KeyPair;
pub type UntweakedPublicKey = crate::XOnlyPublicKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct TweakedPublicKey(crate::XOnlyPublicKey);
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)
}
}
pub type UntweakedKeyPair = crate::KeyPair;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct TweakedKeyPair(crate::KeyPair);
pub trait TapTweak {
type TweakedAux;
type TweakedKey;
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> Self::TweakedAux;
fn dangerous_assume_tweaked(self) -> Self::TweakedKey;
}
impl TapTweak for UntweakedPublicKey {
type TweakedAux = (TweakedPublicKey, secp256k1::Parity);
type TweakedKey = TweakedPublicKey;
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> (TweakedPublicKey, secp256k1::Parity) {
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");
debug_assert!(self.tweak_add_check(secp, &output_key, parity, tweak));
(TweakedPublicKey(output_key), parity)
}
fn dangerous_assume_tweaked(self) -> TweakedPublicKey {
TweakedPublicKey(self)
}
}
impl TapTweak for UntweakedKeyPair {
type TweakedAux = TweakedKeyPair;
type TweakedKey = TweakedKeyPair;
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> TweakedKeyPair {
let (pubkey, _parity) = crate::XOnlyPublicKey::from_keypair(&self);
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)
}
fn dangerous_assume_tweaked(self) -> TweakedKeyPair {
TweakedKeyPair(self)
}
}
impl TweakedPublicKey {
#[inline]
pub fn dangerous_assume_tweaked(key: crate::XOnlyPublicKey) -> TweakedPublicKey {
TweakedPublicKey(key)
}
pub fn to_inner(self) -> crate::XOnlyPublicKey {
self.0
}
#[inline]
pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
self.0.serialize()
}
}
impl TweakedKeyPair {
#[inline]
pub fn dangerous_assume_tweaked(pair: crate::KeyPair) -> TweakedKeyPair {
TweakedKeyPair(pair)
}
#[inline]
#[deprecated(since = "0.29.0", note = "use to_inner instead")]
pub fn into_inner(self) -> crate::KeyPair {
self.0
}
#[inline]
pub fn to_inner(self) -> crate::KeyPair {
self.0
}
}
impl From<TweakedPublicKey> for crate::XOnlyPublicKey {
#[inline]
fn from(pair: TweakedPublicKey) -> Self {
pair.0
}
}
impl From<TweakedKeyPair> for crate::KeyPair {
#[inline]
fn from(pair: TweakedKeyPair) -> Self {
pair.0
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct SchnorrSig {
pub sig: secp256k1::schnorr::Signature,
pub hash_ty: SchnorrSighashType,
}
impl SchnorrSig {
pub fn from_slice(sl: &[u8]) -> Result<Self, SchnorrSigError> {
match sl.len() {
64 => {
let sig = secp256k1::schnorr::Signature::from_slice(sl)
.map_err(SchnorrSigError::Secp256k1)?;
Ok(SchnorrSig { sig, hash_ty: SchnorrSighashType::Default })
},
65 => {
let (hash_ty, sig) = sl.split_last().expect("Slice len checked == 65");
let hash_ty = SchnorrSighashType::from_consensus_u8(*hash_ty)
.map_err(|_| SchnorrSigError::InvalidSighashType(*hash_ty))?;
let sig = secp256k1::schnorr::Signature::from_slice(sig)
.map_err(SchnorrSigError::Secp256k1)?;
Ok(SchnorrSig { sig, hash_ty })
}
len => {
Err(SchnorrSigError::InvalidSchnorrSigSize(len))
}
}
}
pub fn to_vec(self) -> Vec<u8> {
let mut ser_sig = self.sig.as_ref().to_vec();
if self.hash_ty == SchnorrSighashType::Default {
} else {
ser_sig.push(self.hash_ty as u8);
}
ser_sig
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[non_exhaustive]
pub enum SchnorrSigError {
InvalidSighashType(u8),
Secp256k1(secp256k1::Error),
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) =>
write_err!(f, "Schnorr signature has correct len but is malformed"; e),
SchnorrSigError::InvalidSchnorrSigSize(sz) =>
write!(f, "Invalid Schnorr signature size: {}", sz),
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
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,
}
}
}
impl From<secp256k1::Error> for SchnorrSigError {
fn from(e: secp256k1::Error) -> SchnorrSigError {
SchnorrSigError::Secp256k1(e)
}
}