Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Musig2 module #716

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ required-features = ["hashes", "std"]
name = "generate_keys"
required-features = ["rand", "std"]

[[example]]
name = "musig"
required-features = ["rand", "std"]

[workspace]
members = ["secp256k1-sys"]
exclude = ["no_std_test"]
103 changes: 103 additions & 0 deletions examples/musig.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
extern crate secp256k1;

use secp256k1::musig::{
new_nonce_pair, AggregatedNonce, KeyAggCache, PartialSignature, PublicNonce,
Session, SessionSecretRand,
};
use secp256k1::{Keypair, Message, PublicKey, Scalar, Secp256k1, SecretKey, pubkey_sort};

fn main() {
let secp = Secp256k1::new();
let mut rng = rand::thread_rng();

let (seckey1, pubkey1) = secp.generate_keypair(&mut rng);

let seckey2 = SecretKey::new(&mut rng);
let pubkey2 = PublicKey::from_secret_key(&secp, &seckey2);

let pubkeys = [pubkey1, pubkey2];
let mut pubkeys_ref: Vec<&PublicKey> = pubkeys.iter().collect();
let pubkeys_ref = pubkeys_ref.as_mut_slice();

pubkey_sort(&secp, pubkeys_ref);

let mut musig_key_agg_cache = KeyAggCache::new(&secp, pubkeys_ref);

let plain_tweak: [u8; 32] = *b"this could be a BIP32 tweak....\0";
let xonly_tweak: [u8; 32] = *b"this could be a Taproot tweak..\0";

let plain_tweak = Scalar::from_be_bytes(plain_tweak).unwrap();
musig_key_agg_cache.pubkey_ec_tweak_add(&secp, &plain_tweak).unwrap();

let xonly_tweak = Scalar::from_be_bytes(xonly_tweak).unwrap();
let tweaked_agg_pk = musig_key_agg_cache.pubkey_xonly_tweak_add(&secp, &xonly_tweak).unwrap();

let agg_pk = musig_key_agg_cache.agg_pk();

assert_eq!(agg_pk, tweaked_agg_pk.x_only_public_key().0);

let msg_bytes: [u8; 32] = *b"this_could_be_the_hash_of_a_msg!";
let msg = Message::from_digest_slice(&msg_bytes).unwrap();

let musig_session_sec_rand1 = SessionSecretRand::from_rng(&mut rng);

let nonce_pair1 = new_nonce_pair(
&secp,
musig_session_sec_rand1,
Some(&musig_key_agg_cache),
Some(seckey1),
pubkey1,
Some(msg),
None,
);

let musig_session_sec_rand2 = SessionSecretRand::from_rng(&mut rng);

let nonce_pair2 = new_nonce_pair(
&secp,
musig_session_sec_rand2,
Some(&musig_key_agg_cache),
Some(seckey2),
pubkey2,
Some(msg),
None,
);

let sec_nonce1 = nonce_pair1.0;
let pub_nonce1 = nonce_pair1.1;

let sec_nonce2 = nonce_pair2.0;
let pub_nonce2 = nonce_pair2.1;

let nonces = [pub_nonce1, pub_nonce2];
let nonces_ref: Vec<&PublicNonce> = nonces.iter().collect();
let nonces_ref = nonces_ref.as_slice();

let agg_nonce = AggregatedNonce::new(&secp, nonces_ref);

let session = Session::new(&secp, &musig_key_agg_cache, agg_nonce, msg);

let keypair1 = Keypair::from_secret_key(&secp, &seckey1);
let partial_sign1 =
session.partial_sign(&secp, sec_nonce1, &keypair1, &musig_key_agg_cache);

let keypair2 = Keypair::from_secret_key(&secp, &seckey2);
let partial_sign2 =
session.partial_sign(&secp, sec_nonce2, &keypair2, &musig_key_agg_cache);

let is_partial_signature_valid =
session.partial_verify(&secp, &musig_key_agg_cache, partial_sign1, pub_nonce1, pubkey1);
assert!(is_partial_signature_valid);

let is_partial_signature_valid =
session.partial_verify(&secp, &musig_key_agg_cache, partial_sign2, pub_nonce2, pubkey2);
assert!(is_partial_signature_valid);

let partial_sigs = [partial_sign1, partial_sign2];
let partial_sigs_ref: Vec<&PartialSignature> = partial_sigs.iter().collect();
let partial_sigs_ref = partial_sigs_ref.as_slice();

let aggregated_signature = session.partial_sig_agg(partial_sigs_ref);

assert!(aggregated_signature.verify(&secp, &agg_pk, &msg_bytes).is_ok());
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way this example is written makes it difficult to understand how one would use the API in a real-world application where the signers are not in a single binary but distributed and need to exchange messages. I suggest restructuring the code such that operations of each signer are separated. Maybe it'd be even better to use threads and channels to simulate message transmission unless it makes the code too complicated (I think it shouldn't since it should be just a few additional lines.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion. Looking into this.

1 change: 1 addition & 0 deletions secp256k1-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ fn main() {
.define("ENABLE_MODULE_SCHNORRSIG", Some("1"))
.define("ENABLE_MODULE_EXTRAKEYS", Some("1"))
.define("ENABLE_MODULE_ELLSWIFT", Some("1"))
.define("ENABLE_MODULE_MUSIG", Some("1"))
// upstream sometimes introduces calls to printf, which we cannot compile
// with WASM due to its lack of libc. printf is never necessary and we can
// just #define it away.
Expand Down
186 changes: 186 additions & 0 deletions secp256k1-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,147 @@ extern "C" {
hashfp: EllswiftEcdhHashFn,
data: *mut c_void)
-> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubnonce_parse")]
pub fn secp256k1_musig_pubnonce_parse(
cx: *const Context,
nonce: *mut MusigPubNonce,
in66: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubnonce_serialize")]
pub fn secp256k1_musig_pubnonce_serialize(
cx: *const Context,
out66: *mut c_uchar,
nonce: *const MusigPubNonce,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_aggnonce_parse")]
pub fn secp256k1_musig_aggnonce_parse(
cx: *const Context,
nonce: *mut MusigAggNonce,
in66: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_aggnonce_serialize")]
pub fn secp256k1_musig_aggnonce_serialize(
cx: *const Context,
out66: *mut c_uchar,
nonce: *const MusigAggNonce,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_parse")]
pub fn secp256k1_musig_partial_sig_parse(
cx: *const Context,
sig: *mut MusigPartialSignature,
in32: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_serialize")]
pub fn secp256k1_musig_partial_sig_serialize(
cx: *const Context,
out32: *mut c_uchar,
sig: *const MusigPartialSignature,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_agg")]
pub fn secp256k1_musig_pubkey_agg(
cx: *const Context,
agg_pk: *mut XOnlyPublicKey,
keyagg_cache: *mut MusigKeyAggCache,
pubkeys: *const *const PublicKey,
n_pubkeys: size_t,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming),link_name = "rustsecp256k1_v0_11_musig_pubkey_get")]
pub fn secp256k1_musig_pubkey_get(
cx: *const Context,
agg_pk: *mut PublicKey,
keyagg_cache: *const MusigKeyAggCache,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_ec_tweak_add")]
pub fn secp256k1_musig_pubkey_ec_tweak_add(
cx: *const Context,
output_pubkey: *mut PublicKey,
keyagg_cache: *mut MusigKeyAggCache,
tweak32: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_xonly_tweak_add")]
pub fn secp256k1_musig_pubkey_xonly_tweak_add(
cx: *const Context,
output_pubkey: *mut PublicKey,
keyagg_cache: *mut MusigKeyAggCache,
tweak32: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_gen")]
pub fn secp256k1_musig_nonce_gen(
cx: *const Context,
secnonce: *mut MusigSecNonce,
pubnonce: *mut MusigPubNonce,
session_secrand32: *const c_uchar,
seckey: *const c_uchar,
pubkey: *const PublicKey,
msg32: *const c_uchar,
keyagg_cache: *const MusigKeyAggCache,
extra_input32: *const c_uchar,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_agg")]
pub fn secp256k1_musig_nonce_agg(
cx: *const Context,
aggnonce: *mut MusigAggNonce,
pubnonces: *const *const MusigPubNonce,
n_pubnonces: size_t,
) -> c_int;


#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_process")]
pub fn secp256k1_musig_nonce_process(
cx: *const Context,
session: *mut MusigSession,
aggnonce: *const MusigAggNonce,
msg32: *const c_uchar,
keyagg_cache: *const MusigKeyAggCache,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sign")]
pub fn secp256k1_musig_partial_sign(
cx: *const Context,
partial_sig: *mut MusigPartialSignature,
secnonce: *mut MusigSecNonce,
keypair: *const Keypair,
keyagg_cache: *const MusigKeyAggCache,
session: *const MusigSession,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_verify")]
pub fn secp256k1_musig_partial_sig_verify(
cx: *const Context,
partial_sig: *const MusigPartialSignature,
pubnonce: *const MusigPubNonce,
pubkey: *const PublicKey,
keyagg_cache: *const MusigKeyAggCache,
session: *const MusigSession,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_agg")]
pub fn secp256k1_musig_partial_sig_agg(
cx: *const Context,
sig64: *mut c_uchar,
session: *const MusigSession,
partial_sigs: *const *const MusigPartialSignature,
n_sigs: size_t,
) -> c_int;

#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_ec_pubkey_sort")]
pub fn secp256k1_ec_pubkey_sort(
ctx: *const Context,
pubkeys: *mut *const PublicKey,
n_pubkeys: size_t
) -> c_int;
}

#[cfg(not(secp256k1_fuzz))]
Expand Down Expand Up @@ -1098,6 +1239,51 @@ impl <T: CPtr> CPtr for Option<T> {
}
}

pub const MUSIG_KEYAGG_LEN: usize = 197;
pub const MUSIG_SECNONCE_LEN: usize = 132;
pub const MUSIG_PUBNONCE_LEN: usize = 132;
pub const MUSIG_AGGNONCE_LEN: usize = 132;
pub const MUSIG_AGGNONCE_SERIALIZED_LEN: usize = 66;
pub const MUSIG_PUBNONCE_SERIALIZED_LEN: usize = 66;
pub const MUSIG_SESSION_LEN: usize = 133;
pub const MUSIG_PART_SIG_LEN: usize = 36;

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MusigKeyAggCache([c_uchar; MUSIG_KEYAGG_LEN]);
impl_array_newtype!(MusigKeyAggCache, c_uchar, MUSIG_KEYAGG_LEN);
impl_raw_debug!(MusigKeyAggCache);

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct MusigSecNonce([c_uchar; MUSIG_SECNONCE_LEN]);
impl_array_newtype!(MusigSecNonce, c_uchar, MUSIG_SECNONCE_LEN);
impl_raw_debug!(MusigSecNonce);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This leaks the nonce. We need to hide it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Done in 2ea5674


#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MusigPubNonce([c_uchar; MUSIG_PUBNONCE_LEN]);
impl_array_newtype!(MusigPubNonce, c_uchar, MUSIG_PUBNONCE_LEN);
impl_raw_debug!(MusigPubNonce);

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MusigAggNonce([c_uchar; MUSIG_AGGNONCE_LEN]);
impl_array_newtype!(MusigAggNonce, c_uchar, MUSIG_AGGNONCE_LEN);
impl_raw_debug!(MusigAggNonce);

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MusigSession([c_uchar; MUSIG_SESSION_LEN]);
impl_array_newtype!(MusigSession, c_uchar, MUSIG_SESSION_LEN);
impl_raw_debug!(MusigSession);

#[repr(C)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MusigPartialSignature([c_uchar; MUSIG_PART_SIG_LEN]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FTR these struct declarations looked wrong but are indeed correct based on the current API.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think they should be changed?

impl_array_newtype!(MusigPartialSignature, c_uchar, MUSIG_PART_SIG_LEN);
impl_raw_debug!(MusigPartialSignature);

#[cfg(secp256k1_fuzz)]
mod fuzz_dummy {
use super::*;
Expand Down
31 changes: 31 additions & 0 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use core::ops::{self, BitXor};
use core::{fmt, ptr, str};

use secp256k1_sys::secp256k1_ec_pubkey_sort;
#[cfg(feature = "serde")]
use serde::ser::SerializeTuple;

Expand Down Expand Up @@ -1602,6 +1603,36 @@ impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
}
}

/// Sort public keys using lexicographic (of compressed serialization) order.
/// Example:
///
/// ```rust
/// # # [cfg(any(test, feature = "rand-std"))] {
/// # use secp256k1::rand::{thread_rng, RngCore};
/// # use secp256k1::{Secp256k1, SecretKey, Keypair, PublicKey, pubkey_sort};
/// # let secp = Secp256k1::new();
/// # let sk1 = SecretKey::new(&mut thread_rng());
/// # let pub_key1 = PublicKey::from_secret_key(&secp, &sk1);
/// # let sk2 = SecretKey::new(&mut thread_rng());
/// # let pub_key2 = PublicKey::from_secret_key(&secp, &sk2);
/// #
/// # let pubkeys = [pub_key1, pub_key2];
/// # let mut pubkeys_ref: Vec<&PublicKey> = pubkeys.iter().collect();
/// # let pubkeys_ref = pubkeys_ref.as_mut_slice();
/// #
/// # pubkey_sort(&secp, pubkeys_ref);
/// # }
/// ```
pub fn pubkey_sort<C: Verification>(secp: &Secp256k1<C>, pubkeys: &mut [&PublicKey]) {
let cx = secp.ctx().as_ptr();
unsafe {
let mut pubkeys_ref = core::slice::from_raw_parts(pubkeys.as_c_ptr() as *mut *const ffi::PublicKey, pubkeys.len());
if secp256k1_ec_pubkey_sort(cx, pubkeys_ref.as_mut_c_ptr(), pubkeys_ref.len()) == 0 {
unreachable!("Invalid public keys for sorting function")
}
}
}

#[cfg(test)]
#[allow(unused_imports)]
mod test {
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ pub mod constants;
pub mod ecdh;
pub mod ecdsa;
pub mod ellswift;
pub mod musig;
pub mod scalar;
pub mod schnorr;
#[cfg(feature = "serde")]
Expand All @@ -191,7 +192,7 @@ pub use crate::context::{
};
use crate::ffi::types::AlignedType;
use crate::ffi::CPtr;
pub use crate::key::{InvalidParityValue, Keypair, Parity, PublicKey, SecretKey, XOnlyPublicKey};
pub use crate::key::{InvalidParityValue, Keypair, Parity, PublicKey, SecretKey, XOnlyPublicKey, pubkey_sort};
pub use crate::scalar::Scalar;

/// Trait describing something that promises to be a 32-byte uniformly random number.
Expand Down
Loading
Loading