-
Notifications
You must be signed in to change notification settings - Fork 29
/
musig.rs
1210 lines (1123 loc) · 46 KB
/
musig.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The MuSig2 multisignature scheme.
//!
//! ## Synopsis
//!
//! ```
//! use schnorr_fun::{musig::{MuSig, Party}, Schnorr, Message, nonce::Deterministic};
//! use sha2::Sha256;
//! // use sha256 with deterministic nonce generation
//! let musig = MuSig::<Sha256, Schnorr<Sha256, Deterministic<Sha256>>>::default();
//! // create a keylist
//! # use schnorr_fun::fun::Scalar;
//! # let kp1 = musig.schnorr.new_keypair(Scalar::random(&mut rand::thread_rng()));
//! # let kp3 = musig.schnorr.new_keypair(Scalar::random(&mut rand::thread_rng()));
//! # let p1_pubkey = kp1.public_key();
//! # let p3_pubkey = kp3.public_key();
//! # let my_keypair = musig.schnorr.new_keypair(Scalar::random(&mut rand::thread_rng()));
//! # let _keylist = musig.new_keylist(vec![
//! # Party::Local(kp1),
//! # Party::Remote(my_keypair.public_key()),
//! # Party::Local(kp3),
//! # ]);
//! let keylist = musig.new_keylist(vec![
//! Party::Remote(p1_pubkey),
//! Party::Local(my_keypair),
//! Party::Remote(p3_pubkey),
//! ]);
//! let message = Message::plain("my-app", b"chancellor on brink of second bailout for banks");
//! // generate our aggregate key
//! let agg_key = keylist.agg_public_key();
//! // start a MuSig2 session by first exchanging nonces.
//! // Since we're using deterministic nonces it's important we only use the session id once
//! let my_nonces = musig.gen_nonces(&keylist, b"session-id-1337");
//! // send this to the other parties
//! let my_public_nonce = my_nonces[0].public;
//! # let nonces = musig.gen_nonces(&_keylist, b"session-id-1337");
//! # let p1_nonce = nonces[0].public;
//! # let p3_nonce = nonces[1].public;
//! # let _session = musig.start_sign_session_deterministic(&_keylist, my_nonces.iter().map(|n| n.public), b"session-id-1337", message).unwrap();
//! // Once you've got the nonces from the other two (p1_nonce and p3_nonce) you can start the signing session.
//! let session = musig.start_sign_session(&keylist, my_nonces, [p1_nonce, p3_nonce], message).unwrap();
//! // but since we're using deterministic nonce generation we can just remember the session id.
//! // You should guarantee that this is not called ever again with the same session id!!!!
//! let session = musig.start_sign_session_deterministic(&keylist, [p1_nonce, p3_nonce], b"session-id-1337", message).unwrap();
//! // sign with our (single) local keypair
//! let my_sig = musig.sign_all(&keylist, &session)[0];
//! # let _sigs = musig.sign_all(&_keylist, &_session);
//! # let p1_sig = _sigs[0];
//! # let p3_sig = _sigs[1];
//! // recieve p1_sig and p3_sig from somewhere and check they're valid
//! assert!(musig.verify_partial_signature(&keylist, &session, 0, p1_sig));
//! assert!(musig.verify_partial_signature(&keylist, &session, 2, p3_sig));
//! // combine them with ours into the final signature
//! let sig = musig.combine_partial_signatures(&keylist, &session, [my_sig, p1_sig, p3_sig]);
//! // check it's a valid normal Schnorr signature
//! musig.schnorr.verify(&keylist.agg_verification_key(), message, &sig);
//! ```
//!
//! ## Description
//!
//! The MuSig2 multisignature scheme lets you aggregate multiple public keys into a single public
//! key that requires each corresponding secret key to authorize signatures under the aggregate key.
//!
//! This implementation is protocol compatible with the implementation merged into
//! [secp256k1-zkp].
//!
//! See [the excellent paper] for the abstract details of the protocol.
//!
//! [the excellent paper]: https://eprint.iacr.org/2020/1261.pdf
//! [secp256k1-zkp]: https://github.com/ElementsProject/secp256k1-zkp/pull/131
use crate::{adaptor::EncryptedSignature, KeyPair, Message, Schnorr, Signature, Vec};
use secp256kfun::{
derive_nonce,
digest::{generic_array::typenum::U32, Digest},
g,
hash::{HashAdd, Tagged},
marker::*,
nonce::{Deterministic, NonceGen},
s, Point, Scalar, XOnly, G,
};
/// The MuSig context.
pub struct MuSig<H, S = ()> {
/// The hash used to compress the key list to 32 bytes.
pub pk_hash: H,
/// The hash used to generate each key's coefficient.
pub coeff_hash: H,
/// The hash used to generate the nonce coefficients.
pub nonce_coeff_hash: H,
/// The instance of the underlying Schnorr context.
pub schnorr: S,
}
impl<H: Tagged, S> MuSig<H, S> {
fn _new(schnorr: S) -> Self {
Self {
pk_hash: H::default().tagged(b"KeyAgg list"),
coeff_hash: H::default().tagged(b"KeyAgg coefficient"),
nonce_coeff_hash: H::default().tagged(b"MuSig/noncecoef"),
schnorr,
}
}
}
impl<H: Tagged, S: Default> Default for MuSig<H, S> {
fn default() -> Self {
MuSig::_new(S::default())
}
}
impl<H: Tagged> MuSig<H, ()> {
/// Creates a MuSig context that can only do key aggregation.
///
/// # Example
///
/// ```
/// # use schnorr_fun::fun::{ XOnly };
/// # let key1 = XOnly::random(&mut rand::thread_rng());
/// # let key2 = XOnly::random(&mut rand::thread_rng());
/// use schnorr_fun::musig::{MuSig, Party};
/// use sha2::Sha256;
/// let musig = MuSig::<Sha256>::keyagg_only();
/// let keylist = musig.new_keylist(vec![Party::Remote(key1), Party::Remote(key2)]);
/// println!("{:?}", keylist.agg_public_key())
/// ```
pub fn keyagg_only() -> Self {
Self::_new(())
}
}
impl<H: Tagged, NG, GT> MuSig<H, Schnorr<H, NG, GT>> {
/// Generate a new MuSig context from a Schnorr context.
pub fn new(schnorr: Schnorr<H, NG, GT>) -> Self {
Self::_new(schnorr)
}
}
/// A party in the protocol.
///
/// A party is either local (we know the secret key) or remote (we only know the public key).
#[derive(Debug, Clone)]
pub enum Party {
/// A local party (we have the keypair)
Local(KeyPair),
/// A remote party (we only know the public key)
Remote(XOnly),
}
/// A struct which represents a list of keys aggregated into a single key.
///
/// This can't be serialized but it's very efficient to re-create it from the initial list of keys.
#[derive(Debug, Clone)]
pub struct KeyList {
/// The parties involved in the key aggregation.
parties: Vec<Party>,
/// The coefficients of each key
coefs: Vec<Scalar>,
/// The aggregate key
agg_key: Point<EvenY>,
/// The
tweak: Scalar<Public, Zero>,
needs_negation: bool,
}
impl KeyList {
/// The `XOnly` aggeregated key for the keylist.
pub fn agg_public_key(&self) -> XOnly {
self.agg_key.to_xonly()
}
/// The aggregated key for the keylist as a `Point`.
pub fn agg_verification_key(&self) -> Point<EvenY> {
self.agg_key
}
/// An iterator over the **public keys** of each party in the keylist.
pub fn keys(&self) -> impl Iterator<Item = XOnly> + '_ {
self.parties.iter().map(|party| match party {
Party::Local(keypair) => keypair.public_key(),
Party::Remote(xonly) => *xonly,
})
}
/// *Tweak* the aggregated key with a scalar so that the resulting key is equal to the existing
/// key plus `tweak * G`. The tweak mutates the public key while still allowing the original set
/// of signers to sign under the new key.
///
/// This is how you embed a taproot commitment into a key.
///
/// ## Return value
///
/// Returns a new keylist with the same parties but a different aggregated public key. In the
/// unusual case that the tweak is exactly equal to the negation of the aggregated secret key
/// this returns `None`.
pub fn tweak(&self, tweak: Scalar<impl Secrecy, impl ZeroChoice>) -> Option<Self> {
let mut tweak = s!(self.tweak + tweak).mark::<Public>();
let (agg_key, needs_negation) = g!(self.agg_key + tweak * G)
.mark::<NonZero>()?
.into_point_with_even_y();
tweak.conditional_negate(needs_negation);
let needs_negation = self.needs_negation ^ needs_negation;
Some(KeyList {
parties: self.parties.clone(),
coefs: self.coefs.clone(),
agg_key,
tweak,
needs_negation,
})
}
}
impl<H: Digest<OutputSize = U32> + Clone, S> MuSig<H, S> {
/// Generates a new key list from a list of parties.
///
/// Each party can be local (you know the secret key) or remote (you only know the public key).
///
/// ## Example
///
/// ```
/// use schnorr_fun::{
/// fun::{Point, Scalar, XOnly},
/// musig::{MuSig, Party},
/// nonce::Deterministic,
/// Schnorr,
/// };
/// # let my_secret_key = Scalar::random(&mut rand::thread_rng());
/// # let their_public_key = XOnly::random(&mut rand::thread_rng());
/// use sha2::Sha256;
/// let musig = MuSig::<Sha256, Schnorr<Sha256, Deterministic<Sha256>>>::default();
/// let my_keypair = musig.schnorr.new_keypair(my_secret_key);
/// // Note the keys have to come in the same order on the other side!
/// let keylist = musig.new_keylist(vec![
/// Party::Local(my_keypair),
/// Party::Remote(their_public_key),
/// ]);
/// ```
pub fn new_keylist(&self, parties: Vec<Party>) -> KeyList {
let keys = parties
.iter()
.map(|party| match party {
Party::Local(keypair) => keypair.public_key(),
Party::Remote(xonly) => *xonly,
})
.collect::<Vec<_>>();
let coeff_hash = {
let L = self.pk_hash.clone().add(&keys[..]).finalize();
self.coeff_hash.clone().add(L.as_slice())
};
let mut second = None;
let coefs = keys
.iter()
.map(|key| {
// This is the logic for IsSecond from appendix B of the MuSig2 paper
if second.is_none() && key != &keys[0] {
second = Some(key);
}
if second != Some(key) {
Scalar::from_hash(coeff_hash.clone().add(key))
} else {
Scalar::one()
}
})
.collect::<Vec<_>>();
let points = keys.into_iter().map(|x| x.to_point()).collect::<Vec<_>>();
let (agg_key, needs_negation) = crate::fun::op::lincomb(coefs.iter(), points.iter())
.expect_nonzero("computationally unreachable: linear combination of hash ranomized points cannot add to zero")
.into_point_with_even_y();
KeyList {
parties,
coefs,
agg_key,
tweak: Scalar::zero().mark::<Public>(),
needs_negation,
}
}
}
/// A nonce (pair of points) that each party must share with the others in the first stage of signing.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Nonce(pub [Point; 2]);
impl Nonce {
/// Reads the pair of nonces from 66 bytes (two 33-byte serialized points).
pub fn from_bytes(bytes: [u8; 66]) -> Option<Self> {
let R1 = Point::from_slice(&bytes[..33])?;
let R2 = Point::from_slice(&bytes[33..])?;
Some(Nonce([R1, R2]))
}
/// Serializes a public nonce as as 66 bytes (two 33-byte serialized points).
pub fn to_bytes(&self) -> [u8; 66] {
let mut bytes = [0u8; 66];
bytes[..33].copy_from_slice(self.0[0].to_bytes().as_ref());
bytes[33..].copy_from_slice(self.0[1].to_bytes().as_ref());
bytes
}
}
secp256kfun::impl_fromstr_deserialize! {
name => "MuSig2 public nonce pair",
fn from_bytes(bytes: [u8;66]) -> Option<Nonce> {
Nonce::from_bytes(bytes)
}
}
secp256kfun::impl_display_serialize! {
fn to_bytes(nonce: &Nonce) -> [u8;66] {
nonce.to_bytes()
}
}
/// A pair of secret nonces along with the public portion.
///
/// Depending on whether you are using determinisitc nonce derivation or not
#[derive(Debug, Clone, PartialEq)]
pub struct NonceKeyPair {
/// The public nonce
pub public: Nonce,
/// The secret nonce
pub secret: [Scalar; 2],
}
impl NonceKeyPair {
/// Deserializes a nonce key pair from 64-bytes (two 32-byte serialized scalars).
pub fn from_bytes(bytes: [u8; 64]) -> Option<Self> {
let r1 = Scalar::from_slice(&bytes[..32])?.mark::<NonZero>()?;
let r2 = Scalar::from_slice(&bytes[32..])?.mark::<NonZero>()?;
let R1 = g!(r1 * G).normalize();
let R2 = g!(r2 * G).normalize();
let pub_nonce = Nonce([R1, R2]);
Some(NonceKeyPair {
public: pub_nonce,
secret: [r1, r2],
})
}
/// Serializes a nonce key pair to 64-bytes (two 32-bytes serialized scalars).
pub fn to_bytes(&self) -> [u8; 64] {
let mut bytes = [0u8; 64];
bytes[..32].copy_from_slice(self.secret[0].to_bytes().as_ref());
bytes[32..].copy_from_slice(self.secret[1].to_bytes().as_ref());
bytes
}
}
secp256kfun::impl_fromstr_deserialize! {
name => "MuSig secret nonce pair",
fn from_bytes(bytes: [u8;64]) -> Option<NonceKeyPair> {
NonceKeyPair::from_bytes(bytes)
}
}
secp256kfun::impl_display_serialize! {
fn to_bytes(nkp: &NonceKeyPair) -> [u8;64] {
nkp.to_bytes()
}
}
impl<H: Digest<OutputSize = U32> + Clone, NG: NonceGen, GT> MuSig<H, Schnorr<H, NG, GT>> {
/// Generate nonces for your local keys in keylist.
///
/// It is very important to carefully consider the implications of your choice of underlying
/// [`NonceGen`].
///
/// Using a [`Synthetic`] nonce generator will mean you don't have to worry about passing a
/// unique `sid` (session id) to this function for each signing session. The downside is that
/// you must recall the result of `gen_nonces` somewhere and store it for use when you want to
/// start the signing session with [`start_sign_session`].
///
/// Using a [`Deterministic`] nonce generator means you **must** never start two signing
/// sessions with nonces generated from the same `sid`. If you do your secret key will be
/// recoverable from the two partial signatures you created with the same nonce. The upside is
/// that you can call [`start_sign_session_deterministic`] with the `sid` you orignally passed
/// to `gen_nonces` without having to store the output of `gen_nonces`.
///
/// Note that the API allows you to BYO nonces by creating `NonceKeyPair`s manually.
///
/// [`NonceGen`]: secp256kfun::nonce::NonceGen
/// [`Synthetic`]: secp256kfun::nonce::Synthetic
/// [`Deterministic`]: secp256kfun::nonce::Deterministic
/// [`start_sign_session`]: Self::start_sign_session
/// [`start_sign_session_deterministic`]: Self::start_sign_session_deterministic
pub fn gen_nonces(&self, keylist: &KeyList, sid: &[u8]) -> Vec<NonceKeyPair> {
keylist
.parties
.iter()
.filter_map(|party| match party {
Party::Local(keypair) => {
let r1 = derive_nonce!(
nonce_gen => self.schnorr.nonce_gen(),
secret => keypair.secret_key(),
public => [ b"r1", keypair.public_key(), keylist.agg_public_key(), sid]
);
let r2 = derive_nonce!(
nonce_gen => self.schnorr.nonce_gen(),
secret => keypair.secret_key(),
public => [ b"r2", keypair.public_key(), keylist.agg_public_key(), sid]
);
let R1 = g!(r1 * G).normalize();
let R2 = g!(r2 * G).normalize();
Some(NonceKeyPair {
public: Nonce([R1, R2]),
secret: [r1, r2],
})
}
Party::Remote(_) => None,
})
.collect()
}
}
/// Marker type for indicating the [`SignSession`] is being used to create an ordinary Schnorr
/// signature.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct Ordinary;
/// Marks the [`SignSession`] as being used to create an adaptor (a.k.a. one-time encrypted)
/// signature.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct Adaptor {
y_needs_negation: bool,
}
/// A signing session.
///
/// Created by [`start_sign_session`] or [`start_encrypted_sign_session`].
/// The type parameter records whether you are trying to jointly generate a signature or an adaptor signature.
///
/// [`start_sign_session`]: MuSig::start_sign_session
/// [`start_encrypted_sign_session`]: MuSig::start_encrypted_sign_session
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(crate = "serde_crate")
)]
pub struct SignSession<T = Ordinary> {
b: Scalar<Public, Zero>,
c: Scalar<Public, Zero>,
local_secret_nonces: Vec<[Scalar; 2]>,
public_nonces: Vec<Nonce>,
R: Point<EvenY>,
signing_type: T,
}
impl<H: Digest<OutputSize = U32> + Clone, NG, GT> MuSig<H, Schnorr<H, NG, GT>> {
/// Start a signing session.
///
/// You must provide you local secret nonces (the public portion must be shared with the other signer(s)).
/// If you are using deterministic signing it's possible to use [`start_sign_session_deterministic`] instead.
///
/// ## Return Value
///
/// Returns `None` in the case that the `remote_noces` have been (maliciously) selected to
/// cancel out your local nonces.
/// This is not a security issue -- we just can't continue the protocol if this happens.
///
/// [`start_sign_session_deterministic`]: Self::start_sign_session_deterministic
pub fn start_sign_session(
&self,
keylist: &KeyList,
local_nonces: Vec<NonceKeyPair>,
remote_nonces: impl IntoIterator<Item = Nonce>,
message: Message<'_, Public>,
) -> Option<SignSession> {
let (b, c, local_secret_nonces, public_nonces, R, _) = self._start_sign_session(
keylist,
local_nonces,
remote_nonces,
message,
&Point::zero(),
)?;
Some(SignSession {
b,
c,
local_secret_nonces,
public_nonces,
R,
signing_type: Ordinary,
})
}
/// Start an encrypted signing session
///
/// i.e. a session to produce an adaptor signature under `encryption_key`.
///
/// You must provide you local secret nonces (the public portion must be shared with the other
/// signer(s)). If you are using deterministic signing it's possible to use
/// [`start_encrypted_sign_session_deterministic`] instead.
///
/// ## Return Value
///
/// Returns `None` in the case that the `remote_noces` have been (maliciously) selected to
/// cancel out your local nonces.
/// This is not a security issue -- we just can't continue the protocol if this happens.
///
/// [`start_encrypted_sign_session_deterministic`]: Self::start_sign_session_deterministic
pub fn start_encrypted_sign_session(
&self,
keylist: &KeyList,
local_nonces: Vec<NonceKeyPair>,
remote_nonces: impl IntoIterator<Item = Nonce>,
message: Message<'_, Public>,
encryption_key: &Point<impl PointType, impl Secrecy>,
) -> Option<SignSession<Adaptor>> {
let (b, c, local_secret_nonces, public_nonces, R, y_needs_negation) = self
._start_sign_session(
keylist,
local_nonces,
remote_nonces,
message,
encryption_key,
)?;
Some(SignSession {
b,
c,
local_secret_nonces,
public_nonces,
R,
signing_type: Adaptor { y_needs_negation },
})
}
/// Starts a signing session with a message and all the nonces.
pub fn _start_sign_session(
&self,
keylist: &KeyList,
local_nonces: Vec<NonceKeyPair>,
remote_nonces: impl IntoIterator<Item = Nonce>,
message: Message<'_, Public>,
encryption_key: &Point<impl PointType, impl Secrecy, impl ZeroChoice>,
) -> Option<(
Scalar<Public, Zero>,
Scalar<Public, Zero>,
Vec<[Scalar; 2]>,
Vec<Nonce>,
Point<EvenY>,
bool,
)> {
let mut remote_nonces = remote_nonces.into_iter();
let mut local_pubnonces = local_nonces.iter().map(|nonce| nonce.public);
let mut Rs = keylist
.parties
.iter()
.map(|party| match party {
Party::Local(_) => local_pubnonces
.next()
.expect("missing local nonce keypair -- must have one for each local party"),
Party::Remote(_) => remote_nonces.next().expect("missing remote nonce"),
})
.collect::<Vec<_>>();
assert!(
remote_nonces.next().is_none(),
"Too many remote nonces passed in"
);
assert!(
local_pubnonces.next().is_none(),
"Too many local nonces passed in"
);
let agg_Rs = Rs
.iter()
.fold([Point::zero().mark::<Jacobian>(); 2], |acc, nonce| {
[
g!({ acc[0] } + { nonce.0[0] }),
g!({ acc[1] } + { nonce.0[1] }),
]
});
let agg_Rs = [
g!({ agg_Rs[0] } + encryption_key)
.normalize()
.mark::<NonZero>()?,
agg_Rs[1].normalize().mark::<NonZero>()?,
];
let b = {
let H = self.nonce_coeff_hash.clone();
Scalar::from_hash(H.add(agg_Rs).add(keylist.agg_public_key()).add(message))
}
.mark::<(Public, Zero)>();
let (R, r_needs_negation) = g!({ agg_Rs[0] } + b * { agg_Rs[1] } )
.normalize()
.expect_nonzero("computationally unreachable: one of the coefficients is a hash output that commits to both point")
.into_point_with_even_y();
for R in &mut Rs {
R.0[0] = R.0[0].conditional_negate(r_needs_negation);
R.0[1] = R.0[1].conditional_negate(r_needs_negation);
}
let local_secret_nonces = local_nonces
.into_iter()
.map(|local_nonce| {
let mut secret = local_nonce.secret;
secret[0].conditional_negate(r_needs_negation);
secret[1].conditional_negate(r_needs_negation);
secret
})
.collect();
let c = self
.schnorr
.challenge(R.to_xonly(), keylist.agg_public_key(), message);
Some((b, c, local_secret_nonces, Rs, R, r_needs_negation))
}
/// Generates partial signatures (or partial encrypted signatures depending on `T`) under each of the `Local` entries in `keylist`.
///
/// The order of the partial signatures returned is the order of them in the keylist.
pub fn sign_all<T>(
&self,
keylist: &KeyList,
session: &SignSession<T>,
) -> Vec<Scalar<Public, Zero>> {
let c = session.c;
keylist
.parties
.iter()
.enumerate()
.filter_map(|(i, party)| match party {
Party::Local(keypair) => Some((i, keypair)),
Party::Remote(_) => None,
})
.enumerate()
.map(|(j, (i, keypair))| {
let x = keypair.secret_key();
let [ref r1, ref r2] = session.local_secret_nonces[j];
let b = session.b;
let mut a = keylist.coefs[i].clone();
a.conditional_negate(keylist.needs_negation);
s!(c * a * x + r1 + b * r2).mark::<(Public, Zero)>()
})
.collect()
}
#[must_use]
/// Verifies a partial signature (or partial encrypted signature depending on `T`).
///
/// You must provide the `index` of the party (the index of the key in `keylist`).
pub fn verify_partial_signature<T>(
&self,
keylist: &KeyList,
session: &SignSession<T>,
index: usize,
partial_sig: Scalar<Public, Zero>,
) -> bool {
let c = session.c;
let b = session.b;
let s = &partial_sig;
let mut a = keylist.coefs[index].clone();
a.conditional_negate(keylist.needs_negation);
let X = keylist.keys().nth(index).unwrap().to_point();
let [ref R1, ref R2] = &session.public_nonces[index].0;
g!((c * a) * X + R1 + b * R2 - s * G).is_zero()
}
/// Combines all the partial signatures into a single `Signature`.
///
/// Note this does not check the validity of any of the partial signatures. You should either check
/// each one using [`verify_partial_signature`] or use [`verify`] on the returned `Signature` to check validity.
///
/// [`verify`]: crate::Schnorr::verify
/// [`verify_partial_signature`]: Self::verify_partial_signature
pub fn combine_partial_signatures(
&self,
keylist: &KeyList,
session: &SignSession<Ordinary>,
partial_sigs: impl IntoIterator<Item = Scalar<Public, Zero>>,
) -> Signature {
let (R, s) = self._combine_partial_signatures(keylist, &session, partial_sigs);
Signature { R: R.to_xonly(), s }
}
/// Combines all the partial encrypted signatures into one encrypted signature.
///
/// Note this does not check the validity of any of the partial signatures. You should either check
/// each one using [`verify_partial_signature`] or use [`verify_encrypted_signature`] on the returned `Signature` to check validity.
///
/// [`verify_encrypted_signature`]: crate::adaptor::Adaptor::verify_encrypted_signature
/// [`verify_partial_signature`]: Self::verify_partial_signature
pub fn combine_partial_encrypted_signatures(
&self,
keylist: &KeyList,
session: &SignSession<Adaptor>,
partial_encrypted_sigs: impl IntoIterator<Item = Scalar<Public, Zero>>,
) -> EncryptedSignature {
let (R, s_hat) =
self._combine_partial_signatures(keylist, &session, partial_encrypted_sigs);
EncryptedSignature {
R,
s_hat,
needs_negation: session.signing_type.y_needs_negation,
}
}
fn _combine_partial_signatures<T>(
&self,
keylist: &KeyList,
session: &SignSession<T>,
partial_sigs: impl IntoIterator<Item = Scalar<Public, Zero>>,
) -> (Point<EvenY>, Scalar<Public, Zero>) {
let ck = s!(session.c * keylist.tweak);
let sum_s = partial_sigs
.into_iter()
.reduce(|acc, s| s!(acc + s).mark::<Public>())
.unwrap_or(Scalar::zero().mark::<Public>());
let s = s!(sum_s + ck).mark::<Public>();
(session.R, s)
}
}
impl<H: Digest<OutputSize = U32> + Clone, GT, HNG> MuSig<H, Schnorr<H, Deterministic<HNG>, GT>>
where
Deterministic<HNG>: NonceGen,
{
/// Same as [`start_sign_session`] but re-generate the local nonces deterministically from the
/// `sid` instead of passing them in.
///
/// [`start_sign_session`]: Self::start_sign_session
pub fn start_sign_session_deterministic(
&self,
keylist: &KeyList,
remote_nonces: impl IntoIterator<Item = Nonce>,
sid: &[u8],
message: Message<'_, Public>,
) -> Option<SignSession> {
let local_nonces = self.gen_nonces(keylist, sid);
self.start_sign_session(keylist, local_nonces, remote_nonces, message)
}
/// Same as [`start_encrypted_sign_session`] but re-generate the local nonces deterministically from the
/// `sid` instead of passing them in.
///
/// [`start_encrypted_sign_session`]: Self::start_encrypted_sign_session
pub fn start_encrypted_sign_session_deterministic(
&self,
keylist: &KeyList,
remote_nonces: impl IntoIterator<Item = Nonce>,
sid: &[u8],
message: Message<'_, Public>,
encryption_key: &Point<impl PointType, impl Secrecy>,
) -> Option<SignSession<Adaptor>> {
let local_nonces = self.gen_nonces(keylist, sid);
self.start_encrypted_sign_session(
keylist,
local_nonces,
remote_nonces,
message,
encryption_key,
)
}
}
#[cfg(test)]
mod test {
use crate::adaptor::Adaptor;
use super::*;
use secp256kfun::{nonce::Deterministic, proptest::prelude::*};
use sha2::Sha256;
proptest! {
#[test]
fn test_end_to_end(sk1 in any::<Scalar>(), sk2 in any::<Scalar>(), sk3 in any::<Scalar>()) {
let schnorr = Schnorr::<Sha256, _>::new(Deterministic::<Sha256>::default());
let musig = MuSig::new(schnorr);
let keypair1 = musig
.schnorr
.new_keypair(sk1);
let keypair2 = musig
.schnorr
.new_keypair(sk2);
let keypair3 = musig
.schnorr
.new_keypair(sk3);
let keylist_p1 = musig.new_keylist(vec![
Party::Local(keypair1.clone()),
Party::Remote(keypair2.public_key()),
Party::Local(keypair3.clone()),
]);
let keylist_p2 = musig.new_keylist(vec![
Party::Remote(keypair1.public_key()),
Party::Local(keypair2),
Party::Remote(keypair3.public_key()),
]);
assert_eq!(keylist_p1.agg_public_key(), keylist_p2.agg_public_key());
let p1_nonces = musig.gen_nonces(&keylist_p1, b"test");
let p2_nonces = musig.gen_nonces(&keylist_p2, b"test");
let message =
Message::<Public>::plain("test", b"Chancellor on brink of second bailout for banks");
let p1_session = musig
.start_sign_session(
&keylist_p1,
p1_nonces.clone(),
p2_nonces.iter().map(|nonce| nonce.public),
message,
)
.unwrap();
let p2_session = musig
.start_sign_session_deterministic(
&keylist_p2,
p1_nonces.iter().map(|nonce| nonce.public),
b"test",
message,
)
.unwrap();
let p1_sigs = musig.sign_all(&keylist_p1, &p1_session);
assert_eq!(p1_sigs.len(), 2);
for (j, i) in [0, 2].iter().enumerate() {
assert!(musig.verify_partial_signature(&keylist_p2, &p2_session, *i, p1_sigs[j]));
assert!(musig.verify_partial_signature(&keylist_p1, &p1_session, *i, p1_sigs[j]));
}
let p2_sigs = musig.sign_all(&keylist_p2, &p2_session);
assert_eq!(p2_sigs.len(), 1);
assert!(musig.verify_partial_signature(&keylist_p2, &p2_session, 1, p2_sigs[0]));
assert!(musig.verify_partial_signature(&keylist_p1, &p1_session, 1, p2_sigs[0]));
let partial_sigs = [p1_sigs, p2_sigs].concat();
let sig_p1 = musig.combine_partial_signatures(&keylist_p1, &p1_session, partial_sigs.clone());
let sig_p2 = musig.combine_partial_signatures(&keylist_p2, &p2_session, partial_sigs);
assert_eq!(sig_p1, sig_p2);
assert!(musig
.schnorr
.verify(&keylist_p1.agg_verification_key(), message, &sig_p1));
assert!(musig
.schnorr
.verify(&keylist_p2.agg_verification_key(), message, &sig_p2));
}
#[test]
fn test_musig_adaptor(sk1 in any::<Scalar>(), sk2 in any::<Scalar>(), sk3 in any::<Scalar>(), y in any::<Scalar>()) {
let schnorr = Schnorr::<Sha256, _>::new(Deterministic::<Sha256>::default());
let musig = MuSig::new(schnorr);
let keypair1 = musig
.schnorr
.new_keypair(sk1);
let keypair2 = musig
.schnorr
.new_keypair(sk2);
let keypair3 = musig
.schnorr
.new_keypair(sk3);
let encryption_key = musig.schnorr.encryption_key_for(&y);
let keylist_p1 = musig.new_keylist(vec![
Party::Local(keypair1.clone()),
Party::Remote(keypair2.public_key()),
Party::Local(keypair3.clone()),
]);
let keylist_p2 = musig.new_keylist(vec![
Party::Remote(keypair1.public_key()),
Party::Local(keypair2),
Party::Remote(keypair3.public_key()),
]);
assert_eq!(keylist_p1.agg_public_key(), keylist_p2.agg_public_key());
let p1_nonces = musig.gen_nonces(&keylist_p1, b"test");
let p2_nonces = musig.gen_nonces(&keylist_p2, b"test");
let message =
Message::<Public>::plain("test", b"Chancellor on brink of second bailout for banks");
let p1_session = musig
.start_encrypted_sign_session(
&keylist_p1,
p1_nonces.clone(),
p2_nonces.iter().map(|nonce| nonce.public),
message,
&encryption_key
)
.unwrap();
let p2_session = musig
.start_encrypted_sign_session_deterministic(
&keylist_p2,
p1_nonces.iter().map(|nonce| nonce.public),
b"test",
message,
&encryption_key
)
.unwrap();
let p1_sigs = musig.sign_all(&keylist_p1, &p1_session);
assert_eq!(p1_sigs.len(), 2);
for (j, i) in [0, 2].iter().enumerate() {
assert!(musig.verify_partial_signature(&keylist_p2, &p2_session, *i, p1_sigs[j]));
assert!(musig.verify_partial_signature(&keylist_p1, &p1_session, *i, p1_sigs[j]));
}
let p2_sigs = musig.sign_all(&keylist_p2, &p2_session);
assert_eq!(p2_sigs.len(), 1);
assert!(musig.verify_partial_signature(&keylist_p2, &p2_session, 1, p2_sigs[0]));
assert!(musig.verify_partial_signature(&keylist_p1, &p1_session, 1, p2_sigs[0]));
let partial_sigs = [p1_sigs, p2_sigs].concat();
let sig_p1 = musig.combine_partial_encrypted_signatures(&keylist_p1, &p1_session, partial_sigs.clone());
let sig_p2 = musig.combine_partial_encrypted_signatures(&keylist_p2, &p2_session, partial_sigs);
assert_eq!(sig_p1, sig_p2);
assert!(musig
.schnorr
.verify_encrypted_signature(&keylist_p1.agg_verification_key(), &encryption_key, message, &sig_p1));
assert!(musig
.schnorr
.verify_encrypted_signature(&keylist_p2.agg_verification_key(), &encryption_key, message, &sig_p2));
}
}
#[test]
fn sign_test_vectors() {
let musig = MuSig::<Sha256, Schnorr<Sha256, Deterministic<Sha256>>>::default();
let X1 = XOnly::from_bytes([
0xF9, 0x30, 0x8A, 0x01, 0x92, 0x58, 0xC3, 0x10, 0x49, 0x34, 0x4F, 0x85, 0xF8, 0x9D,
0x52, 0x29, 0xB5, 0x31, 0xC8, 0x45, 0x83, 0x6F, 0x99, 0xB0, 0x86, 0x01, 0xF1, 0x13,
0xBC, 0xE0, 0x36, 0xF9,
])
.unwrap();
let X2 = XOnly::from_bytes([
0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23,
0x41, 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, 0xD8, 0x43, 0x24, 0x0F, 0x7B,
0x50, 0x2B, 0xA6, 0x59,
])
.unwrap();
let keypair = musig.schnorr.new_keypair(
Scalar::from_bytes([
0x7F, 0xB9, 0xE0, 0xE6, 0x87, 0xAD, 0xA1, 0xEE, 0xBF, 0x7E, 0xCF, 0xE2, 0xF2, 0x1E,
0x73, 0xEB, 0xDB, 0x51, 0xA7, 0xD4, 0x50, 0x94, 0x8D, 0xFE, 0x8D, 0x76, 0xD7, 0xF2,
0xD1, 0x00, 0x76, 0x71,
])
.unwrap()
.mark::<NonZero>()
.unwrap(),
);
let secnonce = NonceKeyPair::from_bytes([
0x50, 0x8B, 0x81, 0xA6, 0x11, 0xF1, 0x00, 0xA6, 0xB2, 0xB6, 0xB2, 0x96, 0x56, 0x59,
0x08, 0x98, 0xAF, 0x48, 0x8B, 0xCF, 0x2E, 0x1F, 0x55, 0xCF, 0x22, 0xE5, 0xCF, 0xB8,
0x44, 0x21, 0xFE, 0x61, 0xFA, 0x27, 0xFD, 0x49, 0xB1, 0xD5, 0x00, 0x85, 0xB4, 0x81,
0x28, 0x5E, 0x1C, 0xA2, 0x05, 0xD5, 0x5C, 0x82, 0xCC, 0x1B, 0x31, 0xFF, 0x5C, 0xD5,
0x4A, 0x48, 0x98, 0x29, 0x35, 0x59, 0x01, 0xF7,
])
.unwrap();
let agg_pubnonce = Nonce::from_bytes([
0x02, 0x84, 0x65, 0xFC, 0xF0, 0xBB, 0xDB, 0xCF, 0x44, 0x3A, 0xAB, 0xCC, 0xE5, 0x33,
0xD4, 0x2B, 0x4B, 0x5A, 0x10, 0x96, 0x6A, 0xC0, 0x9A, 0x49, 0x65, 0x5E, 0x8C, 0x42,
0xDA, 0xAB, 0x8F, 0xCD, 0x61, 0x03, 0x74, 0x96, 0xA3, 0xCC, 0x86, 0x92, 0x6D, 0x45,
0x2C, 0xAF, 0xCF, 0xD5, 0x5D, 0x25, 0x97, 0x2C, 0xA1, 0x67, 0x5D, 0x54, 0x93, 0x10,
0xDE, 0x29, 0x6B, 0xFF, 0x42, 0xF7, 0x2E, 0xEE, 0xA8, 0xC9,
])
.unwrap();
let remote_nonces = vec![
agg_pubnonce,
Nonce([-secnonce.public.0[0], -secnonce.public.0[1]]),
];
let msg = [
0xF9, 0x54, 0x66, 0xD0, 0x86, 0x77, 0x0E, 0x68, 0x99, 0x64, 0x66, 0x42, 0x19, 0x26,
0x6F, 0xE5, 0xED, 0x21, 0x5C, 0x92, 0xAE, 0x20, 0xBA, 0xB5, 0xC9, 0xD7, 0x9A, 0xDD,
0xDD, 0xF3, 0xC0, 0xCF,
];
{
let keylist = musig.new_keylist(vec![
Party::Local(keypair.clone()),
Party::Remote(X1),
Party::Remote(X2),
]);
let session = musig
.start_sign_session(
&keylist,
vec![secnonce.clone()],
remote_nonces.clone(),
Message::<Public>::raw(&msg),
)
.unwrap();
let scalar = musig.sign_all(&keylist, &session)[0];
let expected = Scalar::from_bytes([
0x68, 0x53, 0x7C, 0xC5, 0x23, 0x4E, 0x50, 0x5B, 0xD1, 0x40, 0x61, 0xF8, 0xDA, 0x9E,
0x90, 0xC2, 0x20, 0xA1, 0x81, 0x85, 0x5F, 0xD8, 0xBD, 0xB7, 0xF1, 0x27, 0xBB, 0x12,
0x40, 0x3B, 0x4D, 0x3B,