-
Notifications
You must be signed in to change notification settings - Fork 271
/
key.rs
1436 lines (1283 loc) · 47.5 KB
/
key.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
// Bitcoin secp256k1 bindings
// Written in 2014 by
// Dawid Ciężarkiewicz
// Andrew Poelstra
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Public and secret keys
#[cfg(any(test, feature = "rand"))] use rand::Rng;
use core::{fmt, ptr, str};
use super::{from_hex, Secp256k1};
use super::Error::{self, InvalidPublicKey, InvalidPublicKeySum, InvalidSecretKey};
use ::{Signing};
use Verification;
use constants;
use ffi::{self, CPtr};
/// Secret 256-bit key used as `x` in an ECDSA signature
pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
impl_array_newtype!(SecretKey, u8, constants::SECRET_KEY_SIZE);
impl_display_secret!(SecretKey);
impl str::FromStr for SecretKey {
type Err = Error;
fn from_str(s: &str) -> Result<SecretKey, Error> {
let mut res = [0u8; constants::SECRET_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SECRET_KEY_SIZE) => SecretKey::from_slice(&res),
_ => Err(Error::InvalidSecretKey)
}
}
}
/// The number 1 encoded as a secret key
pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1]);
/// A Secp256k1 public key, used for verification of signatures
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[repr(transparent)]
pub struct PublicKey(ffi::PublicKey);
impl fmt::LowerHex for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ser = self.serialize();
for ch in &ser[..] {
write!(f, "{:02x}", *ch)?;
}
Ok(())
}
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl str::FromStr for PublicKey {
type Err = Error;
fn from_str(s: &str) -> Result<PublicKey, Error> {
let mut res = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::PUBLIC_KEY_SIZE) => {
PublicKey::from_slice(
&res[0..constants::PUBLIC_KEY_SIZE]
)
}
Ok(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE) => {
PublicKey::from_slice(&res)
}
_ => Err(Error::InvalidPublicKey)
}
}
}
#[cfg(any(test, feature = "rand"))]
fn random_32_bytes<R: Rng + ?Sized>(rng: &mut R) -> [u8; 32] {
let mut ret = [0u8; 32];
rng.fill_bytes(&mut ret);
ret
}
impl SecretKey {
/// Creates a new random secret key. Requires compilation with the "rand" feature.
#[inline]
#[cfg(any(test, feature = "rand"))]
pub fn new<R: Rng + ?Sized>(rng: &mut R) -> SecretKey {
let mut data = random_32_bytes(rng);
unsafe {
while ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
data = random_32_bytes(rng);
}
}
SecretKey(data)
}
/// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key
#[inline]
pub fn from_slice(data: &[u8])-> Result<SecretKey, Error> {
match data.len() {
constants::SECRET_KEY_SIZE => {
let mut ret = [0u8; constants::SECRET_KEY_SIZE];
unsafe {
if ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
return Err(InvalidSecretKey);
}
}
ret[..].copy_from_slice(data);
Ok(SecretKey(ret))
}
_ => Err(InvalidSecretKey)
}
}
/// Creates a new secret key using data from BIP-340 [`KeyPair`]
#[inline]
pub fn from_keypair(keypair: &KeyPair) -> Self {
let mut sk = [0u8; constants::SECRET_KEY_SIZE];
unsafe {
let ret = ffi::secp256k1_keypair_sec(
ffi::secp256k1_context_no_precomp,
sk.as_mut_c_ptr(),
keypair.as_ptr()
);
debug_assert_eq!(ret, 1);
}
SecretKey(sk)
}
/// Serialize the secret key as byte value
#[inline]
pub fn serialize_secret(&self) -> [u8; constants::SECRET_KEY_SIZE] {
self.0
}
#[inline]
/// Negates one secret key.
pub fn negate_assign(
&mut self
) {
unsafe {
let res = ffi::secp256k1_ec_seckey_negate(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr()
);
debug_assert_eq!(res, 1);
}
}
#[inline]
/// Adds one secret key to another, modulo the curve order. WIll
/// return an error if the resulting key would be invalid or if
/// the tweak was not a 32-byte length slice.
pub fn add_assign(
&mut self,
other: &[u8],
) -> Result<(), Error> {
if other.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
if ffi::secp256k1_ec_seckey_tweak_add(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
other.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(())
}
}
}
#[inline]
/// Multiplies one secret key by another, modulo the curve order. Will
/// return an error if the resulting key would be invalid or if
/// the tweak was not a 32-byte length slice.
pub fn mul_assign(
&mut self,
other: &[u8],
) -> Result<(), Error> {
if other.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
if ffi::secp256k1_ec_seckey_tweak_mul(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
other.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(())
}
}
}
}
#[cfg(feature = "serde")]
impl ::serde::Serialize for SecretKey {
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
let mut buf = [0u8; 64];
s.serialize_str(::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
} else {
s.serialize_bytes(&self[..])
}
}
}
#[cfg(feature = "serde")]
impl<'de> ::serde::Deserialize<'de> for SecretKey {
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"a hex string representing 32 byte SecretKey"
))
} else {
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
"raw 32 bytes SecretKey",
SecretKey::from_slice
))
}
}
}
impl PublicKey {
/// Obtains a raw const pointer suitable for use with FFI functions
#[inline]
pub fn as_ptr(&self) -> *const ffi::PublicKey {
&self.0
}
/// Obtains a raw mutable pointer suitable for use with FFI functions
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey {
&mut self.0
}
/// Creates a new public key from a secret key.
#[inline]
pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>,
sk: &SecretKey)
-> PublicKey {
unsafe {
let mut pk = ffi::PublicKey::new();
// We can assume the return value because it's not possible to construct
// an invalid `SecretKey` without transmute trickery or something
let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_c_ptr());
debug_assert_eq!(res, 1);
PublicKey(pk)
}
}
/// Creates a public key directly from a slice
#[inline]
pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
if data.is_empty() {return Err(Error::InvalidPublicKey);}
unsafe {
let mut pk = ffi::PublicKey::new();
if ffi::secp256k1_ec_pubkey_parse(
ffi::secp256k1_context_no_precomp,
&mut pk,
data.as_c_ptr(),
data.len() as usize,
) == 1
{
Ok(PublicKey(pk))
} else {
Err(InvalidPublicKey)
}
}
}
/// Creates a new compressed public key using data from BIP-340 [`KeyPair`].
#[inline]
pub fn from_keypair(keypair: &KeyPair) -> Self {
unsafe {
let mut pk = ffi::PublicKey::new();
let ret = ffi::secp256k1_keypair_pub(
ffi::secp256k1_context_no_precomp,
&mut pk,
keypair.as_ptr()
);
debug_assert_eq!(ret, 1);
PublicKey(pk)
}
}
#[inline]
/// Serialize the key as a byte-encoded pair of values. In compressed form
/// the y-coordinate is represented by only a single bit, as x determines
/// it up to one bit.
pub fn serialize(&self) -> [u8; constants::PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::PUBLIC_KEY_SIZE];
unsafe {
let mut ret_len = constants::PUBLIC_KEY_SIZE as usize;
let err = ffi::secp256k1_ec_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
&mut ret_len,
self.as_c_ptr(),
ffi::SECP256K1_SER_COMPRESSED,
);
debug_assert_eq!(err, 1);
debug_assert_eq!(ret_len, ret.len());
}
ret
}
/// Serialize the key as a byte-encoded pair of values, in uncompressed form
pub fn serialize_uncompressed(&self) -> [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
unsafe {
let mut ret_len = constants::UNCOMPRESSED_PUBLIC_KEY_SIZE as usize;
let err = ffi::secp256k1_ec_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
&mut ret_len,
self.as_c_ptr(),
ffi::SECP256K1_SER_UNCOMPRESSED,
);
debug_assert_eq!(err, 1);
debug_assert_eq!(ret_len, ret.len());
}
ret
}
#[inline]
/// Negates the pk to the pk `self` in place
/// Will return an error if the pk would be invalid.
pub fn negate_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>
) {
unsafe {
let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx, &mut self.0);
debug_assert_eq!(res, 1);
}
}
#[inline]
/// Adds the pk corresponding to `other` to the pk `self` in place
/// Will return an error if the resulting key would be invalid or
/// if the tweak was not a 32-byte length slice.
pub fn add_exp_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
other: &[u8]
) -> Result<(), Error> {
if other.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx, &mut self.0, other.as_c_ptr()) == 1 {
Ok(())
} else {
Err(Error::InvalidTweak)
}
}
}
#[inline]
/// Muliplies the pk `self` in place by the scalar `other`
/// Will return an error if the resulting key would be invalid or
/// if the tweak was not a 32-byte length slice.
pub fn mul_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
other: &[u8],
) -> Result<(), Error> {
if other.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx, &mut self.0, other.as_c_ptr()) == 1 {
Ok(())
} else {
Err(Error::InvalidTweak)
}
}
}
/// Adds a second key to this one, returning the sum. Returns an error if
/// the result would be the point at infinity, i.e. we are adding this point
/// to its own negation
pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
PublicKey::combine_keys(&[self, other])
}
/// Adds the keys in the provided slice together, returning the sum. Returns
/// an error if the result would be the point at infinity, i.e. we are adding
/// a point to its own negation, if the provided slice has no element in it,
/// or if the number of element it contains is greater than i32::MAX.
pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
use core::mem::transmute;
use core::i32::MAX;
if keys.is_empty() || keys.len() > MAX as usize {
return Err(InvalidPublicKeySum);
}
unsafe {
let mut ret = ffi::PublicKey::new();
let ptrs : &[*const ffi::PublicKey] =
transmute::<&[&PublicKey], &[*const ffi::PublicKey]>(keys);
if ffi::secp256k1_ec_pubkey_combine(
ffi::secp256k1_context_no_precomp,
&mut ret,
ptrs.as_c_ptr(),
keys.len() as i32
) == 1
{
Ok(PublicKey(ret))
} else {
Err(InvalidPublicKeySum)
}
}
}
}
impl CPtr for PublicKey {
type Target = ffi::PublicKey;
fn as_c_ptr(&self) -> *const Self::Target {
self.as_ptr()
}
fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
self.as_mut_ptr()
}
}
/// Creates a new public key from a FFI public key
impl From<ffi::PublicKey> for PublicKey {
#[inline]
fn from(pk: ffi::PublicKey) -> PublicKey {
PublicKey(pk)
}
}
#[cfg(feature = "serde")]
impl ::serde::Serialize for PublicKey {
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.collect_str(self)
} else {
s.serialize_bytes(&self.serialize())
}
}
}
#[cfg(feature = "serde")]
impl<'de> ::serde::Deserialize<'de> for PublicKey {
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"an ASCII hex string representing a public key"
))
} else {
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
"a bytestring representing a public key",
PublicKey::from_slice
))
}
}
}
impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &PublicKey) -> Option<::core::cmp::Ordering> {
self.serialize().partial_cmp(&other.serialize())
}
}
impl Ord for PublicKey {
fn cmp(&self, other: &PublicKey) -> ::core::cmp::Ordering {
self.serialize().cmp(&other.serialize())
}
}
/// Opaque data structure that holds a keypair consisting of a secret and a public key.
#[derive(Clone)]
pub struct KeyPair(ffi::KeyPair);
impl_display_secret!(KeyPair);
impl KeyPair {
/// Obtains a raw const pointer suitable for use with FFI functions
#[inline]
pub fn as_ptr(&self) -> *const ffi::KeyPair {
&self.0
}
/// Obtains a raw mutable pointer suitable for use with FFI functions
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::KeyPair {
&mut self.0
}
/// Creates a Schnorr KeyPair directly from generic Secp256k1 secret key
///
/// # Panic
///
/// Panics if internal representation of the provided [`SecretKey`] does not hold correct secret
/// key value obtained from Secp256k1 library previously, specifically when secret key value is
/// out-of-range (0 or in excess of the group order).
#[inline]
pub fn from_secret_key<C: Signing>(
secp: &Secp256k1<C>,
sk: SecretKey,
) -> KeyPair {
unsafe {
let mut kp = ffi::KeyPair::new();
if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, sk.as_c_ptr()) == 1 {
KeyPair(kp)
} else {
panic!("the provided secret key is invalid: it is corrupted or was not produced by Secp256k1 library")
}
}
}
/// Creates a Schnorr KeyPair directly from a secret key slice.
///
/// # Errors
///
/// [`Error::InvalidSecretKey`] if the provided data has an incorrect length, exceeds Secp256k1
/// field `p` value or the corresponding public key is not even.
#[inline]
pub fn from_seckey_slice<C: Signing>(
secp: &Secp256k1<C>,
data: &[u8],
) -> Result<KeyPair, Error> {
if data.is_empty() || data.len() != constants::SECRET_KEY_SIZE {
return Err(Error::InvalidSecretKey);
}
unsafe {
let mut kp = ffi::KeyPair::new();
if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, data.as_c_ptr()) == 1 {
Ok(KeyPair(kp))
} else {
Err(Error::InvalidSecretKey)
}
}
}
/// Creates a Schnorr KeyPair directly from a secret key string
///
/// # Errors
///
/// [`Error::InvalidSecretKey`] if corresponding public key for the provided secret key is not even.
#[inline]
pub fn from_seckey_str<C: Signing>(secp: &Secp256k1<C>, s: &str) -> Result<KeyPair, Error> {
let mut res = [0u8; constants::SECRET_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SECRET_KEY_SIZE) => {
KeyPair::from_seckey_slice(secp, &res[0..constants::SECRET_KEY_SIZE])
}
_ => Err(Error::InvalidPublicKey),
}
}
/// Creates a new random secret key. Requires compilation with the "rand" feature.
#[inline]
#[cfg(any(test, feature = "rand"))]
pub fn new<R: ::rand::Rng + ?Sized, C: Signing>(secp: &Secp256k1<C>, rng: &mut R) -> KeyPair {
let mut random_32_bytes = || {
let mut ret = [0u8; 32];
rng.fill_bytes(&mut ret);
ret
};
let mut data = random_32_bytes();
unsafe {
let mut keypair = ffi::KeyPair::new();
while ffi::secp256k1_keypair_create(secp.ctx, &mut keypair, data.as_c_ptr()) == 0 {
data = random_32_bytes();
}
KeyPair(keypair)
}
}
/// Serialize the key pair as a secret key byte value
#[inline]
pub fn serialize_secret(&self) -> [u8; constants::SECRET_KEY_SIZE] {
*SecretKey::from_keypair(self).as_ref()
}
/// Tweak a keypair by adding the given tweak to the secret key and updating the public key
/// accordingly.
///
/// Will return an error if the resulting key would be invalid or if the tweak was not a 32-byte
/// length slice.
///
/// NB: Will not error if the tweaked public key has an odd value and can't be used for
/// BIP 340-342 purposes.
// TODO: Add checked implementation
#[inline]
pub fn tweak_add_assign<C: Verification>(
&mut self,
secp: &Secp256k1<C>,
tweak: &[u8],
) -> Result<(), Error> {
if tweak.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
let err = ffi::secp256k1_keypair_xonly_tweak_add(
secp.ctx,
&mut self.0,
tweak.as_c_ptr(),
);
if err == 1 {
Ok(())
} else {
Err(Error::InvalidTweak)
}
}
}
}
impl From<KeyPair> for SecretKey {
#[inline]
fn from(pair: KeyPair) -> Self {
SecretKey::from_keypair(&pair)
}
}
impl<'a> From<&'a KeyPair> for SecretKey {
#[inline]
fn from(pair: &'a KeyPair) -> Self {
SecretKey::from_keypair(pair)
}
}
impl From<KeyPair> for PublicKey {
#[inline]
fn from(pair: KeyPair) -> Self {
PublicKey::from_keypair(&pair)
}
}
impl<'a> From<&'a KeyPair> for PublicKey {
#[inline]
fn from(pair: &'a KeyPair) -> Self {
PublicKey::from_keypair(pair)
}
}
/// A x-only public key, used for verification of Schnorr signatures and serialized according to BIP-340.
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
pub struct XOnlyPublicKey(ffi::XOnlyPublicKey);
impl fmt::LowerHex for XOnlyPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ser = self.serialize();
for ch in &ser[..] {
write!(f, "{:02x}", *ch)?;
}
Ok(())
}
}
impl fmt::Display for XOnlyPublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl str::FromStr for XOnlyPublicKey {
type Err = Error;
fn from_str(s: &str) -> Result<XOnlyPublicKey, Error> {
let mut res = [0u8; constants::SCHNORRSIG_PUBLIC_KEY_SIZE];
match from_hex(s, &mut res) {
Ok(constants::SCHNORRSIG_PUBLIC_KEY_SIZE) => {
XOnlyPublicKey::from_slice(&res[0..constants::SCHNORRSIG_PUBLIC_KEY_SIZE])
}
_ => Err(Error::InvalidPublicKey),
}
}
}
impl XOnlyPublicKey {
/// Obtains a raw const pointer suitable for use with FFI functions
#[inline]
pub fn as_ptr(&self) -> *const ffi::XOnlyPublicKey {
&self.0
}
/// Obtains a raw mutable pointer suitable for use with FFI functions
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::XOnlyPublicKey {
&mut self.0
}
/// Creates a new Schnorr public key from a Schnorr key pair.
#[inline]
pub fn from_keypair<C: Signing>(secp: &Secp256k1<C>, keypair: &KeyPair) -> XOnlyPublicKey {
let mut pk_parity = 0;
unsafe {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let ret = ffi::secp256k1_keypair_xonly_pub(
secp.ctx,
&mut xonly_pk,
&mut pk_parity,
keypair.as_ptr(),
);
debug_assert_eq!(ret, 1);
XOnlyPublicKey(xonly_pk)
}
}
/// Creates a Schnorr public key directly from a slice
///
/// # Errors
///
/// Returns [`Error::InvalidPublicKey`] if the length of the data slice is not 32 bytes or the
/// slice does not represent a valid Secp256k1 point x coordinate
#[inline]
pub fn from_slice(data: &[u8]) -> Result<XOnlyPublicKey, Error> {
if data.is_empty() || data.len() != constants::SCHNORRSIG_PUBLIC_KEY_SIZE {
return Err(Error::InvalidPublicKey);
}
unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
if ffi::secp256k1_xonly_pubkey_parse(
ffi::secp256k1_context_no_precomp,
&mut pk,
data.as_c_ptr(),
) == 1
{
Ok(XOnlyPublicKey(pk))
} else {
Err(Error::InvalidPublicKey)
}
}
}
#[inline]
/// Serialize the key as a byte-encoded x coordinate value (32 bytes).
pub fn serialize(&self) -> [u8; constants::SCHNORRSIG_PUBLIC_KEY_SIZE] {
let mut ret = [0u8; constants::SCHNORRSIG_PUBLIC_KEY_SIZE];
unsafe {
let err = ffi::secp256k1_xonly_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
self.as_c_ptr(),
);
debug_assert_eq!(err, 1);
}
ret
}
/// Tweak an x-only PublicKey by adding the generator multiplied with the given tweak to it.
///
/// Returns a boolean representing the parity of the tweaked key, which can be provided to
/// `tweak_add_check` which can be used to verify a tweak more efficiently than regenerating
/// it and checking equality. Will return an error if the resulting key would be invalid or
/// if the tweak was not a 32-byte length slice.
pub fn tweak_add_assign<V: Verification>(
&mut self,
secp: &Secp256k1<V>,
tweak: &[u8],
) -> Result<bool, Error> {
if tweak.len() != 32 {
return Err(Error::InvalidTweak);
}
unsafe {
let mut pubkey = ffi::PublicKey::new();
let mut err = ffi::secp256k1_xonly_pubkey_tweak_add(
secp.ctx,
&mut pubkey,
self.as_c_ptr(),
tweak.as_c_ptr(),
);
if err != 1 {
return Err(Error::InvalidTweak);
}
let mut parity: ::secp256k1_sys::types::c_int = 0;
err = ffi::secp256k1_xonly_pubkey_from_pubkey(
secp.ctx,
&mut self.0,
&mut parity,
&pubkey,
);
if err == 0 {
Err(Error::InvalidPublicKey)
} else {
Ok(parity != 0)
}
}
}
/// Verify that a tweak produced by `tweak_add_assign` was computed correctly
///
/// Should be called on the original untweaked key. Takes the tweaked key and
/// output parity from `tweak_add_assign` as input.
///
/// Currently this is not much more efficient than just recomputing the tweak
/// and checking equality. However, in future this API will support batch
/// verification, which is significantly faster, so it is wise to design
/// protocols with this in mind.
pub fn tweak_add_check<V: Verification>(
&self,
secp: &Secp256k1<V>,
tweaked_key: &Self,
tweaked_parity: bool,
tweak: [u8; 32],
) -> bool {
let tweaked_ser = tweaked_key.serialize();
unsafe {
let err = ffi::secp256k1_xonly_pubkey_tweak_add_check(
secp.ctx,
tweaked_ser.as_c_ptr(),
if tweaked_parity { 1 } else { 0 },
&self.0,
tweak.as_c_ptr(),
);
err == 1
}
}
}
impl CPtr for XOnlyPublicKey {
type Target = ffi::XOnlyPublicKey;
fn as_c_ptr(&self) -> *const Self::Target {
self.as_ptr()
}
fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
self.as_mut_ptr()
}
}
/// Creates a new Schnorr public key from a FFI x-only public key
impl From<ffi::XOnlyPublicKey> for XOnlyPublicKey {
#[inline]
fn from(pk: ffi::XOnlyPublicKey) -> XOnlyPublicKey {
XOnlyPublicKey(pk)
}
}
impl From<::key::PublicKey> for XOnlyPublicKey {
fn from(src: ::key::PublicKey) -> XOnlyPublicKey {
unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
assert_eq!(
1,
ffi::secp256k1_xonly_pubkey_from_pubkey(
ffi::secp256k1_context_no_precomp,
&mut pk,
ptr::null_mut(),
src.as_c_ptr(),
)
);
XOnlyPublicKey(pk)
}
}
}
#[cfg(feature = "serde")]
impl ::serde::Serialize for XOnlyPublicKey {
fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if s.is_human_readable() {
s.collect_str(self)
} else {
s.serialize_bytes(&self.serialize())
}
}
}
#[cfg(feature = "serde")]
impl<'de> ::serde::Deserialize<'de> for XOnlyPublicKey {
fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
if d.is_human_readable() {
d.deserialize_str(super::serde_util::FromStrVisitor::new(
"a hex string representing 32 byte schnorr public key"
))
} else {
d.deserialize_bytes(super::serde_util::BytesVisitor::new(
"raw 32 bytes schnorr public key",
XOnlyPublicKey::from_slice
))
}
}
}
#[cfg(test)]
mod test {
use Secp256k1;
use {from_hex, to_hex};
use super::super::Error::{InvalidPublicKey, InvalidSecretKey};
use super::{PublicKey, SecretKey};
use super::super::constants;
use rand::{Error, ErrorKind, RngCore, thread_rng};
use rand_core::impls;
use std::iter;
use std::str::FromStr;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test as test;
macro_rules! hex {
($hex:expr) => ({
let mut result = vec![0; $hex.len() / 2];
from_hex($hex, &mut result).expect("valid hex string");
result
});
}
#[test]
fn skey_from_slice() {
let sk = SecretKey::from_slice(&[1; 31]);
assert_eq!(sk, Err(InvalidSecretKey));
let sk = SecretKey::from_slice(&[1; 32]);
assert!(sk.is_ok());
}
#[test]
fn pubkey_from_slice() {
assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
assert_eq!(PublicKey::from_slice(&[1, 2, 3]), Err(InvalidPublicKey));
let uncompressed = PublicKey::from_slice(&[4, 54, 57, 149, 239, 162, 148, 175, 246, 254, 239, 75, 154, 152, 10, 82, 234, 224, 85, 220, 40, 100, 57, 121, 30, 162, 94, 156, 135, 67, 74, 49, 179, 57, 236, 53, 162, 124, 149, 144, 168, 77, 74, 30, 72, 211, 229, 110, 111, 55, 96, 193, 86, 227, 183, 152, 195, 155, 51, 247, 123, 113, 60, 228, 188]);
assert!(uncompressed.is_ok());
let compressed = PublicKey::from_slice(&[3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41, 111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78]);
assert!(compressed.is_ok());
}
#[test]
fn keypair_slice_round_trip() {
let s = Secp256k1::new();
let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
assert_eq!(SecretKey::from_slice(&sk1[..]), Ok(sk1));
assert_eq!(PublicKey::from_slice(&pk1.serialize()[..]), Ok(pk1));
assert_eq!(PublicKey::from_slice(&pk1.serialize_uncompressed()[..]), Ok(pk1));
}
#[test]
fn invalid_secret_key() {
// Zero
assert_eq!(SecretKey::from_slice(&[0; 32]), Err(InvalidSecretKey));
assert_eq!(
SecretKey::from_str(&format!("0000000000000000000000000000000000000000000000000000000000000000")),
Err(InvalidSecretKey)
);
// -1
assert_eq!(SecretKey::from_slice(&[0xff; 32]), Err(InvalidSecretKey));
// Top of range
assert!(SecretKey::from_slice(&[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
]).is_ok());
// One past top of range
assert!(SecretKey::from_slice(&[
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41,
]).is_err());