cashweb_secp256k1/
key.rs

1// Bitcoin secp256k1 bindings
2// Written in 2014 by
3//   Dawid Ciężarkiewicz
4//   Andrew Poelstra
5//
6// To the extent possible under law, the author(s) have dedicated all
7// copyright and related and neighboring rights to this software to
8// the public domain worldwide. This software is distributed without
9// any warranty.
10//
11// You should have received a copy of the CC0 Public Domain Dedication
12// along with this software.
13// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
14//
15
16//! # Public and secret keys
17
18#[cfg(any(test, feature = "rand"))]
19use rand::Rng;
20
21use core::{fmt, str};
22
23use super::Error::{self, InvalidPublicKey, InvalidSecretKey};
24use super::{from_hex, Secp256k1};
25use constants;
26use ffi::{self, CPtr};
27use Signing;
28use Verification;
29
30/// Secret 256-bit key used as `x` in an ECDSA signature
31pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
32impl_array_newtype!(SecretKey, u8, constants::SECRET_KEY_SIZE);
33impl_pretty_debug!(SecretKey);
34
35impl fmt::LowerHex for SecretKey {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        for ch in &self.0[..] {
38            write!(f, "{:02x}", *ch)?;
39        }
40        Ok(())
41    }
42}
43
44impl fmt::Display for SecretKey {
45    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46        fmt::LowerHex::fmt(self, f)
47    }
48}
49
50impl str::FromStr for SecretKey {
51    type Err = Error;
52    fn from_str(s: &str) -> Result<SecretKey, Error> {
53        let mut res = [0; constants::SECRET_KEY_SIZE];
54        match from_hex(s, &mut res) {
55            Ok(constants::SECRET_KEY_SIZE) => Ok(SecretKey(res)),
56            _ => Err(Error::InvalidSecretKey),
57        }
58    }
59}
60
61/// The number 1 encoded as a secret key
62pub const ONE_KEY: SecretKey = SecretKey([
63    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,
64]);
65
66/// A Secp256k1 public key, used for verification of signatures
67#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
68pub struct PublicKey(ffi::PublicKey);
69
70impl fmt::LowerHex for PublicKey {
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        let ser = self.serialize();
73        for ch in &ser[..] {
74            write!(f, "{:02x}", *ch)?;
75        }
76        Ok(())
77    }
78}
79
80impl fmt::Display for PublicKey {
81    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82        fmt::LowerHex::fmt(self, f)
83    }
84}
85
86impl str::FromStr for PublicKey {
87    type Err = Error;
88    fn from_str(s: &str) -> Result<PublicKey, Error> {
89        let mut res = [0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
90        match from_hex(s, &mut res) {
91            Ok(constants::PUBLIC_KEY_SIZE) => {
92                PublicKey::from_slice(&res[0..constants::PUBLIC_KEY_SIZE])
93            }
94            Ok(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE) => PublicKey::from_slice(&res),
95            _ => Err(Error::InvalidPublicKey),
96        }
97    }
98}
99
100#[cfg(any(test, feature = "rand"))]
101fn random_32_bytes<R: Rng + ?Sized>(rng: &mut R) -> [u8; 32] {
102    let mut ret = [0u8; 32];
103    rng.fill_bytes(&mut ret);
104    ret
105}
106
107impl SecretKey {
108    /// Creates a new random secret key. Requires compilation with the "rand" feature.
109    #[inline]
110    #[cfg(any(test, feature = "rand"))]
111    pub fn new<R: Rng + ?Sized>(rng: &mut R) -> SecretKey {
112        let mut data = random_32_bytes(rng);
113        unsafe {
114            while ffi::secp256k1_ec_seckey_verify(
115                ffi::secp256k1_context_no_precomp,
116                data.as_c_ptr(),
117            ) == 0
118            {
119                data = random_32_bytes(rng);
120            }
121        }
122        SecretKey(data)
123    }
124
125    /// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key
126    #[inline]
127    pub fn from_slice(data: &[u8]) -> Result<SecretKey, Error> {
128        match data.len() {
129            constants::SECRET_KEY_SIZE => {
130                let mut ret = [0; constants::SECRET_KEY_SIZE];
131                unsafe {
132                    if ffi::secp256k1_ec_seckey_verify(
133                        ffi::secp256k1_context_no_precomp,
134                        data.as_c_ptr(),
135                    ) == 0
136                    {
137                        return Err(InvalidSecretKey);
138                    }
139                }
140                ret[..].copy_from_slice(data);
141                Ok(SecretKey(ret))
142            }
143            _ => Err(InvalidSecretKey),
144        }
145    }
146
147    #[inline]
148    /// Negates one secret key.
149    pub fn negate_assign(&mut self) {
150        unsafe {
151            let res = ffi::secp256k1_ec_seckey_negate(
152                ffi::secp256k1_context_no_precomp,
153                self.as_mut_c_ptr(),
154            );
155            debug_assert_eq!(res, 1);
156        }
157    }
158
159    #[inline]
160    /// Adds one secret key to another, modulo the curve order. WIll
161    /// return an error if the resulting key would be invalid or if
162    /// the tweak was not a 32-byte length slice.
163    pub fn add_assign(&mut self, other: &[u8]) -> Result<(), Error> {
164        if other.len() != 32 {
165            return Err(Error::InvalidTweak);
166        }
167        unsafe {
168            if ffi::secp256k1_ec_seckey_tweak_add(
169                ffi::secp256k1_context_no_precomp,
170                self.as_mut_c_ptr(),
171                other.as_c_ptr(),
172            ) != 1
173            {
174                Err(Error::InvalidTweak)
175            } else {
176                Ok(())
177            }
178        }
179    }
180
181    #[inline]
182    /// Multiplies one secret key by another, modulo the curve order. Will
183    /// return an error if the resulting key would be invalid or if
184    /// the tweak was not a 32-byte length slice.
185    pub fn mul_assign(&mut self, other: &[u8]) -> Result<(), Error> {
186        if other.len() != 32 {
187            return Err(Error::InvalidTweak);
188        }
189        unsafe {
190            if ffi::secp256k1_ec_seckey_tweak_mul(
191                ffi::secp256k1_context_no_precomp,
192                self.as_mut_c_ptr(),
193                other.as_c_ptr(),
194            ) != 1
195            {
196                Err(Error::InvalidTweak)
197            } else {
198                Ok(())
199            }
200        }
201    }
202}
203
204serde_impl!(SecretKey, constants::SECRET_KEY_SIZE);
205
206impl PublicKey {
207    /// Obtains a raw const pointer suitable for use with FFI functions
208    #[inline]
209    pub fn as_ptr(&self) -> *const ffi::PublicKey {
210        &self.0
211    }
212
213    /// Obtains a raw mutable pointer suitable for use with FFI functions
214    #[inline]
215    pub fn as_mut_ptr(&mut self) -> *mut ffi::PublicKey {
216        &mut self.0
217    }
218
219    /// Creates a new public key from a secret key.
220    #[inline]
221    pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> PublicKey {
222        unsafe {
223            let mut pk = ffi::PublicKey::new();
224            // We can assume the return value because it's not possible to construct
225            // an invalid `SecretKey` without transmute trickery or something
226            let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_c_ptr());
227            debug_assert_eq!(res, 1);
228            PublicKey(pk)
229        }
230    }
231
232    /// Creates a public key directly from a slice
233    #[inline]
234    pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
235        if data.is_empty() {
236            return Err(Error::InvalidPublicKey);
237        }
238
239        unsafe {
240            let mut pk = ffi::PublicKey::new();
241            if ffi::secp256k1_ec_pubkey_parse(
242                ffi::secp256k1_context_no_precomp,
243                &mut pk,
244                data.as_c_ptr(),
245                data.len() as usize,
246            ) == 1
247            {
248                Ok(PublicKey(pk))
249            } else {
250                Err(InvalidPublicKey)
251            }
252        }
253    }
254
255    #[inline]
256    /// Serialize the key as a byte-encoded pair of values. In compressed form
257    /// the y-coordinate is represented by only a single bit, as x determines
258    /// it up to one bit.
259    pub fn serialize(&self) -> [u8; constants::PUBLIC_KEY_SIZE] {
260        let mut ret = [0; constants::PUBLIC_KEY_SIZE];
261
262        unsafe {
263            let mut ret_len = constants::PUBLIC_KEY_SIZE as usize;
264            let err = ffi::secp256k1_ec_pubkey_serialize(
265                ffi::secp256k1_context_no_precomp,
266                ret.as_mut_c_ptr(),
267                &mut ret_len,
268                self.as_c_ptr(),
269                ffi::SECP256K1_SER_COMPRESSED,
270            );
271            debug_assert_eq!(err, 1);
272            debug_assert_eq!(ret_len, ret.len());
273        }
274        ret
275    }
276
277    /// Serialize the key as a byte-encoded pair of values, in uncompressed form
278    pub fn serialize_uncompressed(&self) -> [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] {
279        let mut ret = [0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE];
280
281        unsafe {
282            let mut ret_len = constants::UNCOMPRESSED_PUBLIC_KEY_SIZE as usize;
283            let err = ffi::secp256k1_ec_pubkey_serialize(
284                ffi::secp256k1_context_no_precomp,
285                ret.as_mut_c_ptr(),
286                &mut ret_len,
287                self.as_c_ptr(),
288                ffi::SECP256K1_SER_UNCOMPRESSED,
289            );
290            debug_assert_eq!(err, 1);
291            debug_assert_eq!(ret_len, ret.len());
292        }
293        ret
294    }
295
296    #[inline]
297    /// Negates the pk to the pk `self` in place
298    /// Will return an error if the pk would be invalid.
299    pub fn negate_assign<C: Verification>(&mut self, secp: &Secp256k1<C>) {
300        unsafe {
301            let res = ffi::secp256k1_ec_pubkey_negate(secp.ctx, &mut self.0);
302            debug_assert_eq!(res, 1);
303        }
304    }
305
306    #[inline]
307    /// Adds the pk corresponding to `other` to the pk `self` in place
308    /// Will return an error if the resulting key would be invalid or
309    /// if the tweak was not a 32-byte length slice.
310    pub fn add_exp_assign<C: Verification>(
311        &mut self,
312        secp: &Secp256k1<C>,
313        other: &[u8],
314    ) -> Result<(), Error> {
315        if other.len() != 32 {
316            return Err(Error::InvalidTweak);
317        }
318        unsafe {
319            if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx, &mut self.0, other.as_c_ptr()) == 1 {
320                Ok(())
321            } else {
322                Err(Error::InvalidTweak)
323            }
324        }
325    }
326
327    #[inline]
328    /// Muliplies the pk `self` in place by the scalar `other`
329    /// Will return an error if the resulting key would be invalid or
330    /// if the tweak was not a 32-byte length slice.
331    pub fn mul_assign<C: Verification>(
332        &mut self,
333        secp: &Secp256k1<C>,
334        other: &[u8],
335    ) -> Result<(), Error> {
336        if other.len() != 32 {
337            return Err(Error::InvalidTweak);
338        }
339        unsafe {
340            if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx, &mut self.0, other.as_c_ptr()) == 1 {
341                Ok(())
342            } else {
343                Err(Error::InvalidTweak)
344            }
345        }
346    }
347
348    /// Adds a second key to this one, returning the sum. Returns an error if
349    /// the result would be the point at infinity, i.e. we are adding this point
350    /// to its own negation
351    pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
352        unsafe {
353            let mut ret = ffi::PublicKey::new();
354            let ptrs = [self.as_c_ptr(), other.as_c_ptr()];
355            if ffi::secp256k1_ec_pubkey_combine(
356                ffi::secp256k1_context_no_precomp,
357                &mut ret,
358                ptrs.as_c_ptr(),
359                2,
360            ) == 1
361            {
362                Ok(PublicKey(ret))
363            } else {
364                Err(InvalidPublicKey)
365            }
366        }
367    }
368}
369
370impl CPtr for PublicKey {
371    type Target = ffi::PublicKey;
372    fn as_c_ptr(&self) -> *const Self::Target {
373        self.as_ptr()
374    }
375
376    fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
377        self.as_mut_ptr()
378    }
379}
380
381/// Creates a new public key from a FFI public key
382impl From<ffi::PublicKey> for PublicKey {
383    #[inline]
384    fn from(pk: ffi::PublicKey) -> PublicKey {
385        PublicKey(pk)
386    }
387}
388
389serde_impl_from_slice!(PublicKey);
390
391impl PartialOrd for PublicKey {
392    fn partial_cmp(&self, other: &PublicKey) -> Option<::core::cmp::Ordering> {
393        self.serialize().partial_cmp(&other.serialize())
394    }
395}
396
397impl Ord for PublicKey {
398    fn cmp(&self, other: &PublicKey) -> ::core::cmp::Ordering {
399        self.serialize().cmp(&other.serialize())
400    }
401}
402
403#[cfg(test)]
404mod test {
405    use super::super::constants;
406    use super::super::Error::{InvalidPublicKey, InvalidSecretKey};
407    use super::{PublicKey, SecretKey};
408    use from_hex;
409    use Secp256k1;
410
411    use rand::{thread_rng, Error, ErrorKind, RngCore};
412    use rand_core::impls;
413    use std::iter;
414    use std::str::FromStr;
415
416    #[cfg(target_arch = "wasm32")]
417    use wasm_bindgen_test::wasm_bindgen_test as test;
418
419    macro_rules! hex {
420        ($hex:expr) => {{
421            let mut result = vec![0; $hex.len() / 2];
422            from_hex($hex, &mut result).expect("valid hex string");
423            result
424        }};
425    }
426
427    #[test]
428    fn skey_from_slice() {
429        let sk = SecretKey::from_slice(&[1; 31]);
430        assert_eq!(sk, Err(InvalidSecretKey));
431
432        let sk = SecretKey::from_slice(&[1; 32]);
433        assert!(sk.is_ok());
434    }
435
436    #[test]
437    fn pubkey_from_slice() {
438        assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
439        assert_eq!(PublicKey::from_slice(&[1, 2, 3]), Err(InvalidPublicKey));
440
441        let uncompressed = PublicKey::from_slice(&[
442            4, 54, 57, 149, 239, 162, 148, 175, 246, 254, 239, 75, 154, 152, 10, 82, 234, 224, 85,
443            220, 40, 100, 57, 121, 30, 162, 94, 156, 135, 67, 74, 49, 179, 57, 236, 53, 162, 124,
444            149, 144, 168, 77, 74, 30, 72, 211, 229, 110, 111, 55, 96, 193, 86, 227, 183, 152, 195,
445            155, 51, 247, 123, 113, 60, 228, 188,
446        ]);
447        assert!(uncompressed.is_ok());
448
449        let compressed = PublicKey::from_slice(&[
450            3, 23, 183, 225, 206, 31, 159, 148, 195, 42, 67, 115, 146, 41, 248, 140, 11, 3, 51, 41,
451            111, 180, 110, 143, 114, 134, 88, 73, 198, 174, 52, 184, 78,
452        ]);
453        assert!(compressed.is_ok());
454    }
455
456    #[test]
457    fn keypair_slice_round_trip() {
458        let s = Secp256k1::new();
459
460        let (sk1, pk1) = s.generate_keypair(&mut thread_rng());
461        assert_eq!(SecretKey::from_slice(&sk1[..]), Ok(sk1));
462        assert_eq!(PublicKey::from_slice(&pk1.serialize()[..]), Ok(pk1));
463        assert_eq!(
464            PublicKey::from_slice(&pk1.serialize_uncompressed()[..]),
465            Ok(pk1)
466        );
467    }
468
469    #[test]
470    fn invalid_secret_key() {
471        // Zero
472        assert_eq!(SecretKey::from_slice(&[0; 32]), Err(InvalidSecretKey));
473        // -1
474        assert_eq!(SecretKey::from_slice(&[0xff; 32]), Err(InvalidSecretKey));
475        // Top of range
476        assert!(SecretKey::from_slice(&[
477            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
478            0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C,
479            0xD0, 0x36, 0x41, 0x40,
480        ])
481        .is_ok());
482        // One past top of range
483        assert!(SecretKey::from_slice(&[
484            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
485            0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C,
486            0xD0, 0x36, 0x41, 0x41,
487        ])
488        .is_err());
489    }
490
491    #[test]
492    fn test_out_of_range() {
493        struct BadRng(u8);
494        impl RngCore for BadRng {
495            fn next_u32(&mut self) -> u32 {
496                unimplemented!()
497            }
498            fn next_u64(&mut self) -> u64 {
499                unimplemented!()
500            }
501            // This will set a secret key to a little over the
502            // group order, then decrement with repeated calls
503            // until it returns a valid key
504            fn fill_bytes(&mut self, data: &mut [u8]) {
505                let group_order: [u8; 32] = [
506                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
507                    0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2,
508                    0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41,
509                ];
510                assert_eq!(data.len(), 32);
511                data.copy_from_slice(&group_order[..]);
512                data[31] = self.0;
513                self.0 -= 1;
514            }
515            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
516                self.fill_bytes(dest);
517                Ok(())
518            }
519        }
520
521        let s = Secp256k1::new();
522        s.generate_keypair(&mut BadRng(0xff));
523    }
524
525    #[test]
526    fn test_pubkey_from_bad_slice() {
527        // Bad sizes
528        assert_eq!(
529            PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE - 1]),
530            Err(InvalidPublicKey)
531        );
532        assert_eq!(
533            PublicKey::from_slice(&[0; constants::PUBLIC_KEY_SIZE + 1]),
534            Err(InvalidPublicKey)
535        );
536        assert_eq!(
537            PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1]),
538            Err(InvalidPublicKey)
539        );
540        assert_eq!(
541            PublicKey::from_slice(&[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 1]),
542            Err(InvalidPublicKey)
543        );
544
545        // Bad parse
546        assert_eq!(
547            PublicKey::from_slice(&[0xff; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE]),
548            Err(InvalidPublicKey)
549        );
550        assert_eq!(
551            PublicKey::from_slice(&[0x55; constants::PUBLIC_KEY_SIZE]),
552            Err(InvalidPublicKey)
553        );
554        assert_eq!(PublicKey::from_slice(&[]), Err(InvalidPublicKey));
555    }
556
557    #[test]
558    fn test_seckey_from_bad_slice() {
559        // Bad sizes
560        assert_eq!(
561            SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE - 1]),
562            Err(InvalidSecretKey)
563        );
564        assert_eq!(
565            SecretKey::from_slice(&[0; constants::SECRET_KEY_SIZE + 1]),
566            Err(InvalidSecretKey)
567        );
568        // Bad parse
569        assert_eq!(
570            SecretKey::from_slice(&[0xff; constants::SECRET_KEY_SIZE]),
571            Err(InvalidSecretKey)
572        );
573        assert_eq!(
574            SecretKey::from_slice(&[0x00; constants::SECRET_KEY_SIZE]),
575            Err(InvalidSecretKey)
576        );
577        assert_eq!(SecretKey::from_slice(&[]), Err(InvalidSecretKey));
578    }
579
580    #[test]
581    fn test_debug_output() {
582        struct DumbRng(u32);
583        impl RngCore for DumbRng {
584            fn next_u32(&mut self) -> u32 {
585                self.0 = self.0.wrapping_add(1);
586                self.0
587            }
588            fn next_u64(&mut self) -> u64 {
589                self.next_u32() as u64
590            }
591            fn fill_bytes(&mut self, dest: &mut [u8]) {
592                impls::fill_bytes_via_next(self, dest);
593            }
594
595            fn try_fill_bytes(&mut self, _dest: &mut [u8]) -> Result<(), Error> {
596                Err(Error::new(ErrorKind::Unavailable, "not implemented"))
597            }
598        }
599
600        let s = Secp256k1::new();
601        let (sk, _) = s.generate_keypair(&mut DumbRng(0));
602
603        assert_eq!(
604            &format!("{:?}", sk),
605            "SecretKey(0100000000000000020000000000000003000000000000000400000000000000)"
606        );
607    }
608
609    #[test]
610    fn test_display_output() {
611        static SK_BYTES: [u8; 32] = [
612            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
613            0x06, 0x07, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x63, 0x63, 0x63, 0x63,
614            0x63, 0x63, 0x63, 0x63,
615        ];
616
617        let s = Secp256k1::signing_only();
618        let sk = SecretKey::from_slice(&SK_BYTES).expect("sk");
619        let pk = PublicKey::from_secret_key(&s, &sk);
620
621        assert_eq!(
622            sk.to_string(),
623            "01010101010101010001020304050607ffff0000ffff00006363636363636363"
624        );
625        assert_eq!(
626            SecretKey::from_str("01010101010101010001020304050607ffff0000ffff00006363636363636363")
627                .unwrap(),
628            sk
629        );
630        assert_eq!(
631            pk.to_string(),
632            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
633        );
634        assert_eq!(
635            PublicKey::from_str(
636                "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166"
637            )
638            .unwrap(),
639            pk
640        );
641        assert_eq!(
642            PublicKey::from_str(
643                "04\
644                18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
645                84B84DB303A340CD7D6823EE88174747D12A67D2F8F2F9BA40846EE5EE7A44F6"
646            )
647            .unwrap(),
648            pk
649        );
650
651        assert!(SecretKey::from_str(
652            "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
653        )
654        .is_err());
655        assert!(SecretKey::from_str(
656            "01010101010101010001020304050607ffff0000ffff0000636363636363636363"
657        )
658        .is_err());
659        assert!(SecretKey::from_str(
660            "01010101010101010001020304050607ffff0000ffff0000636363636363636"
661        )
662        .is_err());
663        assert!(SecretKey::from_str(
664            "01010101010101010001020304050607ffff0000ffff000063636363636363"
665        )
666        .is_err());
667        assert!(SecretKey::from_str(
668            "01010101010101010001020304050607ffff0000ffff000063636363636363xx"
669        )
670        .is_err());
671        assert!(PublicKey::from_str(
672            "0300000000000000000000000000000000000000000000000000000000000000000"
673        )
674        .is_err());
675        assert!(PublicKey::from_str(
676            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16601"
677        )
678        .is_err());
679        assert!(PublicKey::from_str(
680            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd16"
681        )
682        .is_err());
683        assert!(PublicKey::from_str(
684            "0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
685        )
686        .is_err());
687        assert!(PublicKey::from_str(
688            "xx0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd1"
689        )
690        .is_err());
691
692        let long_str: String = iter::repeat('a').take(1024 * 1024).collect();
693        assert!(SecretKey::from_str(&long_str).is_err());
694        assert!(PublicKey::from_str(&long_str).is_err());
695    }
696
697    #[test]
698    fn test_pubkey_serialize() {
699        struct DumbRng(u32);
700        impl RngCore for DumbRng {
701            fn next_u32(&mut self) -> u32 {
702                self.0 = self.0.wrapping_add(1);
703                self.0
704            }
705            fn next_u64(&mut self) -> u64 {
706                self.next_u32() as u64
707            }
708            fn try_fill_bytes(&mut self, _dest: &mut [u8]) -> Result<(), Error> {
709                Err(Error::new(ErrorKind::Unavailable, "not implemented"))
710            }
711
712            fn fill_bytes(&mut self, dest: &mut [u8]) {
713                impls::fill_bytes_via_next(self, dest);
714            }
715        }
716
717        let s = Secp256k1::new();
718        let (_, pk1) = s.generate_keypair(&mut DumbRng(0));
719        assert_eq!(
720            &pk1.serialize_uncompressed()[..],
721            &[
722                4, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
723                9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229, 185, 28, 165,
724                110, 27, 3, 162, 126, 238, 167, 157, 242, 221, 76, 251, 237, 34, 231, 72, 39, 245,
725                3, 191, 64, 111, 170, 117, 103, 82, 28, 102, 163
726            ][..]
727        );
728        assert_eq!(
729            &pk1.serialize()[..],
730            &[
731                3, 124, 121, 49, 14, 253, 63, 197, 50, 39, 194, 107, 17, 193, 219, 108, 154, 126,
732                9, 181, 248, 2, 12, 149, 233, 198, 71, 149, 134, 250, 184, 154, 229
733            ][..]
734        );
735    }
736
737    #[test]
738    fn test_addition() {
739        let s = Secp256k1::new();
740
741        let (mut sk1, mut pk1) = s.generate_keypair(&mut thread_rng());
742        let (mut sk2, mut pk2) = s.generate_keypair(&mut thread_rng());
743
744        assert_eq!(PublicKey::from_secret_key(&s, &sk1), pk1);
745        assert!(sk1.add_assign(&sk2[..]).is_ok());
746        assert!(pk1.add_exp_assign(&s, &sk2[..]).is_ok());
747        assert_eq!(PublicKey::from_secret_key(&s, &sk1), pk1);
748
749        assert_eq!(PublicKey::from_secret_key(&s, &sk2), pk2);
750        assert!(sk2.add_assign(&sk1[..]).is_ok());
751        assert!(pk2.add_exp_assign(&s, &sk1[..]).is_ok());
752        assert_eq!(PublicKey::from_secret_key(&s, &sk2), pk2);
753    }
754
755    #[test]
756    fn test_multiplication() {
757        let s = Secp256k1::new();
758
759        let (mut sk1, mut pk1) = s.generate_keypair(&mut thread_rng());
760        let (mut sk2, mut pk2) = s.generate_keypair(&mut thread_rng());
761
762        assert_eq!(PublicKey::from_secret_key(&s, &sk1), pk1);
763        assert!(sk1.mul_assign(&sk2[..]).is_ok());
764        assert!(pk1.mul_assign(&s, &sk2[..]).is_ok());
765        assert_eq!(PublicKey::from_secret_key(&s, &sk1), pk1);
766
767        assert_eq!(PublicKey::from_secret_key(&s, &sk2), pk2);
768        assert!(sk2.mul_assign(&sk1[..]).is_ok());
769        assert!(pk2.mul_assign(&s, &sk1[..]).is_ok());
770        assert_eq!(PublicKey::from_secret_key(&s, &sk2), pk2);
771    }
772
773    #[test]
774    fn test_negation() {
775        let s = Secp256k1::new();
776
777        let (mut sk, mut pk) = s.generate_keypair(&mut thread_rng());
778
779        let original_sk = sk;
780        let original_pk = pk;
781
782        assert_eq!(PublicKey::from_secret_key(&s, &sk), pk);
783        sk.negate_assign();
784        pk.negate_assign(&s);
785        assert_ne!(original_sk, sk);
786        assert_ne!(original_pk, pk);
787        sk.negate_assign();
788        pk.negate_assign(&s);
789        assert_eq!(original_sk, sk);
790        assert_eq!(original_pk, pk);
791        assert_eq!(PublicKey::from_secret_key(&s, &sk), pk);
792    }
793
794    #[test]
795    fn pubkey_hash() {
796        use std::collections::hash_map::DefaultHasher;
797        use std::collections::HashSet;
798        use std::hash::{Hash, Hasher};
799
800        fn hash<T: Hash>(t: &T) -> u64 {
801            let mut s = DefaultHasher::new();
802            t.hash(&mut s);
803            s.finish()
804        }
805
806        let s = Secp256k1::new();
807        let mut set = HashSet::new();
808        const COUNT: usize = 1024;
809        for _ in 0..COUNT {
810            let (_, pk) = s.generate_keypair(&mut thread_rng());
811            let hash = hash(&pk);
812            assert!(!set.contains(&hash));
813            set.insert(hash);
814        }
815        assert_eq!(set.len(), COUNT);
816    }
817
818    #[test]
819    fn pubkey_combine() {
820        let compressed1 = PublicKey::from_slice(&hex!(
821            "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
822        ))
823        .unwrap();
824        let compressed2 = PublicKey::from_slice(&hex!(
825            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
826        ))
827        .unwrap();
828        let exp_sum = PublicKey::from_slice(&hex!(
829            "0384526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07"
830        ))
831        .unwrap();
832
833        let sum1 = compressed1.combine(&compressed2);
834        assert!(sum1.is_ok());
835        let sum2 = compressed2.combine(&compressed1);
836        assert!(sum2.is_ok());
837        assert_eq!(sum1, sum2);
838        assert_eq!(sum1.unwrap(), exp_sum);
839    }
840
841    #[test]
842    fn pubkey_equal() {
843        let pk1 = PublicKey::from_slice(&hex!(
844            "0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"
845        ))
846        .unwrap();
847        let pk2 = pk1;
848        let pk3 = PublicKey::from_slice(&hex!(
849            "02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"
850        ))
851        .unwrap();
852
853        assert!(pk1 == pk2);
854        assert!(pk1 <= pk2);
855        assert!(pk2 <= pk1);
856        assert!(!(pk2 < pk1));
857        assert!(!(pk1 < pk2));
858
859        assert!(pk3 > pk1);
860        assert!(pk1 < pk3);
861        assert!(pk3 >= pk1);
862        assert!(pk1 <= pk3);
863    }
864
865    #[cfg(feature = "serde")]
866    #[test]
867    fn test_signature_serde() {
868        use serde_test::{assert_tokens, Configure, Token};
869        static SK_BYTES: [u8; 32] = [
870            1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 3, 4, 5, 6, 7, 0xff, 0xff, 0, 0, 0xff, 0xff, 0, 0, 99,
871            99, 99, 99, 99, 99, 99, 99,
872        ];
873        static SK_STR: &'static str = "\
874            01010101010101010001020304050607ffff0000ffff00006363636363636363\
875        ";
876        static PK_BYTES: [u8; 33] = [
877            0x02, 0x18, 0x84, 0x57, 0x81, 0xf6, 0x31, 0xc4, 0x8f, 0x1c, 0x97, 0x09, 0xe2, 0x30,
878            0x92, 0x06, 0x7d, 0x06, 0x83, 0x7f, 0x30, 0xaa, 0x0c, 0xd0, 0x54, 0x4a, 0xc8, 0x87,
879            0xfe, 0x91, 0xdd, 0xd1, 0x66,
880        ];
881        static PK_STR: &'static str = "\
882            0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166\
883        ";
884
885        let s = Secp256k1::new();
886
887        let sk = SecretKey::from_slice(&SK_BYTES).unwrap();
888        let pk = PublicKey::from_secret_key(&s, &sk);
889
890        assert_tokens(&sk.compact(), &[Token::BorrowedBytes(&SK_BYTES[..])]);
891        assert_tokens(&sk.readable(), &[Token::BorrowedStr(SK_STR)]);
892        assert_tokens(&pk.compact(), &[Token::BorrowedBytes(&PK_BYTES[..])]);
893        assert_tokens(&pk.readable(), &[Token::BorrowedStr(PK_STR)]);
894    }
895}