secp256k1_test/
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
18use std::marker;
19use arrayvec::ArrayVec;
20use rand::Rng;
21use serialize::{Decoder, Decodable, Encoder, Encodable};
22use serde::{Serialize, Deserialize, Serializer, Deserializer};
23
24use super::{Secp256k1, ContextFlag};
25use super::Error::{self, IncapableContext, InvalidPublicKey, InvalidSecretKey};
26use constants;
27use ffi;
28
29/// Secret 256-bit key used as `x` in an ECDSA signature
30pub struct SecretKey([u8; constants::SECRET_KEY_SIZE]);
31impl_array_newtype!(SecretKey, u8, constants::SECRET_KEY_SIZE);
32impl_pretty_debug!(SecretKey);
33
34/// The number 1 encoded as a secret key
35/// Deprecated; `static` is not what I want; use `ONE_KEY` instead
36pub static ONE: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
37                                       0, 0, 0, 0, 0, 0, 0, 0,
38                                       0, 0, 0, 0, 0, 0, 0, 0,
39                                       0, 0, 0, 0, 0, 0, 0, 1]);
40
41/// The number 0 encoded as a secret key
42pub const ZERO_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
43                                           0, 0, 0, 0, 0, 0, 0, 0,
44                                           0, 0, 0, 0, 0, 0, 0, 0,
45                                           0, 0, 0, 0, 0, 0, 0, 0]);
46
47/// The number 1 encoded as a secret key
48pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
49                                          0, 0, 0, 0, 0, 0, 0, 0,
50                                          0, 0, 0, 0, 0, 0, 0, 0,
51                                          0, 0, 0, 0, 0, 0, 0, 1]);
52
53/// A Secp256k1 public key, used for verification of signatures
54#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
55pub struct PublicKey(ffi::PublicKey);
56
57
58fn random_32_bytes<R: Rng>(rng: &mut R) -> [u8; 32] {
59    let mut ret = [0u8; 32];
60    rng.fill_bytes(&mut ret);
61    ret
62}
63
64impl SecretKey {
65    /// Creates a new random secret key
66    #[inline]
67    pub fn new<R: Rng>(secp: &Secp256k1, rng: &mut R) -> SecretKey {
68        let mut data = random_32_bytes(rng);
69        unsafe {
70            while ffi::secp256k1_ec_seckey_verify(secp.ctx, data.as_ptr()) == 0 {
71                data = random_32_bytes(rng);
72            }
73        }
74        SecretKey(data)
75    }
76
77    /// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key
78    #[inline]
79    pub fn from_slice(secp: &Secp256k1, data: &[u8])
80                        -> Result<SecretKey, Error> {
81        match data.len() {
82            constants::SECRET_KEY_SIZE => {
83                let mut ret = [0; constants::SECRET_KEY_SIZE];
84                unsafe {
85                    if ffi::secp256k1_ec_seckey_verify(secp.ctx, data.as_ptr()) == 0 {
86                        return Err(InvalidSecretKey);
87                    }
88                }
89                ret[..].copy_from_slice(data);
90                Ok(SecretKey(ret))
91            }
92            _ => Err(InvalidSecretKey)
93        }
94    }
95
96    #[inline]
97    /// Adds one secret key to another, modulo the curve order
98    pub fn add_assign(&mut self, secp: &Secp256k1, other: &SecretKey)
99                     -> Result<(), Error> {
100        unsafe {
101            if ffi::secp256k1_ec_privkey_tweak_add(secp.ctx, self.as_mut_ptr(), other.as_ptr()) != 1 {
102                Err(InvalidSecretKey)
103            } else {
104                Ok(())
105            }
106        }
107    }
108
109    #[inline]
110    /// Multiplies one secret key by another, modulo the curve order
111    pub fn mul_assign(&mut self, secp: &Secp256k1, other: &SecretKey)
112                     -> Result<(), Error> {
113        unsafe {
114            if ffi::secp256k1_ec_privkey_tweak_mul(secp.ctx, self.as_mut_ptr(), other.as_ptr()) != 1 {
115                Err(InvalidSecretKey)
116            } else {
117                Ok(())
118            }
119        }
120    }
121}
122
123impl PublicKey {
124    /// Creates a new zeroed out public key
125    #[inline]
126    pub fn new() -> PublicKey {
127        PublicKey(ffi::PublicKey::new())
128    }
129
130    /// Determines whether a pubkey is valid
131    #[inline]
132    pub fn is_valid(&self) -> bool {
133        // The only invalid pubkey the API should be able to create is
134        // the zero one.
135        self.0[..].iter().any(|&x| x != 0)
136    }
137
138    /// Obtains a raw pointer suitable for use with FFI functions
139    #[inline]
140    pub fn as_ptr(&self) -> *const ffi::PublicKey {
141        &self.0 as *const _
142    }
143
144    /// Creates a new public key from a secret key.
145    #[inline]
146    pub fn from_secret_key(secp: &Secp256k1,
147                           sk: &SecretKey)
148                           -> Result<PublicKey, Error> {
149        if secp.caps == ContextFlag::VerifyOnly || secp.caps == ContextFlag::None {
150            return Err(IncapableContext);
151        }
152        let mut pk = unsafe { ffi::PublicKey::blank() };
153        unsafe {
154            // We can assume the return value because it's not possible to construct
155            // an invalid `SecretKey` without transmute trickery or something
156            let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_ptr());
157            debug_assert_eq!(res, 1);
158        }
159        Ok(PublicKey(pk))
160    }
161
162    /// Creates a public key directly from a slice
163    #[inline]
164    pub fn from_slice(secp: &Secp256k1, data: &[u8])
165                      -> Result<PublicKey, Error> {
166
167        let mut pk = unsafe { ffi::PublicKey::blank() };
168        unsafe {
169            if ffi::secp256k1_ec_pubkey_parse(secp.ctx, &mut pk, data.as_ptr(),
170                                              data.len() as ::libc::size_t) == 1 {
171                Ok(PublicKey(pk))
172            } else {
173                Err(InvalidPublicKey)
174            }
175        }
176    }
177
178    #[inline]
179    /// Serialize the key as a byte-encoded pair of values. In compressed form
180    /// the y-coordinate is represented by only a single bit, as x determines
181    /// it up to one bit.
182    pub fn serialize_vec(&self, secp: &Secp256k1, compressed: bool) -> ArrayVec<[u8; constants::PUBLIC_KEY_SIZE]> {
183        let mut ret = ArrayVec::new();
184
185        unsafe {
186            let mut ret_len = constants::PUBLIC_KEY_SIZE as ::libc::size_t;
187            let compressed = if compressed { ffi::SECP256K1_SER_COMPRESSED } else { ffi::SECP256K1_SER_UNCOMPRESSED };
188            let err = ffi::secp256k1_ec_pubkey_serialize(secp.ctx, ret.as_ptr(),
189                                                         &mut ret_len, self.as_ptr(),
190                                                         compressed);
191            debug_assert_eq!(err, 1);
192            ret.set_len(ret_len as usize);
193        }
194        ret
195    }
196
197    #[inline]
198    /// Adds the pk corresponding to `other` to the pk `self` in place
199    pub fn add_exp_assign(&mut self, secp: &Secp256k1, other: &SecretKey)
200                         -> Result<(), Error> {
201        if secp.caps == ContextFlag::SignOnly || secp.caps == ContextFlag::None {
202            return Err(IncapableContext);
203        }
204        unsafe {
205            if ffi::secp256k1_ec_pubkey_tweak_add(secp.ctx, &mut self.0 as *mut _,
206                                                  other.as_ptr()) == 1 {
207                Ok(())
208            } else {
209                Err(InvalidSecretKey)
210            }
211        }
212    }
213
214    #[inline]
215    /// Muliplies the pk `self` in place by the scalar `other`
216    pub fn mul_assign(&mut self, secp: &Secp256k1, other: &SecretKey)
217                         -> Result<(), Error> {
218        if secp.caps == ContextFlag::SignOnly || secp.caps == ContextFlag::None {
219            return Err(IncapableContext);
220        }
221        unsafe {
222            if ffi::secp256k1_ec_pubkey_tweak_mul(secp.ctx, &mut self.0 as *mut _,
223                                                  other.as_ptr()) == 1 {
224                Ok(())
225            } else {
226                Err(InvalidSecretKey)
227            }
228        }
229    }
230}
231
232impl Decodable for PublicKey {
233    fn decode<D: Decoder>(d: &mut D) -> Result<PublicKey, D::Error> {
234        d.read_seq(|d, len| {
235            let s = Secp256k1::with_caps(::ContextFlag::None);
236            if len == constants::UNCOMPRESSED_PUBLIC_KEY_SIZE {
237                unsafe {
238                    use std::mem;
239                    let mut ret: [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] = mem::uninitialized();
240                    for i in 0..len {
241                        ret[i] = try!(d.read_seq_elt(i, |d| Decodable::decode(d)));
242                    }
243                    PublicKey::from_slice(&s, &ret).map_err(|_| d.error("invalid public key"))
244                }
245            } else if len == constants::COMPRESSED_PUBLIC_KEY_SIZE {
246                unsafe {
247                    use std::mem;
248                    let mut ret: [u8; constants::COMPRESSED_PUBLIC_KEY_SIZE] = mem::uninitialized();
249                    for i in 0..len {
250                        ret[i] = try!(d.read_seq_elt(i, |d| Decodable::decode(d)));
251                    }
252                    PublicKey::from_slice(&s, &ret).map_err(|_| d.error("invalid public key"))
253                }
254            } else {
255                Err(d.error("Invalid length"))
256            }
257        })
258    }
259}
260
261/// Creates a new public key from a FFI public key
262impl From<ffi::PublicKey> for PublicKey {
263    #[inline]
264    fn from(pk: ffi::PublicKey) -> PublicKey {
265        PublicKey(pk)
266    }
267}
268
269
270impl Encodable for PublicKey {
271    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
272        let secp = Secp256k1::with_caps(::ContextFlag::None);
273        self.serialize_vec(&secp, true).encode(s)
274    }
275}
276
277impl<'de> Deserialize<'de> for PublicKey {
278    fn deserialize<D>(d: D) -> Result<PublicKey, D::Error>
279        where D: Deserializer<'de>
280    {
281        use serde::de;
282        struct Visitor {
283            marker: marker::PhantomData<PublicKey>,
284        }
285        impl<'de> de::Visitor<'de> for Visitor {
286            type Value = PublicKey;
287
288            #[inline]
289            fn visit_seq<A>(self, mut a: A) -> Result<PublicKey, A::Error>
290                where A: de::SeqAccess<'de>
291            {
292                debug_assert!(constants::UNCOMPRESSED_PUBLIC_KEY_SIZE >= constants::COMPRESSED_PUBLIC_KEY_SIZE);
293
294                let s = Secp256k1::with_caps(::ContextFlag::None);
295                unsafe {
296                    use std::mem;
297                    let mut ret: [u8; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE] = mem::uninitialized();
298
299                    let mut read_len = 0;
300                    while read_len < constants::UNCOMPRESSED_PUBLIC_KEY_SIZE {
301                        let read_ch = match try!(a.next_element()) {
302                            Some(c) => c,
303                            None => break
304                        };
305                        ret[read_len] = read_ch;
306                        read_len += 1;
307                    }
308                    let one_after_last : Option<u8> = try!(a.next_element());
309                    if one_after_last.is_some() {
310                        return Err(de::Error::invalid_length(read_len + 1, &self));
311                    }
312
313                    match read_len {
314                        constants::UNCOMPRESSED_PUBLIC_KEY_SIZE | constants::COMPRESSED_PUBLIC_KEY_SIZE
315                            => PublicKey::from_slice(&s, &ret[..read_len]).map_err(
316                                |e| match e {
317                                        InvalidPublicKey => de::Error::invalid_value(de::Unexpected::Seq, &self),
318                                        _ => de::Error::custom(&e.to_string()),
319                                    }
320                                ),
321                        _ => Err(de::Error::invalid_length(read_len, &self)),
322                    }
323                }
324            }
325
326            fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
327                write!(f, "a sequence of {} or {} bytes representing a valid compressed or uncompressed public key",
328                       constants::COMPRESSED_PUBLIC_KEY_SIZE, constants::UNCOMPRESSED_PUBLIC_KEY_SIZE)
329            }
330        }
331
332        // Begin actual function
333        d.deserialize_seq(Visitor { marker: ::std::marker::PhantomData })
334    }
335}
336
337impl Serialize for PublicKey {
338    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
339        where S: Serializer
340    {
341        let secp = Secp256k1::with_caps(::ContextFlag::None);
342        (&self.serialize_vec(&secp, true)[..]).serialize(s)
343    }
344}
345
346#[cfg(test)]
347mod test {
348    use super::super::{Secp256k1, ContextFlag};
349    use super::super::Error::{InvalidPublicKey, InvalidSecretKey, IncapableContext};
350    use super::{PublicKey, SecretKey};
351    use super::super::constants;
352
353    use rand::{Rng, thread_rng};
354
355    #[test]
356    fn skey_from_slice() {
357        let s = Secp256k1::new();
358        let sk = SecretKey::from_slice(&s, &[1; 31]);
359        assert_eq!(sk, Err(InvalidSecretKey));
360
361        let sk = SecretKey::from_slice(&s, &[1; 32]);
362        assert!(sk.is_ok());
363    }
364
365    #[test]
366    fn pubkey_from_slice() {
367        let s = Secp256k1::new();
368        assert_eq!(PublicKey::from_slice(&s, &[]), Err(InvalidPublicKey));
369        assert_eq!(PublicKey::from_slice(&s, &[1, 2, 3]), Err(InvalidPublicKey));
370
371        let uncompressed = PublicKey::from_slice(&s, &[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]);
372        assert!(uncompressed.is_ok());
373
374        let compressed = PublicKey::from_slice(&s, &[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]);
375        assert!(compressed.is_ok());
376    }
377
378    #[test]
379    fn keypair_slice_round_trip() {
380        let s = Secp256k1::new();
381
382        let (sk1, pk1) = s.generate_keypair(&mut thread_rng()).unwrap();
383        assert_eq!(SecretKey::from_slice(&s, &sk1[..]), Ok(sk1));
384        assert_eq!(PublicKey::from_slice(&s, &pk1.serialize_vec(&s, true)[..]), Ok(pk1));
385        assert_eq!(PublicKey::from_slice(&s, &pk1.serialize_vec(&s, false)[..]), Ok(pk1));
386    }
387
388    #[test]
389    fn invalid_secret_key() {
390        let s = Secp256k1::new();
391        // Zero
392        assert_eq!(SecretKey::from_slice(&s, &[0; 32]), Err(InvalidSecretKey));
393        // -1
394        assert_eq!(SecretKey::from_slice(&s, &[0xff; 32]), Err(InvalidSecretKey));
395        // Top of range
396        assert!(SecretKey::from_slice(&s,
397                                      &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
398                                        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
399                                        0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
400                                        0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40]).is_ok());
401        // One past top of range
402        assert!(SecretKey::from_slice(&s,
403                                      &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
404                                        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
405                                        0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
406                                        0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41]).is_err());
407    }
408
409    #[test]
410    fn test_pubkey_from_slice_bad_context() {
411        let s = Secp256k1::without_caps();
412        let sk = SecretKey::new(&s, &mut thread_rng());
413        assert_eq!(PublicKey::from_secret_key(&s, &sk), Err(IncapableContext));
414
415        let s = Secp256k1::with_caps(ContextFlag::VerifyOnly);
416        assert_eq!(PublicKey::from_secret_key(&s, &sk), Err(IncapableContext));
417
418        let s = Secp256k1::with_caps(ContextFlag::SignOnly);
419        assert!(PublicKey::from_secret_key(&s, &sk).is_ok());
420
421        let s = Secp256k1::with_caps(ContextFlag::Full);
422        assert!(PublicKey::from_secret_key(&s, &sk).is_ok());
423    }
424
425    #[test]
426    fn test_add_exp_bad_context() {
427        let s = Secp256k1::with_caps(ContextFlag::Full);
428        let (sk, mut pk) = s.generate_keypair(&mut thread_rng()).unwrap();
429
430        assert!(pk.add_exp_assign(&s, &sk).is_ok());
431
432        let s = Secp256k1::with_caps(ContextFlag::VerifyOnly);
433        assert!(pk.add_exp_assign(&s, &sk).is_ok());
434
435        let s = Secp256k1::with_caps(ContextFlag::SignOnly);
436        assert_eq!(pk.add_exp_assign(&s, &sk), Err(IncapableContext));
437
438        let s = Secp256k1::with_caps(ContextFlag::None);
439        assert_eq!(pk.add_exp_assign(&s, &sk), Err(IncapableContext));
440    }
441
442    #[test]
443    fn test_bad_deserialize() {
444        use std::io::Cursor;
445        use serialize::{json, Decodable};
446
447        let zero31 = "[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]".as_bytes();
448        let json31 = json::Json::from_reader(&mut Cursor::new(zero31)).unwrap();
449        let zero32 = "[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,0]".as_bytes();
450        let json32 = json::Json::from_reader(&mut Cursor::new(zero32)).unwrap();
451        let zero65 = "[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,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,0,0,0]".as_bytes();
452        let json65 = json::Json::from_reader(&mut Cursor::new(zero65)).unwrap();
453        let string = "\"my key\"".as_bytes();
454        let json = json::Json::from_reader(&mut Cursor::new(string)).unwrap();
455
456        // Invalid length
457        let mut decoder = json::Decoder::new(json31.clone());
458        assert!(<PublicKey as Decodable>::decode(&mut decoder).is_err());
459        let mut decoder = json::Decoder::new(json31.clone());
460        assert!(<SecretKey as Decodable>::decode(&mut decoder).is_err());
461        let mut decoder = json::Decoder::new(json32.clone());
462        assert!(<PublicKey as Decodable>::decode(&mut decoder).is_err());
463        let mut decoder = json::Decoder::new(json32.clone());
464        assert!(<SecretKey as Decodable>::decode(&mut decoder).is_ok());
465        let mut decoder = json::Decoder::new(json65.clone());
466        assert!(<PublicKey as Decodable>::decode(&mut decoder).is_err());
467        let mut decoder = json::Decoder::new(json65.clone());
468        assert!(<SecretKey as Decodable>::decode(&mut decoder).is_err());
469
470        // Syntax error
471        let mut decoder = json::Decoder::new(json.clone());
472        assert!(<PublicKey as Decodable>::decode(&mut decoder).is_err());
473        let mut decoder = json::Decoder::new(json.clone());
474        assert!(<SecretKey as Decodable>::decode(&mut decoder).is_err());
475    }
476
477    #[test]
478    fn test_serialize() {
479        use std::io::Cursor;
480        use serialize::{json, Decodable, Encodable};
481
482        macro_rules! round_trip (
483            ($var:ident) => ({
484                let start = $var;
485                let mut encoded = String::new();
486                {
487                    let mut encoder = json::Encoder::new(&mut encoded);
488                    start.encode(&mut encoder).unwrap();
489                }
490                let json = json::Json::from_reader(&mut Cursor::new(encoded.as_bytes())).unwrap();
491                let mut decoder = json::Decoder::new(json);
492                let decoded = Decodable::decode(&mut decoder);
493                assert_eq!(Ok(Some(start)), decoded);
494            })
495        );
496
497        let s = Secp256k1::new();
498        for _ in 0..500 {
499            let (sk, pk) = s.generate_keypair(&mut thread_rng()).unwrap();
500            round_trip!(sk);
501            round_trip!(pk);
502        }
503    }
504
505    #[test]
506    fn test_bad_serde_deserialize() {
507        use serde::Deserialize;
508        use json;
509
510        // Invalid length
511        let zero31 = "[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]";
512        let mut json = json::de::Deserializer::from_str(zero31);
513        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
514        let mut json = json::de::Deserializer::from_str(zero31);
515        assert!(<SecretKey as Deserialize>::deserialize(&mut json).is_err());
516
517        let zero32 = "[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,0]";
518        let mut json = json::de::Deserializer::from_str(zero32);
519        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
520        let mut json = json::de::Deserializer::from_str(zero32);
521        assert!(<SecretKey as Deserialize>::deserialize(&mut json).is_ok());
522
523        let zero33 = "[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,0,0]";
524        let mut json = json::de::Deserializer::from_str(zero33);
525        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
526        let mut json = json::de::Deserializer::from_str(zero33);
527        assert!(<SecretKey as Deserialize>::deserialize(&mut json).is_err());
528
529        let trailing66 = "[4,149,16,196,140,38,92,239,179,65,59,224,230,183,91,238,240,46,186,252,
530                        175,102,52,249,98,178,123,72,50,171,196,254,236,1,189,143,242,227,16,87,
531                        247,183,162,68,237,140,92,205,151,129,166,58,111,96,123,64,180,147,51,12,
532                        209,89,236,213,206,17]";
533        let mut json = json::de::Deserializer::from_str(trailing66);
534        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
535
536        // The first 65 bytes of trailing66 are valid
537        let valid65 = "[4,149,16,196,140,38,92,239,179,65,59,224,230,183,91,238,240,46,186,252,
538                        175,102,52,249,98,178,123,72,50,171,196,254,236,1,189,143,242,227,16,87,
539                        247,183,162,68,237,140,92,205,151,129,166,58,111,96,123,64,180,147,51,12,
540                        209,89,236,213,206]";
541        let mut json = json::de::Deserializer::from_str(valid65);
542        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_ok());
543
544        // All zeroes pk is invalid
545        let zero65 = "[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,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,0,0,0]";
546        let mut json = json::de::Deserializer::from_str(zero65);
547        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
548        let mut json = json::de::Deserializer::from_str(zero65);
549        assert!(<SecretKey as Deserialize>::deserialize(&mut json).is_err());
550
551        // Syntax error
552        let string = "\"my key\"";
553        let mut json = json::de::Deserializer::from_str(string);
554        assert!(<PublicKey as Deserialize>::deserialize(&mut json).is_err());
555        let mut json = json::de::Deserializer::from_str(string);
556        assert!(<SecretKey as Deserialize>::deserialize(&mut json).is_err());
557    }
558
559
560    #[test]
561    fn test_serialize_serde() {
562        let s = Secp256k1::new();
563        for _ in 0..500 {
564            let (sk, pk) = s.generate_keypair(&mut thread_rng()).unwrap();
565            round_trip_serde!(sk);
566            round_trip_serde!(pk);
567        }
568    }
569
570    #[test]
571    fn test_out_of_range() {
572
573        struct BadRng(u8);
574        impl Rng for BadRng {
575            fn next_u32(&mut self) -> u32 { unimplemented!() }
576            // This will set a secret key to a little over the
577            // group order, then decrement with repeated calls
578            // until it returns a valid key
579            fn fill_bytes(&mut self, data: &mut [u8]) {
580                let group_order: [u8; 32] = [
581                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
582                    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
583                    0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
584                    0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41];
585                assert_eq!(data.len(), 32);
586                data.copy_from_slice(&group_order[..]);
587                data[31] = self.0;
588                self.0 -= 1;
589            }
590        }
591
592        let s = Secp256k1::new();
593        s.generate_keypair(&mut BadRng(0xff)).unwrap();
594    }
595
596    #[test]
597    fn test_pubkey_from_bad_slice() {
598        let s = Secp256k1::new();
599        // Bad sizes
600        assert_eq!(PublicKey::from_slice(&s, &[0; constants::COMPRESSED_PUBLIC_KEY_SIZE - 1]),
601                   Err(InvalidPublicKey));
602        assert_eq!(PublicKey::from_slice(&s, &[0; constants::COMPRESSED_PUBLIC_KEY_SIZE + 1]),
603                   Err(InvalidPublicKey));
604        assert_eq!(PublicKey::from_slice(&s, &[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1]),
605                   Err(InvalidPublicKey));
606        assert_eq!(PublicKey::from_slice(&s, &[0; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 1]),
607                   Err(InvalidPublicKey));
608
609        // Bad parse
610        assert_eq!(PublicKey::from_slice(&s, &[0xff; constants::UNCOMPRESSED_PUBLIC_KEY_SIZE]),
611                   Err(InvalidPublicKey));
612        assert_eq!(PublicKey::from_slice(&s, &[0x55; constants::COMPRESSED_PUBLIC_KEY_SIZE]),
613                   Err(InvalidPublicKey));
614    }
615
616    #[test]
617    fn test_debug_output() {
618        struct DumbRng(u32);
619        impl Rng for DumbRng {
620            fn next_u32(&mut self) -> u32 {
621                self.0 = self.0.wrapping_add(1);
622                self.0
623            }
624        }
625
626        let s = Secp256k1::new();
627        let (sk, _) = s.generate_keypair(&mut DumbRng(0)).unwrap();
628
629        assert_eq!(&format!("{:?}", sk),
630                   "SecretKey(0200000001000000040000000300000006000000050000000800000007000000)");
631    }
632
633    #[test]
634    fn test_pubkey_serialize() {
635        struct DumbRng(u32);
636        impl Rng for DumbRng {
637            fn next_u32(&mut self) -> u32 {
638                self.0 = self.0.wrapping_add(1);
639                self.0
640            }
641        }
642
643        let s = Secp256k1::new();
644        let (_, pk1) = s.generate_keypair(&mut DumbRng(0)).unwrap();
645        assert_eq!(&pk1.serialize_vec(&s, false)[..],
646                   &[4, 149, 16, 196, 140, 38, 92, 239, 179, 65, 59, 224, 230, 183, 91, 238, 240, 46, 186, 252, 175, 102, 52, 249, 98, 178, 123, 72, 50, 171, 196, 254, 236, 1, 189, 143, 242, 227, 16, 87, 247, 183, 162, 68, 237, 140, 92, 205, 151, 129, 166, 58, 111, 96, 123, 64, 180, 147, 51, 12, 209, 89, 236, 213, 206][..]);
647        assert_eq!(&pk1.serialize_vec(&s, true)[..],
648                   &[2, 149, 16, 196, 140, 38, 92, 239, 179, 65, 59, 224, 230, 183, 91, 238, 240, 46, 186, 252, 175, 102, 52, 249, 98, 178, 123, 72, 50, 171, 196, 254, 236][..]);
649    }
650
651    #[test]
652    fn test_addition() {
653        let s = Secp256k1::new();
654
655        let (mut sk1, mut pk1) = s.generate_keypair(&mut thread_rng()).unwrap();
656        let (mut sk2, mut pk2) = s.generate_keypair(&mut thread_rng()).unwrap();
657
658        assert_eq!(PublicKey::from_secret_key(&s, &sk1).unwrap(), pk1);
659        assert!(sk1.add_assign(&s, &sk2).is_ok());
660        assert!(pk1.add_exp_assign(&s, &sk2).is_ok());
661        assert_eq!(PublicKey::from_secret_key(&s, &sk1).unwrap(), pk1);
662
663        assert_eq!(PublicKey::from_secret_key(&s, &sk2).unwrap(), pk2);
664        assert!(sk2.add_assign(&s, &sk1).is_ok());
665        assert!(pk2.add_exp_assign(&s, &sk1).is_ok());
666        assert_eq!(PublicKey::from_secret_key(&s, &sk2).unwrap(), pk2);
667    }
668
669    #[test]
670    fn test_multiplication() {
671        let s = Secp256k1::new();
672
673        let (mut sk1, mut pk1) = s.generate_keypair(&mut thread_rng()).unwrap();
674        let (mut sk2, mut pk2) = s.generate_keypair(&mut thread_rng()).unwrap();
675
676        assert_eq!(PublicKey::from_secret_key(&s, &sk1).unwrap(), pk1);
677        assert!(sk1.mul_assign(&s, &sk2).is_ok());
678        assert!(pk1.mul_assign(&s, &sk2).is_ok());
679        assert_eq!(PublicKey::from_secret_key(&s, &sk1).unwrap(), pk1);
680
681        assert_eq!(PublicKey::from_secret_key(&s, &sk2).unwrap(), pk2);
682        assert!(sk2.mul_assign(&s, &sk1).is_ok());
683        assert!(pk2.mul_assign(&s, &sk1).is_ok());
684        assert_eq!(PublicKey::from_secret_key(&s, &sk2).unwrap(), pk2);
685    }
686
687    #[test]
688    fn pubkey_hash() {
689        use std::collections::hash_map::DefaultHasher;
690        use std::hash::{Hash, Hasher};
691        use std::collections::HashSet;
692
693        fn hash<T: Hash>(t: &T) -> u64 {
694            let mut s = DefaultHasher::new();
695            t.hash(&mut s);
696            s.finish()
697        }
698
699        let s = Secp256k1::new();
700        let mut set = HashSet::new();
701        const COUNT : usize = 1024;
702        let count = (0..COUNT).map(|_| {
703            let (_, pk) = s.generate_keypair(&mut thread_rng()).unwrap();
704            let hash = hash(&pk);
705            assert!(!set.contains(&hash));
706            set.insert(hash);
707        }).count();
708        assert_eq!(count, COUNT);
709    }
710}
711
712