Skip to content

Commit 4d36fef

Browse files
committed
Merge #716: Add Musig2 module
c6fc3d7 run cargo fmt (Andrew Poelstra) 2f0f9d8 Add Musig2 example file (jlest01) dd26c30 Add Musig2 module (jlest01) e90015e Add function to sort public keys (jlest01) f384a2d Add Rust FFI for Musig2 module (jlest01) a21d6ca Enable musig module in the `secp256k1-sys/build.rs` (jlest01) Pull request description: This PR adds a `musig` module based on bitcoin-core/secp256k1#1479. The structure is based on sanket1729's BlockstreamResearch/rust-secp256k1-zkp#48, but I removed the code related to adaptor signatures. There is an example file in `examples/musig.rs` and can be run with `cargo run --example musig --features "rand std"`. The `ffi` functions were added to `secp256k1-sys/src/lib.rs` and the API level functions to the new `src/musig.rs` file. ACKs for top commit: apoelstra: ACK c6fc3d7; successfully ran local tests Tree-SHA512: ea4cf0add66976604a01f7e2b44a2e4f82c3ff4a48edcb214ff8e2dc7c04992e7d5ae9e68a8f93ee21b8d478b96786083a335b46eefe4aa1af5e7c62421d1330
2 parents 7758313 + c6fc3d7 commit 4d36fef

File tree

7 files changed

+1545
-1
lines changed

7 files changed

+1545
-1
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ required-features = ["hashes", "std"]
6666
name = "generate_keys"
6767
required-features = ["rand", "std"]
6868

69+
[[example]]
70+
name = "musig"
71+
required-features = ["rand", "std"]
72+
6973
[workspace]
7074
members = ["secp256k1-sys"]
7175
exclude = ["no_std_test"]

examples/musig.rs

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
extern crate secp256k1;
2+
3+
use secp256k1::musig::{
4+
new_nonce_pair, AggregatedNonce, KeyAggCache, PartialSignature, PublicNonce, Session,
5+
SessionSecretRand,
6+
};
7+
use secp256k1::{pubkey_sort, Keypair, Message, PublicKey, Scalar, Secp256k1, SecretKey};
8+
9+
fn main() {
10+
let secp = Secp256k1::new();
11+
let mut rng = rand::thread_rng();
12+
13+
let (seckey1, pubkey1) = secp.generate_keypair(&mut rng);
14+
15+
let seckey2 = SecretKey::new(&mut rng);
16+
let pubkey2 = PublicKey::from_secret_key(&secp, &seckey2);
17+
18+
let pubkeys = [pubkey1, pubkey2];
19+
let mut pubkeys_ref: Vec<&PublicKey> = pubkeys.iter().collect();
20+
let pubkeys_ref = pubkeys_ref.as_mut_slice();
21+
22+
pubkey_sort(&secp, pubkeys_ref);
23+
24+
let mut musig_key_agg_cache = KeyAggCache::new(&secp, pubkeys_ref);
25+
26+
let plain_tweak: [u8; 32] = *b"this could be a BIP32 tweak....\0";
27+
let xonly_tweak: [u8; 32] = *b"this could be a Taproot tweak..\0";
28+
29+
let plain_tweak = Scalar::from_be_bytes(plain_tweak).unwrap();
30+
musig_key_agg_cache.pubkey_ec_tweak_add(&secp, &plain_tweak).unwrap();
31+
32+
let xonly_tweak = Scalar::from_be_bytes(xonly_tweak).unwrap();
33+
let tweaked_agg_pk = musig_key_agg_cache.pubkey_xonly_tweak_add(&secp, &xonly_tweak).unwrap();
34+
35+
let agg_pk = musig_key_agg_cache.agg_pk();
36+
37+
assert_eq!(agg_pk, tweaked_agg_pk.x_only_public_key().0);
38+
39+
let msg_bytes: [u8; 32] = *b"this_could_be_the_hash_of_a_msg!";
40+
let msg = Message::from_digest_slice(&msg_bytes).unwrap();
41+
42+
let musig_session_sec_rand1 = SessionSecretRand::from_rng(&mut rng);
43+
44+
let nonce_pair1 = new_nonce_pair(
45+
&secp,
46+
musig_session_sec_rand1,
47+
Some(&musig_key_agg_cache),
48+
Some(seckey1),
49+
pubkey1,
50+
Some(msg),
51+
None,
52+
);
53+
54+
let musig_session_sec_rand2 = SessionSecretRand::from_rng(&mut rng);
55+
56+
let nonce_pair2 = new_nonce_pair(
57+
&secp,
58+
musig_session_sec_rand2,
59+
Some(&musig_key_agg_cache),
60+
Some(seckey2),
61+
pubkey2,
62+
Some(msg),
63+
None,
64+
);
65+
66+
let sec_nonce1 = nonce_pair1.0;
67+
let pub_nonce1 = nonce_pair1.1;
68+
69+
let sec_nonce2 = nonce_pair2.0;
70+
let pub_nonce2 = nonce_pair2.1;
71+
72+
let nonces = [pub_nonce1, pub_nonce2];
73+
let nonces_ref: Vec<&PublicNonce> = nonces.iter().collect();
74+
let nonces_ref = nonces_ref.as_slice();
75+
76+
let agg_nonce = AggregatedNonce::new(&secp, nonces_ref);
77+
78+
let session = Session::new(&secp, &musig_key_agg_cache, agg_nonce, msg);
79+
80+
let keypair1 = Keypair::from_secret_key(&secp, &seckey1);
81+
let partial_sign1 = session.partial_sign(&secp, sec_nonce1, &keypair1, &musig_key_agg_cache);
82+
83+
let keypair2 = Keypair::from_secret_key(&secp, &seckey2);
84+
let partial_sign2 = session.partial_sign(&secp, sec_nonce2, &keypair2, &musig_key_agg_cache);
85+
86+
let is_partial_signature_valid =
87+
session.partial_verify(&secp, &musig_key_agg_cache, partial_sign1, pub_nonce1, pubkey1);
88+
assert!(is_partial_signature_valid);
89+
90+
let is_partial_signature_valid =
91+
session.partial_verify(&secp, &musig_key_agg_cache, partial_sign2, pub_nonce2, pubkey2);
92+
assert!(is_partial_signature_valid);
93+
94+
let partial_sigs = [partial_sign1, partial_sign2];
95+
let partial_sigs_ref: Vec<&PartialSignature> = partial_sigs.iter().collect();
96+
let partial_sigs_ref = partial_sigs_ref.as_slice();
97+
98+
let aggregated_signature = session.partial_sig_agg(partial_sigs_ref);
99+
100+
assert!(aggregated_signature.verify(&secp, &agg_pk, &msg_bytes).is_ok());
101+
}

secp256k1-sys/build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ fn main() {
2626
.define("ENABLE_MODULE_SCHNORRSIG", Some("1"))
2727
.define("ENABLE_MODULE_EXTRAKEYS", Some("1"))
2828
.define("ENABLE_MODULE_ELLSWIFT", Some("1"))
29+
.define("ENABLE_MODULE_MUSIG", Some("1"))
2930
// upstream sometimes introduces calls to printf, which we cannot compile
3031
// with WASM due to its lack of libc. printf is never necessary and we can
3132
// just #define it away.

secp256k1-sys/src/lib.rs

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,147 @@ extern "C" {
672672
hashfp: EllswiftEcdhHashFn,
673673
data: *mut c_void)
674674
-> c_int;
675+
676+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubnonce_parse")]
677+
pub fn secp256k1_musig_pubnonce_parse(
678+
cx: *const Context,
679+
nonce: *mut MusigPubNonce,
680+
in66: *const c_uchar,
681+
) -> c_int;
682+
683+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubnonce_serialize")]
684+
pub fn secp256k1_musig_pubnonce_serialize(
685+
cx: *const Context,
686+
out66: *mut c_uchar,
687+
nonce: *const MusigPubNonce,
688+
) -> c_int;
689+
690+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_aggnonce_parse")]
691+
pub fn secp256k1_musig_aggnonce_parse(
692+
cx: *const Context,
693+
nonce: *mut MusigAggNonce,
694+
in66: *const c_uchar,
695+
) -> c_int;
696+
697+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_aggnonce_serialize")]
698+
pub fn secp256k1_musig_aggnonce_serialize(
699+
cx: *const Context,
700+
out66: *mut c_uchar,
701+
nonce: *const MusigAggNonce,
702+
) -> c_int;
703+
704+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_parse")]
705+
pub fn secp256k1_musig_partial_sig_parse(
706+
cx: *const Context,
707+
sig: *mut MusigPartialSignature,
708+
in32: *const c_uchar,
709+
) -> c_int;
710+
711+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_serialize")]
712+
pub fn secp256k1_musig_partial_sig_serialize(
713+
cx: *const Context,
714+
out32: *mut c_uchar,
715+
sig: *const MusigPartialSignature,
716+
) -> c_int;
717+
718+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_agg")]
719+
pub fn secp256k1_musig_pubkey_agg(
720+
cx: *const Context,
721+
agg_pk: *mut XOnlyPublicKey,
722+
keyagg_cache: *mut MusigKeyAggCache,
723+
pubkeys: *const *const PublicKey,
724+
n_pubkeys: size_t,
725+
) -> c_int;
726+
727+
#[cfg_attr(not(rust_secp_no_symbol_renaming),link_name = "rustsecp256k1_v0_11_musig_pubkey_get")]
728+
pub fn secp256k1_musig_pubkey_get(
729+
cx: *const Context,
730+
agg_pk: *mut PublicKey,
731+
keyagg_cache: *const MusigKeyAggCache,
732+
) -> c_int;
733+
734+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_ec_tweak_add")]
735+
pub fn secp256k1_musig_pubkey_ec_tweak_add(
736+
cx: *const Context,
737+
output_pubkey: *mut PublicKey,
738+
keyagg_cache: *mut MusigKeyAggCache,
739+
tweak32: *const c_uchar,
740+
) -> c_int;
741+
742+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_pubkey_xonly_tweak_add")]
743+
pub fn secp256k1_musig_pubkey_xonly_tweak_add(
744+
cx: *const Context,
745+
output_pubkey: *mut PublicKey,
746+
keyagg_cache: *mut MusigKeyAggCache,
747+
tweak32: *const c_uchar,
748+
) -> c_int;
749+
750+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_gen")]
751+
pub fn secp256k1_musig_nonce_gen(
752+
cx: *const Context,
753+
secnonce: *mut MusigSecNonce,
754+
pubnonce: *mut MusigPubNonce,
755+
session_secrand32: *const c_uchar,
756+
seckey: *const c_uchar,
757+
pubkey: *const PublicKey,
758+
msg32: *const c_uchar,
759+
keyagg_cache: *const MusigKeyAggCache,
760+
extra_input32: *const c_uchar,
761+
) -> c_int;
762+
763+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_agg")]
764+
pub fn secp256k1_musig_nonce_agg(
765+
cx: *const Context,
766+
aggnonce: *mut MusigAggNonce,
767+
pubnonces: *const *const MusigPubNonce,
768+
n_pubnonces: size_t,
769+
) -> c_int;
770+
771+
772+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_nonce_process")]
773+
pub fn secp256k1_musig_nonce_process(
774+
cx: *const Context,
775+
session: *mut MusigSession,
776+
aggnonce: *const MusigAggNonce,
777+
msg32: *const c_uchar,
778+
keyagg_cache: *const MusigKeyAggCache,
779+
) -> c_int;
780+
781+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sign")]
782+
pub fn secp256k1_musig_partial_sign(
783+
cx: *const Context,
784+
partial_sig: *mut MusigPartialSignature,
785+
secnonce: *mut MusigSecNonce,
786+
keypair: *const Keypair,
787+
keyagg_cache: *const MusigKeyAggCache,
788+
session: *const MusigSession,
789+
) -> c_int;
790+
791+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_verify")]
792+
pub fn secp256k1_musig_partial_sig_verify(
793+
cx: *const Context,
794+
partial_sig: *const MusigPartialSignature,
795+
pubnonce: *const MusigPubNonce,
796+
pubkey: *const PublicKey,
797+
keyagg_cache: *const MusigKeyAggCache,
798+
session: *const MusigSession,
799+
) -> c_int;
800+
801+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_musig_partial_sig_agg")]
802+
pub fn secp256k1_musig_partial_sig_agg(
803+
cx: *const Context,
804+
sig64: *mut c_uchar,
805+
session: *const MusigSession,
806+
partial_sigs: *const *const MusigPartialSignature,
807+
n_sigs: size_t,
808+
) -> c_int;
809+
810+
#[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_11_ec_pubkey_sort")]
811+
pub fn secp256k1_ec_pubkey_sort(
812+
ctx: *const Context,
813+
pubkeys: *mut *const PublicKey,
814+
n_pubkeys: size_t
815+
) -> c_int;
675816
}
676817

677818
#[cfg(not(secp256k1_fuzz))]
@@ -1097,6 +1238,94 @@ impl <T: CPtr> CPtr for Option<T> {
10971238
}
10981239
}
10991240
}
1241+
/// Total length (in bytes) of the key aggregation context.
1242+
/// This structure packs all metadata needed for aggregating individual public keys
1243+
/// into a single MuSig2 aggregated key (including coefficients and any extra metadata).
1244+
pub const MUSIG_KEYAGG_LEN: usize = 197;
1245+
1246+
/// Length (in bytes) of the secret nonce structure used in a MuSig2 session.
1247+
/// It holds the secret (ephemeral) nonces used internally for nonce derivation
1248+
/// before the corresponding public nonces are computed.
1249+
pub const MUSIG_SECNONCE_LEN: usize = 132;
1250+
1251+
/// Length (in bytes) of the public nonce structure.
1252+
/// This is derived from the secret nonce and shared among participants to build
1253+
/// nonce commitments in the MuSig2 protocol.
1254+
pub const MUSIG_PUBNONCE_LEN: usize = 132;
1255+
1256+
/// Length (in bytes) of the aggregated nonce structure.
1257+
/// Represents the combined nonce obtained by aggregating the individual public nonces
1258+
/// from all participants for the final signature computation.
1259+
pub const MUSIG_AGGNONCE_LEN: usize = 132;
1260+
1261+
/// Serialized length (in bytes) of the aggregated nonce.
1262+
/// This is the compact form (typically using a compressed representation) used for
1263+
/// transmitting or storing the aggregated nonce.
1264+
pub const MUSIG_AGGNONCE_SERIALIZED_LEN: usize = 66;
1265+
1266+
/// Serialized length (in bytes) of an individual public nonce.
1267+
/// This compact serialized form is what gets exchanged between signers.
1268+
pub const MUSIG_PUBNONCE_SERIALIZED_LEN: usize = 66;
1269+
1270+
/// Length (in bytes) of the session structure.
1271+
/// The session object holds all state needed for a MuSig2 signing session (e.g. aggregated nonce,
1272+
/// key aggregation info, and other state necessary for computing partial signatures).
1273+
pub const MUSIG_SESSION_LEN: usize = 133;
1274+
1275+
/// Length (in bytes) of the internal representation of a partial signature.
1276+
/// This structure include magic bytes ([0xeb, 0xfb, 0x1a, 0x32]) alongside the actual signature scalar.
1277+
pub const MUSIG_PART_SIG_LEN: usize = 36;
1278+
1279+
/// Serialized length (in bytes) of a partial signature.
1280+
/// This is the compact form (typically just the 32-byte scalar) that is used when communicating
1281+
/// partial signatures to be combined into the final signature.
1282+
pub const MUSIG_PART_SIG_SERIALIZED_LEN: usize = 32;
1283+
1284+
#[repr(C)]
1285+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1286+
pub struct MusigKeyAggCache([c_uchar; MUSIG_KEYAGG_LEN]);
1287+
impl_array_newtype!(MusigKeyAggCache, c_uchar, MUSIG_KEYAGG_LEN);
1288+
impl_raw_debug!(MusigKeyAggCache);
1289+
1290+
#[repr(C)]
1291+
#[derive(Copy, Clone, PartialEq, Eq)]
1292+
pub struct MusigSecNonce([c_uchar; MUSIG_SECNONCE_LEN]);
1293+
impl_array_newtype!(MusigSecNonce, c_uchar, MUSIG_SECNONCE_LEN);
1294+
impl_raw_debug!(MusigSecNonce);
1295+
1296+
impl MusigSecNonce {
1297+
pub fn dangerous_from_bytes(bytes: [c_uchar; MUSIG_SECNONCE_LEN]) -> Self {
1298+
MusigSecNonce(bytes)
1299+
}
1300+
1301+
pub fn dangerous_into_bytes(self) -> [c_uchar; MUSIG_SECNONCE_LEN] {
1302+
self.0
1303+
}
1304+
}
1305+
1306+
#[repr(C)]
1307+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1308+
pub struct MusigPubNonce([c_uchar; MUSIG_PUBNONCE_LEN]);
1309+
impl_array_newtype!(MusigPubNonce, c_uchar, MUSIG_PUBNONCE_LEN);
1310+
impl_raw_debug!(MusigPubNonce);
1311+
1312+
#[repr(C)]
1313+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1314+
pub struct MusigAggNonce([c_uchar; MUSIG_AGGNONCE_LEN]);
1315+
impl_array_newtype!(MusigAggNonce, c_uchar, MUSIG_AGGNONCE_LEN);
1316+
impl_raw_debug!(MusigAggNonce);
1317+
1318+
#[repr(C)]
1319+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1320+
pub struct MusigSession([c_uchar; MUSIG_SESSION_LEN]);
1321+
impl_array_newtype!(MusigSession, c_uchar, MUSIG_SESSION_LEN);
1322+
impl_raw_debug!(MusigSession);
1323+
1324+
#[repr(C)]
1325+
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1326+
pub struct MusigPartialSignature([c_uchar; MUSIG_PART_SIG_LEN]);
1327+
impl_array_newtype!(MusigPartialSignature, c_uchar, MUSIG_PART_SIG_LEN);
1328+
impl_raw_debug!(MusigPartialSignature);
11001329

11011330
#[cfg(secp256k1_fuzz)]
11021331
mod fuzz_dummy {

0 commit comments

Comments
 (0)