Migrate to rand 0.6.

master
Andreas Fackler 6 years ago committed by Andreas Fackler
parent 1b1df40c67
commit a14e7d1867
  1. 8
      Cargo.toml
  2. 12
      benches/bench.rs
  3. 86
      src/lib.rs
  4. 2
      src/mock/mod.rs
  5. 2
      src/mock/ms8.rs
  6. 5
      src/poly.rs
  7. 7
      src/serde_impl.rs

@ -23,13 +23,13 @@ byteorder = "1.2.7"
errno = "0.2.4" errno = "0.2.4"
failure = "0.1.3" failure = "0.1.3"
hex_fmt = "0.2.0" hex_fmt = "0.2.0"
init_with = "1.1.0"
lazy_static = "1.1.0" lazy_static = "1.1.0"
log = "0.4.5" log = "0.4.5"
memsec = "0.5.4" memsec = "0.5.4"
pairing = { version = "0.14.2", features = ["u128-support"] } pairing = { version = "0.14.2", features = ["u128-support"] }
rand = "0.4.3" rand = "0.6.1"
rand_derive = "0.3.1" rand04_compat = { git = "https://github.com/poanetwork/rand04_compat" }
rand_chacha = "0.1.0"
serde = "1.0.80" serde = "1.0.80"
serde_derive = "1.0.80" serde_derive = "1.0.80"
tiny-keccak = "1.4.2" tiny-keccak = "1.4.2"
@ -37,8 +37,8 @@ tiny-keccak = "1.4.2"
[dev-dependencies] [dev-dependencies]
bincode = "1.0.1" bincode = "1.0.1"
criterion = "0.2.5" criterion = "0.2.5"
rand = "0.4.3"
serde_derive = "1.0.80" serde_derive = "1.0.80"
rand_xorshift = "0.1.0"
[[bench]] [[bench]]
name = "bench" name = "bench"

@ -4,11 +4,13 @@ use threshold_crypto::Fr;
const TEST_DEGREES: [usize; 4] = [5, 10, 20, 40]; const TEST_DEGREES: [usize; 4] = [5, 10, 20, 40];
const TEST_THRESHOLDS: [usize; 4] = [5, 10, 20, 40]; const TEST_THRESHOLDS: [usize; 4] = [5, 10, 20, 40];
const RNG_SEED: [u32; 4] = [1, 2, 3, 4]; const RNG_SEED: [u8; 16] = *b"0123456789abcdef";
mod poly_benches { mod poly_benches {
use super::*; use super::*;
use rand::{Rng, SeedableRng, XorShiftRng}; use rand::SeedableRng;
use rand04_compat::RngExt;
use rand_xorshift::XorShiftRng;
/// Benchmarks multiplication of two polynomials. /// Benchmarks multiplication of two polynomials.
fn multiplication(c: &mut Criterion) { fn multiplication(c: &mut Criterion) {
@ -67,7 +69,8 @@ mod poly_benches {
c.bench_function_over_inputs( c.bench_function_over_inputs(
"Polynomial interpolation", "Polynomial interpolation",
move |b, &&deg| { move |b, &&deg| {
let rand_samples = || (0..=deg).map(|i| (i, rng.gen::<Fr>())).collect::<Vec<_>>(); let mut gen_tuple = |i: usize| (i, rng.gen04::<Fr>());
let rand_samples = move || (0..=deg).map(&mut gen_tuple).collect::<Vec<_>>();
b.iter_with_setup(rand_samples, Poly::interpolate) b.iter_with_setup(rand_samples, Poly::interpolate)
}, },
&TEST_DEGREES, &TEST_DEGREES,
@ -83,7 +86,8 @@ mod poly_benches {
mod public_key_set_benches { mod public_key_set_benches {
use super::*; use super::*;
use rand::{SeedableRng, XorShiftRng}; use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use threshold_crypto::SecretKeySet; use threshold_crypto::SecretKeySet;

@ -24,13 +24,13 @@ use std::fmt;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::ptr::copy_nonoverlapping; use std::ptr::copy_nonoverlapping;
use byteorder::{BigEndian, ByteOrder};
use hex_fmt::HexFmt; use hex_fmt::HexFmt;
use init_with::InitWith;
use log::debug; use log::debug;
use pairing::{CurveAffine, CurveProjective, EncodedPoint, Engine, Field}; use pairing::{CurveAffine, CurveProjective, EncodedPoint, Engine, Field};
use rand::{ChaChaRng, OsRng, Rand, Rng, SeedableRng}; use rand::distributions::{Distribution, Standard};
use rand_derive::Rand; use rand::{rngs::OsRng, Rng, SeedableRng};
use rand04_compat::RngExt;
use rand_chacha::ChaChaRng;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use tiny_keccak::sha3_256; use tiny_keccak::sha3_256;
@ -59,9 +59,6 @@ pub const PK_SIZE: usize = 48;
#[cfg(not(feature = "use-insecure-test-only-mock-crypto"))] #[cfg(not(feature = "use-insecure-test-only-mock-crypto"))]
pub const SIG_SIZE: usize = 96; pub const SIG_SIZE: usize = 96;
/// The number of words (`u32`) in a ChaCha RNG seed.
const CHACHA_RNG_SEED_SIZE: usize = 8;
const ERR_OS_RNG: &str = "could not initialize the OS random number generator"; const ERR_OS_RNG: &str = "could not initialize the OS random number generator";
/// A public key. /// A public key.
@ -104,7 +101,7 @@ impl PublicKey {
/// Encrypts the message. /// Encrypts the message.
pub fn encrypt_with_rng<R: Rng, M: AsRef<[u8]>>(&self, rng: &mut R, msg: M) -> Ciphertext { pub fn encrypt_with_rng<R: Rng, M: AsRef<[u8]>>(&self, rng: &mut R, msg: M) -> Ciphertext {
let r: Fr = rng.gen(); let r: Fr = rng.gen04();
let u = G1Affine::one().mul(r); let u = G1Affine::one().mul(r);
let v: Vec<u8> = { let v: Vec<u8> = {
let g = self.0.into_affine().mul(r); let g = self.0.into_affine().mul(r);
@ -175,9 +172,15 @@ impl PublicKeyShare {
/// A signature. /// A signature.
// Note: Random signatures can be generated for testing. // Note: Random signatures can be generated for testing.
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Rand)] #[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct Signature(#[serde(with = "serde_impl::projective")] G2); pub struct Signature(#[serde(with = "serde_impl::projective")] G2);
impl Distribution<Signature> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Signature {
Signature(rng.gen04())
}
}
impl fmt::Debug for Signature { impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let uncomp = self.0.into_affine().into_uncompressed(); let uncomp = self.0.into_affine().into_uncompressed();
@ -220,9 +223,15 @@ impl Signature {
/// A signature share. /// A signature share.
// Note: Random signature shares can be generated for testing. // Note: Random signature shares can be generated for testing.
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Rand, Hash)] #[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Hash)]
pub struct SignatureShare(pub Signature); pub struct SignatureShare(pub Signature);
impl Distribution<SignatureShare> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SignatureShare {
SignatureShare(rng.gen())
}
}
impl fmt::Debug for SignatureShare { impl fmt::Debug for SignatureShare {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let uncomp = (self.0).0.into_affine().into_uncompressed(); let uncomp = (self.0).0.into_affine().into_uncompressed();
@ -256,12 +265,9 @@ impl Default for SecretKey {
} }
} }
/// Creates a random `SecretKey` from a given RNG. If you do not need to specify your own RNG, you impl Distribution<SecretKey> for Standard {
/// should use `SecretKey::random()` as your constructor instead. fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SecretKey {
impl Rand for SecretKey { SecretKey(Box::new(rng.gen04()))
fn rand<R: Rng>(rng: &mut R) -> Self {
let mut fr = Fr::rand(rng);
SecretKey::from_mut(&mut fr)
} }
} }
@ -318,8 +324,7 @@ impl SecretKey {
/// [`rand::thead_rng()`](https://docs.rs/rand/0.4.3/rand/fn.thread_rng.html) internally as /// [`rand::thead_rng()`](https://docs.rs/rand/0.4.3/rand/fn.thread_rng.html) internally as
/// its RNG. /// its RNG.
pub fn random() -> Self { pub fn random() -> Self {
let mut rng = rand::thread_rng(); rand::random()
SecretKey::rand(&mut rng)
} }
/// Returns the matching public key. /// Returns the matching public key.
@ -359,9 +364,15 @@ impl SecretKey {
} }
/// A secret key share. /// A secret key share.
#[derive(Clone, PartialEq, Eq, Rand, Default)] #[derive(Clone, PartialEq, Eq, Default)]
pub struct SecretKeyShare(SecretKey); pub struct SecretKeyShare(SecretKey);
impl Distribution<SecretKeyShare> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SecretKeyShare {
SecretKeyShare(rng.gen())
}
}
impl fmt::Debug for SecretKeyShare { impl fmt::Debug for SecretKeyShare {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("SecretKeyShare").field(&"...").finish() f.debug_tuple("SecretKeyShare").field(&"...").finish()
@ -445,9 +456,15 @@ impl Ciphertext {
} }
/// A decryption share. A threshold of decryption shares can be used to decrypt a message. /// A decryption share. A threshold of decryption shares can be used to decrypt a message.
#[derive(Clone, Deserialize, Serialize, Debug, PartialEq, Eq, Rand)] #[derive(Clone, Deserialize, Serialize, Debug, PartialEq, Eq)]
pub struct DecryptionShare(#[serde(with = "serde_impl::projective")] G1); pub struct DecryptionShare(#[serde(with = "serde_impl::projective")] G1);
impl Distribution<DecryptionShare> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> DecryptionShare {
DecryptionShare(rng.gen04())
}
}
impl Hash for DecryptionShare { impl Hash for DecryptionShare {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.0.into_affine().into_compressed().as_ref().hash(state); self.0.into_affine().into_compressed().as_ref().hash(state);
@ -577,11 +594,7 @@ impl SecretKeySet {
/// Returns a hash of the given message in `G2`. /// Returns a hash of the given message in `G2`.
pub fn hash_g2<M: AsRef<[u8]>>(msg: M) -> G2 { pub fn hash_g2<M: AsRef<[u8]>>(msg: M) -> G2 {
let digest = sha3_256(msg.as_ref()); let digest = sha3_256(msg.as_ref());
let seed = <[u32; CHACHA_RNG_SEED_SIZE]>::init_with_indices(|i| { ChaChaRng::from_seed(digest).gen04()
BigEndian::read_u32(&digest.as_ref()[(4 * i)..(4 * i + 4)])
});
let mut rng = ChaChaRng::from_seed(&seed);
rng.gen()
} }
/// Returns a hash of the group element and message, in the second group. /// Returns a hash of the group element and message, in the second group.
@ -600,12 +613,9 @@ fn hash_g1_g2<M: AsRef<[u8]>>(g1: G1, msg: M) -> G2 {
/// Returns the bitwise xor of `bytes` with a sequence of pseudorandom bytes determined by `g1`. /// Returns the bitwise xor of `bytes` with a sequence of pseudorandom bytes determined by `g1`.
fn xor_with_hash(g1: G1, bytes: &[u8]) -> Vec<u8> { fn xor_with_hash(g1: G1, bytes: &[u8]) -> Vec<u8> {
let digest = sha3_256(g1.into_affine().into_compressed().as_ref()); let digest = sha3_256(g1.into_affine().into_compressed().as_ref());
let seed = <[u32; CHACHA_RNG_SEED_SIZE]>::init_with_indices(|i| { let mut rng = ChaChaRng::from_seed(digest);
BigEndian::read_u32(&digest.as_ref()[(4 * i)..(4 * i + 4)])
});
let mut rng = ChaChaRng::from_seed(&seed);
let xor = |(a, b): (u8, &u8)| a ^ b; let xor = |(a, b): (u8, &u8)| a ^ b;
rng.gen_iter().zip(bytes).map(xor).collect() rng.gen_iter04().zip(bytes).map(xor).collect()
} }
use std::borrow::Borrow; use std::borrow::Borrow;
@ -674,7 +684,8 @@ mod tests {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use rand::{self, random, Rng}; use rand::{self, distributions::Standard, random, Rng};
use rand04_compat::rand04::random as random04;
#[test] #[test]
fn test_interpolate() { fn test_interpolate() {
@ -828,7 +839,7 @@ mod tests {
#[test] #[test]
fn test_hash_g2() { fn test_hash_g2() {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let msg: Vec<u8> = (0..1000).map(|_| rng.gen()).collect(); let msg: Vec<u8> = rng.sample_iter(&Standard).take(1000).collect();
let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect(); let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect();
let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect(); let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect();
@ -841,11 +852,11 @@ mod tests {
#[test] #[test]
fn test_hash_g1_g2() { fn test_hash_g1_g2() {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let msg: Vec<u8> = (0..1000).map(|_| rng.gen()).collect(); let msg: Vec<u8> = rng.sample_iter(&Standard).take(1000).collect();
let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect(); let msg_end0: Vec<u8> = msg.iter().chain(b"end0").cloned().collect();
let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect(); let msg_end1: Vec<u8> = msg.iter().chain(b"end1").cloned().collect();
let g0 = rng.gen(); let g0 = random04();
let g1 = rng.gen(); let g1 = random04();
assert_eq!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg)); assert_eq!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg));
assert_ne!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg_end0)); assert_ne!(hash_g1_g2(g0, &msg), hash_g1_g2(g0, &msg_end0));
@ -856,9 +867,8 @@ mod tests {
/// Some basic sanity checks for the `hash_bytes` function. /// Some basic sanity checks for the `hash_bytes` function.
#[test] #[test]
fn test_xor_with_hash() { fn test_xor_with_hash() {
let mut rng = rand::thread_rng(); let g0 = random04();
let g0 = rng.gen(); let g1 = random04();
let g1 = rng.gen();
let xwh = xor_with_hash; let xwh = xor_with_hash;
assert_eq!(xwh(g0, &[0; 5]), xwh(g0, &[0; 5])); assert_eq!(xwh(g0, &[0; 5]), xwh(g0, &[0; 5]));
assert_ne!(xwh(g0, &[0; 5]), xwh(g1, &[0; 5])); assert_ne!(xwh(g0, &[0; 5]), xwh(g1, &[0; 5]));

@ -15,7 +15,7 @@ pub mod ms8;
use std::{fmt, mem, slice}; use std::{fmt, mem, slice};
use pairing::{EncodedPoint, Field, GroupDecodingError, PrimeField}; use pairing::{EncodedPoint, Field, GroupDecodingError, PrimeField};
use rand; use rand04_compat::rand04 as rand;
use super::{CurveAffine, CurveProjective, Engine}; use super::{CurveAffine, CurveProjective, Engine};

@ -14,7 +14,7 @@ use byteorder::{BigEndian, ByteOrder};
use pairing::{ use pairing::{
Field, LegendreSymbol, PrimeField, PrimeFieldDecodingError, PrimeFieldRepr, SqrtField, Field, LegendreSymbol, PrimeField, PrimeFieldDecodingError, PrimeFieldRepr, SqrtField,
}; };
use rand; use rand04_compat::rand04 as rand;
/// Modular exponentiation /// Modular exponentiation
/// ///

@ -24,6 +24,7 @@ use std::{cmp, iter, ops};
use pairing::{CurveAffine, CurveProjective, Field}; use pairing::{CurveAffine, CurveProjective, Field};
use rand::Rng; use rand::Rng;
use rand04_compat::RngExt;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use crate::error::{Error, Result}; use crate::error::{Error, Result};
@ -295,7 +296,7 @@ impl Poly {
if degree == usize::max_value() { if degree == usize::max_value() {
return Err(Error::DegreeTooHigh); return Err(Error::DegreeTooHigh);
} }
let coeff: Vec<Fr> = (0..=degree).map(|_| rng.gen()).collect(); let coeff: Vec<Fr> = rng.gen_iter04().take(degree + 1).collect();
Ok(Poly::from(coeff)) Ok(Poly::from(coeff))
} }
@ -566,7 +567,7 @@ impl BivarPoly {
.ok_or(Error::DegreeTooHigh)?; .ok_or(Error::DegreeTooHigh)?;
let poly = BivarPoly { let poly = BivarPoly {
degree, degree,
coeff: (0..len).map(|_| rng.gen()).collect(), coeff: rng.gen_iter04().take(len).collect(),
}; };
Ok(poly) Ok(poly)
} }

@ -201,7 +201,8 @@ pub mod field_vec {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use bincode; use bincode;
use rand::{self, Rng}; use rand;
use rand04_compat::RngExt;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use crate::poly::BivarPoly; use crate::poly::BivarPoly;
@ -225,8 +226,8 @@ mod tests {
fn vecs() { fn vecs() {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let vecs = Vecs { let vecs = Vecs {
curve_points: rng.gen_iter().take(10).collect(), curve_points: rng.gen_iter04().take(10).collect(),
field_elements: rng.gen_iter().take(10).collect(), field_elements: rng.gen_iter04().take(10).collect(),
}; };
let ser_vecs = bincode::serialize(&vecs).expect("serialize vecs"); let ser_vecs = bincode::serialize(&vecs).expect("serialize vecs");
let de_vecs = bincode::deserialize(&ser_vecs).expect("deserialize vecs"); let de_vecs = bincode::deserialize(&ser_vecs).expect("deserialize vecs");

Loading…
Cancel
Save