2021-04-12 11:24:25 +00:00
|
|
|
// Rust Bitcoin Library
|
|
|
|
// Written in 2014 by
|
|
|
|
// Andrew Poelstra <apoelstra@wpsoftware.net>
|
|
|
|
// To the extent possible under law, the author(s) have dedicated all
|
|
|
|
// copyright and related and neighboring rights to this software to
|
|
|
|
// the public domain worldwide. This software is distributed without
|
|
|
|
// any warranty.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the CC0 Public Domain Dedication
|
|
|
|
// along with this software.
|
|
|
|
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
|
|
|
|
//
|
|
|
|
|
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;
|
|
|
|
use prelude::*;
|
|
|
|
|
2021-04-12 11:24:25 +00:00
|
|
|
pub use secp256k1::schnorrsig::{PublicKey, KeyPair};
|
2021-11-16 00:00:12 +00:00
|
|
|
use secp256k1::{self, Secp256k1, Verification, constants};
|
2021-11-24 22:45:27 +00:00
|
|
|
use hashes::Hash;
|
2021-11-07 06:11:43 +00:00
|
|
|
use util::taproot::{TapBranchHash, TapTweakHash};
|
2021-11-16 00:00:12 +00:00
|
|
|
use SchnorrSigHashType;
|
2021-11-07 06:11:43 +00:00
|
|
|
|
|
|
|
/// Untweaked Schnorr public key
|
|
|
|
pub type UntweakedPublicKey = PublicKey;
|
|
|
|
|
|
|
|
/// Tweaked Schnorr public key
|
2021-11-29 02:18:22 +00:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
2021-11-07 06:11:43 +00:00
|
|
|
pub struct TweakedPublicKey(PublicKey);
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 06:11:43 +00:00
|
|
|
/// A trait for tweaking Schnorr public keys
|
|
|
|
pub trait TapTweak {
|
|
|
|
/// Tweaks an untweaked public key given an untweaked key and optional script tree merkle root.
|
2021-11-12 21:36:31 +00:00
|
|
|
///
|
|
|
|
/// This is done by using the equation Q = P + H(P|c)G, where
|
2021-11-07 06:11:43 +00:00
|
|
|
/// * Q is the tweaked key
|
|
|
|
/// * P is the internal key
|
|
|
|
/// * 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.
|
|
|
|
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> (TweakedPublicKey, bool);
|
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.
|
|
|
|
fn dangerous_assume_tweaked(self) -> TweakedPublicKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TapTweak for UntweakedPublicKey {
|
2021-12-02 03:43:38 +00:00
|
|
|
fn tap_tweak<C: Verification>(self, secp: &Secp256k1<C>, merkle_root: Option<TapBranchHash>) -> (TweakedPublicKey, bool) {
|
2021-11-24 22:45:27 +00:00
|
|
|
let tweak_value = TapTweakHash::from_key_and_tweak(self, merkle_root).into_inner();
|
2021-11-07 06:11:43 +00:00
|
|
|
let mut output_key = self.clone();
|
|
|
|
let parity = output_key.tweak_add_assign(&secp, &tweak_value).expect("Tap tweak failed");
|
2021-12-02 03:13:33 +00:00
|
|
|
|
|
|
|
debug_assert!(self.tweak_add_check(&secp, &output_key, parity, tweak_value));
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TweakedPublicKey {
|
2021-12-02 03:40:24 +00:00
|
|
|
/// Creates a new [`TweakedPublicKey`] from a [`PublicKey`]. No tweak is applied, consider
|
|
|
|
/// calling `tap_tweak` on an [`UntweakedPublicKey`] instead of using this constructor.
|
|
|
|
pub fn dangerous_assume_tweaked(key: PublicKey) -> 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.
|
2021-11-07 06:11:43 +00:00
|
|
|
pub fn into_inner(self) -> PublicKey {
|
|
|
|
self.0
|
|
|
|
}
|
2021-11-12 21:36:31 +00:00
|
|
|
|
2021-12-10 00:42:43 +00:00
|
|
|
/// Returns a reference to underlying public key.
|
2021-11-12 21:36:31 +00:00
|
|
|
pub fn as_inner(&self) -> &PublicKey {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
|
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]
|
|
|
|
pub fn serialize(&self) -> [u8; constants::SCHNORRSIG_PUBLIC_KEY_SIZE] {
|
|
|
|
self.0.serialize()
|
|
|
|
}
|
2021-11-29 02:17:16 +00:00
|
|
|
}
|
2021-11-16 00:00:12 +00:00
|
|
|
|
|
|
|
/// A BIP340-341 serialized schnorr signature with the corresponding hash type.
|
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
2021-10-28 07:43:02 +00:00
|
|
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
2021-11-16 00:00:12 +00:00
|
|
|
pub struct SchnorrSig {
|
|
|
|
/// The underlying schnorr signature
|
|
|
|
pub sig: secp256k1::schnorrsig::Signature,
|
|
|
|
/// The corresponding hash type
|
|
|
|
pub hash_ty: SchnorrSigHashType,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SchnorrSig {
|
|
|
|
|
|
|
|
/// Deserialize from slice
|
|
|
|
pub fn from_slice(sl: &[u8]) -> Result<Self, SchnorrSigError> {
|
|
|
|
match sl.len() {
|
|
|
|
64 => {
|
|
|
|
// default type
|
|
|
|
let sig = secp256k1::schnorrsig::Signature::from_slice(sl)
|
|
|
|
.map_err(SchnorrSigError::Secp256k1)?;
|
|
|
|
return 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_u8(*hash_ty)
|
|
|
|
.map_err(|_| SchnorrSigError::InvalidSighashType(*hash_ty))?;
|
|
|
|
let sig = secp256k1::schnorrsig::Signature::from_slice(sig)
|
|
|
|
.map_err(SchnorrSigError::Secp256k1)?;
|
|
|
|
Ok(SchnorrSig { sig, hash_ty })
|
|
|
|
}
|
|
|
|
len => {
|
|
|
|
Err(SchnorrSigError::InvalidSchnorrSigSize(len))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Serialize SchnorrSig
|
|
|
|
pub fn to_vec(&self) -> Vec<u8> {
|
|
|
|
// TODO: add support to serialize to a writer to SerializedSig
|
|
|
|
let mut ser_sig = self.sig.as_ref().to_vec();
|
|
|
|
if self.hash_ty == SchnorrSigHashType::Default {
|
|
|
|
// 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)]
|
|
|
|
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) =>
|
|
|
|
write!(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 {}
|
|
|
|
|
|
|
|
impl From<secp256k1::Error> for SchnorrSigError {
|
|
|
|
|
|
|
|
fn from(e: secp256k1::Error) -> SchnorrSigError {
|
|
|
|
SchnorrSigError::Secp256k1(e)
|
|
|
|
}
|
|
|
|
}
|