#![deny(non_upper_case_globals, non_camel_case_types, non_snake_case)]
#![warn(missing_docs, missing_copy_implementations, missing_debug_implementations)]
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(bench, feature(test))]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(any(test, feature = "std"))]
extern crate core;
#[cfg(bench)]
extern crate test;
#[cfg(feature = "hashes")]
pub extern crate hashes;
#[macro_use]
mod macros;
#[macro_use]
mod secret;
mod context;
mod key;
pub mod constants;
pub mod ecdh;
pub mod ecdsa;
pub mod ellswift;
pub mod scalar;
pub mod schnorr;
#[cfg(feature = "serde")]
mod serde_util;
use core::marker::PhantomData;
use core::ptr::NonNull;
use core::{fmt, mem, str};
#[cfg(feature = "global-context")]
pub use context::global::SECP256K1;
#[cfg(feature = "hashes")]
use hashes::Hash;
#[cfg(feature = "rand")]
pub use rand;
pub use secp256k1_sys as ffi;
#[cfg(feature = "serde")]
pub use serde;
pub use crate::context::*;
use crate::ffi::types::AlignedType;
use crate::ffi::CPtr;
pub use crate::key::{PublicKey, SecretKey, *};
pub use crate::scalar::Scalar;
pub trait ThirtyTwoByteHash {
fn into_32(self) -> [u8; 32];
}
#[cfg(feature = "hashes")]
impl ThirtyTwoByteHash for hashes::sha256::Hash {
fn into_32(self) -> [u8; 32] { self.to_byte_array() }
}
#[cfg(feature = "hashes")]
impl ThirtyTwoByteHash for hashes::sha256d::Hash {
fn into_32(self) -> [u8; 32] { self.to_byte_array() }
}
#[cfg(feature = "hashes")]
impl<T: hashes::sha256t::Tag> ThirtyTwoByteHash for hashes::sha256t::Hash<T> {
fn into_32(self) -> [u8; 32] { self.to_byte_array() }
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Message([u8; constants::MESSAGE_SIZE]);
impl_array_newtype!(Message, u8, constants::MESSAGE_SIZE);
impl_pretty_debug!(Message);
impl Message {
#[inline]
#[deprecated(since = "0.28.0", note = "use from_digest_slice instead")]
pub fn from_slice(digest: &[u8]) -> Result<Message, Error> {
Message::from_digest_slice(digest)
}
#[inline]
pub fn from_digest(digest: [u8; 32]) -> Message { Message(digest) }
#[inline]
pub fn from_digest_slice(digest: &[u8]) -> Result<Message, Error> {
match digest.len() {
constants::MESSAGE_SIZE => {
let mut ret = [0u8; constants::MESSAGE_SIZE];
ret[..].copy_from_slice(digest);
Ok(Message(ret))
}
_ => Err(Error::InvalidMessage),
}
}
#[cfg(feature = "hashes")]
pub fn from_hashed_data<H: ThirtyTwoByteHash + hashes::Hash>(data: &[u8]) -> Self {
<H as hashes::Hash>::hash(data).into()
}
}
impl<T: ThirtyTwoByteHash> From<T> for Message {
fn from(t: T) -> Message { Message(t.into_32()) }
}
impl fmt::LowerHex for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.0.iter() {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
}
#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
pub enum Error {
IncorrectSignature,
InvalidMessage,
InvalidPublicKey,
InvalidSignature,
InvalidSecretKey,
InvalidSharedSecret,
InvalidRecoveryId,
InvalidTweak,
NotEnoughMemory,
InvalidPublicKeySum,
InvalidParityValue(key::InvalidParityValue),
InvalidEllSwift,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use Error::*;
match *self {
IncorrectSignature => f.write_str("signature failed verification"),
InvalidMessage => f.write_str("message was not 32 bytes (do you need to hash?)"),
InvalidPublicKey => f.write_str("malformed public key"),
InvalidSignature => f.write_str("malformed signature"),
InvalidSecretKey => f.write_str("malformed or out-of-range secret key"),
InvalidSharedSecret => f.write_str("malformed or out-of-range shared secret"),
InvalidRecoveryId => f.write_str("bad recovery id"),
InvalidTweak => f.write_str("bad tweak"),
NotEnoughMemory => f.write_str("not enough memory allocated"),
InvalidPublicKeySum => f.write_str(
"the sum of public keys was invalid or the input vector lengths was less than 1",
),
InvalidParityValue(e) => write_err!(f, "couldn't create parity"; e),
InvalidEllSwift => f.write_str("malformed EllSwift value"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::IncorrectSignature => None,
Error::InvalidMessage => None,
Error::InvalidPublicKey => None,
Error::InvalidSignature => None,
Error::InvalidSecretKey => None,
Error::InvalidSharedSecret => None,
Error::InvalidRecoveryId => None,
Error::InvalidTweak => None,
Error::NotEnoughMemory => None,
Error::InvalidPublicKeySum => None,
Error::InvalidParityValue(error) => Some(error),
Error::InvalidEllSwift => None,
}
}
}
pub struct Secp256k1<C: Context> {
ctx: NonNull<ffi::Context>,
phantom: PhantomData<C>,
}
unsafe impl<C: Context> Send for Secp256k1<C> {}
unsafe impl<C: Context> Sync for Secp256k1<C> {}
impl<C: Context> PartialEq for Secp256k1<C> {
fn eq(&self, _other: &Secp256k1<C>) -> bool { true }
}
impl<C: Context> Eq for Secp256k1<C> {}
impl<C: Context> Drop for Secp256k1<C> {
fn drop(&mut self) {
unsafe {
let size = ffi::secp256k1_context_preallocated_clone_size(self.ctx.as_ptr());
ffi::secp256k1_context_preallocated_destroy(self.ctx);
C::deallocate(self.ctx.as_ptr() as _, size);
}
}
}
impl<C: Context> fmt::Debug for Secp256k1<C> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<secp256k1 context {:?}, {}>", self.ctx, C::DESCRIPTION)
}
}
impl<C: Context> Secp256k1<C> {
pub fn ctx(&self) -> NonNull<ffi::Context> { self.ctx }
pub fn preallocate_size_gen() -> usize {
let word_size = mem::size_of::<AlignedType>();
let bytes = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
(bytes + word_size - 1) / word_size
}
#[cfg(feature = "rand")]
pub fn randomize<R: rand::Rng + ?Sized>(&mut self, rng: &mut R) {
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
self.seeded_randomize(&seed);
}
pub fn seeded_randomize(&mut self, seed: &[u8; 32]) {
unsafe {
let err = ffi::secp256k1_context_randomize(self.ctx, seed.as_c_ptr());
assert_eq!(err, 1);
}
}
}
impl<C: Signing> Secp256k1<C> {
#[inline]
#[cfg(feature = "rand")]
pub fn generate_keypair<R: rand::Rng + ?Sized>(
&self,
rng: &mut R,
) -> (key::SecretKey, key::PublicKey) {
let sk = key::SecretKey::new(rng);
let pk = key::PublicKey::from_secret_key(self, &sk);
(sk, pk)
}
}
#[inline]
#[cfg(all(feature = "global-context", feature = "rand"))]
pub fn generate_keypair<R: rand::Rng + ?Sized>(rng: &mut R) -> (key::SecretKey, key::PublicKey) {
SECP256K1.generate_keypair(rng)
}
fn from_hex(hex: &str, target: &mut [u8]) -> Result<usize, ()> {
if hex.len() % 2 == 1 || hex.len() > target.len() * 2 {
return Err(());
}
let mut b = 0;
let mut idx = 0;
for c in hex.bytes() {
b <<= 4;
match c {
b'A'..=b'F' => b |= c - b'A' + 10,
b'a'..=b'f' => b |= c - b'a' + 10,
b'0'..=b'9' => b |= c - b'0',
_ => return Err(()),
}
if (idx & 1) == 1 {
target[idx / 2] = b;
b = 0;
}
idx += 1;
}
Ok(idx / 2)
}
#[inline]
fn to_hex<'a>(src: &[u8], target: &'a mut [u8]) -> Result<&'a str, ()> {
let hex_len = src.len() * 2;
if target.len() < hex_len {
return Err(());
}
const HEX_TABLE: [u8; 16] = *b"0123456789abcdef";
let mut i = 0;
for &b in src {
target[i] = HEX_TABLE[usize::from(b >> 4)];
target[i + 1] = HEX_TABLE[usize::from(b & 0b00001111)];
i += 2;
}
let result = &target[..hex_len];
debug_assert!(str::from_utf8(result).is_ok());
return unsafe { Ok(str::from_utf8_unchecked(result)) };
}
#[cfg(feature = "rand")]
pub(crate) fn random_32_bytes<R: rand::Rng + ?Sized>(rng: &mut R) -> [u8; 32] {
let mut ret = [0u8; 32];
rng.fill(&mut ret);
ret
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test as test;
use super::*;
macro_rules! hex {
($hex:expr) => {{
let mut result = vec![0; $hex.len() / 2];
from_hex($hex, &mut result).expect("valid hex string");
result
}};
}
#[test]
#[cfg(feature = "rand-std")]
#[allow(unknown_lints)]
#[allow(renamed_and_removed_lints)]
#[allow(undropped_manually_drops)]
#[allow(clippy::unknown_manually_drops)]
fn test_raw_ctx() {
use std::mem::{forget, ManuallyDrop};
let ctx_full = Secp256k1::new();
let ctx_sign = Secp256k1::signing_only();
let ctx_vrfy = Secp256k1::verification_only();
let full = unsafe { Secp256k1::from_raw_all(ctx_full.ctx) };
let sign = unsafe { Secp256k1::from_raw_signing_only(ctx_sign.ctx) };
let mut vrfy = unsafe { Secp256k1::from_raw_verification_only(ctx_vrfy.ctx) };
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&[2u8; 32]).unwrap();
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
assert!(vrfy.verify_ecdsa(&msg, &sig, &pk).is_ok());
assert!(full.verify_ecdsa(&msg, &sig, &pk).is_ok());
drop(full);
drop(ctx_full);
unsafe {
let sz = ffi::secp256k1_context_preallocated_clone_size(ctx_sign.ctx.as_ptr());
ManuallyDrop::into_inner(sign);
SignOnly::deallocate(ctx_sign.ctx.as_ptr() as *mut u8, sz);
forget(ctx_sign);
}
unsafe {
let sz = ffi::secp256k1_context_preallocated_clone_size(ctx_vrfy.ctx.as_ptr());
ManuallyDrop::drop(&mut vrfy);
VerifyOnly::deallocate(ctx_vrfy.ctx.as_ptr() as *mut u8, sz);
forget(ctx_vrfy);
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
#[ignore] #[cfg(feature = "alloc")]
fn test_panic_raw_ctx_should_terminate_abnormally() {
let pk = PublicKey::from(unsafe { ffi::PublicKey::new() });
pk.serialize();
}
#[test]
#[cfg(feature = "rand-std")]
fn test_preallocation() {
use crate::ffi::types::AlignedType;
let mut buf_ful = vec![AlignedType::zeroed(); Secp256k1::preallocate_size()];
let mut buf_sign = vec![AlignedType::zeroed(); Secp256k1::preallocate_signing_size()];
let mut buf_vfy = vec![AlignedType::zeroed(); Secp256k1::preallocate_verification_size()];
let full = Secp256k1::preallocated_new(&mut buf_ful).unwrap();
let sign = Secp256k1::preallocated_signing_only(&mut buf_sign).unwrap();
let vrfy = Secp256k1::preallocated_verification_only(&mut buf_vfy).unwrap();
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&[2u8; 32]).unwrap();
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
assert!(vrfy.verify_ecdsa(&msg, &sig, &pk).is_ok());
assert!(full.verify_ecdsa(&msg, &sig, &pk).is_ok());
}
#[test]
#[cfg(feature = "rand-std")]
fn capabilities() {
let sign = Secp256k1::signing_only();
let vrfy = Secp256k1::verification_only();
let full = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
assert!(vrfy.verify_ecdsa(&msg, &sig, &pk).is_ok());
assert!(full.verify_ecdsa(&msg, &sig, &pk).is_ok());
let (pk_slice, sk_slice) = (&pk.serialize(), &sk[..]);
let new_pk = PublicKey::from_slice(pk_slice).unwrap();
let new_sk = SecretKey::from_slice(sk_slice).unwrap();
assert_eq!(sk, new_sk);
assert_eq!(pk, new_pk);
}
#[test]
#[cfg(feature = "rand-std")]
fn signature_serialize_roundtrip() {
let mut s = Secp256k1::new();
s.randomize(&mut rand::thread_rng());
for _ in 0..100 {
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
let sig1 = s.sign_ecdsa(&msg, &sk);
let der = sig1.serialize_der();
let sig2 = ecdsa::Signature::from_der(&der[..]).unwrap();
assert_eq!(sig1, sig2);
let compact = sig1.serialize_compact();
let sig2 = ecdsa::Signature::from_compact(&compact[..]).unwrap();
assert_eq!(sig1, sig2);
assert!(ecdsa::Signature::from_compact(&der[..]).is_err());
assert!(ecdsa::Signature::from_compact(&compact[0..4]).is_err());
assert!(ecdsa::Signature::from_der(&compact[..]).is_err());
assert!(ecdsa::Signature::from_der(&der[0..4]).is_err());
}
}
#[test]
fn signature_display() {
let hex_str = "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45";
let byte_str = hex!(hex_str);
assert_eq!(
ecdsa::Signature::from_der(&byte_str).expect("byte str decode"),
ecdsa::Signature::from_str(hex_str).expect("byte str decode")
);
let sig = ecdsa::Signature::from_str(hex_str).expect("byte str decode");
assert_eq!(&sig.to_string(), hex_str);
assert_eq!(&format!("{:?}", sig), hex_str);
assert!(ecdsa::Signature::from_str(
"3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab4"
)
.is_err());
assert!(ecdsa::Signature::from_str(
"3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab"
)
.is_err());
assert!(ecdsa::Signature::from_str(
"3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eabxx"
)
.is_err());
assert!(ecdsa::Signature::from_str(
"3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45\
72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45"
)
.is_err());
let hex_str = "30450221009d0bad576719d32ae76bedb34c774866673cbde3f4e12951555c9408e6ce774b02202876e7102f204f6bfee26c967c3926ce702cf97d4b010062e193f763190f6776";
let sig = ecdsa::Signature::from_str(hex_str).expect("byte str decode");
assert_eq!(&format!("{}", sig), hex_str);
}
#[test]
fn signature_lax_der() {
macro_rules! check_lax_sig(
($hex:expr) => ({
let sig = hex!($hex);
assert!(ecdsa::Signature::from_der_lax(&sig[..]).is_ok());
})
);
check_lax_sig!("304402204c2dd8a9b6f8d425fcd8ee9a20ac73b619906a6367eac6cb93e70375225ec0160220356878eff111ff3663d7e6bf08947f94443845e0dcc54961664d922f7660b80c");
check_lax_sig!("304402202ea9d51c7173b1d96d331bd41b3d1b4e78e66148e64ed5992abd6ca66290321c0220628c47517e049b3e41509e9d71e480a0cdc766f8cdec265ef0017711c1b5336f");
check_lax_sig!("3045022100bf8e050c85ffa1c313108ad8c482c4849027937916374617af3f2e9a881861c9022023f65814222cab09d5ec41032ce9c72ca96a5676020736614de7b78a4e55325a");
check_lax_sig!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45");
check_lax_sig!("3046022100eaa5f90483eb20224616775891397d47efa64c68b969db1dacb1c30acdfc50aa022100cf9903bbefb1c8000cf482b0aeeb5af19287af20bd794de11d82716f9bae3db1");
check_lax_sig!("3045022047d512bc85842ac463ca3b669b62666ab8672ee60725b6c06759e476cebdc6c102210083805e93bd941770109bcc797784a71db9e48913f702c56e60b1c3e2ff379a60");
check_lax_sig!("3044022023ee4e95151b2fbbb08a72f35babe02830d14d54bd7ed1320e4751751d1baa4802206235245254f58fd1be6ff19ca291817da76da65c2f6d81d654b5185dd86b8acf");
}
#[test]
#[cfg(feature = "rand-std")]
fn sign_and_verify_ecdsa() {
let mut s = Secp256k1::new();
s.randomize(&mut rand::thread_rng());
let noncedata = [42u8; 32];
for _ in 0..100 {
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Ok(()));
let noncedata_sig = s.sign_ecdsa_with_noncedata(&msg, &sk, &noncedata);
assert_eq!(s.verify_ecdsa(&msg, &noncedata_sig, &pk), Ok(()));
let low_r_sig = s.sign_ecdsa_low_r(&msg, &sk);
assert_eq!(s.verify_ecdsa(&msg, &low_r_sig, &pk), Ok(()));
let grind_r_sig = s.sign_ecdsa_grind_r(&msg, &sk, 1);
assert_eq!(s.verify_ecdsa(&msg, &grind_r_sig, &pk), Ok(()));
let compact = sig.serialize_compact();
if compact[0] < 0x80 {
assert_eq!(sig, low_r_sig);
} else {
#[cfg(not(secp256k1_fuzz))] assert_ne!(sig, low_r_sig);
}
#[cfg(not(secp256k1_fuzz))] assert!(ecdsa::compact_sig_has_zero_first_bit(&low_r_sig.0));
#[cfg(not(secp256k1_fuzz))] assert!(ecdsa::der_length_check(&grind_r_sig.0, 70));
}
}
#[test]
#[cfg(feature = "rand-std")]
fn sign_and_verify_extreme() {
let mut s = Secp256k1::new();
s.randomize(&mut rand::thread_rng());
let mut wild_keys = [[0u8; 32]; 2];
let mut wild_msgs = [[0u8; 32]; 2];
wild_keys[0][0] = 1;
wild_msgs[0][0] = 1;
use constants;
wild_keys[1][..].copy_from_slice(&constants::CURVE_ORDER[..]);
wild_msgs[1][..].copy_from_slice(&constants::CURVE_ORDER[..]);
wild_keys[1][0] -= 1;
wild_msgs[1][0] -= 1;
for key in wild_keys.iter().map(|k| SecretKey::from_slice(&k[..]).unwrap()) {
for msg in wild_msgs.iter().map(|m| Message::from_digest_slice(&m[..]).unwrap()) {
let sig = s.sign_ecdsa(&msg, &key);
let low_r_sig = s.sign_ecdsa_low_r(&msg, &key);
let grind_r_sig = s.sign_ecdsa_grind_r(&msg, &key, 1);
let pk = PublicKey::from_secret_key(&s, &key);
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Ok(()));
assert_eq!(s.verify_ecdsa(&msg, &low_r_sig, &pk), Ok(()));
assert_eq!(s.verify_ecdsa(&msg, &grind_r_sig, &pk), Ok(()));
}
}
}
#[test]
#[cfg(feature = "rand-std")]
fn sign_and_verify_fail() {
let mut s = Secp256k1::new();
s.randomize(&mut rand::thread_rng());
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
}
#[test]
fn test_bad_slice() {
assert_eq!(
ecdsa::Signature::from_der(&[0; constants::MAX_SIGNATURE_SIZE + 1]),
Err(Error::InvalidSignature)
);
assert_eq!(
ecdsa::Signature::from_der(&[0; constants::MAX_SIGNATURE_SIZE]),
Err(Error::InvalidSignature)
);
assert_eq!(
Message::from_digest_slice(&[0; constants::MESSAGE_SIZE - 1]),
Err(Error::InvalidMessage)
);
assert_eq!(
Message::from_digest_slice(&[0; constants::MESSAGE_SIZE + 1]),
Err(Error::InvalidMessage)
);
assert!(Message::from_digest_slice(&[0; constants::MESSAGE_SIZE]).is_ok());
assert!(Message::from_digest_slice(&[1; constants::MESSAGE_SIZE]).is_ok());
}
#[test]
#[cfg(feature = "rand-std")]
fn test_hex() {
use rand::RngCore;
use super::to_hex;
let mut rng = rand::thread_rng();
const AMOUNT: usize = 1024;
for i in 0..AMOUNT {
let mut hex_buf = [255u8; AMOUNT * 2];
let mut src_buf = [0u8; AMOUNT];
let mut result_buf = [0u8; AMOUNT];
let src = &mut src_buf[0..i];
rng.fill_bytes(src);
let hex = to_hex(src, &mut hex_buf).unwrap();
assert_eq!(from_hex(hex, &mut result_buf).unwrap(), i);
assert_eq!(src, &result_buf[..i]);
}
assert!(to_hex(&[1; 2], &mut [0u8; 3]).is_err());
assert!(to_hex(&[1; 2], &mut [0u8; 4]).is_ok());
assert!(from_hex("deadbeaf", &mut [0u8; 3]).is_err());
assert!(from_hex("deadbeaf", &mut [0u8; 4]).is_ok());
assert!(from_hex("a", &mut [0u8; 4]).is_err());
assert!(from_hex("ag", &mut [0u8; 4]).is_err());
}
#[test]
#[cfg(not(secp256k1_fuzz))] #[cfg(any(feature = "alloc", feature = "std"))]
fn test_noncedata() {
let secp = Secp256k1::new();
let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
let msg = Message::from_digest_slice(&msg).unwrap();
let noncedata = [42u8; 32];
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
.unwrap();
let expected_sig = hex!("24861b3edd4e7da43319c635091405feced6efa4ec99c3c3c35f6c3ba0ed8816116772e84994084db85a6c20589f6a85af569d42275c2a5dd900da5776b99d5d");
let expected_sig = ecdsa::Signature::from_compact(&expected_sig).unwrap();
let sig = secp.sign_ecdsa_with_noncedata(&msg, &sk, &noncedata);
assert_eq!(expected_sig, sig);
}
#[test]
#[cfg(not(secp256k1_fuzz))] #[cfg(any(feature = "alloc", feature = "std"))]
fn test_low_s() {
let sig = hex!("3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45");
let pk = hex!("031ee99d2b786ab3b0991325f2de8489246a6a3fdb700f6d0511b1d80cf5f4cd43");
let msg = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");
let secp = Secp256k1::new();
let mut sig = ecdsa::Signature::from_der(&sig[..]).unwrap();
let pk = PublicKey::from_slice(&pk[..]).unwrap();
let msg = Message::from_digest_slice(&msg[..]).unwrap();
assert_eq!(secp.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
sig.normalize_s();
assert_eq!(secp.verify_ecdsa(&msg, &sig, &pk), Ok(()));
}
#[test]
#[cfg(not(secp256k1_fuzz))] #[cfg(any(feature = "alloc", feature = "std"))]
fn test_low_r() {
let secp = Secp256k1::new();
let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
let msg = Message::from_digest_slice(&msg).unwrap();
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
.unwrap();
let expected_sig = hex!("047dd4d049db02b430d24c41c7925b2725bcd5a85393513bdec04b4dc363632b1054d0180094122b380f4cfa391e6296244da773173e78fc745c1b9c79f7b713");
let expected_sig = ecdsa::Signature::from_compact(&expected_sig).unwrap();
let sig = secp.sign_ecdsa_low_r(&msg, &sk);
assert_eq!(expected_sig, sig);
}
#[test]
#[cfg(not(secp256k1_fuzz))] #[cfg(any(feature = "alloc", feature = "std"))]
fn test_grind_r() {
let secp = Secp256k1::new();
let msg = hex!("ef2d5b9a7c61865a95941d0f04285420560df7e9d76890ac1b8867b12ce43167");
let msg = Message::from_digest_slice(&msg).unwrap();
let sk =
SecretKey::from_str("848355d75fe1c354cf05539bb29b2015f1863065bcb6766b44d399ab95c3fa0b")
.unwrap();
let expected_sig = ecdsa::Signature::from_str("304302202ffc447100d518c8ba643d11f3e6a83a8640488e7d2537b1954b942408be6ea3021f26e1248dd1e52160c3a38af9769d91a1a806cab5f9d508c103464d3c02d6e1").unwrap();
let sig = secp.sign_ecdsa_grind_r(&msg, &sk, 2);
assert_eq!(expected_sig, sig);
}
#[cfg(feature = "serde")]
#[cfg(not(secp256k1_fuzz))] #[cfg(any(feature = "alloc", feature = "std"))]
#[test]
fn test_serde() {
use serde_test::{assert_tokens, Configure, Token};
let s = Secp256k1::new();
let msg = Message::from_digest_slice(&[1; 32]).unwrap();
let sk = SecretKey::from_slice(&[2; 32]).unwrap();
let sig = s.sign_ecdsa(&msg, &sk);
static SIG_BYTES: [u8; 71] = [
48, 69, 2, 33, 0, 157, 11, 173, 87, 103, 25, 211, 42, 231, 107, 237, 179, 76, 119, 72,
102, 103, 60, 189, 227, 244, 225, 41, 81, 85, 92, 148, 8, 230, 206, 119, 75, 2, 32, 40,
118, 231, 16, 47, 32, 79, 107, 254, 226, 108, 150, 124, 57, 38, 206, 112, 44, 249, 125,
75, 1, 0, 98, 225, 147, 247, 99, 25, 15, 103, 118,
];
static SIG_STR: &str = "\
30450221009d0bad576719d32ae76bedb34c774866673cbde3f4e12951555c9408e6ce77\
4b02202876e7102f204f6bfee26c967c3926ce702cf97d4b010062e193f763190f6776\
";
assert_tokens(&sig.compact(), &[Token::BorrowedBytes(&SIG_BYTES[..])]);
assert_tokens(&sig.compact(), &[Token::Bytes(&SIG_BYTES)]);
assert_tokens(&sig.compact(), &[Token::ByteBuf(&SIG_BYTES)]);
assert_tokens(&sig.readable(), &[Token::BorrowedStr(SIG_STR)]);
assert_tokens(&sig.readable(), &[Token::Str(SIG_STR)]);
assert_tokens(&sig.readable(), &[Token::String(SIG_STR)]);
}
#[cfg(feature = "global-context")]
#[test]
fn test_global_context() {
use crate::SECP256K1;
let sk_data = hex!("e6dd32f8761625f105c39a39f19370b3521d845a12456d60ce44debd0a362641");
let sk = SecretKey::from_slice(&sk_data).unwrap();
let msg_data = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");
let msg = Message::from_digest_slice(&msg_data).unwrap();
let pk = PublicKey::from_secret_key(SECP256K1, &sk);
let sig = SECP256K1.sign_ecdsa(&msg, &sk);
assert!(SECP256K1.verify_ecdsa(&msg, &sig, &pk).is_ok());
}
#[cfg(feature = "hashes")]
#[test]
fn test_from_hash() {
use hashes::{sha256, sha256d, Hash};
let test_bytes = "Hello world!".as_bytes();
let hash = sha256::Hash::hash(test_bytes);
let msg = Message::from(hash);
assert_eq!(msg.0, hash.to_byte_array());
assert_eq!(msg, Message::from_hashed_data::<hashes::sha256::Hash>(test_bytes));
let hash = sha256d::Hash::hash(test_bytes);
let msg = Message::from(hash);
assert_eq!(msg.0, hash.to_byte_array());
assert_eq!(msg, Message::from_hashed_data::<hashes::sha256d::Hash>(test_bytes));
}
}
#[cfg(bench)]
#[cfg(feature = "rand-std")]
mod benches {
use rand::rngs::mock::StepRng;
use test::{black_box, Bencher};
use super::{Message, Secp256k1};
#[bench]
pub fn generate(bh: &mut Bencher) {
let s = Secp256k1::new();
let mut r = StepRng::new(1, 1);
bh.iter(|| {
let (sk, pk) = s.generate_keypair(&mut r);
black_box(sk);
black_box(pk);
});
}
#[bench]
pub fn bench_sign_ecdsa(bh: &mut Bencher) {
let s = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
bh.iter(|| {
let sig = s.sign_ecdsa(&msg, &sk);
black_box(sig);
});
}
#[bench]
pub fn bench_verify_ecdsa(bh: &mut Bencher) {
let s = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
bh.iter(|| {
let res = s.verify_ecdsa(&msg, &sig, &pk).unwrap();
black_box(res);
});
}
}