musig2 0.4.0

Flexible Rust implementation of the MuSig2 multisignature protocol, compatible with Bitcoin.
Documentation
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
use crate::errors::{SigningError, VerifyError};
use crate::{tagged_hashes, AggNonce, KeyAggContext, PubNonce, SecNonce};

use secp::{MaybePoint, MaybeScalar, Point, Scalar, G};

use sha2::Digest as _;

/// The size of a serialized partial signature in bytes.
pub const PARTIAL_SIGNATURE_SIZE: usize = 32;

/// Partial signatures are just scalars in the range `[0, n)`.
///
/// See the documentation of [`secp::MaybeScalar`] for the
/// parsing, serializing, and conversion traits available
/// on this type.
pub type PartialSignature = MaybeScalar;

/// Computes the challenge hash `e` for for a signature. You probably don't need
/// to call this directly. Instead use [`sign_solo`][crate::sign_solo] or
/// [`sign_partial`][crate::sign_partial].
pub fn compute_challenge_hash_tweak<S: From<MaybeScalar>>(
    final_nonce_xonly: &[u8; 32],
    aggregated_pubkey: &Point,
    message: impl AsRef<[u8]>,
) -> S {
    let hash: [u8; 32] = tagged_hashes::BIP0340_CHALLENGE_TAG_HASHER
        .clone()
        .chain_update(final_nonce_xonly)
        .chain_update(aggregated_pubkey.serialize_xonly())
        .chain_update(message.as_ref())
        .finalize()
        .into();

    S::from(MaybeScalar::reduce_from(&hash))
}

/// Compute a partial signature on a message encrypted under an adaptor point.
///
/// The partial signature returned from this function is a potentially-zero
/// scalar value which can then be passed to other signers for verification
/// and aggregation.
///
/// Once aggregated, the signature must be adapted with the discrete log
/// (secret key) of `adaptor_point` for the signature to be considered valid.
///
/// Returns [`SigningError::UnknownKey`] if the given secret key does not belong to this
/// `key_agg_ctx`.
///
/// Returns [`SigningError::SecNoncePubkeyMismatch`] if the provided [`SecNonce`] was
/// generated for a different participant's pubkey.
///
/// As an added safety, we also verify the partial signature before returning it.
/// If this check fails, this function returns [`SigningError::SelfVerifyFail`].
pub fn sign_partial_adaptor<T: From<PartialSignature>>(
    key_agg_ctx: &KeyAggContext,
    seckey: impl Into<Scalar>,
    secnonce: SecNonce,
    aggregated_nonce: &AggNonce,
    adaptor_point: impl Into<MaybePoint>,
    message: impl AsRef<[u8]>,
) -> Result<T, SigningError> {
    let adaptor_point: MaybePoint = adaptor_point.into();
    let seckey: Scalar = seckey.into();
    let pubkey = seckey.base_point_mul();

    // As a side-effect, looking up the cached key coefficient also confirms
    // the individual key is indeed part of the aggregated key.
    let key_coeff = key_agg_ctx
        .key_coefficient(pubkey)
        .ok_or(SigningError::UnknownKey)?;

    if secnonce.pubkey != pubkey {
        return Err(SigningError::SecNoncePubkeyMismatch);
    }

    let aggregated_pubkey = key_agg_ctx.pubkey;
    let pubnonce = secnonce.public_nonce();

    let b: MaybeScalar = aggregated_nonce.nonce_coefficient(aggregated_pubkey, &message);
    let final_nonce: Point = aggregated_nonce.final_nonce(b);
    let adapted_nonce = final_nonce + adaptor_point;

    // `d` is negated if only one of the parity accumulator OR the aggregated pubkey
    // has odd parity.
    let d = seckey.negate_if(aggregated_pubkey.parity() ^ key_agg_ctx.parity_acc);

    let nonce_x_bytes = adapted_nonce.serialize_xonly();
    let e: MaybeScalar = compute_challenge_hash_tweak(&nonce_x_bytes, &aggregated_pubkey, &message);

    // if has_even_Y(R):
    //   k = k1 + b*k2
    // else:
    //   k = (n-k1) + b(n-k2)
    //     = n - (k1 + b*k2)
    let secnonce_sum = (secnonce.k1 + b * secnonce.k2).negate_if(adapted_nonce.parity());

    // s = k + e*a*d
    let partial_signature = secnonce_sum + (e * key_coeff * d);

    verify_partial_adaptor(
        key_agg_ctx,
        partial_signature,
        aggregated_nonce,
        adaptor_point,
        pubkey,
        &pubnonce,
        &message,
    )?;

    Ok(T::from(partial_signature))
}

/// Compute a partial signature on a message.
///
/// The partial signature returned from this function is a potentially-zero
/// scalar value which can then be passed to other signers for verification
/// and aggregation.
///
/// This is equivalent to invoking [`sign_partial_adaptor`], but passing
/// [`MaybePoint::Infinity`] as the adaptor point.
///
/// Returns [`SigningError::UnknownKey`] if the given secret key does not belong to this
/// `key_agg_ctx`.
///
/// Returns [`SigningError::SecNoncePubkeyMismatch`] if the provided [`SecNonce`] was
/// generated for a different participant's pubkey.
///
/// As an added safety, we also verify the partial signature before returning it.
/// If this check fails, this function returns [`SigningError::SelfVerifyFail`].
pub fn sign_partial<T: From<PartialSignature>>(
    key_agg_ctx: &KeyAggContext,
    seckey: impl Into<Scalar>,
    secnonce: SecNonce,
    aggregated_nonce: &AggNonce,
    message: impl AsRef<[u8]>,
) -> Result<T, SigningError> {
    sign_partial_adaptor(
        key_agg_ctx,
        seckey,
        secnonce,
        aggregated_nonce,
        MaybePoint::Infinity,
        message,
    )
}

/// Verify a partial signature, usually from an untrusted co-signer,
/// which has been encrypted under an adaptor point.
///
/// If `verify_partial_adaptor` succeeds for every signature in
/// a signing session, the resulting aggregated signature is guaranteed
/// to be valid once it is adapted with the discrete log (secret key)
/// of `adaptor_point`.
///
/// Note that partial signatures are _not_ unforgeable!
/// Validity of a partial signature should not be relied on for this property.
/// See <https://gist.github.com/AdamISZ/ca974ed67889cedc738c4a1f65ff620b> for details.
///
/// Returns an error if the given public key doesn't belong to the
/// `key_agg_ctx`, or if the signature is invalid.
pub fn verify_partial_adaptor(
    key_agg_ctx: &KeyAggContext,
    partial_signature: impl Into<PartialSignature>,
    aggregated_nonce: &AggNonce,
    adaptor_point: impl Into<MaybePoint>,
    individual_pubkey: impl Into<Point>,
    individual_pubnonce: &PubNonce,
    message: impl AsRef<[u8]>,
) -> Result<(), VerifyError> {
    let partial_signature: MaybeScalar = partial_signature.into();

    // As a side-effect, looking up the cached effective key also confirms
    // the individual key is indeed part of the aggregated key.
    let effective_pubkey: MaybePoint = key_agg_ctx
        .effective_pubkey(individual_pubkey)
        .ok_or(VerifyError::UnknownKey)?;

    let aggregated_pubkey = key_agg_ctx.pubkey;

    let b: MaybeScalar = aggregated_nonce.nonce_coefficient(aggregated_pubkey, &message);
    let final_nonce: Point = aggregated_nonce.final_nonce(b);
    let adapted_nonce = final_nonce + adaptor_point.into();

    let mut effective_nonce = individual_pubnonce.R1 + b * individual_pubnonce.R2;

    // Don't need constant time ops here as adapted_nonce is public.
    if adapted_nonce.has_odd_y() {
        effective_nonce = -effective_nonce;
    }

    let nonce_x_bytes = adapted_nonce.serialize_xonly();
    let e: MaybeScalar = compute_challenge_hash_tweak(&nonce_x_bytes, &aggregated_pubkey, &message);

    // s * G == R + (g * gacc * e * a * P)
    let challenge_parity = aggregated_pubkey.parity() ^ key_agg_ctx.parity_acc;
    let challenge_point = (e * effective_pubkey).negate_if(challenge_parity);

    if partial_signature * G != effective_nonce + challenge_point {
        return Err(VerifyError::BadSignature);
    }

    Ok(())
}

/// Verify a partial signature, usually from an untrusted co-signer.
///
/// If `verify_partial` succeeds for every signature in
/// a signing session, the resulting aggregated signature is guaranteed
/// to be valid.
///
/// Note that partial signatures are _not_ unforgeable!
/// Validity of a partial signature should not be relied on for this property.
/// See <https://gist.github.com/AdamISZ/ca974ed67889cedc738c4a1f65ff620b> for details.
///
/// This function is effectively the same as invoking [`verify_partial_adaptor`]
/// but passing [`MaybePoint::Infinity`] as the adaptor point.
///
/// Returns an error if the given public key doesn't belong to the
/// `key_agg_ctx`, or if the signature is invalid.
pub fn verify_partial(
    key_agg_ctx: &KeyAggContext,
    partial_signature: impl Into<PartialSignature>,
    aggregated_nonce: &AggNonce,
    individual_pubkey: impl Into<Point>,
    individual_pubnonce: &PubNonce,
    message: impl AsRef<[u8]>,
) -> Result<(), VerifyError> {
    verify_partial_adaptor(
        key_agg_ctx,
        partial_signature,
        aggregated_nonce,
        MaybePoint::Infinity,
        individual_pubkey,
        individual_pubnonce,
        message,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::DecodeError;
    use crate::testhex;

    #[test]
    fn sign_partial_rejects_secnonce_bound_to_different_pubkey() {
        let seckey = Scalar::try_from([0x11; 32]).unwrap();
        let other_seckey = Scalar::try_from([0x22; 32]).unwrap();

        let pubkey = seckey.base_point_mul();
        let other_pubkey = other_seckey.base_point_mul();
        let key_agg_ctx = KeyAggContext::new([pubkey]).unwrap();
        let aggregated_pubkey: Point = key_agg_ctx.aggregated_pubkey();
        let message = b"key-bound nonce regression";

        let secnonce = SecNonce::generate([0xAA; 32], seckey, aggregated_pubkey, message, b"");
        let mut secnonce_bytes: Vec<u8> = secnonce.into();
        secnonce_bytes.truncate(64);
        secnonce_bytes.extend_from_slice(&other_pubkey.serialize());

        let mismatched_secnonce = SecNonce::from_bytes(&secnonce_bytes).unwrap();
        let aggregated_nonce = AggNonce::sum([mismatched_secnonce.public_nonce()]);

        let err = sign_partial::<PartialSignature>(
            &key_agg_ctx,
            seckey,
            mismatched_secnonce,
            &aggregated_nonce,
            message,
        )
        .expect_err("sign_partial accepted a secnonce bound to another public key");

        assert_eq!(err, SigningError::SecNoncePubkeyMismatch);
    }

    #[test]
    fn sign_partial_reports_unknown_key_before_secnonce_mismatch() {
        fn scalar(value: u128) -> Scalar {
            Scalar::try_from(value).unwrap()
        }

        let member_seckey = scalar(1);
        let signing_seckey = scalar(2);
        let nonce_pubkey = scalar(3).base_point_mul();

        let key_agg_ctx = KeyAggContext::new([member_seckey.base_point_mul()]).unwrap();
        let secnonce = SecNonce::new(scalar(4), scalar(5), nonce_pubkey);
        let aggregated_nonce = AggNonce::sum([secnonce.public_nonce()]);

        let err = sign_partial::<PartialSignature>(
            &key_agg_ctx,
            signing_seckey,
            secnonce,
            &aggregated_nonce,
            b"unknown key takes precedence",
        )
        .expect_err("sign_partial accepted a signer outside the key aggregation context");

        assert_eq!(err, SigningError::UnknownKey);
    }

    #[test]
    fn test_partial_sign_and_verify() {
        const SIGN_VERIFY_VECTORS: &[u8] = include_bytes!("test_vectors/sign_verify_vectors.json");

        #[derive(serde::Deserialize)]
        struct ValidSignVerifyTestCase {
            key_indices: Vec<usize>,
            nonce_indices: Vec<usize>,
            aggnonce_index: usize,
            msg_index: usize,
            signer_index: usize,
            expected: MaybeScalar,
        }

        #[derive(serde::Deserialize, Clone)]
        struct SignError {
            signer: Option<usize>,
            contrib: Option<String>,
        }

        #[derive(serde::Deserialize, Clone)]
        struct SignErrorTestCase {
            key_indices: Vec<usize>,
            aggnonce_index: usize,
            msg_index: usize,
            secnonce_index: usize,
            error: SignError,
            comment: String,
        }

        #[derive(serde::Deserialize)]
        struct VerifyFailTestCase {
            #[serde(rename = "sig", deserialize_with = "testhex::deserialize")]
            partial_signature: Vec<u8>,
            key_indices: Vec<usize>,
            nonce_indices: Vec<usize>,
            msg_index: usize,
            signer_index: usize,
            comment: String,
        }

        #[derive(serde::Deserialize)]
        struct VerifyErrorTestCase {
            #[serde(rename = "sig", deserialize_with = "testhex::deserialize")]
            partial_signature: Vec<u8>,
            key_indices: Vec<usize>,
            nonce_indices: Vec<usize>,
            error: SignError,
            comment: String,
        }

        #[derive(serde::Deserialize)]
        struct SignVerifyVectors {
            #[serde(rename = "sk")]
            seckey: Scalar,

            #[serde(deserialize_with = "testhex::deserialize_vec")]
            pubkeys: Vec<[u8; 33]>,

            #[serde(rename = "secnonces", deserialize_with = "testhex::deserialize_vec")]
            secret_nonces: Vec<[u8; 97]>,

            #[serde(rename = "pnonces", deserialize_with = "testhex::deserialize_vec")]
            public_nonces: Vec<[u8; 66]>,

            #[serde(rename = "aggnonces", deserialize_with = "testhex::deserialize_vec")]
            aggregated_nonces: Vec<[u8; 66]>,

            #[serde(rename = "msgs", deserialize_with = "testhex::deserialize_vec")]
            messages: Vec<Vec<u8>>,

            valid_test_cases: Vec<ValidSignVerifyTestCase>,
            sign_error_test_cases: Vec<SignErrorTestCase>,
            verify_fail_test_cases: Vec<VerifyFailTestCase>,
            verify_error_test_cases: Vec<VerifyErrorTestCase>,
        }

        let vectors: SignVerifyVectors = serde_json::from_slice(SIGN_VERIFY_VECTORS)
            .expect("error parsing test vectors from sign_verify.json");

        let secnonce = SecNonce::try_from(vectors.secret_nonces[0].as_ref())
            .expect("error parsing secret nonce");

        for (test_index, test_case) in vectors.valid_test_cases.into_iter().enumerate() {
            let pubkeys: Vec<Point> = test_case
                .key_indices
                .into_iter()
                .map(|i| {
                    Point::try_from(&vectors.pubkeys[i]).unwrap_or_else(|_| {
                        panic!(
                            "invalid pubkey used in valid test: {}",
                            base16ct::lower::encode_string(&vectors.pubkeys[i])
                        )
                    })
                })
                .collect();

            let signer_pubkey = pubkeys[test_case.signer_index];
            assert_eq!(signer_pubkey, vectors.seckey.base_point_mul());

            let aggnonce_bytes = &vectors.aggregated_nonces[test_case.aggnonce_index];
            let aggregated_nonce = AggNonce::from_bytes(aggnonce_bytes).unwrap_or_else(|_| {
                panic!(
                    "invalid aggregated nonce used in valid test case: {}",
                    base16ct::lower::encode_string(aggnonce_bytes)
                )
            });

            let key_agg_ctx =
                KeyAggContext::new(pubkeys).expect("error constructing key aggregation context");

            let message = &vectors.messages[test_case.msg_index];

            let partial_signature: PartialSignature = sign_partial(
                &key_agg_ctx,
                vectors.seckey,
                secnonce.clone(),
                &aggregated_nonce,
                message,
            )
            .expect("error during partial signing");

            assert_eq!(
                partial_signature, test_case.expected,
                "partial signature does not match expected for test case {}",
                test_index,
            );

            let adaptor_secret = MaybeScalar::Valid(vectors.seckey);
            let adaptor_point = adaptor_secret * G;
            let partial_adaptor_signature: PartialSignature = sign_partial_adaptor(
                &key_agg_ctx,
                vectors.seckey,
                secnonce.clone(),
                &aggregated_nonce,
                adaptor_point,
                message,
            )
            .expect("error during partial adaptor signing");

            let public_nonces: Vec<PubNonce> = test_case
                .nonce_indices
                .into_iter()
                .map(|i| {
                    PubNonce::from_bytes(&vectors.public_nonces[i]).unwrap_or_else(|_| {
                        panic!(
                            "invalid pubnonce in valid test: {}",
                            base16ct::lower::encode_string(&vectors.public_nonces[i])
                        )
                    })
                })
                .collect();

            // Ensure the aggregated nonce in the test vector is correct
            assert_eq!(&AggNonce::sum(&public_nonces), &aggregated_nonce);

            verify_partial(
                &key_agg_ctx,
                partial_signature,
                &aggregated_nonce,
                signer_pubkey,
                &public_nonces[test_case.signer_index],
                message,
            )
            .expect("failed to verify valid partial signature");

            verify_partial_adaptor(
                &key_agg_ctx,
                partial_adaptor_signature,
                &aggregated_nonce,
                adaptor_point,
                signer_pubkey,
                &public_nonces[test_case.signer_index],
                message,
            )
            .expect("failed to verify valid partial signature");
        }

        // invalid input test case 0: signer's pubkey is not in the key_agg_ctx
        {
            let test_case = vectors.sign_error_test_cases[0].clone();

            let pubkeys: Vec<Point> = test_case
                .key_indices
                .into_iter()
                .map(|i| Point::try_from(&vectors.pubkeys[i]).unwrap())
                .collect();

            let aggnonce_bytes = &vectors.aggregated_nonces[test_case.aggnonce_index];
            let aggregated_nonce = AggNonce::from_bytes(aggnonce_bytes).unwrap();

            let key_agg_ctx =
                KeyAggContext::new(pubkeys).expect("error constructing key aggregation context");

            let message = &vectors.messages[test_case.msg_index];

            assert_eq!(
                sign_partial::<PartialSignature>(
                    &key_agg_ctx,
                    vectors.seckey,
                    secnonce,
                    &aggregated_nonce,
                    message,
                ),
                Err(SigningError::UnknownKey),
                "partial signing should fail for pubkey not in key_agg_ctx",
            );
        }

        // invalid input test case 1: invalid pubkey
        {
            let test_case = &vectors.sign_error_test_cases[1];
            for (signer_index, &key_index) in test_case.key_indices.iter().enumerate() {
                let result = Point::try_from(&vectors.pubkeys[key_index]);
                if signer_index == test_case.error.signer.unwrap() {
                    assert_eq!(
                        result,
                        Err(secp::errors::InvalidPointBytes),
                        "expected invalid signer pubkey"
                    );
                } else {
                    result.expect("expected valid signer pubkey");
                }
            }
        }

        // invalid input test case 2, 3, and 4: invalid aggnonce
        {
            for test_case in vectors.sign_error_test_cases[2..5].iter() {
                let result =
                    AggNonce::from_bytes(&vectors.aggregated_nonces[test_case.aggnonce_index]);

                assert_eq!(
                    result,
                    Err(DecodeError::from(secp::errors::InvalidPointBytes)),
                    "{} - invalid AggNonce should fail to decode",
                    &test_case.comment
                );
            }
        }

        // invalid input test case 5: invalid secnonce
        {
            let test_case = &vectors.sign_error_test_cases[5];
            let result = SecNonce::from_bytes(&vectors.secret_nonces[test_case.secnonce_index]);
            assert_eq!(
                result,
                Err(DecodeError::from(secp::errors::InvalidScalarBytes)),
                "invalid SecNonce should fail to decode"
            );
        }

        // Verification failure test cases 0 and 1: fake signatures
        {
            for test_case in vectors.verify_fail_test_cases[..2].iter() {
                let pubkeys: Vec<Point> = test_case
                    .key_indices
                    .iter()
                    .map(|&i| Point::try_from(&vectors.pubkeys[i]).unwrap())
                    .collect();

                let signer_pubkey = pubkeys[test_case.signer_index];

                let key_agg_ctx = KeyAggContext::new(pubkeys)
                    .expect("error constructing key aggregation context");

                let public_nonces: Vec<PubNonce> = test_case
                    .nonce_indices
                    .iter()
                    .map(|&i| PubNonce::from_bytes(&vectors.public_nonces[i]).unwrap())
                    .collect();

                let aggregated_nonce = AggNonce::sum(&public_nonces);

                let message = &vectors.messages[test_case.msg_index];

                let partial_signature =
                    MaybeScalar::try_from(test_case.partial_signature.as_slice())
                        .expect("unexpected invalid partial signature");

                assert_eq!(
                    verify_partial(
                        &key_agg_ctx,
                        partial_signature,
                        &aggregated_nonce,
                        signer_pubkey,
                        &public_nonces[test_case.signer_index],
                        message,
                    ),
                    Err(VerifyError::BadSignature),
                    "{} - unexpected success while verifying invalid partial signature",
                    test_case.comment,
                );
            }
        }

        // Verification failure test case 2: invalid signature
        {
            let test_case = &vectors.verify_fail_test_cases[2];
            let result = PartialSignature::try_from(test_case.partial_signature.as_slice());
            assert_eq!(
                result,
                Err(secp::errors::InvalidScalarBytes),
                "unexpected valid partial signature"
            );
        }

        for test_case in vectors.verify_error_test_cases.iter() {
            PartialSignature::try_from(test_case.partial_signature.as_slice())
                .expect("verify error test should use a valid partial signature scalar");

            let invalid_signer = test_case
                .error
                .signer
                .expect("verify error test should identify a signer");

            match test_case.error.contrib.as_deref() {
                Some("pubnonce") => {
                    for (signer_index, &nonce_index) in test_case.nonce_indices.iter().enumerate() {
                        let result = PubNonce::from_bytes(&vectors.public_nonces[nonce_index]);
                        if signer_index == invalid_signer {
                            assert_eq!(
                                result,
                                Err(DecodeError::from(secp::errors::InvalidPointBytes)),
                                "{} - expected invalid pubnonce for signer {}",
                                test_case.comment,
                                signer_index,
                            );
                        } else {
                            result.unwrap_or_else(|_| {
                                panic!(
                                    "{} - unexpected pubnonce parsing error for signer {}",
                                    test_case.comment, signer_index
                                )
                            });
                        }
                    }
                }
                Some("pubkey") => {
                    for (signer_index, &key_index) in test_case.key_indices.iter().enumerate() {
                        let result = Point::try_from(&vectors.pubkeys[key_index]);
                        if signer_index == invalid_signer {
                            assert_eq!(
                                result,
                                Err(secp::errors::InvalidPointBytes),
                                "{} - expected invalid pubkey for signer {}",
                                test_case.comment,
                                signer_index,
                            );
                        } else {
                            result.unwrap_or_else(|_| {
                                panic!(
                                    "{} - unexpected pubkey parsing error for signer {}",
                                    test_case.comment, signer_index
                                )
                            });
                        }
                    }
                }
                other => panic!(
                    "{} - unsupported verify error contribution: {:?}",
                    test_case.comment, other
                ),
            }
        }
    }

    #[test]
    fn test_sign_with_tweaks() {
        const TWEAK_VECTORS: &[u8] = include_bytes!("test_vectors/tweak_vectors.json");

        #[derive(serde::Deserialize)]
        struct ValidTweakTestCase {
            key_indices: Vec<usize>,
            nonce_indices: Vec<usize>,
            tweak_indices: Vec<usize>,
            is_xonly: Vec<bool>,
            signer_index: usize,
            #[serde(rename = "expected")]
            partial_signature: MaybeScalar,
        }

        #[derive(serde::Deserialize)]
        struct TweakVectors {
            #[serde(rename = "sk")]
            seckey: Scalar,
            pubkeys: Vec<Point>,

            #[serde(rename = "secnonce")]
            secret_nonces: SecNonce,

            #[serde(rename = "pnonces")]
            public_nonces: Vec<PubNonce>,

            #[serde(rename = "aggnonce")]
            aggregated_nonce: AggNonce,

            #[serde(deserialize_with = "testhex::deserialize_vec")]
            tweaks: Vec<Vec<u8>>,

            #[serde(rename = "msg", deserialize_with = "testhex::deserialize")]
            message: Vec<u8>,

            valid_test_cases: Vec<ValidTweakTestCase>,
        }

        let vectors: TweakVectors =
            serde_json::from_slice(TWEAK_VECTORS).expect("failed to parse test_vectors/tweak.json");

        for test_case in vectors.valid_test_cases {
            let pubkeys: Vec<Point> = test_case
                .key_indices
                .into_iter()
                .map(|i| vectors.pubkeys[i])
                .collect();

            let signer_pubkey = pubkeys[test_case.signer_index];

            let mut key_agg_ctx =
                KeyAggContext::new(pubkeys).expect("error creating key aggregation context");

            key_agg_ctx = test_case
                .tweak_indices
                .into_iter()
                .map(|i| {
                    Scalar::try_from(vectors.tweaks[i].as_slice())
                        .expect("failed to parse valid tweak value")
                })
                .zip(test_case.is_xonly)
                .fold(key_agg_ctx, |ctx, (tweak, is_xonly)| {
                    ctx.with_tweak(tweak, is_xonly).unwrap_or_else(|_| {
                        panic!("failed to tweak key agg context with {:x}", tweak)
                    })
                });

            let partial_signature: PartialSignature = sign_partial(
                &key_agg_ctx,
                vectors.seckey,
                vectors.secret_nonces.clone(),
                &vectors.aggregated_nonce,
                &vectors.message,
            )
            .expect("error during partial signing");

            assert_eq!(
                partial_signature, test_case.partial_signature,
                "incorrect tweaked partial signature",
            );

            let public_nonces: Vec<&PubNonce> = test_case
                .nonce_indices
                .into_iter()
                .map(|i| &vectors.public_nonces[i])
                .collect();

            verify_partial(
                &key_agg_ctx,
                partial_signature,
                &vectors.aggregated_nonce,
                signer_pubkey,
                public_nonces[test_case.signer_index],
                &vectors.message,
            )
            .expect("failed to verify valid partial signature");
        }
    }
}