cashweb_secp256k1/
lib.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//! # Secp256k1
17//! Rust bindings for Pieter Wuille's secp256k1 library, which is used for
18//! fast and accurate manipulation of ECDSA signatures on the secp256k1
19//! curve. Such signatures are used extensively by the Bitcoin network
20//! and its derivatives.
21//!
22//! To minimize dependencies, some functions are feature-gated. To generate
23//! random keys or to re-randomize a context object, compile with the "rand"
24//! feature. To de/serialize objects with serde, compile with "serde".
25//!
26//! Where possible, the bindings use the Rust type system to ensure that
27//! API usage errors are impossible. For example, the library uses context
28//! objects that contain precomputation tables which are created on object
29//! construction. Since this is a slow operation (10+ milliseconds, vs ~50
30//! microseconds for typical crypto operations, on a 2.70 Ghz i7-6820HQ)
31//! the tables are optional, giving a performance boost for users who only
32//! care about signing, only care about verification, or only care about
33//! parsing. In the upstream library, if you attempt to sign a message using
34//! a context that does not support this, it will trigger an assertion
35//! failure and terminate the program. In `rust-secp256k1`, this is caught
36//! at compile-time; in fact, it is impossible to compile code that will
37//! trigger any assertion failures in the upstream library.
38//!
39//! ```rust
40//! # #[cfg(all(feature="rand", feature="bitcoin_hashes"))] {
41//! use cashweb_secp256k1::rand::rngs::OsRng;
42//! use cashweb_secp256k1::{Secp256k1, Message};
43//! use cashweb_secp256k1::bitcoin_hashes::sha256;
44//!
45//! let secp = Secp256k1::new();
46//! let mut rng = OsRng::new().expect("OsRng");
47//! let (secret_key, public_key) = secp.generate_keypair(&mut rng);
48//! let message = Message::from_hashed_data::<sha256::Hash>("Hello World!".as_bytes());
49//!
50//! let sig = secp.sign(&message, &secret_key);
51//! assert!(secp.verify(&message, &sig, &public_key).is_ok());
52//! # }
53//! ```
54//!
55//! The above code requires `rust-secp256k1` to be compiled with the `rand` and `bitcoin_hashes`
56//! feature enabled, to get access to [`generate_keypair`](struct.Secp256k1.html#method.generate_keypair)
57//! Alternately, keys and messages can be parsed from slices, like
58//!
59//! ```rust
60//! use self::cashweb_secp256k1::{Secp256k1, Message, SecretKey, PublicKey};
61//!
62//! let secp = Secp256k1::new();
63//! let secret_key = SecretKey::from_slice(&[0xcd; 32]).expect("32 bytes, within curve order");
64//! let public_key = PublicKey::from_secret_key(&secp, &secret_key);
65//! // This is unsafe unless the supplied byte slice is the output of a cryptographic hash function.
66//! // See the above example for how to use this library together with bitcoin_hashes.
67//! let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
68//!
69//! let sig = secp.sign(&message, &secret_key);
70//! assert!(secp.verify(&message, &sig, &public_key).is_ok());
71//! ```
72//!
73//! Users who only want to verify signatures can use a cheaper context, like so:
74//!
75//! ```rust
76//! use cashweb_secp256k1::{Secp256k1, Message, Signature, PublicKey};
77//!
78//! let secp = Secp256k1::verification_only();
79//!
80//! let public_key = PublicKey::from_slice(&[
81//!     0x02,
82//!     0xc6, 0x6e, 0x7d, 0x89, 0x66, 0xb5, 0xc5, 0x55,
83//!     0xaf, 0x58, 0x05, 0x98, 0x9d, 0xa9, 0xfb, 0xf8,
84//!     0xdb, 0x95, 0xe1, 0x56, 0x31, 0xce, 0x35, 0x8c,
85//!     0x3a, 0x17, 0x10, 0xc9, 0x62, 0x67, 0x90, 0x63,
86//! ]).expect("public keys must be 33 or 65 bytes, serialized according to SEC 2");
87//!
88//! let message = Message::from_slice(&[
89//!     0xaa, 0xdf, 0x7d, 0xe7, 0x82, 0x03, 0x4f, 0xbe,
90//!     0x3d, 0x3d, 0xb2, 0xcb, 0x13, 0xc0, 0xcd, 0x91,
91//!     0xbf, 0x41, 0xcb, 0x08, 0xfa, 0xc7, 0xbd, 0x61,
92//!     0xd5, 0x44, 0x53, 0xcf, 0x6e, 0x82, 0xb4, 0x50,
93//! ]).expect("messages must be 32 bytes and are expected to be hashes");
94//!
95//! let sig = Signature::from_compact(&[
96//!     0xdc, 0x4d, 0xc2, 0x64, 0xa9, 0xfe, 0xf1, 0x7a,
97//!     0x3f, 0x25, 0x34, 0x49, 0xcf, 0x8c, 0x39, 0x7a,
98//!     0xb6, 0xf1, 0x6f, 0xb3, 0xd6, 0x3d, 0x86, 0x94,
99//!     0x0b, 0x55, 0x86, 0x82, 0x3d, 0xfd, 0x02, 0xae,
100//!     0x3b, 0x46, 0x1b, 0xb4, 0x33, 0x6b, 0x5e, 0xcb,
101//!     0xae, 0xfd, 0x66, 0x27, 0xaa, 0x92, 0x2e, 0xfc,
102//!     0x04, 0x8f, 0xec, 0x0c, 0x88, 0x1c, 0x10, 0xc4,
103//!     0xc9, 0x42, 0x8f, 0xca, 0x69, 0xc1, 0x32, 0xa2,
104//! ]).expect("compact signatures are 64 bytes; DER signatures are 68-72 bytes");
105//!
106//! # #[cfg(not(rust_secp_fuzz))]
107//! assert!(secp.verify(&message, &sig, &public_key).is_ok());
108//! ```
109//!
110//! Observe that the same code using, say [`signing_only`](struct.Secp256k1.html#method.signing_only)
111//! to generate a context would simply not compile.
112//!
113
114// Coding conventions
115#![deny(non_upper_case_globals)]
116#![deny(non_camel_case_types)]
117#![deny(non_snake_case)]
118#![deny(unused_mut)]
119#![warn(missing_docs)]
120#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
121#![cfg_attr(all(test, feature = "unstable"), feature(test))]
122
123#[macro_use]
124pub extern crate cashweb_secp256k1_sys;
125pub use cashweb_secp256k1_sys as ffi;
126
127#[cfg(feature = "bitcoin_hashes")]
128pub extern crate bitcoin_hashes;
129#[cfg(any(test, feature = "rand"))]
130pub extern crate rand;
131#[cfg(any(test))]
132extern crate rand_core;
133#[cfg(feature = "serde")]
134pub extern crate serde;
135#[cfg(all(test, feature = "serde"))]
136extern crate serde_test;
137#[cfg(all(test, feature = "unstable"))]
138extern crate test;
139#[cfg(any(test, feature = "rand"))]
140use rand::Rng;
141#[cfg(any(test, feature = "std"))]
142extern crate core;
143#[cfg(all(test, target_arch = "wasm32"))]
144extern crate wasm_bindgen_test;
145
146use core::{fmt, ptr, str};
147
148#[macro_use]
149mod macros;
150pub mod constants;
151mod context;
152pub mod ecdh;
153pub mod key;
154#[cfg(feature = "recovery")]
155pub mod recovery;
156pub mod schnorrsig;
157
158pub use context::*;
159use core::marker::PhantomData;
160use core::mem;
161use core::ops::Deref;
162use ffi::{types::AlignedType, CPtr};
163pub use key::PublicKey;
164pub use key::SecretKey;
165
166#[cfg(feature = "global-context")]
167pub use context::global::SECP256K1;
168
169#[cfg(feature = "bitcoin_hashes")]
170use bitcoin_hashes::Hash;
171
172/// An ECDSA signature
173#[derive(Copy, Clone, PartialEq, Eq)]
174pub struct Signature(ffi::Signature);
175
176/// A DER serialized Signature
177#[derive(Copy, Clone)]
178pub struct SerializedSignature {
179    data: [u8; 72],
180    len: usize,
181}
182
183impl fmt::Debug for Signature {
184    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
185        fmt::Display::fmt(self, f)
186    }
187}
188
189impl fmt::Display for Signature {
190    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191        let sig = self.serialize_der();
192        for v in sig.iter() {
193            write!(f, "{:02x}", v)?;
194        }
195        Ok(())
196    }
197}
198
199impl str::FromStr for Signature {
200    type Err = Error;
201    fn from_str(s: &str) -> Result<Signature, Error> {
202        let mut res = [0; 72];
203        match from_hex(s, &mut res) {
204            Ok(x) => Signature::from_der(&res[0..x]),
205            _ => Err(Error::InvalidSignature),
206        }
207    }
208}
209
210/// Trait describing something that promises to be a 32-byte random number; in particular,
211/// it has negligible probability of being zero or overflowing the group order. Such objects
212/// may be converted to `Message`s without any error paths.
213pub trait ThirtyTwoByteHash {
214    /// Converts the object into a 32-byte array
215    fn into_32(self) -> [u8; 32];
216}
217
218#[cfg(feature = "bitcoin_hashes")]
219impl ThirtyTwoByteHash for bitcoin_hashes::sha256::Hash {
220    fn into_32(self) -> [u8; 32] {
221        self.into_inner()
222    }
223}
224
225#[cfg(feature = "bitcoin_hashes")]
226impl ThirtyTwoByteHash for bitcoin_hashes::sha256d::Hash {
227    fn into_32(self) -> [u8; 32] {
228        self.into_inner()
229    }
230}
231
232#[cfg(feature = "bitcoin_hashes")]
233impl<T: bitcoin_hashes::sha256t::Tag> ThirtyTwoByteHash for bitcoin_hashes::sha256t::Hash<T> {
234    fn into_32(self) -> [u8; 32] {
235        self.into_inner()
236    }
237}
238
239impl SerializedSignature {
240    /// Get a pointer to the underlying data with the specified capacity.
241    pub(crate) fn get_data_mut_ptr(&mut self) -> *mut u8 {
242        self.data.as_mut_ptr()
243    }
244
245    /// Get the capacity of the underlying data buffer.
246    pub fn capacity(&self) -> usize {
247        self.data.len()
248    }
249
250    /// Get the len of the used data.
251    pub fn len(&self) -> usize {
252        self.len
253    }
254
255    /// Set the length of the object.
256    pub(crate) fn set_len(&mut self, len: usize) {
257        self.len = len;
258    }
259
260    /// Convert the serialized signature into the Signature struct.
261    /// (This DER deserializes it)
262    pub fn to_signature(&self) -> Result<Signature, Error> {
263        Signature::from_der(&self)
264    }
265
266    /// Create a SerializedSignature from a Signature.
267    /// (this DER serializes it)
268    pub fn from_signature(sig: &Signature) -> SerializedSignature {
269        sig.serialize_der()
270    }
271
272    /// Check if the space is zero.
273    pub fn is_empty(&self) -> bool {
274        self.len() == 0
275    }
276}
277
278impl Signature {
279    #[inline]
280    /// Converts a DER-encoded byte slice to a signature
281    pub fn from_der(data: &[u8]) -> Result<Signature, Error> {
282        if data.is_empty() {
283            return Err(Error::InvalidSignature);
284        }
285
286        unsafe {
287            let mut ret = ffi::Signature::new();
288            if ffi::secp256k1_ecdsa_signature_parse_der(
289                ffi::secp256k1_context_no_precomp,
290                &mut ret,
291                data.as_c_ptr(),
292                data.len() as usize,
293            ) == 1
294            {
295                Ok(Signature(ret))
296            } else {
297                Err(Error::InvalidSignature)
298            }
299        }
300    }
301
302    /// Converts a 64-byte compact-encoded byte slice to a signature
303    pub fn from_compact(data: &[u8]) -> Result<Signature, Error> {
304        if data.len() != 64 {
305            return Err(Error::InvalidSignature);
306        }
307
308        unsafe {
309            let mut ret = ffi::Signature::new();
310            if ffi::secp256k1_ecdsa_signature_parse_compact(
311                ffi::secp256k1_context_no_precomp,
312                &mut ret,
313                data.as_c_ptr(),
314            ) == 1
315            {
316                Ok(Signature(ret))
317            } else {
318                Err(Error::InvalidSignature)
319            }
320        }
321    }
322
323    /// Converts a "lax DER"-encoded byte slice to a signature. This is basically
324    /// only useful for validating signatures in the Bitcoin blockchain from before
325    /// 2016. It should never be used in new applications. This library does not
326    /// support serializing to this "format"
327    pub fn from_der_lax(data: &[u8]) -> Result<Signature, Error> {
328        if data.is_empty() {
329            return Err(Error::InvalidSignature);
330        }
331
332        unsafe {
333            let mut ret = ffi::Signature::new();
334            if ffi::ecdsa_signature_parse_der_lax(
335                ffi::secp256k1_context_no_precomp,
336                &mut ret,
337                data.as_c_ptr(),
338                data.len() as usize,
339            ) == 1
340            {
341                Ok(Signature(ret))
342            } else {
343                Err(Error::InvalidSignature)
344            }
345        }
346    }
347
348    /// Normalizes a signature to a "low S" form. In ECDSA, signatures are
349    /// of the form (r, s) where r and s are numbers lying in some finite
350    /// field. The verification equation will pass for (r, s) iff it passes
351    /// for (r, -s), so it is possible to ``modify'' signatures in transit
352    /// by flipping the sign of s. This does not constitute a forgery since
353    /// the signed message still cannot be changed, but for some applications,
354    /// changing even the signature itself can be a problem. Such applications
355    /// require a "strong signature". It is believed that ECDSA is a strong
356    /// signature except for this ambiguity in the sign of s, so to accommodate
357    /// these applications libsecp256k1 will only accept signatures for which
358    /// s is in the lower half of the field range. This eliminates the
359    /// ambiguity.
360    ///
361    /// However, for some systems, signatures with high s-values are considered
362    /// valid. (For example, parsing the historic Bitcoin blockchain requires
363    /// this.) For these applications we provide this normalization function,
364    /// which ensures that the s value lies in the lower half of its range.
365    pub fn normalize_s(&mut self) {
366        unsafe {
367            // Ignore return value, which indicates whether the sig
368            // was already normalized. We don't care.
369            ffi::secp256k1_ecdsa_signature_normalize(
370                ffi::secp256k1_context_no_precomp,
371                self.as_mut_c_ptr(),
372                self.as_c_ptr(),
373            );
374        }
375    }
376
377    /// Obtains a raw pointer suitable for use with FFI functions
378    #[inline]
379    pub fn as_ptr(&self) -> *const ffi::Signature {
380        &self.0
381    }
382
383    /// Obtains a raw mutable pointer suitable for use with FFI functions
384    #[inline]
385    pub fn as_mut_ptr(&mut self) -> *mut ffi::Signature {
386        &mut self.0
387    }
388
389    #[inline]
390    /// Serializes the signature in DER format
391    pub fn serialize_der(&self) -> SerializedSignature {
392        let mut ret = SerializedSignature::default();
393        let mut len: usize = ret.capacity();
394        unsafe {
395            let err = ffi::secp256k1_ecdsa_signature_serialize_der(
396                ffi::secp256k1_context_no_precomp,
397                ret.get_data_mut_ptr(),
398                &mut len,
399                self.as_c_ptr(),
400            );
401            debug_assert!(err == 1);
402            ret.set_len(len);
403        }
404        ret
405    }
406
407    #[inline]
408    /// Serializes the signature in compact format
409    pub fn serialize_compact(&self) -> [u8; 64] {
410        let mut ret = [0; 64];
411        unsafe {
412            let err = ffi::secp256k1_ecdsa_signature_serialize_compact(
413                ffi::secp256k1_context_no_precomp,
414                ret.as_mut_c_ptr(),
415                self.as_c_ptr(),
416            );
417            debug_assert!(err == 1);
418        }
419        ret
420    }
421}
422
423impl CPtr for Signature {
424    type Target = ffi::Signature;
425    fn as_c_ptr(&self) -> *const Self::Target {
426        self.as_ptr()
427    }
428
429    fn as_mut_c_ptr(&mut self) -> *mut Self::Target {
430        self.as_mut_ptr()
431    }
432}
433
434/// Creates a new signature from a FFI signature
435impl From<ffi::Signature> for Signature {
436    #[inline]
437    fn from(sig: ffi::Signature) -> Signature {
438        Signature(sig)
439    }
440}
441
442#[cfg(feature = "serde")]
443impl ::serde::Serialize for Signature {
444    fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
445        if s.is_human_readable() {
446            s.collect_str(self)
447        } else {
448            s.serialize_bytes(&self.serialize_der())
449        }
450    }
451}
452
453#[cfg(feature = "serde")]
454impl<'de> ::serde::Deserialize<'de> for Signature {
455    fn deserialize<D: ::serde::Deserializer<'de>>(d: D) -> Result<Signature, D::Error> {
456        use serde::de::Error;
457        use str::FromStr;
458        if d.is_human_readable() {
459            let sl: &str = ::serde::Deserialize::deserialize(d)?;
460            Signature::from_str(sl).map_err(D::Error::custom)
461        } else {
462            let sl: &[u8] = ::serde::Deserialize::deserialize(d)?;
463            Signature::from_der(sl).map_err(D::Error::custom)
464        }
465    }
466}
467
468/// A (hashed) message input to an ECDSA signature
469pub struct Message([u8; constants::MESSAGE_SIZE]);
470impl_array_newtype!(Message, u8, constants::MESSAGE_SIZE);
471impl_pretty_debug!(Message);
472
473impl Message {
474    /// **If you just want to sign an arbitrary message use `Message::from_hashed_data` instead.**
475    ///
476    /// Converts a `MESSAGE_SIZE`-byte slice to a message object. **WARNING:** the slice has to be a
477    /// cryptographically secure hash of the actual message that's going to be signed. Otherwise
478    /// the result of signing isn't a
479    /// [secure signature](https://twitter.com/pwuille/status/1063582706288586752).
480    #[inline]
481    pub fn from_slice(data: &[u8]) -> Result<Message, Error> {
482        match data.len() {
483            constants::MESSAGE_SIZE => {
484                let mut ret = [0; constants::MESSAGE_SIZE];
485                ret[..].copy_from_slice(data);
486                Ok(Message(ret))
487            }
488            _ => Err(Error::InvalidMessage),
489        }
490    }
491
492    /// Constructs a `Message` by hashing `data` with hash algorithm `H`. This requires the feature
493    /// `bitcoin_hashes` to be enabled.
494    /// ```rust
495    /// extern crate bitcoin_hashes;
496    /// # extern crate cashweb_secp256k1;
497    /// use cashweb_secp256k1::Message;
498    /// use bitcoin_hashes::sha256;
499    /// use bitcoin_hashes::Hash;
500    ///
501    /// let m1 = Message::from_hashed_data::<sha256::Hash>("Hello world!".as_bytes());
502    /// // is equivalent to
503    /// let m2 = Message::from(sha256::Hash::hash("Hello world!".as_bytes()));
504    ///
505    /// assert_eq!(m1, m2);
506    /// ```
507    #[cfg(feature = "bitcoin_hashes")]
508    pub fn from_hashed_data<H: ThirtyTwoByteHash + bitcoin_hashes::Hash>(data: &[u8]) -> Self {
509        <H as bitcoin_hashes::Hash>::hash(data).into()
510    }
511}
512
513impl<T: ThirtyTwoByteHash> From<T> for Message {
514    /// Converts a 32-byte hash directly to a message without error paths
515    fn from(t: T) -> Message {
516        Message(t.into_32())
517    }
518}
519
520/// An ECDSA error
521#[derive(Copy, PartialEq, Eq, Clone, Debug)]
522pub enum Error {
523    /// Signature failed verification
524    IncorrectSignature,
525    /// Badly sized message ("messages" are actually fixed-sized digests; see the `MESSAGE_SIZE`
526    /// constant)
527    InvalidMessage,
528    /// Bad public key
529    InvalidPublicKey,
530    /// Bad signature
531    InvalidSignature,
532    /// Bad secret key
533    InvalidSecretKey,
534    /// Bad recovery id
535    InvalidRecoveryId,
536    /// Invalid tweak for add_*_assign or mul_*_assign
537    InvalidTweak,
538    /// `tweak_add_check` failed on an xonly public key
539    TweakCheckFailed,
540    /// Didn't pass enough memory to context creation with preallocated memory
541    NotEnoughMemory,
542}
543
544impl Error {
545    fn as_str(&self) -> &str {
546        match *self {
547            Error::IncorrectSignature => "secp: signature failed verification",
548            Error::InvalidMessage => "secp: message was not 32 bytes (do you need to hash?)",
549            Error::InvalidPublicKey => "secp: malformed public key",
550            Error::InvalidSignature => "secp: malformed signature",
551            Error::InvalidSecretKey => "secp: malformed or out-of-range secret key",
552            Error::InvalidRecoveryId => "secp: bad recovery id",
553            Error::InvalidTweak => "secp: bad tweak",
554            Error::TweakCheckFailed => "secp: xonly_pubkey_tewak_add_check failed",
555            Error::NotEnoughMemory => "secp: not enough memory allocated",
556        }
557    }
558}
559
560// Passthrough Debug to Display, since errors should be user-visible
561impl fmt::Display for Error {
562    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
563        f.write_str(self.as_str())
564    }
565}
566
567#[cfg(feature = "std")]
568impl std::error::Error for Error {}
569
570/// The secp256k1 engine, used to execute all signature operations
571pub struct Secp256k1<C: Context> {
572    ctx: *mut ffi::Context,
573    phantom: PhantomData<C>,
574    size: usize,
575}
576
577// The underlying secp context does not contain any references to memory it does not own
578unsafe impl<C: Context> Send for Secp256k1<C> {}
579// The API does not permit any mutation of `Secp256k1` objects except through `&mut` references
580unsafe impl<C: Context> Sync for Secp256k1<C> {}
581
582impl<C: Context> PartialEq for Secp256k1<C> {
583    fn eq(&self, _other: &Secp256k1<C>) -> bool {
584        true
585    }
586}
587
588impl Default for SerializedSignature {
589    fn default() -> SerializedSignature {
590        SerializedSignature {
591            data: [0u8; 72],
592            len: 0,
593        }
594    }
595}
596
597impl PartialEq for SerializedSignature {
598    fn eq(&self, other: &SerializedSignature) -> bool {
599        self.data[..self.len] == other.data[..other.len]
600    }
601}
602
603impl AsRef<[u8]> for SerializedSignature {
604    fn as_ref(&self) -> &[u8] {
605        &self.data[..self.len]
606    }
607}
608
609impl Deref for SerializedSignature {
610    type Target = [u8];
611    fn deref(&self) -> &[u8] {
612        &self.data[..self.len]
613    }
614}
615
616impl Eq for SerializedSignature {}
617
618impl<C: Context> Eq for Secp256k1<C> {}
619
620impl<C: Context> Drop for Secp256k1<C> {
621    fn drop(&mut self) {
622        unsafe {
623            ffi::secp256k1_context_preallocated_destroy(self.ctx);
624            C::deallocate(self.ctx as _, self.size);
625        }
626    }
627}
628
629impl<C: Context> fmt::Debug for Secp256k1<C> {
630    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631        write!(f, "<secp256k1 context {:?}, {}>", self.ctx, C::DESCRIPTION)
632    }
633}
634
635impl<C: Context> Secp256k1<C> {
636    /// Getter for the raw pointer to the underlying secp256k1 context. This
637    /// shouldn't be needed with normal usage of the library. It enables
638    /// extending the Secp256k1 with more cryptographic algorithms outside of
639    /// this crate.
640    pub fn ctx(&self) -> &*mut ffi::Context {
641        &self.ctx
642    }
643
644    /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all)
645    pub fn preallocate_size_gen() -> usize {
646        let word_size = mem::size_of::<AlignedType>();
647        let bytes = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
648
649        (bytes + word_size - 1) / word_size
650    }
651
652    /// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance;
653    /// see comment in libsecp256k1 commit d2275795f by Gregory Maxwell. Requires
654    /// compilation with "rand" feature.
655    #[cfg(any(test, feature = "rand"))]
656    pub fn randomize<R: Rng + ?Sized>(&mut self, rng: &mut R) {
657        let mut seed = [0; 32];
658        rng.fill_bytes(&mut seed);
659        self.seeded_randomize(&seed);
660    }
661
662    /// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance given 32 bytes of
663    /// cryptographically-secure random data;
664    /// see comment in libsecp256k1 commit d2275795f by Gregory Maxwell.
665    pub fn seeded_randomize(&mut self, seed: &[u8; 32]) {
666        unsafe {
667            let err = ffi::secp256k1_context_randomize(self.ctx, seed.as_c_ptr());
668            // This function cannot fail; it has an error return for future-proofing.
669            // We do not expose this error since it is impossible to hit, and we have
670            // precedent for not exposing impossible errors (for example in
671            // `PublicKey::from_secret_key` where it is impossible to create an invalid
672            // secret key through the API.)
673            // However, if this DOES fail, the result is potentially weaker side-channel
674            // resistance, which is deadly and undetectable, so we take out the entire
675            // thread to be on the safe side.
676            assert_eq!(err, 1);
677        }
678    }
679}
680
681fn der_length_check(sig: &ffi::Signature, max_len: usize) -> bool {
682    let mut ser_ret = [0; 72];
683    let mut len: usize = ser_ret.len();
684    unsafe {
685        let err = ffi::secp256k1_ecdsa_signature_serialize_der(
686            ffi::secp256k1_context_no_precomp,
687            ser_ret.as_mut_c_ptr(),
688            &mut len,
689            sig,
690        );
691        debug_assert!(err == 1);
692    }
693    len <= max_len
694}
695
696fn compact_sig_has_zero_first_bit(sig: &ffi::Signature) -> bool {
697    let mut compact = [0; 64];
698    unsafe {
699        let err = ffi::secp256k1_ecdsa_signature_serialize_compact(
700            ffi::secp256k1_context_no_precomp,
701            compact.as_mut_c_ptr(),
702            sig,
703        );
704        debug_assert!(err == 1);
705    }
706    compact[0] < 0x80
707}
708
709impl<C: Signing> Secp256k1<C> {
710    /// Constructs a signature for `msg` using the secret key `sk` and RFC6979 nonce
711    /// Requires a signing-capable context.
712    pub fn sign(&self, msg: &Message, sk: &key::SecretKey) -> Signature {
713        unsafe {
714            let mut ret = ffi::Signature::new();
715            // We can assume the return value because it's not possible to construct
716            // an invalid signature from a valid `Message` and `SecretKey`
717            assert_eq!(
718                ffi::secp256k1_ecdsa_sign(
719                    self.ctx,
720                    &mut ret,
721                    msg.as_c_ptr(),
722                    sk.as_c_ptr(),
723                    ffi::secp256k1_nonce_function_rfc6979,
724                    ptr::null()
725                ),
726                1
727            );
728            Signature::from(ret)
729        }
730    }
731
732    fn sign_grind_with_check(
733        &self,
734        msg: &Message,
735        sk: &key::SecretKey,
736        check: impl Fn(&ffi::Signature) -> bool,
737    ) -> Signature {
738        let mut entropy_p: *const ffi::types::c_void = ptr::null();
739        let mut counter: u32 = 0;
740        let mut extra_entropy = [0u8; 32];
741        loop {
742            unsafe {
743                let mut ret = ffi::Signature::new();
744                // We can assume the return value because it's not possible to construct
745                // an invalid signature from a valid `Message` and `SecretKey`
746                assert_eq!(
747                    ffi::secp256k1_ecdsa_sign(
748                        self.ctx,
749                        &mut ret,
750                        msg.as_c_ptr(),
751                        sk.as_c_ptr(),
752                        ffi::secp256k1_nonce_function_rfc6979,
753                        entropy_p
754                    ),
755                    1
756                );
757                if check(&ret) {
758                    return Signature::from(ret);
759                }
760
761                counter += 1;
762                // From 1.32 can use `to_le_bytes` instead
763                let le_counter = counter.to_le();
764                let le_counter_bytes: [u8; 4] = mem::transmute(le_counter);
765                for (i, b) in le_counter_bytes.iter().enumerate() {
766                    extra_entropy[i] = *b;
767                }
768
769                entropy_p = extra_entropy.as_ptr() as *const ffi::types::c_void;
770
771                // When fuzzing, these checks will usually spinloop forever, so just short-circuit them.
772                #[cfg(rust_secp_fuzz)]
773                return Signature::from(ret);
774            }
775        }
776    }
777
778    /// Constructs a signature for `msg` using the secret key `sk`, RFC6979 nonce
779    /// and "grinds" the nonce by passing extra entropy if necessary to produce
780    /// a signature that is less than 71 - bytes_to_grund bytes. The number
781    /// of signing operation performed by this function is exponential in the
782    /// number of bytes grinded.
783    /// Requires a signing capable context.
784    pub fn sign_grind_r(
785        &self,
786        msg: &Message,
787        sk: &key::SecretKey,
788        bytes_to_grind: usize,
789    ) -> Signature {
790        let len_check = |s: &ffi::Signature| der_length_check(s, 71 - bytes_to_grind);
791        return self.sign_grind_with_check(msg, sk, len_check);
792    }
793
794    /// Constructs a signature for `msg` using the secret key `sk`, RFC6979 nonce
795    /// and "grinds" the nonce by passing extra entropy if necessary to produce
796    /// a signature that is less than 71 bytes and compatible with the low r
797    /// signature implementation of bitcoin core. In average, this function
798    /// will perform two signing operations.
799    /// Requires a signing capable context.
800    pub fn sign_low_r(&self, msg: &Message, sk: &key::SecretKey) -> Signature {
801        return self.sign_grind_with_check(msg, sk, compact_sig_has_zero_first_bit);
802    }
803
804    /// Generates a random keypair. Convenience function for `key::SecretKey::new`
805    /// and `key::PublicKey::from_secret_key`; call those functions directly for
806    /// batch key generation. Requires a signing-capable context. Requires compilation
807    /// with the "rand" feature.
808    #[inline]
809    #[cfg(any(test, feature = "rand"))]
810    pub fn generate_keypair<R: Rng + ?Sized>(
811        &self,
812        rng: &mut R,
813    ) -> (key::SecretKey, key::PublicKey) {
814        let sk = key::SecretKey::new(rng);
815        let pk = key::PublicKey::from_secret_key(self, &sk);
816        (sk, pk)
817    }
818}
819
820impl<C: Verification> Secp256k1<C> {
821    /// Checks that `sig` is a valid ECDSA signature for `msg` using the public
822    /// key `pubkey`. Returns `Ok(())` on success. Note that this function cannot
823    /// be used for Bitcoin consensus checking since there may exist signatures
824    /// which OpenSSL would verify but not libsecp256k1, or vice-versa. Requires a
825    /// verify-capable context.
826    ///
827    /// ```rust
828    /// # #[cfg(feature="rand")] {
829    /// # use cashweb_secp256k1::rand::rngs::OsRng;
830    /// # use cashweb_secp256k1::{Secp256k1, Message, Error};
831    /// #
832    /// # let secp = Secp256k1::new();
833    /// # let mut rng = OsRng::new().expect("OsRng");
834    /// # let (secret_key, public_key) = secp.generate_keypair(&mut rng);
835    /// #
836    /// let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
837    /// let sig = secp.sign(&message, &secret_key);
838    /// assert_eq!(secp.verify(&message, &sig, &public_key), Ok(()));
839    ///
840    /// let message = Message::from_slice(&[0xcd; 32]).expect("32 bytes");
841    /// assert_eq!(secp.verify(&message, &sig, &public_key), Err(Error::IncorrectSignature));
842    /// # }
843    /// ```
844    #[inline]
845    pub fn verify(&self, msg: &Message, sig: &Signature, pk: &key::PublicKey) -> Result<(), Error> {
846        unsafe {
847            if ffi::secp256k1_ecdsa_verify(self.ctx, sig.as_c_ptr(), msg.as_c_ptr(), pk.as_c_ptr())
848                == 0
849            {
850                Err(Error::IncorrectSignature)
851            } else {
852                Ok(())
853            }
854        }
855    }
856}
857
858/// Utility function used to parse hex into a target u8 buffer. Returns
859/// the number of bytes converted or an error if it encounters an invalid
860/// character or unexpected end of string.
861fn from_hex(hex: &str, target: &mut [u8]) -> Result<usize, ()> {
862    if hex.len() % 2 == 1 || hex.len() > target.len() * 2 {
863        return Err(());
864    }
865
866    let mut b = 0;
867    let mut idx = 0;
868    for c in hex.bytes() {
869        b <<= 4;
870        match c {
871            b'A'..=b'F' => b |= c - b'A' + 10,
872            b'a'..=b'f' => b |= c - b'a' + 10,
873            b'0'..=b'9' => b |= c - b'0',
874            _ => return Err(()),
875        }
876        if (idx & 1) == 1 {
877            target[idx / 2] = b;
878            b = 0;
879        }
880        idx += 1;
881    }
882    Ok(idx / 2)
883}
884
885#[cfg(test)]
886mod tests {
887    use rand::{thread_rng, RngCore};
888    use std::marker::PhantomData;
889    use std::str::FromStr;
890
891    use super::constants;
892    use super::from_hex;
893    use super::Error::{IncorrectSignature, InvalidMessage, InvalidSignature};
894    use super::{Message, Secp256k1, Signature};
895    use context::*;
896    use ffi::{self, types::AlignedType};
897    use key::{PublicKey, SecretKey};
898
899    #[cfg(target_arch = "wasm32")]
900    use wasm_bindgen_test::wasm_bindgen_test as test;
901
902    macro_rules! hex {
903        ($hex:expr) => {{
904            let mut result = vec![0; $hex.len() / 2];
905            from_hex($hex, &mut result).expect("valid hex string");
906            result
907        }};
908    }
909
910    #[test]
911    fn test_manual_create_destroy() {
912        let ctx_full = unsafe { ffi::secp256k1_context_create(AllPreallocated::FLAGS) };
913        let ctx_sign = unsafe { ffi::secp256k1_context_create(SignOnlyPreallocated::FLAGS) };
914        let ctx_vrfy = unsafe { ffi::secp256k1_context_create(VerifyOnlyPreallocated::FLAGS) };
915
916        let size = 0;
917        let full: Secp256k1<AllPreallocated> = Secp256k1 {
918            ctx: ctx_full,
919            phantom: PhantomData,
920            size,
921        };
922        let sign: Secp256k1<SignOnlyPreallocated> = Secp256k1 {
923            ctx: ctx_sign,
924            phantom: PhantomData,
925            size,
926        };
927        let vrfy: Secp256k1<VerifyOnlyPreallocated> = Secp256k1 {
928            ctx: ctx_vrfy,
929            phantom: PhantomData,
930            size,
931        };
932
933        let (sk, pk) = full.generate_keypair(&mut thread_rng());
934        let msg = Message::from_slice(&[2u8; 32]).unwrap();
935        // Try signing
936        assert_eq!(sign.sign(&msg, &sk), full.sign(&msg, &sk));
937        let sig = full.sign(&msg, &sk);
938
939        // Try verifying
940        assert!(vrfy.verify(&msg, &sig, &pk).is_ok());
941        assert!(full.verify(&msg, &sig, &pk).is_ok());
942
943        drop(full);
944        drop(sign);
945        drop(vrfy);
946
947        unsafe { ffi::secp256k1_context_destroy(ctx_vrfy) };
948        unsafe { ffi::secp256k1_context_destroy(ctx_sign) };
949        unsafe { ffi::secp256k1_context_destroy(ctx_full) };
950    }
951
952    #[test]
953    fn test_raw_ctx() {
954        use std::mem::ManuallyDrop;
955
956        let ctx_full = Secp256k1::new();
957        let ctx_sign = Secp256k1::signing_only();
958        let ctx_vrfy = Secp256k1::verification_only();
959
960        let mut full = unsafe { Secp256k1::from_raw_all(ctx_full.ctx) };
961        let mut sign = unsafe { Secp256k1::from_raw_signining_only(ctx_sign.ctx) };
962        let mut vrfy = unsafe { Secp256k1::from_raw_verification_only(ctx_vrfy.ctx) };
963
964        let (sk, pk) = full.generate_keypair(&mut thread_rng());
965        let msg = Message::from_slice(&[2u8; 32]).unwrap();
966        // Try signing
967        assert_eq!(sign.sign(&msg, &sk), full.sign(&msg, &sk));
968        let sig = full.sign(&msg, &sk);
969
970        // Try verifying
971        assert!(vrfy.verify(&msg, &sig, &pk).is_ok());
972        assert!(full.verify(&msg, &sig, &pk).is_ok());
973
974        unsafe {
975            ManuallyDrop::drop(&mut full);
976            ManuallyDrop::drop(&mut sign);
977            ManuallyDrop::drop(&mut vrfy);
978        }
979        drop(ctx_full);
980        drop(ctx_sign);
981        drop(ctx_vrfy);
982    }
983
984    #[cfg(not(target_arch = "wasm32"))]
985    #[test]
986    #[should_panic]
987    fn test_panic_raw_ctx() {
988        let ctx_vrfy = Secp256k1::verification_only();
989        let raw_ctx_verify_as_full = unsafe { Secp256k1::from_raw_all(ctx_vrfy.ctx) };
990        let (sk, _) = raw_ctx_verify_as_full.generate_keypair(&mut thread_rng());
991        let msg = Message::from_slice(&[2u8; 32]).unwrap();
992        // Try signing
993        raw_ctx_verify_as_full.sign(&msg, &sk);
994    }
995
996    #[test]
997    fn test_preallocation() {
998        let mut buf_ful = vec![AlignedType::zeroed(); Secp256k1::preallocate_size()];
999        let mut buf_sign = vec![AlignedType::zeroed(); Secp256k1::preallocate_signing_size()];
1000        let mut buf_vfy = vec![AlignedType::zeroed(); Secp256k1::preallocate_verification_size()];
1001
1002        let full = Secp256k1::preallocated_new(&mut buf_ful).unwrap();
1003        let sign = Secp256k1::preallocated_signing_only(&mut buf_sign).unwrap();
1004        let vrfy = Secp256k1::preallocated_verification_only(&mut buf_vfy).unwrap();
1005
1006        //        drop(buf_vfy); // The buffer can't get dropped before the context.
1007        //        println!("{:?}", buf_ful[5]); // Can't even read the data thanks to the borrow checker.
1008
1009        let (sk, pk) = full.generate_keypair(&mut thread_rng());
1010        let msg = Message::from_slice(&[2u8; 32]).unwrap();
1011        // Try signing
1012        assert_eq!(sign.sign(&msg, &sk), full.sign(&msg, &sk));
1013        let sig = full.sign(&msg, &sk);
1014
1015        // Try verifying
1016        assert!(vrfy.verify(&msg, &sig, &pk).is_ok());
1017        assert!(full.verify(&msg, &sig, &pk).is_ok());
1018    }
1019
1020    #[test]
1021    fn capabilities() {
1022        let sign = Secp256k1::signing_only();
1023        let vrfy = Secp256k1::verification_only();
1024        let full = Secp256k1::new();
1025
1026        let mut msg = [0u8; 32];
1027        thread_rng().fill_bytes(&mut msg);
1028        let msg = Message::from_slice(&msg).unwrap();
1029
1030        // Try key generation
1031        let (sk, pk) = full.generate_keypair(&mut thread_rng());
1032
1033        // Try signing
1034        assert_eq!(sign.sign(&msg, &sk), full.sign(&msg, &sk));
1035        let sig = full.sign(&msg, &sk);
1036
1037        // Try verifying
1038        assert!(vrfy.verify(&msg, &sig, &pk).is_ok());
1039        assert!(full.verify(&msg, &sig, &pk).is_ok());
1040
1041        // Check that we can produce keys from slices with no precomputation
1042        let (pk_slice, sk_slice) = (&pk.serialize(), &sk[..]);
1043        let new_pk = PublicKey::from_slice(pk_slice).unwrap();
1044        let new_sk = SecretKey::from_slice(sk_slice).unwrap();
1045        assert_eq!(sk, new_sk);
1046        assert_eq!(pk, new_pk);
1047    }
1048
1049    #[test]
1050    fn signature_serialize_roundtrip() {
1051        let mut s = Secp256k1::new();
1052        s.randomize(&mut thread_rng());
1053
1054        let mut msg = [0; 32];
1055        for _ in 0..100 {
1056            thread_rng().fill_bytes(&mut msg);
1057            let msg = Message::from_slice(&msg).unwrap();
1058
1059            let (sk, _) = s.generate_keypair(&mut thread_rng());
1060            let sig1 = s.sign(&msg, &sk);
1061            let der = sig1.serialize_der();
1062            let sig2 = Signature::from_der(&der[..]).unwrap();
1063            assert_eq!(sig1, sig2);
1064
1065            let compact = sig1.serialize_compact();
1066            let sig2 = Signature::from_compact(&compact[..]).unwrap();
1067            assert_eq!(sig1, sig2);
1068
1069            assert!(Signature::from_compact(&der[..]).is_err());
1070            assert!(Signature::from_compact(&compact[0..4]).is_err());
1071            assert!(Signature::from_der(&compact[..]).is_err());
1072            assert!(Signature::from_der(&der[0..4]).is_err());
1073        }
1074    }
1075
1076    #[test]
1077    fn signature_display() {
1078        let hex_str = "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45";
1079        let byte_str = hex!(hex_str);
1080
1081        assert_eq!(
1082            Signature::from_der(&byte_str).expect("byte str decode"),
1083            Signature::from_str(&hex_str).expect("byte str decode")
1084        );
1085
1086        let sig = Signature::from_str(&hex_str).expect("byte str decode");
1087        assert_eq!(&sig.to_string(), hex_str);
1088        assert_eq!(&format!("{:?}", sig), hex_str);
1089
1090        assert!(Signature::from_str(
1091            "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
1092             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab4"
1093        )
1094        .is_err());
1095        assert!(Signature::from_str(
1096            "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
1097             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab"
1098        )
1099        .is_err());
1100        assert!(Signature::from_str(
1101            "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
1102             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eabxx"
1103        )
1104        .is_err());
1105        assert!(Signature::from_str(
1106            "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
1107             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
1108             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
1109             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
1110             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
1111             72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45"
1112        )
1113        .is_err());
1114
1115        // 71 byte signature
1116        let hex_str = "30450221009d0bad576719d32ae76bedb34c774866673cbde3f4e12951555c9408e6ce774b02202876e7102f204f6bfee26c967c3926ce702cf97d4b010062e193f763190f6776";
1117        let sig = Signature::from_str(&hex_str).expect("byte str decode");
1118        assert_eq!(&format!("{}", sig), hex_str);
1119    }
1120
1121    #[test]
1122    fn signature_lax_der() {
1123        macro_rules! check_lax_sig(
1124            ($hex:expr) => ({
1125                let sig = hex!($hex);
1126                assert!(Signature::from_der_lax(&sig[..]).is_ok());
1127            })
1128        );
1129
1130        check_lax_sig!("304402204c2dd8a9b6f8d425fcd8ee9a20ac73b619906a6367eac6cb93e70375225ec0160220356878eff111ff3663d7e6bf08947f94443845e0dcc54961664d922f7660b80c");
1131        check_lax_sig!("304402202ea9d51c7173b1d96d331bd41b3d1b4e78e66148e64ed5992abd6ca66290321c0220628c47517e049b3e41509e9d71e480a0cdc766f8cdec265ef0017711c1b5336f");
1132        check_lax_sig!("3045022100bf8e050c85ffa1c313108ad8c482c4849027937916374617af3f2e9a881861c9022023f65814222cab09d5ec41032ce9c72ca96a5676020736614de7b78a4e55325a");
1133        check_lax_sig!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45");
1134        check_lax_sig!("3046022100eaa5f90483eb20224616775891397d47efa64c68b969db1dacb1c30acdfc50aa022100cf9903bbefb1c8000cf482b0aeeb5af19287af20bd794de11d82716f9bae3db1");
1135        check_lax_sig!("3045022047d512bc85842ac463ca3b669b62666ab8672ee60725b6c06759e476cebdc6c102210083805e93bd941770109bcc797784a71db9e48913f702c56e60b1c3e2ff379a60");
1136        check_lax_sig!("3044022023ee4e95151b2fbbb08a72f35babe02830d14d54bd7ed1320e4751751d1baa4802206235245254f58fd1be6ff19ca291817da76da65c2f6d81d654b5185dd86b8acf");
1137    }
1138
1139    #[test]
1140    fn sign_and_verify() {
1141        let mut s = Secp256k1::new();
1142        s.randomize(&mut thread_rng());
1143
1144        let mut msg = [0; 32];
1145        for _ in 0..100 {
1146            thread_rng().fill_bytes(&mut msg);
1147            let msg = Message::from_slice(&msg).unwrap();
1148
1149            let (sk, pk) = s.generate_keypair(&mut thread_rng());
1150            let sig = s.sign(&msg, &sk);
1151            assert_eq!(s.verify(&msg, &sig, &pk), Ok(()));
1152            let low_r_sig = s.sign_low_r(&msg, &sk);
1153            assert_eq!(s.verify(&msg, &low_r_sig, &pk), Ok(()));
1154            let grind_r_sig = s.sign_grind_r(&msg, &sk, 1);
1155            assert_eq!(s.verify(&msg, &grind_r_sig, &pk), Ok(()));
1156            let compact = sig.serialize_compact();
1157            if compact[0] < 0x80 {
1158                assert_eq!(sig, low_r_sig);
1159            } else {
1160                #[cfg(not(rust_secp_fuzz))] // mocked sig generation doesn't produce low-R sigs
1161                assert_ne!(sig, low_r_sig);
1162            }
1163            #[cfg(not(rust_secp_fuzz))] // mocked sig generation doesn't produce low-R sigs
1164            assert!(super::compact_sig_has_zero_first_bit(&low_r_sig.0));
1165            #[cfg(not(rust_secp_fuzz))] // mocked sig generation doesn't produce low-R sigs
1166            assert!(super::der_length_check(&grind_r_sig.0, 70));
1167        }
1168    }
1169
1170    #[test]
1171    fn sign_and_verify_extreme() {
1172        let mut s = Secp256k1::new();
1173        s.randomize(&mut thread_rng());
1174
1175        // Wild keys: 1, CURVE_ORDER - 1
1176        // Wild msgs: 1, CURVE_ORDER - 1
1177        let mut wild_keys = [[0; 32]; 2];
1178        let mut wild_msgs = [[0; 32]; 2];
1179
1180        wild_keys[0][0] = 1;
1181        wild_msgs[0][0] = 1;
1182
1183        use constants;
1184        wild_keys[1][..].copy_from_slice(&constants::CURVE_ORDER[..]);
1185        wild_msgs[1][..].copy_from_slice(&constants::CURVE_ORDER[..]);
1186
1187        wild_keys[1][0] -= 1;
1188        wild_msgs[1][0] -= 1;
1189
1190        for key in wild_keys
1191            .iter()
1192            .map(|k| SecretKey::from_slice(&k[..]).unwrap())
1193        {
1194            for msg in wild_msgs
1195                .iter()
1196                .map(|m| Message::from_slice(&m[..]).unwrap())
1197            {
1198                let sig = s.sign(&msg, &key);
1199                let low_r_sig = s.sign_low_r(&msg, &key);
1200                let grind_r_sig = s.sign_grind_r(&msg, &key, 1);
1201                let pk = PublicKey::from_secret_key(&s, &key);
1202                assert_eq!(s.verify(&msg, &sig, &pk), Ok(()));
1203                assert_eq!(s.verify(&msg, &low_r_sig, &pk), Ok(()));
1204                assert_eq!(s.verify(&msg, &grind_r_sig, &pk), Ok(()));
1205            }
1206        }
1207    }
1208
1209    #[test]
1210    fn sign_and_verify_fail() {
1211        let mut s = Secp256k1::new();
1212        s.randomize(&mut thread_rng());
1213
1214        let mut msg = [0u8; 32];
1215        thread_rng().fill_bytes(&mut msg);
1216        let msg = Message::from_slice(&msg).unwrap();
1217
1218        let (sk, pk) = s.generate_keypair(&mut thread_rng());
1219
1220        let sig = s.sign(&msg, &sk);
1221
1222        let mut msg = [0u8; 32];
1223        thread_rng().fill_bytes(&mut msg);
1224        let msg = Message::from_slice(&msg).unwrap();
1225        assert_eq!(s.verify(&msg, &sig, &pk), Err(IncorrectSignature));
1226    }
1227
1228    #[test]
1229    fn test_bad_slice() {
1230        assert_eq!(
1231            Signature::from_der(&[0; constants::MAX_SIGNATURE_SIZE + 1]),
1232            Err(InvalidSignature)
1233        );
1234        assert_eq!(
1235            Signature::from_der(&[0; constants::MAX_SIGNATURE_SIZE]),
1236            Err(InvalidSignature)
1237        );
1238
1239        assert_eq!(
1240            Message::from_slice(&[0; constants::MESSAGE_SIZE - 1]),
1241            Err(InvalidMessage)
1242        );
1243        assert_eq!(
1244            Message::from_slice(&[0; constants::MESSAGE_SIZE + 1]),
1245            Err(InvalidMessage)
1246        );
1247        assert!(Message::from_slice(&[0; constants::MESSAGE_SIZE]).is_ok());
1248        assert!(Message::from_slice(&[1; constants::MESSAGE_SIZE]).is_ok());
1249    }
1250
1251    #[test]
1252    #[cfg(not(rust_secp_fuzz))] // fixed sig vectors can't work with fuzz-sigs
1253    fn test_low_s() {
1254        // nb this is a transaction on testnet
1255        // txid 8ccc87b72d766ab3128f03176bb1c98293f2d1f85ebfaf07b82cc81ea6891fa9
1256        //      input number 3
1257        let sig = hex!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45");
1258        let pk = hex!("031ee99d2b786ab3b0991325f2de8489246a6a3fdb700f6d0511b1d80cf5f4cd43");
1259        let msg = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");
1260
1261        let secp = Secp256k1::new();
1262        let mut sig = Signature::from_der(&sig[..]).unwrap();
1263        let pk = PublicKey::from_slice(&pk[..]).unwrap();
1264        let msg = Message::from_slice(&msg[..]).unwrap();
1265
1266        // without normalization we expect this will fail
1267        assert_eq!(secp.verify(&msg, &sig, &pk), Err(IncorrectSignature));
1268        // after normalization it should pass
1269        sig.normalize_s();
1270        assert_eq!(secp.verify(&msg, &sig, &pk), Ok(()));
1271    }
1272
1273    #[test]
1274    #[cfg(not(rust_secp_fuzz))] // fuzz-sigs have fixed size/format
1275    fn test_low_r() {
1276        let secp = Secp256k1::new();
1277        let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
1278        let msg = Message::from_slice(&msg).unwrap();
1279        let sk =
1280            SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
1281                .unwrap();
1282        let expected_sig = hex!("047dd4d049db02b430d24c41c7925b2725bcd5a85393513bdec04b4dc363632b1054d0180094122b380f4cfa391e6296244da773173e78fc745c1b9c79f7b713");
1283        let expected_sig = Signature::from_compact(&expected_sig).unwrap();
1284
1285        let sig = secp.sign_low_r(&msg, &sk);
1286
1287        assert_eq!(expected_sig, sig);
1288    }
1289
1290    #[test]
1291    #[cfg(not(rust_secp_fuzz))] // fuzz-sigs have fixed size/format
1292    fn test_grind_r() {
1293        let secp = Secp256k1::new();
1294        let msg = hex!("ef2d5b9a7c61865a95941d0f04285420560df7e9d76890ac1b8867b12ce43167");
1295        let msg = Message::from_slice(&msg).unwrap();
1296        let sk =
1297            SecretKey::from_str("848355d75fe1c354cf05539bb29b2015f1863065bcb6766b44d399ab95c3fa0b")
1298                .unwrap();
1299        let expected_sig = Signature::from_str("304302202ffc447100d518c8ba643d11f3e6a83a8640488e7d2537b1954b942408be6ea3021f26e1248dd1e52160c3a38af9769d91a1a806cab5f9d508c103464d3c02d6e1").unwrap();
1300
1301        let sig = secp.sign_grind_r(&msg, &sk, 2);
1302
1303        assert_eq!(expected_sig, sig);
1304    }
1305
1306    #[cfg(feature = "serde")]
1307    #[cfg(not(rust_secp_fuzz))] // fixed sig vectors can't work with fuzz-sigs
1308    #[test]
1309    fn test_signature_serde() {
1310        use serde_test::{assert_tokens, Configure, Token};
1311
1312        let s = Secp256k1::new();
1313
1314        let msg = Message::from_slice(&[1; 32]).unwrap();
1315        let sk = SecretKey::from_slice(&[2; 32]).unwrap();
1316        let sig = s.sign(&msg, &sk);
1317        static SIG_BYTES: [u8; 71] = [
1318            48, 69, 2, 33, 0, 157, 11, 173, 87, 103, 25, 211, 42, 231, 107, 237, 179, 76, 119, 72,
1319            102, 103, 60, 189, 227, 244, 225, 41, 81, 85, 92, 148, 8, 230, 206, 119, 75, 2, 32, 40,
1320            118, 231, 16, 47, 32, 79, 107, 254, 226, 108, 150, 124, 57, 38, 206, 112, 44, 249, 125,
1321            75, 1, 0, 98, 225, 147, 247, 99, 25, 15, 103, 118,
1322        ];
1323        static SIG_STR: &'static str = "\
1324            30450221009d0bad576719d32ae76bedb34c774866673cbde3f4e12951555c9408e6ce77\
1325            4b02202876e7102f204f6bfee26c967c3926ce702cf97d4b010062e193f763190f6776\
1326        ";
1327
1328        assert_tokens(&sig.compact(), &[Token::BorrowedBytes(&SIG_BYTES[..])]);
1329        assert_tokens(&sig.readable(), &[Token::BorrowedStr(SIG_STR)]);
1330    }
1331
1332    #[cfg(feature = "global-context")]
1333    #[test]
1334    fn test_global_context() {
1335        use super::SECP256K1;
1336
1337        let sk_data = hex!("e6dd32f8761625f105c39a39f19370b3521d845a12456d60ce44debd0a362641");
1338        let sk = SecretKey::from_slice(&sk_data).unwrap();
1339        let msg_data = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");
1340        let msg = Message::from_slice(&msg_data).unwrap();
1341
1342        // Check usage as explicit parameter
1343        let pk = PublicKey::from_secret_key(&SECP256K1, &sk);
1344
1345        // Check usage as self
1346        let sig = SECP256K1.sign(&msg, &sk);
1347        assert!(SECP256K1.verify(&msg, &sig, &pk).is_ok());
1348    }
1349
1350    #[cfg(feature = "bitcoin_hashes")]
1351    #[test]
1352    fn test_from_hash() {
1353        use bitcoin_hashes;
1354        use bitcoin_hashes::Hash;
1355
1356        let test_bytes = "Hello world!".as_bytes();
1357
1358        let hash = bitcoin_hashes::sha256::Hash::hash(test_bytes);
1359        let msg = Message::from(hash);
1360        assert_eq!(msg.0, hash.into_inner());
1361        assert_eq!(
1362            msg,
1363            Message::from_hashed_data::<bitcoin_hashes::sha256::Hash>(test_bytes)
1364        );
1365
1366        let hash = bitcoin_hashes::sha256d::Hash::hash(test_bytes);
1367        let msg = Message::from(hash);
1368        assert_eq!(msg.0, hash.into_inner());
1369        assert_eq!(
1370            msg,
1371            Message::from_hashed_data::<bitcoin_hashes::sha256d::Hash>(test_bytes)
1372        );
1373    }
1374}
1375
1376#[cfg(all(test, feature = "unstable"))]
1377mod benches {
1378    use rand::{thread_rng, RngCore};
1379    use test::{black_box, Bencher};
1380
1381    use super::{Message, Secp256k1};
1382
1383    #[bench]
1384    pub fn generate(bh: &mut Bencher) {
1385        struct CounterRng(u64);
1386        impl RngCore for CounterRng {
1387            fn next_u32(&mut self) -> u32 {
1388                self.next_u64() as u32
1389            }
1390
1391            fn next_u64(&mut self) -> u64 {
1392                self.0 += 1;
1393                self.0
1394            }
1395
1396            fn fill_bytes(&mut self, dest: &mut [u8]) {
1397                for chunk in dest.chunks_mut(64 / 8) {
1398                    let rand: [u8; 64 / 8] = unsafe { std::mem::transmute(self.next_u64()) };
1399                    chunk.copy_from_slice(&rand[..chunk.len()]);
1400                }
1401            }
1402
1403            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
1404                Ok(self.fill_bytes(dest))
1405            }
1406        }
1407
1408        let s = Secp256k1::new();
1409        let mut r = CounterRng(0);
1410        bh.iter(|| {
1411            let (sk, pk) = s.generate_keypair(&mut r);
1412            black_box(sk);
1413            black_box(pk);
1414        });
1415    }
1416
1417    #[bench]
1418    pub fn bench_sign(bh: &mut Bencher) {
1419        let s = Secp256k1::new();
1420        let mut msg = [0u8; 32];
1421        thread_rng().fill_bytes(&mut msg);
1422        let msg = Message::from_slice(&msg).unwrap();
1423        let (sk, _) = s.generate_keypair(&mut thread_rng());
1424
1425        bh.iter(|| {
1426            let sig = s.sign(&msg, &sk);
1427            black_box(sig);
1428        });
1429    }
1430
1431    #[bench]
1432    pub fn bench_verify(bh: &mut Bencher) {
1433        let s = Secp256k1::new();
1434        let mut msg = [0u8; 32];
1435        thread_rng().fill_bytes(&mut msg);
1436        let msg = Message::from_slice(&msg).unwrap();
1437        let (sk, pk) = s.generate_keypair(&mut thread_rng());
1438        let sig = s.sign(&msg, &sk);
1439
1440        bh.iter(|| {
1441            let res = s.verify(&msg, &sig, &pk).unwrap();
1442            black_box(res);
1443        });
1444    }
1445}