forked from rust-bitcoin/rust-secp256k1
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkey.rs
2454 lines (2174 loc) · 83.1 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
// SPDX-License-Identifier: CC0-1.0
//! Public and secret keys.
//!
use core::ops::{self, BitXor};
use core::{fmt, ptr, str};
#[cfg(feature = "serde")]
use serde::ser::SerializeTuple;
use crate::ellswift::ElligatorSwift;
use crate::ffi::types::c_uint;
use crate::ffi::{self, CPtr};
use crate::Error::{self, InvalidPublicKey, InvalidPublicKeySum, InvalidSecretKey};
#[cfg(feature = "hashes")]
#[allow(deprecated)]
use crate::ThirtyTwoByteHash;
#[cfg(feature = "global-context")]
use crate::SECP256K1;
use crate::{
constants, ecdsa, from_hex, schnorr, Message, Scalar, Secp256k1, Signing, Verification,
};
/// Secret key - a 256-bit key used to create ECDSA and Taproot signatures.
///
/// This value should be generated using a [cryptographically secure pseudorandom number generator].
///
/// # Side channel attacks
///
/// We have attempted to reduce the side channel attack surface by implementing a constant time `eq`
/// method. For similar reasons we explicitly do not implement `PartialOrd`, `Ord`, or `Hash` on
/// `SecretKey`. If you really want to order secrets keys then you can use `AsRef` to get at the
/// underlying bytes and compare them - however this is almost certainly a bad idea.
///
/// # Serde support
///
/// Implements de/serialization with the `serde` feature enabled. We treat the byte value as a tuple
/// of 32 `u8`s for non-human-readable formats. This representation is optimal for for some formats
/// (e.g. [`bincode`]) however other formats may be less optimal (e.g. [`cbor`]).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, SecretKey};
///
/// let secp = Secp256k1::new();
/// let secret_key = SecretKey::new(&mut rand::thread_rng());
/// # }
/// ```
/// [`bincode`]: https://docs.rs/bincode
/// [`cbor`]: https://docs.rs/cbor
/// [cryptographically secure pseudorandom number generator]: https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
#[derive(Copy, Clone)]
pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
impl_display_secret!(SecretKey);
impl_non_secure_erase!(SecretKey, 0, [1u8; constants::SECRET_KEY_SIZE]);
impl PartialEq for SecretKey {
/// This implementation is designed to be constant time to help prevent side channel attacks.
#[inline]
fn eq(&self, other: &Self) -> bool {
let accum = self.0.iter().zip(&other.0).fold(0, |accum, (a, b)| accum | a ^ b);
unsafe { core::ptr::read_volatile(&accum) == 0 }
}
}
impl Eq for SecretKey {}
impl AsRef<[u8; constants::SECRET_KEY_SIZE]> for SecretKey {
/// Gets a reference to the underlying array.
///
/// # Side channel attacks
///
/// Using ordering functions (`PartialOrd`/`Ord`) on a reference to secret keys leaks data
/// because the implementations are not constant time. Doing so will make your code vulnerable
/// to side channel attacks. [`SecretKey::eq`] is implemented using a constant time algorithm,
/// please consider using it to do comparisons of secret keys.
#[inline]
fn as_ref(&self) -> &[u8; constants::SECRET_KEY_SIZE] {
let SecretKey(dat) = self;
dat
}
}
impl<I> ops::Index<I> for SecretKey
where
[u8]: ops::Index<I>,
{
type Output = <[u8] as ops::Index<I>>::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output { &self.0[index] }
}
impl ffi::CPtr for SecretKey {
type Target = u8;
fn as_c_ptr(&self) -> *const Self::Target {
let SecretKey(dat) = self;
dat.as_ptr()
}
fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
let &mut SecretKey(ref mut dat) = self;
dat.as_mut_ptr()
}
}
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),
}
}
}
/// Public key - used to verify ECDSA signatures and to do Taproot tweaks.
///
/// # Serde support
///
/// Implements de/serialization with the `serde` feature enabled. We treat the byte value as a tuple
/// of 33 `u8`s for non-human-readable formats. This representation is optimal for for some formats
/// (e.g. [`bincode`]) however other formats may be less optimal (e.g. [`cbor`]).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use secp256k1::{SecretKey, Secp256k1, PublicKey};
///
/// let secp = Secp256k1::new();
/// let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("32 bytes, within curve order");
/// let public_key = PublicKey::from_secret_key(&secp, &secret_key);
/// # }
/// ```
/// [`bincode`]: https://docs.rs/bincode
/// [`cbor`]: https://docs.rs/cbor
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct PublicKey(ffi::PublicKey);
impl_fast_comparisons!(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),
}
}
}
impl SecretKey {
/// Generates a new random secret key.
///
/// # Examples
///
/// ```
/// # #[cfg(all(feature = "std", feature = "rand-std"))] {
/// use secp256k1::{rand, SecretKey};
/// let secret_key = SecretKey::new(&mut rand::thread_rng());
/// # }
/// ```
#[inline]
#[cfg(feature = "rand")]
pub fn new<R: rand::Rng + ?Sized>(rng: &mut R) -> SecretKey {
let mut data = crate::random_32_bytes(rng);
unsafe {
while ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
data = crate::random_32_bytes(rng);
}
}
SecretKey(data)
}
/// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key.
///
/// # Examples
///
/// ```
/// use secp256k1::SecretKey;
/// let sk = SecretKey::from_slice(&[0xcd; 32]).expect("32 bytes, within curve order");
/// ```
#[inline]
pub fn from_slice(data: &[u8]) -> Result<SecretKey, Error> {
match <[u8; constants::SECRET_KEY_SIZE]>::try_from(data) {
Ok(data) => {
unsafe {
if ffi::secp256k1_ec_seckey_verify(
ffi::secp256k1_context_no_precomp,
data.as_c_ptr(),
) == 0
{
return Err(InvalidSecretKey);
}
}
Ok(SecretKey(data))
}
Err(_) => Err(InvalidSecretKey),
}
}
/// Creates a new secret key using data from BIP-340 [`Keypair`].
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, SecretKey, Keypair};
///
/// let secp = Secp256k1::new();
/// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
/// let secret_key = SecretKey::from_keypair(&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_c_ptr(),
);
debug_assert_eq!(ret, 1);
}
SecretKey(sk)
}
/// Returns the secret key as a byte value.
#[inline]
pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] { self.0 }
/// Negates the secret key.
#[inline]
#[must_use = "you forgot to use the negated secret key"]
pub fn negate(mut self) -> SecretKey {
unsafe {
let res = ffi::secp256k1_ec_seckey_negate(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
);
debug_assert_eq!(res, 1);
}
self
}
/// Tweaks a [`SecretKey`] by adding `tweak` modulo the curve order.
///
/// # Errors
///
/// Returns an error if the resulting key would be invalid.
#[inline]
pub fn add_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
unsafe {
if ffi::secp256k1_ec_seckey_tweak_add(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
tweak.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(self)
}
}
}
/// Tweaks a [`SecretKey`] by multiplying by `tweak` modulo the curve order.
///
/// # Errors
///
/// Returns an error if the resulting key would be invalid.
#[inline]
pub fn mul_tweak(mut self, tweak: &Scalar) -> Result<SecretKey, Error> {
unsafe {
if ffi::secp256k1_ec_seckey_tweak_mul(
ffi::secp256k1_context_no_precomp,
self.as_mut_c_ptr(),
tweak.as_c_ptr(),
) != 1
{
Err(Error::InvalidTweak)
} else {
Ok(self)
}
}
}
/// Constructs an ECDSA signature for `msg` using the global [`SECP256K1`] context.
#[inline]
#[cfg(feature = "global-context")]
pub fn sign_ecdsa(&self, msg: Message) -> ecdsa::Signature { SECP256K1.sign_ecdsa(&msg, self) }
/// Returns the [`Keypair`] for this [`SecretKey`].
///
/// This is equivalent to using [`Keypair::from_secret_key`].
#[inline]
pub fn keypair<C: Signing>(&self, secp: &Secp256k1<C>) -> Keypair {
Keypair::from_secret_key(secp, self)
}
/// Returns the [`PublicKey`] for this [`SecretKey`].
///
/// This is equivalent to using [`PublicKey::from_secret_key`].
#[inline]
pub fn public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
PublicKey::from_secret_key(secp, self)
}
/// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`SecretKey`].
///
/// This is equivalent to `XOnlyPublicKey::from_keypair(self.keypair(secp))`.
#[inline]
pub fn x_only_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> (XOnlyPublicKey, Parity) {
let kp = self.keypair(secp);
XOnlyPublicKey::from_keypair(&kp)
}
}
#[cfg(feature = "hashes")]
#[allow(deprecated)]
impl<T: ThirtyTwoByteHash> From<T> for SecretKey {
/// Converts a 32-byte hash directly to a secret key without error paths.
fn from(t: T) -> SecretKey {
SecretKey::from_slice(&t.into_32()).expect("failed to create secret key")
}
}
#[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; constants::SECRET_KEY_SIZE * 2];
s.serialize_str(crate::to_hex(&self.0, &mut buf).expect("fixed-size hex serialization"))
} else {
let mut tuple = s.serialize_tuple(constants::SECRET_KEY_SIZE)?;
for byte in self.0.iter() {
tuple.serialize_element(byte)?;
}
tuple.end()
}
}
}
#[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 {
let visitor = super::serde_util::Tuple32Visitor::new(
"raw 32 bytes SecretKey",
SecretKey::from_slice,
);
d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor)
}
}
}
impl PublicKey {
/// Obtains a raw const pointer suitable for use with FFI functions.
#[inline]
#[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
pub fn as_ptr(&self) -> *const ffi::PublicKey { self.as_c_ptr() }
/// Obtains a raw mutable pointer suitable for use with FFI functions.
#[inline]
#[deprecated(
since = "0.25.0",
note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
)]
pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey { self.as_mut_c_ptr() }
/// Creates a new public key from a [`SecretKey`].
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, SecretKey, PublicKey};
///
/// let secp = Secp256k1::new();
/// let secret_key = SecretKey::new(&mut rand::thread_rng());
/// let public_key = PublicKey::from_secret_key(&secp, &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.as_ptr(), &mut pk, sk.as_c_ptr());
debug_assert_eq!(res, 1);
PublicKey(pk)
}
}
/// Creates a new public key from an [`ElligatorSwift`].
#[inline]
pub fn from_ellswift(ellswift: ElligatorSwift) -> PublicKey { ElligatorSwift::decode(ellswift) }
/// Creates a new public key from a [`SecretKey`] and the global [`SECP256K1`] context.
#[inline]
#[cfg(feature = "global-context")]
pub fn from_secret_key_global(sk: &SecretKey) -> PublicKey {
PublicKey::from_secret_key(SECP256K1, sk)
}
/// 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(),
) == 1
{
Ok(PublicKey(pk))
} else {
Err(InvalidPublicKey)
}
}
}
/// Creates a new compressed public key using data from BIP-340 [`Keypair`].
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, PublicKey, Keypair};
///
/// let secp = Secp256k1::new();
/// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
/// let public_key = PublicKey::from_keypair(&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_c_ptr(),
);
debug_assert_eq!(ret, 1);
PublicKey(pk)
}
}
/// Creates a [`PublicKey`] using the key material from `pk` combined with the `parity`.
pub fn from_x_only_public_key(pk: XOnlyPublicKey, parity: Parity) -> PublicKey {
let mut buf = [0u8; 33];
// First byte of a compressed key should be `0x02 AND parity`.
buf[0] = match parity {
Parity::Even => 0x02,
Parity::Odd => 0x03,
};
buf[1..].clone_from_slice(&pk.serialize());
PublicKey::from_slice(&buf).expect("we know the buffer is valid")
}
#[inline]
/// Serializes 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];
self.serialize_internal(&mut ret, ffi::SECP256K1_SER_COMPRESSED);
ret
}
#[inline]
/// Serializes 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];
self.serialize_internal(&mut ret, ffi::SECP256K1_SER_UNCOMPRESSED);
ret
}
#[inline(always)]
fn serialize_internal(&self, ret: &mut [u8], flag: c_uint) {
let mut ret_len = ret.len();
let res = unsafe {
ffi::secp256k1_ec_pubkey_serialize(
ffi::secp256k1_context_no_precomp,
ret.as_mut_c_ptr(),
&mut ret_len,
self.as_c_ptr(),
flag,
)
};
debug_assert_eq!(res, 1);
debug_assert_eq!(ret_len, ret.len());
}
/// Negates the public key.
#[inline]
#[must_use = "you forgot to use the negated public key"]
pub fn negate<C: Verification>(mut self, secp: &Secp256k1<C>) -> PublicKey {
unsafe {
let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx.as_ptr(), &mut self.0);
debug_assert_eq!(res, 1);
}
self
}
/// Tweaks a [`PublicKey`] by adding `tweak * G` modulo the curve order.
///
/// # Errors
///
/// Returns an error if the resulting key would be invalid.
#[inline]
pub fn add_exp_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
tweak: &Scalar,
) -> Result<PublicKey, Error> {
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx.as_ptr(), &mut self.0, tweak.as_c_ptr())
== 1
{
Ok(self)
} else {
Err(Error::InvalidTweak)
}
}
}
/// Tweaks a [`PublicKey`] by multiplying by `tweak` modulo the curve order.
///
/// # Errors
///
/// Returns an error if the resulting key would be invalid.
#[inline]
pub fn mul_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
other: &Scalar,
) -> Result<PublicKey, Error> {
unsafe {
if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx.as_ptr(), &mut self.0, other.as_c_ptr())
== 1
{
Ok(self)
} else {
Err(Error::InvalidTweak)
}
}
}
/// Adds a second key to this one, returning the sum.
///
/// # Errors
///
/// If the result would be the point at infinity, i.e. adding this point to its own negation.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1};
///
/// let secp = Secp256k1::new();
/// let mut rng = rand::thread_rng();
/// let (_, pk1) = secp.generate_keypair(&mut rng);
/// let (_, pk2) = secp.generate_keypair(&mut rng);
/// let sum = pk1.combine(&pk2).expect("It's improbable to fail for 2 random public keys");
/// # }
/// ```
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.
///
/// # Errors
///
/// Errors under any of the following conditions:
/// - The result would be the point at infinity, i.e. adding a point to its own negation.
/// - The provided slice is empty.
/// - The number of elements in the provided slice is greater than `i32::MAX`.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, PublicKey};
///
/// let secp = Secp256k1::new();
/// let mut rng = rand::thread_rng();
/// let (_, pk1) = secp.generate_keypair(&mut rng);
/// let (_, pk2) = secp.generate_keypair(&mut rng);
/// let (_, pk3) = secp.generate_keypair(&mut rng);
/// let sum = PublicKey::combine_keys(&[&pk1, &pk2, &pk3]).expect("It's improbable to fail for 3 random public keys");
/// # }
/// ```
pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
use core::i32::MAX;
use core::mem::transmute;
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(),
) == 1
{
Ok(PublicKey(ret))
} else {
Err(InvalidPublicKeySum)
}
}
}
/// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`PublicKey`].
#[inline]
pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
let mut pk_parity = 0;
unsafe {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let ret = ffi::secp256k1_xonly_pubkey_from_pubkey(
ffi::secp256k1_context_no_precomp,
&mut xonly_pk,
&mut pk_parity,
self.as_c_ptr(),
);
debug_assert_eq!(ret, 1);
let parity =
Parity::from_i32(pk_parity).expect("should not panic, pk_parity is 0 or 1");
(XOnlyPublicKey(xonly_pk), parity)
}
}
/// Checks that `sig` is a valid ECDSA signature for `msg` using this public key.
pub fn verify<C: Verification>(
&self,
secp: &Secp256k1<C>,
msg: &Message,
sig: &ecdsa::Signature,
) -> Result<(), Error> {
secp.verify_ecdsa(msg, sig, self)
}
}
/// This trait enables interaction with the FFI layer and even though it is part of the public API
/// normal users should never need to directly interact with FFI types.
impl CPtr for PublicKey {
type Target = ffi::PublicKey;
/// Obtains a const pointer suitable for use with FFI functions.
fn as_c_ptr(&self) -> *const Self::Target { &self.0 }
/// Obtains a mutable pointer suitable for use with FFI functions.
fn as_mut_c_ptr(&mut self) -> *mut Self::Target { &mut self.0 }
}
/// Creates a new public key from a FFI public key.
///
/// Note, normal users should never need to interact directly with FFI types.
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 {
let mut tuple = s.serialize_tuple(constants::PUBLIC_KEY_SIZE)?;
// Serialize in compressed form.
for byte in self.serialize().iter() {
tuple.serialize_element(&byte)?;
}
tuple.end()
}
}
}
#[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 {
let visitor = super::serde_util::Tuple33Visitor::new(
"33 bytes compressed public key",
PublicKey::from_slice,
);
d.deserialize_tuple(constants::PUBLIC_KEY_SIZE, visitor)
}
}
}
/// Opaque data structure that holds a keypair consisting of a secret and a public key.
///
/// # Serde support
///
/// Implements de/serialization with the `serde` and_`global-context` features enabled. Serializes
/// the secret bytes only. We treat the byte value as a tuple of 32 `u8`s for non-human-readable
/// formats. This representation is optimal for for some formats (e.g. [`bincode`]) however other
/// formats may be less optimal (e.g. [`cbor`]). For human-readable formats we use a hex string.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Keypair, Secp256k1};
///
/// let secp = Secp256k1::new();
/// let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
/// let keypair = Keypair::from_secret_key(&secp, &secret_key);
/// # }
/// ```
/// [`bincode`]: https://docs.rs/bincode
/// [`cbor`]: https://docs.rs/cbor
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Keypair(ffi::Keypair);
impl_display_secret!(Keypair);
impl_fast_comparisons!(Keypair);
impl Keypair {
/// Obtains a raw const pointer suitable for use with FFI functions.
#[inline]
#[deprecated(since = "0.25.0", note = "Use Self::as_c_ptr if you need to access the FFI layer")]
pub fn as_ptr(&self) -> *const ffi::Keypair { self.as_c_ptr() }
/// Obtains a raw mutable pointer suitable for use with FFI functions.
#[inline]
#[deprecated(
since = "0.25.0",
note = "Use Self::as_mut_c_ptr if you need to access the FFI layer"
)]
pub fn as_mut_ptr(&mut self) -> *mut ffi::Keypair { self.as_mut_c_ptr() }
/// Creates a [`Keypair`] directly from a Secp256k1 secret key.
#[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.as_ptr(), &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 [`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.as_ptr(), &mut kp, data.as_c_ptr()) == 1 {
Ok(Keypair(kp))
} else {
Err(Error::InvalidSecretKey)
}
}
}
/// Creates a [`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 [`Keypair`] directly from a secret key string and the global [`SECP256K1`] context.
///
/// # Errors
///
/// [`Error::InvalidSecretKey`] if corresponding public key for the provided secret key is not even.
#[inline]
#[cfg(feature = "global-context")]
pub fn from_seckey_str_global(s: &str) -> Result<Keypair, Error> {
Keypair::from_seckey_str(SECP256K1, s)
}
/// Generates a new random secret key.
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{rand, Secp256k1, SecretKey, Keypair};
///
/// let secp = Secp256k1::new();
/// let keypair = Keypair::new(&secp, &mut rand::thread_rng());
/// # }
/// ```
#[inline]
#[cfg(feature = "rand")]
pub fn new<R: rand::Rng + ?Sized, C: Signing>(secp: &Secp256k1<C>, rng: &mut R) -> Keypair {
let mut data = crate::random_32_bytes(rng);
unsafe {
let mut keypair = ffi::Keypair::new();
while ffi::secp256k1_keypair_create(secp.ctx.as_ptr(), &mut keypair, data.as_c_ptr())
== 0
{
data = crate::random_32_bytes(rng);
}
Keypair(keypair)
}
}
/// Generates a new random secret key using the global [`SECP256K1`] context.
#[inline]
#[cfg(all(feature = "global-context", feature = "rand"))]
pub fn new_global<R: ::rand::Rng + ?Sized>(rng: &mut R) -> Keypair {
Keypair::new(SECP256K1, rng)
}
/// Returns the secret bytes for this key pair.
#[inline]
pub fn secret_bytes(&self) -> [u8; constants::SECRET_KEY_SIZE] {
*SecretKey::from_keypair(self).as_ref()
}
/// Tweaks a keypair by first converting the public key to an xonly key and tweaking it.
///
/// # Errors
///
/// Returns an error if the resulting key would be invalid.
///
/// NB: Will not error if the tweaked public key has an odd value and can't be used for
/// BIP 340-342 purposes.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "rand-std")] {
/// use secp256k1::{Secp256k1, Keypair, Scalar};
///
/// let secp = Secp256k1::new();
/// let tweak = Scalar::random();
///
/// let mut keypair = Keypair::new(&secp, &mut rand::thread_rng());
/// let tweaked = keypair.add_xonly_tweak(&secp, &tweak).expect("Improbable to fail with a randomly generated tweak");
/// # }
/// ```
// TODO: Add checked implementation
#[inline]
pub fn add_xonly_tweak<C: Verification>(
mut self,
secp: &Secp256k1<C>,
tweak: &Scalar,
) -> Result<Keypair, Error> {
unsafe {
let err = ffi::secp256k1_keypair_xonly_tweak_add(
secp.ctx.as_ptr(),
&mut self.0,
tweak.as_c_ptr(),
);
if err != 1 {
return Err(Error::InvalidTweak);
}
Ok(self)
}
}
/// Returns the [`SecretKey`] for this [`Keypair`].
///
/// This is equivalent to using [`SecretKey::from_keypair`].
#[inline]
pub fn secret_key(&self) -> SecretKey { SecretKey::from_keypair(self) }
/// Returns the [`PublicKey`] for this [`Keypair`].
///
/// This is equivalent to using [`PublicKey::from_keypair`].
#[inline]
pub fn public_key(&self) -> PublicKey { PublicKey::from_keypair(self) }
/// Returns the [`XOnlyPublicKey`] (and it's [`Parity`]) for this [`Keypair`].
///
/// This is equivalent to using [`XOnlyPublicKey::from_keypair`].
#[inline]
pub fn x_only_public_key(&self) -> (XOnlyPublicKey, Parity) {
XOnlyPublicKey::from_keypair(self)
}
/// Constructs an schnorr signature for `msg` using the global [`SECP256K1`] context.
#[inline]
#[cfg(all(feature = "global-context", feature = "rand-std"))]
pub fn sign_schnorr(&self, msg: Message) -> schnorr::Signature {
SECP256K1.sign_schnorr(&msg, self)
}
/// Attempts to erase the secret within the underlying array.
///
/// Note, however, that the compiler is allowed to freely copy or move the contents
/// of this array to other places in memory. Preventing this behavior is very subtle.
/// For more discussion on this, please see the documentation of the
/// [`zeroize`](https://docs.rs/zeroize) crate.
#[inline]
pub fn non_secure_erase(&mut self) { self.0.non_secure_erase(); }
}
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) }
}
impl str::FromStr for Keypair {
type Err = Error;
#[allow(unused_variables, unreachable_code)] // When built with no default features.
fn from_str(s: &str) -> Result<Self, Self::Err> {