secp256k1_zkp_dev/lib.rs
1// secp256k1-zkp bindings
2// Written in 2019 by
3// Jonas Nick
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! The functions in this module are copied from secp256k1 because they can only be used when
16//! compiled with the `rand` feature. But the other libraries need them as a dev-dependency for
17//! `cargo test` also when `rand` is not enabled. Currently with cargo we can't have a `rand`
18//! dev-dependency and a non-`rand` dependency at the same time (see
19//! https://github.com/rust-lang/cargo/issues/1796).
20pub extern crate rand;
21pub extern crate secp256k1;
22
23use rand::Rng;
24use secp256k1::{PublicKey, Secp256k1, SecretKey, Signing};
25
26fn random_32_bytes<R: Rng>(rng: &mut R) -> [u8; 32] {
27 let mut ret = [0u8; 32];
28 rng.fill_bytes(&mut ret);
29 ret
30}
31
32trait NewSecretKey {
33 fn new<R: Rng>(rng: &mut R) -> SecretKey;
34}
35
36impl NewSecretKey for SecretKey {
37 /// Creates a new random secret key.
38 #[inline]
39 fn new<R: Rng>(rng: &mut R) -> SecretKey {
40 loop {
41 if let Ok(key) = SecretKey::from_slice(&random_32_bytes(rng)) {
42 return key;
43 }
44 }
45 }
46}
47
48pub trait GenerateKeypair {
49 /// Generates a random keypair.
50 fn generate_keypair<R: Rng>(&self, rng: &mut R) -> (SecretKey, PublicKey);
51}
52
53impl<C: Signing> GenerateKeypair for Secp256k1<C> {
54 #[inline]
55 fn generate_keypair<R: Rng>(&self, rng: &mut R) -> (SecretKey, PublicKey) {
56 let sk = SecretKey::new(rng);
57 let pk = PublicKey::from_secret_key(self, &sk);
58 (sk, pk)
59 }
60}