diff --git a/src/lib.rs b/src/lib.rs index 33fa51f7..35158379 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,6 +108,18 @@ pub enum Error { CannotRecoverAdaptorSecret, /// Given adaptor signature is not valid for the provided combination of public key, encryption key and message CannotVerifyAdaptorSignature, + /// Cannot establish Musig pre-session + InvalidMusigPreSession, + /// Invalid tweak to Musig public key + InvalidMusigTweak, + /// Cannot establish a Musig session + InvalidMusigSession, + /// Invalid Musig public nonces + InvalidMusigPubNonce, + /// Invalid Musig partial signature + InvalidMusigPartSig, + /// Cannot extract Musig secret adaptor + InvalidMusigExtract, } // Passthrough Debug to Display, since errors should be user-visible @@ -127,6 +139,12 @@ impl fmt::Display for Error { Error::Upstream(inner) => return write!(f, "{}", inner), Error::InvalidTweakLength => "Tweak must of size 32", Error::TweakOutOfBounds => "Tweak must be less than secp curve order", + Error::InvalidMusigPreSession => "failed to create Musig pre-session", + Error::InvalidMusigTweak => "malformed Musig tweak", + Error::InvalidMusigSession => "failed to create a Musig session", + Error::InvalidMusigPubNonce => "malformed Musig public nonce(s)", + Error::InvalidMusigPartSig => "malformed Musig partial signature", + Error::InvalidMusigExtract => "failed to extract Musig secret adaptor", }; f.write_str(str) diff --git a/src/zkp/mod.rs b/src/zkp/mod.rs index ec800fc4..c948b04b 100644 --- a/src/zkp/mod.rs +++ b/src/zkp/mod.rs @@ -1,6 +1,8 @@ mod ecdsa_adaptor; mod generator; #[cfg(feature = "std")] +mod musig; +#[cfg(feature = "std")] mod pedersen; #[cfg(feature = "std")] mod rangeproof; @@ -11,6 +13,8 @@ mod tag; pub use self::ecdsa_adaptor::*; pub use self::generator::*; #[cfg(feature = "std")] +pub use self::musig::*; +#[cfg(feature = "std")] pub use self::pedersen::*; #[cfg(feature = "std")] pub use self::rangeproof::*; diff --git a/src/zkp/musig.rs b/src/zkp/musig.rs new file mode 100644 index 00000000..79a3d447 --- /dev/null +++ b/src/zkp/musig.rs @@ -0,0 +1,1175 @@ +///! This module implements high-level Rust bindings for a Schnorr-based +///! multi-signature scheme called MuSig2 (https://eprint.iacr.org/2020/1261). +///! It is compatible with bip-schnorr. +///! +///! Documentation tests and some examples in [examples/musig.rs] show how the library can be used. +///! +///! The module also supports adaptor signatures as described in +///! https://github.com/ElementsProject/scriptless-scripts/pull/24 +///! +///! The documentation in this include file is for reference and may not be sufficient +///! for users to begin using the library. A full description of the C API usage can be found +///! in [C-musig.md](secp256k1-sys/depend/secp256k1/src/modules/musig/musig.md), and Rust API +///! usage can be found in [Rust-musig.md](USAGE.md). +use ffi::{self, CPtr}; +use schnorrsig::KeyPair; +use Error; +use Signing; +use {Message, PublicKey, Secp256k1, SecretKey, Signature}; + +/// Data structure containing auxiliary data generated in `pubkey_combine` and +/// required for `session_*_init`. +/// Fields: +/// magic: Set during initialization in `pubkey_combine` to allow +/// detecting an uninitialized object. +/// pk_hash: The 32-byte hash of the original public keys +/// second_pk: Serialized x-coordinate of the second public key in the list. +/// Filled with zeros if there is none. +/// pk_parity: Whether the MuSig-aggregated point was negated when +/// converting it to the combined xonly pubkey. +/// is_tweaked: Whether the combined pubkey was tweaked +/// tweak: If is_tweaked, array with the 32-byte tweak +/// internal_key_parity: If is_tweaked, the parity of the combined pubkey +/// before tweaking +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigPreSession { + inner: ffi::MusigPreSession, + combined_pk: ffi::XOnlyPublicKey, +} + +impl CPtr for MusigPreSession { + type Target = ffi::MusigPreSession; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigPreSession { + /// Create a new MusigPreSession by supplying a list of PublicKeys used in the session + /// + /// Computes a combined public key and the hash of the given public keys. + /// + /// Different orders of `pubkeys` result in different `combined_pk`s. + /// + /// The pubkeys can be sorted before combining with `rustsecp256k1zkp_v0_4_0_xonly_sort` which + /// ensures the same resulting `combined_pk` for the same multiset of pubkeys. + /// This is useful to do before pubkey_combine, such that the order of pubkeys + /// does not affect the combined public key. + /// + /// Returns: MusigPreSession if the public keys were successfully combined, Error otherwise + /// Args: secp: Secp256k1 context object initialized for verification + /// Out: pre_session: `MusigPreSession` struct to be used in + /// `MusigPreSession::process_nonces` or `MusigPreSession::pubkey_tweak_add`. + /// `MusigPreSession` also contains the Musig-combined xonly public key + /// In: pubkeys: input array of public keys to combine. The order + /// is important; a different order will result in a different + /// combined public key + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{MusigPreSession, PublicKey, Secp256k1, SecretKey}; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let _pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// ``` + pub fn new(secp: &Secp256k1, pubkeys: &[PublicKey]) -> Result { + let cx = *secp.ctx(); + let xonlys = pubkeys + .iter() + .map(|k| ffi::xonly_from_pubkey(cx, k.as_ptr()).0) + .collect::>(); + let xonly_ptrs = xonlys + .iter() + .map(|k| k as *const ffi::XOnlyPublicKey) + .collect::>(); + let mut pre_session = ffi::MusigPreSession::new(); + + unsafe { + let mut combined_pk = ffi::XOnlyPublicKey::new(); + if ffi::secp256k1_musig_pubkey_combine( + cx, + // FIXME: passing null pointer to ScratchSpace uses less efficient algorithm + // Need scratch_space_{create,destroy} exposed in public C API to safely handle + // memory + std::ptr::null_mut(), + &mut combined_pk, + &mut pre_session, + xonly_ptrs.as_ptr() as *const *const _, + xonly_ptrs.len(), + ) == 0 + { + Err(Error::InvalidMusigPreSession) + } else { + Ok(Self { + inner: pre_session, + combined_pk, + }) + } + } + } + + /// Tweak an x-only public key by adding the generator multiplied with tweak32 + /// to it. The resulting output_pubkey with the given combined_pk and tweak + /// passes `rustsecp256k1zkp_v0_4_0_xonly_pubkey_tweak_test`. + /// + /// This function is only useful before initializing a signing session. If you + /// are only computing a public key, but not intending to create a signature for + /// it, you can just use `rustsecp256k1zkp_v0_4_0_xonly_pubkey_tweak_add`. Can only be called + /// once with a given pre_session. + /// + /// Returns: Error if the arguments are invalid or the resulting public key would be + /// invalid (only when the tweak is the negation of the corresponding + /// secret key). Tweaked PublicKey otherwise. + /// Args: secp: Secp256k1 context object initialized for verification + /// Out: output_pubkey: PublicKey with the result of the tweak + /// In: tweak32: const reference to a 32-byte tweak. If the tweak is invalid + /// according to rustsecp256k1zkp_v0_4_0_ec_seckey_verify, this function + /// returns Error. For uniformly random 32-byte arrays the + /// chance of being invalid is negligible (around 1 in + /// 2^128) + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{MusigPreSession, PublicKey, Secp256k1, SecretKey}; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let mut pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let _pubkey = pre_session.pubkey_tweak_add(&secp, &[2; 32]).unwrap(); + /// ``` + pub fn pubkey_tweak_add( + &mut self, + secp: &Secp256k1, + tweak: &[u8; 32], + ) -> Result { + let cx = *secp.ctx(); + unsafe { + let mut out = ffi::PublicKey::new(); + if ffi::secp256k1_musig_pubkey_tweak_add( + cx, + self.as_mut_ptr(), + &mut out, + &self.combined_pk, + tweak.as_ptr(), + ) == 0 + { + Err(Error::InvalidMusigTweak) + } else { + Ok(PublicKey::from(out)) + } + } + } + + /// Process MusigPreSession nonces to create a session cache and signature template + /// Takes the public nonces of all signers and computes a session cache that is + /// required for signing and verification of partial signatures and a signature + /// template that is required for combining partial signatures. + /// + /// Returns: Error if the arguments are invalid or if all signers sent invalid + /// pubnonces, MusigCacheTemplate otherwise + /// Args: secp: Secp256k1 context object, initialized for verification + /// Out: musig_cache_template: + /// - stores the MusigCache , which is used for [MusigPreSession::partial_sign] and [MusigPreSession::partial_verify] + /// - stores the MusigTemplate, which is used for [MusigTemplate::partial_sig_combine] + /// - stores an integer that indicates the parity of the combined public nonce. Used for adaptor signatures + /// In: pubnonces: array of 66-byte pubnonces sent by the signers + /// msg: the 32-byte Message to sign + /// adaptor: optional pointer to an adaptor point encoded as a public + /// key if this signing session is part of an adaptor + /// signature protocol + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// let session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// let _cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// ``` + pub fn process_nonces( + &self, + secp: &Secp256k1, + pubnonces: &[MusigPubNonce], + msg: &Message, + adaptor: Option<&PublicKey>, + ) -> Result { + let mut session_cache = MusigSessionCache(ffi::MusigSessionCache::new()); + let mut template = MusigTemplate(ffi::MusigTemplate::new()); + let mut nonce_parity = 0i32; + let nonces = pubnonces.iter().map(|n| n.as_raw_ptr()).collect::>(); + let (adaptor_ptr, parity_ptr) = match adaptor { + Some(a) => (a.as_ptr(), &mut nonce_parity as *mut _), + None => (core::ptr::null(), core::ptr::null_mut()), + }; + unsafe { + if ffi::secp256k1_musig_process_nonces( + *secp.ctx(), + session_cache.as_mut_ptr(), + template.as_mut_ptr(), + parity_ptr, + nonces.as_ptr(), + nonces.len(), + msg.as_ptr(), + &self.combined_pk, + self.as_ptr(), + adaptor_ptr, + ) == 0 + { + Err(Error::InvalidMusigPubNonce) + } else { + Ok(MusigCacheTemplate { + session_cache, + template, + nonce_parity, + }) + } + } + } + + /// Produces a partial signature + /// + /// This function sets the given secnonce to 0 and will abort if given a + /// secnonce that is 0. This is a best effort attempt to protect against nonce + /// reuse. However, this is of course easily defeated if the secnonce has been + /// copied (or serialized). + /// + /// Remember that nonce reuse will immediately leak the secret key! + /// + /// Returns: Error if the arguments are invalid or the provided secnonce has already + /// been used for signing, MusigPartialSignature otherwise + /// Args: ctx: pointer to a context object (cannot be NULL) + /// In/Out: secnonce: MusigSecNonce struct created in [MusigSession::new] + /// In: keypair: Keypair to sign the message with + /// session_cache: MusigSessionCache that was created with [MusigPartialSig::process_nonces] + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let _partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// ``` + pub fn partial_sign( + &self, + secp: &Secp256k1, + secnonce: &mut MusigSecNonce, + cache: &MusigSessionCache, + keypair: &KeyPair, + ) -> Result { + unsafe { + let mut partial_sig = MusigPartialSignature(ffi::MusigPartialSignature::new()); + if ffi::secp256k1_musig_partial_sign( + *secp.ctx(), + partial_sig.as_mut_ptr(), + secnonce.as_mut_ptr(), + keypair.as_ptr(), + self.as_ptr(), + cache.as_ptr(), + ) == 0 + { + Err(Error::InvalidMusigPartSig) + } else { + Ok(partial_sig) + } + } + } + + /// Checks that an individual partial signature verifies + /// + /// This function is essential when using protocols with adaptor signatures. + /// However, it is not essential for regular MuSig's, in the sense that if any + /// partial signatures does not verify, the full signature will also not verify, so the + /// problem will be caught. But this function allows determining the specific party + /// who produced an invalid signature, so that signing can be restarted without them. + /// + /// Returns: false if the arguments are invalid or the partial signature does not + /// verify, true otherwise + /// Args secp: Secp256k1 context object, initialized for verification + /// In: pubnonce: the 66-byte pubnonce sent by the signer who produced + /// the signature + /// pubkey: public key of the signer who produced the signature + /// pre_session: MusigPreSession that was output when the + /// combined public key for this session + /// session_cache: MusigSessionCache that was created with + /// [MusigPartialSig::process_nonces] + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// + /// assert!(pre_session.partial_verify( + /// &secp, + /// cache_template.session_cache(), + /// &session.pubnonce, + /// &pub_key, + /// &partial_sig, + /// )); + /// ``` + pub fn partial_verify( + &self, + secp: &Secp256k1, + cache: &MusigSessionCache, + pubnonce: &MusigPubNonce, + pubkey: &PublicKey, + partial_sig: &MusigPartialSignature, + ) -> bool { + let cx = *secp.ctx(); + let xonly = ffi::xonly_from_pubkey(cx, pubkey.as_ptr()).0; + unsafe { + ffi::secp256k1_musig_partial_sig_verify( + cx, + partial_sig.as_ptr(), + pubnonce.as_raw_ptr(), + &xonly, + self.as_ptr(), + cache.as_ptr(), + ) == 1 + } + } + + /// Get a const reference to the combined public key + pub fn combined_pk(&self) -> &ffi::XOnlyPublicKey { + &self.combined_pk + } + + /// Get a raw const pointer to the inner MusigPreSession + pub fn as_ptr(&self) -> *const ffi::MusigPreSession { + &self.inner + } + + /// Get a raw mut pointer to the inner MusigPreSession + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigPreSession { + &mut self.inner + } +} + +/// Container for Musig session cache, signature template, and nonce parity +/// +/// Output by [MusigPartialSig::process_nonces] +/// +/// - MusigSessionCache is used for [MusigPreSession::partial_sign] and [MusigPreSession::partial_verify] +/// - MusigTemplate is used for [MusigTemplate::partial_sig_combine] +/// - nonce_parity is used in [MusigPartialSig::adapt] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigCacheTemplate { + session_cache: MusigSessionCache, + template: MusigTemplate, + nonce_parity: i32, +} + +impl MusigCacheTemplate { + /// Get a const reference to the MusigSessionCache + pub fn session_cache(&self) -> &MusigSessionCache { + &self.session_cache + } + + /// Get a const reference to the MusigTemplate + pub fn template(&self) -> &MusigTemplate { + &self.template + } + + /// Get the Musig nonce parity + pub fn nonce_parity(&self) -> i32 { + self.nonce_parity + } +} + +/// Opaque data structure that holds a cache for a MuSig session. +/// +/// Guaranteed to be 65 bytes in size. No serialization and parsing functions (yet). +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigSessionCache(ffi::MusigSessionCache); + +impl CPtr for MusigSessionCache { + type Target = ffi::MusigSessionCache; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigSessionCache { + /// Get a const pointer to the inner MusigSessionCache + pub fn as_ptr(&self) -> *const ffi::MusigSessionCache { + &self.0 + } + + /// Get a mut pointer to the inner MusigSessionCache + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigSessionCache { + &mut self.0 + } +} + +/// Opaque data structure that holds a MuSig signature template. +/// +/// Guaranteed to be 64 bytes in size. No serialization and parsing functions (yet). +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigTemplate(ffi::MusigTemplate); + +impl CPtr for MusigTemplate { + type Target = ffi::MusigTemplate; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigTemplate { + /// Combines partial signatures + /// + /// Returns: Error if the arguments are invalid or a partial_sig is out of range, Signature + /// otherwise (which does NOT mean the resulting signature verifies). + /// Args: secp: Secp256k1 context object + /// In: sig_template: MusigTemplate that was created with [MusigPartialSig::process_nonces] + /// partial_sigs: array of MusigPartialSignatures to combine + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// let _sig = cache_template.template().partial_sig_combine(&secp, &[partial_sig]).unwrap(); + /// ``` + pub fn partial_sig_combine( + &self, + secp: &Secp256k1, + partial_sigs: &[MusigPartialSignature], + ) -> Result { + let part_sigs = partial_sigs.iter().map(|s| s.as_ptr()).collect::>(); + let mut sig = [0u8; 64]; + unsafe { + if ffi::secp256k1_musig_partial_sig_combine( + *secp.ctx(), + sig.as_mut_ptr(), + self.as_ptr(), + part_sigs.as_ptr(), + part_sigs.len(), + ) == 0 + { + Err(Error::InvalidMusigPartSig) + } else { + Ok(Signature::from_compact(&sig)?) + } + } + } + + /// Get a const pointer to the inner MusigTemplate + pub fn as_ptr(&self) -> *const ffi::MusigTemplate { + &self.0 + } + + /// Get a mut pointer to the inner MusigTemplate + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigTemplate { + &mut self.0 + } +} + +/// Opaque data structure that holds a partial MuSig signature. +/// +/// Guaranteed to be 32 bytes in size. Serialized and parsed with +/// [MusigPartialSignature::serialize] and [MusigPartialSignature::parse]. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigPartialSignature(ffi::MusigPartialSignature); + +impl CPtr for MusigPartialSignature { + type Target = ffi::MusigPartialSignature; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigPartialSignature { + /// Serialize a MuSigPartialSignature or adaptor signature + /// + /// Returns: 32-byte array when the signature could be serialized, Error otherwise + /// Args: ctx: a Secp256k1 context object + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// + /// let _ser_sig = partial_sig.serialize(&secp).unwrap(); + /// ``` + pub fn serialize(&self, secp: &Secp256k1) -> Result<[u8; 32], Error> { + let mut data = [0; 32]; + unsafe { + if ffi::secp256k1_musig_partial_signature_serialize( + *secp.ctx(), + data.as_mut_ptr(), + self.as_ptr(), + ) == 0 + { + Err(Error::InvalidMusigPartSig) + } else { + Ok(data) + } + } + } + + /// Deserialize a MusigPartialSignature from a portable byte representation + /// Parse and verify a MuSig partial signature. + /// + /// Returns: MusigPartialSignature when the signature could be parsed, Error otherwise. + /// Args: ctx: a secp256k1 context object + /// In: in32: 32-byte serialized signature to be parsed + /// + /// After the call, sig will always be initialized. If parsing failed or the + /// encoded numbers are out of range, signature verification with it is + /// guaranteed to fail for every message and public key. + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{ + /// # Message, MusigPartialSignature, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey, + /// # }; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// None, + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// + /// let ser_sig = partial_sig.serialize(&secp).unwrap(); + /// let _parsed_sig = MusigPartialSignature::parse(&secp, &ser_sig).unwrap(); + /// ``` + pub fn parse(secp: &Secp256k1, data: &[u8]) -> Result { + let mut part_sig = MusigPartialSignature(ffi::MusigPartialSignature::new()); + if data.len() != 32 { + return Err(Error::InvalidMusigPartSig); + } + unsafe { + if ffi::secp256k1_musig_partial_signature_parse( + *secp.ctx(), + part_sig.as_mut_ptr(), + data.as_ptr(), + ) == 0 + { + Err(Error::InvalidMusigPartSig) + } else { + Ok(part_sig) + } + } + } + + /// Converts a partial signature to an adaptor signature by adding a given secret adaptor. + /// + /// Returns: MusigPartialSignature: signature and secret adaptor contained valid values + /// Error: otherwise + /// Args: secp: pointer to a context object (cannot be NULL) + /// In: partial_sig: partial signature to tweak with secret adaptor + /// sec_adaptor32: 32-byte secret adaptor to add to the partial signature + /// nonce_parity: the `nonce_parity` output of [MusigPartialSig::process_nonces] + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// # use secp256k1_zkp::schnorrsig::KeyPair; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// let msg = Message::from_slice(&[3; 32]).unwrap(); + /// + /// let mut session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// Some(&msg), + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let adapt_bytes = [2; 32]; + /// let adapt_sec = SecretKey::from_slice(&adapt_bytes).unwrap(); + /// let adapt_pub = PublicKey::from_secret_key(&secp, &adapt_sec); + /// + /// let cache_template = pre_session.process_nonces( + /// &secp, + /// &[session.pubnonce], + /// &msg, + /// Some(&adapt_pub), + /// ).unwrap(); + /// + /// let keypair = KeyPair::from_secret_key(&secp, sec_key); + /// let partial_sig = pre_session.partial_sign( + /// &secp, + /// &mut session.secnonce, + /// cache_template.session_cache(), + /// &keypair, + /// ).unwrap(); + /// + /// let _adaptor_sig = partial_sig.adapt(&secp, &adapt_sec, cache_template.nonce_parity()).unwrap(); + /// ``` + pub fn adapt( + &self, + secp: &Secp256k1, + sec_adaptor: &SecretKey, + nonce_parity: i32, + ) -> Result { + unsafe { + let mut adaptor_sig = Self(ffi::MusigPartialSignature::new()); + if ffi::secp256k1_musig_partial_sig_adapt( + *secp.ctx(), + adaptor_sig.as_mut_ptr(), + self.as_ptr(), + sec_adaptor.as_ptr(), + nonce_parity, + ) == 0 + { + Err(Error::InvalidMusigPartSig) + } else { + Ok(adaptor_sig) + } + } + } + + /// Get a const pointer to the inner MusigPartialSignature + pub fn as_ptr(&self) -> *const ffi::MusigPartialSignature { + &self.0 + } + + /// Get a mut pointer to the inner MusigPartialSignature + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigPartialSignature { + &mut self.0 + } +} + +/// Extracts a secret adaptor from a MuSig, given all parties' partial +/// signatures. This function will not fail unless given grossly invalid data; if it +/// is merely given signatures that do not verify, the returned value will be +/// nonsense. It is therefore important that all data be verified at earlier steps of +/// any protocol that uses this function. +/// +/// Returns: SecretKey: signatures contained valid data such that an adaptor could be extracted +/// Error: otherwise +/// Args: secp: Secp256k1 context object +/// In: sig: complete 2-of-2 signature +/// partial_sigs: array of partial signatures +/// nonce_parity: the `nonce_parity` output of [MusigPartialSig::process_nonces] +/// +/// Example: +/// +/// ```rust +/// # use secp256k1_zkp::extract_secret_adaptor; +/// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; +/// # use secp256k1_zkp::schnorrsig::KeyPair; +/// let secp = Secp256k1::new(); +/// let sec_bytes = [1; 32]; +/// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); +/// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); +/// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); +/// let msg = Message::from_slice(&[3; 32]).unwrap(); +/// +/// let mut session = MusigSession::new( +/// &secp, +/// [1; 32], +/// Some(&sec_key), +/// Some(&msg), +/// Some(pre_session.combined_pk()), +/// None, +/// ).unwrap(); +/// +/// let adapt_bytes = [2; 32]; +/// let adapt_sec = SecretKey::from_slice(&adapt_bytes).unwrap(); +/// let adapt_pub = PublicKey::from_secret_key(&secp, &adapt_sec); +/// +/// let cache_template = pre_session.process_nonces( +/// &secp, +/// &[session.pubnonce], +/// &msg, +/// Some(&adapt_pub), +/// ).unwrap(); +/// +/// let keypair = KeyPair::from_secret_key(&secp, sec_key); +/// let partial_sig = pre_session.partial_sign( +/// &secp, +/// &mut session.secnonce, +/// cache_template.session_cache(), +/// &keypair, +/// ).unwrap(); +/// +/// let nonce_parity = cache_template.nonce_parity(); +/// let adaptor_sig = partial_sig.adapt(&secp, &adapt_sec, nonce_parity).unwrap(); +/// let sig = cache_template.template().partial_sig_combine(&secp, &[adaptor_sig]).unwrap(); +/// let extracted_sec = extract_secret_adaptor( +/// &secp, +/// &sig, +/// &[partial_sig], +/// nonce_parity, +/// ).unwrap(); +/// assert_eq!(extracted_sec, adapt_sec); +/// ``` +pub fn extract_secret_adaptor( + secp: &Secp256k1, + sig: &Signature, + partial_sigs: &[MusigPartialSignature], + nonce_parity: i32, +) -> Result { + unsafe { + let mut secret = SecretKey::from_slice([1; 32].as_ref())?; + let part_sigs = partial_sigs.iter().map(|s| s.0).collect::>(); + if ffi::secp256k1_musig_extract_secret_adaptor( + *secp.ctx(), + secret.as_mut_ptr(), + sig.serialize_compact().as_ptr(), + part_sigs.as_ptr(), + part_sigs.len(), + nonce_parity, + ) == 0 + { + Err(Error::InvalidMusigExtract) + } else { + Ok(secret) + } + } +} + +/// Guaranteed to be 64 bytes in size. This structure MUST NOT be copied or +/// read or written to it directly. A signer who is online throughout the whole +/// process and can keep this structure in memory can use the provided API +/// functions for a safe standard workflow. See +/// https://blockstream.com/2019/02/18/musig-a-new-multisignature-standard/ for +/// more details about the risks associated with serializing or deserializing +/// this structure. There are no serialization and parsing functions (yet). +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigSecNonce(ffi::MusigSecNonce); + +impl CPtr for MusigSecNonce { + type Target = ffi::MusigSecNonce; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigSecNonce { + /// Get a raw const pointer to the inner MusigPreSession + pub fn as_ptr(&self) -> *const ffi::MusigSecNonce { + &self.0 + } + + /// Get a raw mut pointer to the inner MusigPreSession + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigSecNonce { + &mut self.0 + } +} + +/// Opaque data structure that holds a MuSig public nonce. +/// +/// Guaranteed to be 66 bytes in size. There are no serialization and parsing functions (yet). +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigPubNonce(ffi::MusigPubNonce); + +impl CPtr for MusigPubNonce { + type Target = ffi::MusigPubNonce; + + fn as_c_ptr(&self) -> *const Self::Target { + self.as_ptr() + } + + fn as_mut_c_ptr(&mut self) -> *mut Self::Target { + self.as_mut_ptr() + } +} + +impl MusigPubNonce { + /// Get a raw const pointer to the inner MusigPreSession + pub fn as_ptr(&self) -> *const ffi::MusigPubNonce { + &self.0 + } + + /// Get a raw mut pointer to the inner MusigPreSession + pub fn as_mut_ptr(&mut self) -> *mut ffi::MusigPubNonce { + &mut self.0 + } + + // Internal function to handle C API (may remove in future API iteration) + fn as_raw_ptr(&self) -> *const u8 { + self.0.data.as_ptr() + } + + // Internal function to handle C API (may remove in future API iteration) + fn as_mut_raw_ptr(&mut self) -> *mut u8 { + self.0.data.as_mut_ptr() + } + + /// Combines received nonces into a single nonce + /// + /// This is useful to reduce the communication between signers, because instead + /// of everyone sending nonces to everyone else, there can be one party + /// receiving all nonces, combining the nonces with this function and then + /// sending only the combined nonce back to the signers. The pubnonces argument + /// of [MusigPreSession::process_nonces] then simply becomes an array whose sole + /// element is this combined nonce. + /// + /// Returns: Error if the arguments are invalid or if all signers sent invalid + /// pubnonces, MusigPubNonce otherwise + /// Args: secp: Secp256k1 context object + /// In: pubnonces: array of 66-byte pubnonces sent by the signers + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{MusigPreSession, MusigPubNonce, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// + /// let session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// None, + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// + /// let _combined_pubnonce = MusigPubNonce::combine(&secp, &[session.pubnonce]).unwrap(); + /// ``` + pub fn combine(secp: &Secp256k1, nonces: &[Self]) -> Result { + let mut combined_pubnonce = Self(ffi::MusigPubNonce::new()); + let nonce_ptrs = nonces.iter().map(|n| n.as_raw_ptr()).collect::>(); + unsafe { + if ffi::secp256k1_musig_nonces_combine( + *secp.ctx(), + combined_pubnonce.as_mut_raw_ptr(), + nonce_ptrs.as_ptr(), + nonce_ptrs.len(), + ) == 0 + { + Err(Error::InvalidMusigPubNonce) + } else { + Ok(combined_pubnonce) + } + } + } +} + +/// Musig session data structure containing the +/// secret and public nonce used in a multi-signature signing session +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub struct MusigSession { + /// Musig secret nonce for signing partial signature + pub secnonce: MusigSecNonce, + /// Musig public nonce for signature verification of partial signature, + /// and combining with other participants public nonces for final signature verification + pub pubnonce: MusigPubNonce, +} + +impl MusigSession { + /// Starts a signing session + /// + /// This function derives a secret nonce that will be required for signing and + /// creates a public nonce that is intended to be sent to other signers. + /// + /// MuSig differs from regular Schnorr signing in that implementers _must_ take + /// special care to not reuse a nonce. This can be ensured by following these rules: + /// + /// 1. Always provide a unique session_id32. It is a "number used once". + /// 2. If you already know the signing key, message or combined public key, they + /// can be optionally provided to derive the nonce and increase + /// misuse-resistance. The extra_input32 argument can be used to provide + /// additional data that does not repeat in normal scenarios, such as the + /// current time. + /// 3. If you do not provide a seckey, session_id32 _must_ be UNIFORMLY RANDOM. + /// If you do provide a seckey, session_id32 can instead be a counter (that + /// must never repeat!). However, it is recommended to always choose + /// session_id32 uniformly at random. Note that using the same seckey for + /// multiple MuSig sessions is fine. + /// 4. Avoid copying (or serializing) the secnonce. This reduces the possibility + /// that it is used more than once for signing. + /// + /// Remember that nonce reuse will immediately leak the secret key! + /// + /// Returns: Error if the arguments are invalid and MusigSession otherwise + /// Args: secp: Secp256k1 context object, initialized for signing + /// Out: musig_session: MusigSession object with the secret nonce + /// and the public nonce + /// In: session_id: a 32-byte session_id as explained above. Must be + /// uniformly random unless you really know what you are + /// doing. + /// seckey: the 32-byte secret key that will be used for signing if + /// already known + /// msg: the 32-byte Message that will be signed if already known + /// combined_pk: the combined xonly public key of all signers if already + /// known + /// extra_input32: an optional 32-byte array that is input to the nonce + /// derivation function + /// + /// Example: + /// + /// ```rust + /// # use secp256k1_zkp::{Message, MusigPreSession, MusigSession, PublicKey, Secp256k1, SecretKey}; + /// let secp = Secp256k1::new(); + /// let sec_bytes = [1; 32]; + /// let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + /// let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + /// let pre_session = MusigPreSession::new(&secp, &[pub_key]).unwrap(); + /// + /// let _session = MusigSession::new( + /// &secp, + /// [1; 32], + /// Some(&sec_key), + /// None, + /// Some(pre_session.combined_pk()), + /// None, + /// ).unwrap(); + /// ``` + pub fn new( + secp: &Secp256k1, + session_id: [u8; 32], + seckey: Option<&SecretKey>, + msg: Option<&Message>, + combined_pk: Option<&ffi::XOnlyPublicKey>, + extra_input: Option<&[u8; 32]>, + ) -> Result { + let mut secnonce = MusigSecNonce(ffi::MusigSecNonce::new()); + let mut pubnonce = MusigPubNonce(ffi::MusigPubNonce::new()); + let seckey_ptr = match seckey { + Some(sk) => sk.as_ptr(), + None => core::ptr::null(), + }; + let msg_ptr = match msg { + Some(m) => m.as_ptr(), + None => core::ptr::null(), + }; + let combined_ptr = match combined_pk { + Some(pk) => pk as *const _, + None => core::ptr::null(), + }; + let extra_ptr = match extra_input { + Some(e) => e.as_ptr(), + None => core::ptr::null(), + }; + unsafe { + if ffi::secp256k1_musig_session_init( + *secp.ctx(), + secnonce.as_mut_ptr(), + pubnonce.as_mut_raw_ptr(), + session_id.as_ptr(), + seckey_ptr, + msg_ptr, + combined_ptr, + extra_ptr, + ) == 0 + { + Err(Error::InvalidMusigSession) + } else { + Ok(Self { secnonce, pubnonce }) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rand::{thread_rng, RngCore}; + + #[test] + fn test_pre_session() { + let secp = Secp256k1::new(); + let mut sec_bytes = [0; 32]; + thread_rng().fill_bytes(&mut sec_bytes); + let sec_key = SecretKey::from_slice(&sec_bytes).unwrap(); + let pub_key = PublicKey::from_secret_key(&secp, &sec_key); + + let _pre_session = MusigPreSession::new(&secp, &[pub_key, pub_key]).unwrap(); + } +}