Revert "Overhaul interface to use zero-on-free SecretKeys"

This reverts commit 9889090784.

This is not ready for primetime -- the move prevention also prevents
reborrowing, which makes secret keys nearly unusable.
This commit is contained in:
Andrew Poelstra 2014-09-12 08:28:35 -05:00
parent 9889090784
commit 9cab4e023d
4 changed files with 247 additions and 264 deletions

View File

@ -1,7 +1,7 @@
[package]
name = "bitcoin-secp256k1-rs"
version = "0.1.1"
version = "0.0.1"
authors = [ "Dawid Ciężarkiewicz <dpc@ucore.info>",
"Andrew Poelstra <apoelstra@wpsoftware.net" ]
@ -12,6 +12,3 @@ path = "src/secp256k1.rs"
[dependencies.rust-crypto]
git = "https://github.com/DaGenix/rust-crypto.git"
[dependencies.secretdata]
git = "https://github.com/apoelstra/secretdata.git"

View File

@ -17,13 +17,10 @@
use std::intrinsics::copy_nonoverlapping_memory;
use std::cmp;
use std::default::Default;
use std::fmt;
use std::ptr::zero_memory;
use std::rand::Rng;
use serialize::{Decoder, Decodable, Encoder, Encodable};
use secretdata::SecretData;
use crypto::digest::Digest;
use crypto::sha2::Sha512;
use crypto::hmac::Hmac;
@ -39,17 +36,14 @@ pub struct Nonce([u8, ..constants::NONCE_SIZE]);
impl_array_newtype!(Nonce, u8, constants::NONCE_SIZE)
/// Secret 256-bit key used as `x` in an ECDSA signature
pub struct SecretKey<'a>(SecretData<'a, SecretKeyData>);
pub struct SecretKey([u8, ..constants::SECRET_KEY_SIZE]);
impl_array_newtype!(SecretKey, u8, constants::SECRET_KEY_SIZE)
/// Secret 256-bit key used as `x` in an ECDSA signature
struct SecretKeyData([u8, ..constants::SECRET_KEY_SIZE]);
impl_array_newtype!(SecretKeyData, u8, constants::SECRET_KEY_SIZE)
impl Default for SecretKeyData {
fn default() -> SecretKeyData {
SecretKeyData([0, ..constants::SECRET_KEY_SIZE])
}
}
/// The number 1 encoded as a secret key
pub static ONE: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1]);
/// Public key
#[deriving(Clone, PartialEq, Eq, Show)]
@ -104,7 +98,7 @@ impl Nonce {
/// Generates a deterministic nonce by RFC6979 with HMAC-SHA512
#[inline]
#[allow(non_snake_case)] // so we can match the names in the RFC
pub fn deterministic<'a>(msg: &[u8], key: &SecretKey<'a>) -> Nonce {
pub fn deterministic(msg: &[u8], key: &SecretKey) -> Nonce {
static HMAC_SIZE: uint = 64;
macro_rules! hmac(
@ -160,16 +154,10 @@ impl Nonce {
}
}
impl<'a> SecretKey<'a> {
/// Creates a new zeroed-out secret key
#[inline]
pub fn new() -> SecretKey<'a> {
SecretKey(SecretData::new())
}
impl SecretKey {
/// Creates a new random secret key
#[inline]
pub fn init_rng<R:Rng>(&'a mut self, rng: &mut R) {
pub fn new<R:Rng>(rng: &mut R) -> SecretKey {
init();
let mut data = random_32_bytes(rng);
unsafe {
@ -177,47 +165,36 @@ impl<'a> SecretKey<'a> {
data = random_32_bytes(rng);
}
}
let &SecretKey(ref mut selfdata) = self;
selfdata.move(&mut SecretKeyData(data))
SecretKey(data)
}
/// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key,
/// zeroing out the original data
/// Converts a `SECRET_KEY_SIZE`-byte slice to a secret key
#[inline]
pub fn init_slice(&'a mut self, data: &mut [u8]) -> Result<()> {
pub fn from_slice(data: &[u8]) -> Result<SecretKey> {
init();
match data.len() {
constants::SECRET_KEY_SIZE => {
let &SecretKey(ref mut selfdata) = self;
let mut ret = [0, ..constants::SECRET_KEY_SIZE];
unsafe {
if ffi::secp256k1_ecdsa_seckey_verify(data.as_ptr()) == 0 {
return Err(InvalidSecretKey);
}
copy_nonoverlapping_memory(selfdata.data_mut().as_mut_ptr(),
copy_nonoverlapping_memory(ret.as_mut_ptr(),
data.as_ptr(),
data.len());
zero_memory(data.as_mut_ptr(), data.len());
}
Ok(())
Ok(SecretKey(ret))
}
_ => Err(InvalidSecretKey)
}
}
/// Copies the data from one key to another without zeroing anyth out
#[inline]
pub fn clone_from<'b>(&'a mut self, other: &SecretKey<'b>) {
let &SecretKey(ref mut selfdata) = self;
let &SecretKey(ref otherdata) = other;
selfdata.clone_from(otherdata);
}
#[inline]
/// Adds one secret key to another, modulo the curve order
/// Marked `unsafe` since you must
/// call `init()` (or construct a `Secp256k1`, which does this for you) before
/// using this function
pub fn add_assign<'b>(&mut self, other: &SecretKey<'b>) -> Result<()> {
pub fn add_assign(&mut self, other: &SecretKey) -> Result<()> {
init();
unsafe {
if ffi::secp256k1_ecdsa_privkey_tweak_add(self.as_mut_ptr(), other.as_ptr()) != 1 {
@ -229,24 +206,24 @@ impl<'a> SecretKey<'a> {
}
#[inline]
/// Returns an immutable view of the data as a byteslice
pub fn as_slice<'b>(&'b self) -> &'b [u8] {
let &SecretKey(ref selfdata) = self;
selfdata.data().as_slice()
/// Returns an iterator for the (sk, pk) pairs starting one after this one,
/// and incrementing by one each time
pub fn sequence(&self, compressed: bool) -> Sequence {
Sequence { last_sk: *self, compressed: compressed }
}
}
#[inline]
/// Returns a raw pointer to the underlying secret key data
pub fn as_ptr(&self) -> *const u8 {
let &SecretKey(ref selfdata) = self;
selfdata.data().as_ptr()
/// An iterator of keypairs `(sk + 1, pk*G)`, `(sk + 2, pk*2G)`, ...
pub struct Sequence {
compressed: bool,
last_sk: SecretKey,
}
impl<'a> Iterator<(SecretKey, PublicKey)> for Sequence {
#[inline]
/// Returns a mutable raw pointer to the underlying secret key data
pub fn as_mut_ptr(&mut self) -> *mut u8 {
let &SecretKey(ref mut selfdata) = self;
selfdata.data_mut().as_mut_ptr()
fn next(&mut self) -> Option<(SecretKey, PublicKey)> {
self.last_sk.add_assign(&ONE).unwrap();
Some((self.last_sk, PublicKey::from_secret_key(&self.last_sk, self.compressed)))
}
}
@ -262,7 +239,7 @@ impl PublicKey {
/// Creates a new public key from a secret key.
#[inline]
pub fn from_secret_key<'a>(sk: &SecretKey<'a>, compressed: bool) -> PublicKey {
pub fn from_secret_key(sk: &SecretKey, compressed: bool) -> PublicKey {
let mut pk = PublicKey::new(compressed);
let compressed = if compressed {1} else {0};
let mut len = 0;
@ -360,7 +337,7 @@ impl PublicKey {
#[inline]
/// Adds the pk corresponding to `other` to the pk `self` in place
pub fn add_exp_assign<'a>(&mut self, other: &SecretKey<'a>) -> Result<()> {
pub fn add_exp_assign(&mut self, other: &SecretKey) -> Result<()> {
init();
unsafe {
if ffi::secp256k1_ecdsa_pubkey_tweak_add(self.as_mut_ptr(),
@ -444,17 +421,9 @@ impl <E: Encoder<S>, S> Encodable<E, S> for PublicKey {
}
}
impl<'a> PartialEq for SecretKey<'a> {
fn eq(&self, other: &SecretKey<'a>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a> Eq for SecretKey<'a> {}
impl<'a> fmt::Show for SecretKey<'a> {
impl fmt::Show for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[secret data]")
self.as_slice().fmt(f)
}
}
@ -463,7 +432,9 @@ mod test {
use serialize::hex::FromHex;
use std::rand::task_rng;
use super::super::{InvalidNonce, InvalidPublicKey, InvalidSecretKey};
use test::Bencher;
use super::super::{Secp256k1, InvalidNonce, InvalidPublicKey, InvalidSecretKey};
use super::{Nonce, PublicKey, SecretKey};
#[test]
@ -471,16 +442,17 @@ mod test {
let n = Nonce::from_slice([1, ..31]);
assert_eq!(n, Err(InvalidNonce));
let mut n = SecretKey::new();
assert_eq!(n.init_slice([1, ..32]), Ok(()));
let n = SecretKey::from_slice([1, ..32]);
assert!(n.is_ok());
}
#[test]
fn skey_from_slice() {
let mut sk = SecretKey::new();
assert_eq!(sk.init_slice([1, ..31]), Err(InvalidSecretKey));
let mut sk = SecretKey::new();
assert_eq!(sk.init_slice([1, ..32]), Ok(()));
let sk = SecretKey::from_slice([1, ..31]);
assert_eq!(sk, Err(InvalidSecretKey));
let sk = SecretKey::from_slice([1, ..32]);
assert!(sk.is_ok());
}
#[test]
@ -499,17 +471,14 @@ mod test {
#[test]
fn keypair_slice_round_trip() {
let mut rng = task_rng();
let mut sk1 = SecretKey::new();
sk1.init_rng(&mut rng);
let mut sk2 = SecretKey::new();
sk2.clone_from(&sk1);
let mut s = Secp256k1::new().unwrap();
assert_eq!(sk1, sk2);
let pk1 = PublicKey::from_secret_key(&sk1, false);
let (sk1, pk1) = s.generate_keypair(true);
assert_eq!(SecretKey::from_slice(sk1.as_slice()), Ok(sk1));
assert_eq!(PublicKey::from_slice(pk1.as_slice()), Ok(pk1));
let pk2 = PublicKey::from_secret_key(&sk1, true);
let (sk2, pk2) = s.generate_keypair(false);
assert_eq!(SecretKey::from_slice(sk2.as_slice()), Ok(sk2));
assert_eq!(PublicKey::from_slice(pk2.as_slice()), Ok(pk2));
}
@ -522,33 +491,28 @@ mod test {
#[test]
fn invalid_secret_key() {
let mut sk = SecretKey::new();
// Zero
assert_eq!(sk.init_slice([0, ..32]), Err(InvalidSecretKey));
assert_eq!(SecretKey::from_slice([0, ..32]), Err(InvalidSecretKey));
// -1
assert_eq!(sk.init_slice([0xff, ..32]), Err(InvalidSecretKey));
assert_eq!(SecretKey::from_slice([0xff, ..32]), Err(InvalidSecretKey));
// Top of range
assert_eq!(sk.init_slice([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
assert!(SecretKey::from_slice([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40]), Ok(()));
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40]).is_ok());
// One past top of range
assert_eq!(sk.init_slice([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
assert!(SecretKey::from_slice([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41]), Err(InvalidSecretKey));
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41]).is_err());
}
#[test]
fn test_addition() {
let mut rng = task_rng();
let mut s = Secp256k1::new().unwrap();
let mut sk1 = SecretKey::new();
let mut sk2 = SecretKey::new();
sk1.init_rng(&mut rng);
sk2.init_rng(&mut rng);
let mut pk1 = PublicKey::from_secret_key(&sk1, true);
let mut pk2 = PublicKey::from_secret_key(&sk2, true);
let (mut sk1, mut pk1) = s.generate_keypair(true);
let (mut sk2, mut pk2) = s.generate_keypair(true);
assert_eq!(PublicKey::from_secret_key(&sk1, true), pk1);
assert!(sk1.add_assign(&sk2).is_ok());
@ -569,10 +533,7 @@ mod test {
// from ecdsa.curves import SECP256k1
// # This key was generated randomly
// sk = 0x09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f81
let mut sk = SecretKey::new();
sk.init_slice(hex_slice_mut!("09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f81")).unwrap();
assert_eq!(sk.as_slice(),
hex_slice!("09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f81"));
let sk = SecretKey::from_slice(hex_slice!("09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f81")).unwrap();
// "%x" % rfc6979.generate_k(SECP256k1.generator, sk, hashlib.sha512, hashlib.sha512('').digest())
let nonce = Nonce::deterministic([], &sk);
@ -586,7 +547,7 @@ mod test {
// # Decrease the secret key by one
// sk = 0x09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f80
sk.init_slice(hex_slice_mut!("09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f80")).unwrap();
let sk = SecretKey::from_slice(hex_slice!("09e918bbea76205445e9a73eaad2080a135d1e33e9dd1b3ca8a9a1285e7c1f80")).unwrap();
// "%x" % rfc6979.generate_k(SECP256k1.generator, sk, hashlib.sha512, hashlib.sha512('').digest())
let nonce = Nonce::deterministic([], &sk);
@ -598,6 +559,14 @@ mod test {
assert_eq!(nonce.as_slice(),
hex_slice!("355c589ff662c838aee454d62b12c50a87b7e95ede2431c7cfa40b6ba2fddccd"));
}
#[bench]
pub fn sequence_iterate(bh: &mut Bencher) {
let mut s = Secp256k1::new().unwrap();
let (sk, _) = s.generate_keypair(true);
let mut iter = sk.sequence(true);
bh.iter(|| iter.next())
}
}

View File

@ -27,7 +27,6 @@ macro_rules! impl_array_newtype(
}
#[inline]
#[allow(dead_code)]
/// Provides an immutable view into the object from index `s` inclusive to `e` exclusive
pub fn slice<'a>(&'a self, s: uint, e: uint) -> &'a [$ty] {
let &$thing(ref dat) = self;
@ -35,7 +34,6 @@ macro_rules! impl_array_newtype(
}
#[inline]
#[allow(dead_code)]
/// Provides an immutable view into the object, up to index `n` exclusive
pub fn slice_to<'a>(&'a self, n: uint) -> &'a [$ty] {
let &$thing(ref dat) = self;
@ -43,7 +41,6 @@ macro_rules! impl_array_newtype(
}
#[inline]
#[allow(dead_code)]
/// Provides an immutable view into the object, starting from index `n`
pub fn slice_from<'a>(&'a self, n: uint) -> &'a [$ty] {
let &$thing(ref dat) = self;
@ -65,7 +62,6 @@ macro_rules! impl_array_newtype(
}
#[inline]
#[allow(dead_code)]
/// Returns the length of the object as an array
pub fn len(&self) -> uint { $len }
}
@ -133,10 +129,3 @@ macro_rules! hex_slice(
)
)
macro_rules! hex_slice_mut(
($s:expr) => (
$s.from_hex().unwrap().as_mut_slice()
)
)

View File

@ -37,7 +37,6 @@
#![warn(missing_doc)]
extern crate "rust-crypto" as crypto;
extern crate secretdata;
extern crate libc;
extern crate serialize;
@ -45,9 +44,13 @@ extern crate sync;
extern crate test;
use std::intrinsics::copy_nonoverlapping_memory;
use std::io::IoResult;
use std::rand::{OsRng, Rng, SeedableRng};
use libc::c_int;
use sync::one::{Once, ONCE_INIT};
use crypto::fortuna::Fortuna;
mod macros;
pub mod constants;
pub mod ffi;
@ -132,6 +135,11 @@ pub type Result<T> = ::std::prelude::Result<T, Error>;
static mut Secp256k1_init : Once = ONCE_INIT;
/// The secp256k1 engine, used to execute all signature operations
pub struct Secp256k1 {
rng: Fortuna
}
/// Does one-time initialization of the secp256k1 engine. Can be called
/// multiple times, and is called by the `Secp256k1` constructor. This
/// only needs to be called directly if you are using the library without
@ -145,8 +153,35 @@ pub fn init() {
}
}
impl Secp256k1 {
/// Constructs a new secp256k1 engine.
pub fn new() -> IoResult<Secp256k1> {
init();
let mut osrng = try!(OsRng::new());
let mut seed = [0, ..2048];
osrng.fill_bytes(seed.as_mut_slice());
Ok(Secp256k1 { rng: SeedableRng::from_seed(seed.as_slice()) })
}
/// Generates a random keypair. Convenience function for `key::SecretKey::new`
/// and `key::PublicKey::from_secret_key`; call those functions directly for
/// batch key generation.
#[inline]
pub fn generate_keypair(&mut self, compressed: bool)
-> (key::SecretKey, key::PublicKey) {
let sk = key::SecretKey::new(&mut self.rng);
(sk, key::PublicKey::from_secret_key(&sk, compressed))
}
/// Generates a random nonce. Convenience function for `key::Nonce::new`; call
/// that function directly for batch nonce generation
#[inline]
pub fn generate_nonce(&mut self) -> key::Nonce {
key::Nonce::new(&mut self.rng)
}
/// Constructs a signature for `msg` using the secret key `sk` and nonce `nonce`
pub fn sign<'a>(msg: &[u8], sk: &key::SecretKey<'a>, nonce: &key::Nonce)
pub fn sign(&self, msg: &[u8], sk: &key::SecretKey, nonce: &key::Nonce)
-> Result<Signature> {
let mut sig = [0, ..constants::MAX_SIGNATURE_SIZE];
let mut len = constants::MAX_SIGNATURE_SIZE as c_int;
@ -163,7 +198,7 @@ pub fn sign<'a>(msg: &[u8], sk: &key::SecretKey<'a>, nonce: &key::Nonce)
}
/// Constructs a compact signature for `msg` using the secret key `sk`
pub fn sign_compact<'a>(msg: &[u8], sk: &key::SecretKey<'a>, nonce: &key::Nonce)
pub fn sign_compact(&self, msg: &[u8], sk: &key::SecretKey, nonce: &key::Nonce)
-> Result<(Signature, RecoveryId)> {
let mut sig = [0, ..constants::MAX_SIGNATURE_SIZE];
let mut recid = 0;
@ -179,7 +214,7 @@ pub fn sign_compact<'a>(msg: &[u8], sk: &key::SecretKey<'a>, nonce: &key::Nonce)
/// Determines the public key for which `sig` is a valid signature for
/// `msg`. Returns through the out-pointer `pubkey`.
pub fn recover_compact(msg: &[u8], sig: &[u8],
pub fn recover_compact(&self, msg: &[u8], sig: &[u8],
compressed: bool, recid: RecoveryId)
-> Result<key::PublicKey> {
let mut pk = key::PublicKey::new(compressed);
@ -205,7 +240,7 @@ pub fn recover_compact(msg: &[u8], sig: &[u8],
/// Use `verify_raw` instead.
#[inline]
pub fn verify(msg: &[u8], sig: &Signature, pk: &key::PublicKey) -> Result<()> {
verify_raw(msg, sig.as_slice(), pk)
Secp256k1::verify_raw(msg, sig.as_slice(), pk)
}
/// Checks that `sig` is a valid ECDSA signature for `msg` using the public
@ -227,6 +262,7 @@ pub fn verify_raw(msg: &[u8], sig: &[u8], pk: &key::PublicKey) -> Result<()> {
_ => unreachable!()
}
}
}
#[cfg(test)]
@ -236,9 +272,9 @@ mod tests {
use test::{Bencher, black_box};
use key::{SecretKey, PublicKey, Nonce};
use super::{verify, sign, sign_compact, recover_compact};
use super::{Signature, InvalidPublicKey, IncorrectSignature, InvalidSignature};
use key::{PublicKey, Nonce};
use super::{Secp256k1, Signature};
use super::{InvalidPublicKey, IncorrectSignature, InvalidSignature};
#[test]
fn invalid_pubkey() {
@ -248,134 +284,126 @@ mod tests {
rand::task_rng().fill_bytes(msg.as_mut_slice());
assert_eq!(verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidPublicKey));
assert_eq!(Secp256k1::verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidPublicKey));
}
#[test]
fn valid_pubkey_uncompressed() {
let mut sk = SecretKey::new();
sk.init_rng(&mut rand::task_rng());
let pk = PublicKey::from_secret_key(&sk, false);
let mut s = Secp256k1::new().unwrap();
let (_, pk) = s.generate_keypair(false);
let mut msg = Vec::from_elem(32, 0u8);
let sig = Signature::from_slice([0, ..72]).unwrap();
rand::task_rng().fill_bytes(msg.as_mut_slice());
assert_eq!(verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidSignature));
assert_eq!(Secp256k1::verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidSignature));
}
#[test]
fn valid_pubkey_compressed() {
let mut sk = SecretKey::new();
sk.init_rng(&mut rand::task_rng());
let pk = PublicKey::from_secret_key(&sk, true);
let mut s = Secp256k1::new().unwrap();
let (_, pk) = s.generate_keypair(true);
let mut msg = Vec::from_elem(32, 0u8);
let sig = Signature::from_slice([0, ..72]).unwrap();
rand::task_rng().fill_bytes(msg.as_mut_slice());
assert_eq!(verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidSignature));
assert_eq!(Secp256k1::verify(msg.as_mut_slice(), &sig, &pk), Err(InvalidSignature));
}
#[test]
fn sign_random() {
let mut rng = rand::task_rng();
let mut sk = SecretKey::new();
sk.init_rng(&mut rng);
fn sign() {
let mut s = Secp256k1::new().unwrap();
let mut msg = [0u8, ..32];
rng.fill_bytes(msg);
rand::task_rng().fill_bytes(msg);
let nonce = Nonce::new(&mut rng);
let (sk, _) = s.generate_keypair(false);
let nonce = s.generate_nonce();
sign(msg.as_slice(), &sk, &nonce).unwrap();
s.sign(msg.as_slice(), &sk, &nonce).unwrap();
}
#[test]
fn sign_and_verify() {
let mut rng = rand::task_rng();
let mut s = Secp256k1::new().unwrap();
let mut sk = SecretKey::new();
sk.init_rng(&mut rng);
let pk = PublicKey::from_secret_key(&sk, true);
let mut msg = [0u8, ..32];
rng.fill_bytes(msg);
let nonce = Nonce::new(&mut rng);
let mut msg = Vec::from_elem(32, 0u8);
rand::task_rng().fill_bytes(msg.as_mut_slice());
let sig = sign(msg.as_slice(), &sk, &nonce).unwrap();
assert_eq!(verify(msg.as_slice(), &sig, &pk), Ok(()));
let (sk, pk) = s.generate_keypair(false);
let nonce = s.generate_nonce();
let sig = s.sign(msg.as_slice(), &sk, &nonce).unwrap();
assert_eq!(Secp256k1::verify(msg.as_slice(), &sig, &pk), Ok(()));
}
#[test]
fn sign_and_verify_fail() {
let mut rng = rand::task_rng();
let mut s = Secp256k1::new().unwrap();
let mut sk = SecretKey::new();
sk.init_rng(&mut rng);
let pk = PublicKey::from_secret_key(&sk, true);
let mut msg = [0u8, ..32];
rng.fill_bytes(msg);
let nonce = Nonce::new(&mut rng);
let mut msg = Vec::from_elem(32, 0u8);
rand::task_rng().fill_bytes(msg.as_mut_slice());
let sig = sign(msg.as_slice(), &sk, &nonce).unwrap();
rng.fill_bytes(msg.as_mut_slice());
assert_eq!(verify(msg.as_slice(), &sig, &pk), Err(IncorrectSignature));
let (sk, pk) = s.generate_keypair(false);
let nonce = s.generate_nonce();
let sig = s.sign(msg.as_slice(), &sk, &nonce).unwrap();
rand::task_rng().fill_bytes(msg.as_mut_slice());
assert_eq!(Secp256k1::verify(msg.as_slice(), &sig, &pk), Err(IncorrectSignature));
}
#[test]
fn sign_compact_with_recovery() {
let mut rng = rand::task_rng();
let mut s = Secp256k1::new().unwrap();
let mut sk = SecretKey::new();
sk.init_rng(&mut rng);
assert!(sk != SecretKey::new());
let pk = PublicKey::from_secret_key(&sk, false);
let pk_comp = PublicKey::from_secret_key(&sk, true);
let mut msg = [0u8, ..32];
rng.fill_bytes(msg);
let nonce = Nonce::new(&mut rng);
rand::task_rng().fill_bytes(msg.as_mut_slice());
let (sig, recid) = sign_compact(msg.as_slice(), &sk, &nonce).unwrap();
let (sk, pk) = s.generate_keypair(false);
let nonce = s.generate_nonce();
assert_eq!(recover_compact(msg.as_slice(), sig.as_slice(), false, recid), Ok(pk));
assert_eq!(recover_compact(msg.as_slice(), sig.as_slice(), true, recid), Ok(pk_comp));
let (sig, recid) = s.sign_compact(msg.as_slice(), &sk, &nonce).unwrap();
assert_eq!(s.recover_compact(msg.as_slice(), sig.as_slice(), false, recid), Ok(pk));
}
#[test]
fn deterministic_sign() {
let mut rng = rand::task_rng();
let mut sk = SecretKey::new();
sk.init_rng(&mut rng);
let pk = PublicKey::from_secret_key(&sk, true);
let mut msg = [0u8, ..32];
rng.fill_bytes(msg);
rand::task_rng().fill_bytes(msg.as_mut_slice());
let mut s = Secp256k1::new().unwrap();
let (sk, pk) = s.generate_keypair(true);
let nonce = Nonce::deterministic(msg, &sk);
let sig = sign(msg.as_slice(), &sk, &nonce).unwrap();
assert_eq!(verify(msg.as_slice(), &sig, &pk), Ok(()));
let sig = s.sign(msg.as_slice(), &sk, &nonce).unwrap();
assert_eq!(Secp256k1::verify(msg.as_slice(), &sig, &pk), Ok(()));
}
#[bench]
pub fn generate_compressed(bh: &mut Bencher) {
let mut rng = rand::task_rng();
let mut sk = SecretKey::new();
let mut s = Secp256k1::new().unwrap();
bh.iter( || {
sk.init_rng(&mut rng);
black_box(PublicKey::from_secret_key(&sk, true));
let (sk, pk) = s.generate_keypair(true);
black_box(sk);
black_box(pk);
});
}
#[bench]
pub fn generate_uncompressed(bh: &mut Bencher) {
let mut rng = rand::task_rng();
let mut sk = SecretKey::new();
let mut s = Secp256k1::new().unwrap();
bh.iter( || {
sk.init_rng(&mut rng);
black_box(PublicKey::from_secret_key(&sk, false));
let (sk, pk) = s.generate_keypair(false);
black_box(sk);
black_box(pk);
});
}
}