| 1 |
// Copyright (c) 2020 Apple Inc. |
| 2 |
// SPDX-License-Identifier: MPL-2.0 |
| 3 |
|
| 4 |
//! Tool for generating pseudorandom field elements. |
| 5 |
//! |
| 6 |
//! NOTE: The public API for this module is a work in progress. |
| 7 |
|
| 8 |
use crate::field::{FieldElement, FieldElementExt}; |
| 9 |
#[cfg(all(feature = "crypto-dependencies", feature = "experimental"))] |
| 10 |
use crate::vdaf::xof::SeedStreamAes128; |
| 11 |
use crate::vdaf::xof::{Seed, SeedStreamTurboShake128, Xof, XofTurboShake128}; |
| 12 |
use rand_core::RngCore; |
| 13 |
|
| 14 |
use std::marker::PhantomData; |
| 15 |
use std::ops::ControlFlow; |
| 16 |
|
| 17 |
const BUFFER_SIZE_IN_ELEMENTS: usize = 32; |
| 18 |
|
| 19 |
/// Errors propagated by methods in this module. |
| 20 |
#[derive(Debug, thiserror::Error)] |
| 21 |
#[non_exhaustive] |
| 22 |
pub enum PrngError { |
| 23 |
/// Failure when calling getrandom(). |
| 24 |
#[error("getrandom: {0}")] |
| 25 |
GetRandom(#[from] getrandom::Error), |
| 26 |
} |
| 27 |
|
| 28 |
/// This type implements an iterator that generates a pseudorandom sequence of field elements. The |
| 29 |
/// sequence is derived from a XOF's key stream. |
| 30 |
#[derive(Debug)] |
| 31 |
pub(crate) struct Prng<F, S> { |
| 32 |
phantom: PhantomData<F>, |
| 33 |
seed_stream: S, |
| 34 |
buffer: Vec<u8>, |
| 35 |
buffer_index: usize, |
| 36 |
} |
| 37 |
|
| 38 |
#[cfg(all(feature = "crypto-dependencies", feature = "experimental"))] |
| 39 |
impl<F: FieldElement> Prng<F, SeedStreamAes128> { |
| 40 |
/// Create a [`Prng`] from a seed for Prio 2. The first 16 bytes of the seed and the last 16 |
| 41 |
/// bytes of the seed are used, respectively, for the key and initialization vector for AES128 |
| 42 |
/// in CTR mode. |
| 43 |
pub(crate) fn from_prio2_seed(seed: &[u8; 32]) -> Self { |
| 44 |
let seed_stream = SeedStreamAes128::new(&seed[..16], &seed[16..]); |
| 45 |
Self::from_seed_stream(seed_stream) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
impl<F: FieldElement> Prng<F, SeedStreamTurboShake128> { |
| 50 |
/// Create a [`Prng`] from a randomly generated seed. |
| 51 |
pub(crate) fn new() -> Result<Self, PrngError> { |
| 52 |
let seed = Seed::generate()?; |
| 53 |
Ok(Prng::from_seed_stream(XofTurboShake128::seed_stream( |
| 54 |
&seed, |
| 55 |
&[], |
| 56 |
&[], |
| 57 |
))) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
impl<F, S> Prng<F, S> |
| 62 |
where |
| 63 |
F: FieldElement, |
| 64 |
S: RngCore, |
| 65 |
{ |
| 66 |
pub(crate) fn from_seed_stream(mut seed_stream: S) -> Self { |
| 67 |
let mut buffer = vec![0; BUFFER_SIZE_IN_ELEMENTS * F::ENCODED_SIZE]; |
| 68 |
seed_stream.fill_bytes(&mut buffer); |
| 69 |
|
| 70 |
Self { |
| 71 |
phantom: PhantomData::<F>, |
| 72 |
seed_stream, |
| 73 |
buffer, |
| 74 |
buffer_index: 0, |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
pub(crate) fn get(&mut self) -> F { |
| 79 |
loop { |
| 80 |
// Seek to the next chunk of the buffer that encodes an element of F. |
| 81 |
for i in (self.buffer_index..self.buffer.len()).step_by(F::ENCODED_SIZE) { |
| 82 |
let j = i + F::ENCODED_SIZE; |
| 83 |
|
| 84 |
if j > self.buffer.len() { |
| 85 |
break; |
| 86 |
} |
| 87 |
|
| 88 |
self.buffer_index = j; |
| 89 |
|
| 90 |
match F::from_random_rejection(&self.buffer[i..j]) { |
| 91 |
ControlFlow::Break(x) => return x, |
| 92 |
ControlFlow::Continue(()) => continue, // reject this sample |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
// Refresh buffer with the next chunk of XOF output, filling the front of the buffer |
| 97 |
// with the leftovers. This ensures continuity of the seed stream after converting the |
| 98 |
// `Prng` to a new field type via `into_new_field()`. |
| 99 |
let left_over = self.buffer.len() - self.buffer_index; |
| 100 |
self.buffer.copy_within(self.buffer_index.., 0); |
| 101 |
self.seed_stream.fill_bytes(&mut self.buffer[left_over..]); |
| 102 |
self.buffer_index = 0; |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
/// Convert this object into a field element generator for a different field. |
| 107 |
#[cfg(all(feature = "crypto-dependencies", feature = "experimental"))] |
| 108 |
pub(crate) fn into_new_field<F1: FieldElement>(self) -> Prng<F1, S> { |
| 109 |
Prng { |
| 110 |
phantom: PhantomData, |
| 111 |
seed_stream: self.seed_stream, |
| 112 |
buffer: self.buffer, |
| 113 |
buffer_index: self.buffer_index, |
| 114 |
} |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
impl<F, S> Iterator for Prng<F, S> |
| 119 |
where |
| 120 |
F: FieldElement, |
| 121 |
S: RngCore, |
| 122 |
{ |
| 123 |
type Item = F; |
| 124 |
|
| 125 |
fn next(&mut self) -> Option<F> { |
| 126 |
Some(self.get()) |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
#[cfg(test)] |
| 131 |
mod tests { |
| 132 |
use super::*; |
| 133 |
#[cfg(feature = "experimental")] |
| 134 |
use crate::field::{encode_fieldvec, Field128, FieldPrio2}; |
| 135 |
use crate::{ |
| 136 |
codec::Decode, |
| 137 |
field::Field64, |
| 138 |
vdaf::xof::{Seed, SeedStreamTurboShake128, Xof, XofTurboShake128}, |
| 139 |
}; |
| 140 |
#[cfg(feature = "experimental")] |
| 141 |
use base64::{engine::Engine, prelude::BASE64_STANDARD}; |
| 142 |
#[cfg(feature = "experimental")] |
| 143 |
use sha2::{Digest, Sha256}; |
| 144 |
|
| 145 |
#[test] |
| 146 |
#[cfg(feature = "experimental")] |
| 147 |
fn secret_sharing_interop() { |
| 148 |
let seed = [ |
| 149 |
0xcd, 0x85, 0x5b, 0xd4, 0x86, 0x48, 0xa4, 0xce, 0x52, 0x5c, 0x36, 0xee, 0x5a, 0x71, |
| 150 |
0xf3, 0x0f, 0x66, 0x80, 0xd3, 0x67, 0x53, 0x9a, 0x39, 0x6f, 0x12, 0x2f, 0xad, 0x94, |
| 151 |
0x4d, 0x34, 0xcb, 0x58, |
| 152 |
]; |
| 153 |
|
| 154 |
let reference = [ |
| 155 |
0xd0056ec5, 0xe23f9c52, 0x47e4ddb4, 0xbe5dacf6, 0x4b130aba, 0x530c7a90, 0xe8fc4ee5, |
| 156 |
0xb0569cb7, 0x7774cd3c, 0x7f24e6a5, 0xcc82355d, 0xc41f4f13, 0x67fe193c, 0xc94d63a4, |
| 157 |
0x5d7b474c, 0xcc5c9f5f, 0xe368e1d5, 0x020fa0cf, 0x9e96aa2a, 0xe924137d, 0xfa026ab9, |
| 158 |
0x8ebca0cc, 0x26fc58a5, 0x10a7b173, 0xb9c97291, 0x53ef0e28, 0x069cfb8e, 0xe9383cae, |
| 159 |
0xacb8b748, 0x6f5b9d49, 0x887d061b, 0x86db0c58, |
| 160 |
]; |
| 161 |
|
| 162 |
let share2 = extract_share_from_seed::<FieldPrio2>(reference.len(), &seed); |
| 163 |
|
| 164 |
assert_eq!(share2, reference); |
| 165 |
} |
| 166 |
|
| 167 |
/// takes a seed and hash as base64 encoded strings |
| 168 |
#[cfg(feature = "experimental")] |
| 169 |
fn random_data_interop(seed_base64: &str, hash_base64: &str, len: usize) { |
| 170 |
let seed = BASE64_STANDARD.decode(seed_base64).unwrap(); |
| 171 |
let random_data = extract_share_from_seed::<FieldPrio2>(len, &seed); |
| 172 |
|
| 173 |
let mut random_bytes = Vec::new(); |
| 174 |
encode_fieldvec(&random_data, &mut random_bytes).unwrap(); |
| 175 |
|
| 176 |
let mut hasher = <Sha256 as Digest>::new(); |
| 177 |
hasher.update(&random_bytes); |
| 178 |
let digest = hasher.finalize(); |
| 179 |
assert_eq!(BASE64_STANDARD.encode(digest), hash_base64); |
| 180 |
} |
| 181 |
|
| 182 |
#[test] |
| 183 |
#[cfg(feature = "experimental")] |
| 184 |
fn test_hash_interop() { |
| 185 |
random_data_interop( |
| 186 |
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", |
| 187 |
"RtzeQuuiWdD6bW2ZTobRELDmClz1wLy3HUiKsYsITOI=", |
| 188 |
100_000, |
| 189 |
); |
| 190 |
|
| 191 |
// zero seed |
| 192 |
random_data_interop( |
| 193 |
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", |
| 194 |
"3wHQbSwAn9GPfoNkKe1qSzWdKnu/R+hPPyRwwz6Di+w=", |
| 195 |
100_000, |
| 196 |
); |
| 197 |
// 0, 1, 2 ... seed |
| 198 |
random_data_interop( |
| 199 |
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", |
| 200 |
"RtzeQuuiWdD6bW2ZTobRELDmClz1wLy3HUiKsYsITOI=", |
| 201 |
100_000, |
| 202 |
); |
| 203 |
// one arbirtary fixed seed |
| 204 |
random_data_interop( |
| 205 |
"rkLrnVcU8ULaiuXTvR3OKrfpMX0kQidqVzta1pleKKg=", |
| 206 |
"b1fMXYrGUNR3wOZ/7vmUMmY51QHoPDBzwok0fz6xC0I=", |
| 207 |
100_000, |
| 208 |
); |
| 209 |
// all bits set seed |
| 210 |
random_data_interop( |
| 211 |
"//////////////////////////////////////////8=", |
| 212 |
"iBiDaqLrv7/rX/+vs6akPiprGgYfULdh/XhoD61HQXA=", |
| 213 |
100_000, |
| 214 |
); |
| 215 |
} |
| 216 |
|
| 217 |
#[cfg(feature = "experimental")] |
| 218 |
fn extract_share_from_seed<F: FieldElement>(length: usize, seed: &[u8]) -> Vec<F> { |
| 219 |
assert_eq!(seed.len(), 32); |
| 220 |
Prng::from_prio2_seed(seed.try_into().unwrap()) |
| 221 |
.take(length) |
| 222 |
.collect() |
| 223 |
} |
| 224 |
|
| 225 |
#[test] |
| 226 |
fn rejection_sampling_test_vector() { |
| 227 |
// These constants were found in a brute-force search, and they test that the XOF performs |
| 228 |
// rejection sampling correctly when the raw output exceeds the prime modulus. |
| 229 |
let seed = Seed::get_decoded(&[ |
| 230 |
0xd5, 0x3f, 0xff, 0x5d, 0x88, 0x8c, 0x60, 0x4e, 0x9f, 0x24, 0x16, 0xe1, 0xa2, 0x0a, |
| 231 |
0x62, 0x34, |
| 232 |
]) |
| 233 |
.unwrap(); |
| 234 |
let expected = Field64::from(3401316594827516850); |
| 235 |
|
| 236 |
let seed_stream = XofTurboShake128::seed_stream(&seed, b"", b""); |
| 237 |
let mut prng = Prng::<Field64, _>::from_seed_stream(seed_stream); |
| 238 |
let actual = prng.nth(662).unwrap(); |
| 239 |
assert_eq!(actual, expected); |
| 240 |
|
| 241 |
#[cfg(all(feature = "crypto-dependencies", feature = "experimental"))] |
| 242 |
{ |
| 243 |
let mut seed_stream = XofTurboShake128::seed_stream(&seed, b"", b""); |
| 244 |
let mut actual = <Field64 as FieldElement>::zero(); |
| 245 |
for _ in 0..=662 { |
| 246 |
actual = <Field64 as crate::idpf::IdpfValue>::generate(&mut seed_stream, &()); |
| 247 |
} |
| 248 |
assert_eq!(actual, expected); |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
// Test that the `Prng`'s internal buffer properly copies the end of the buffer to the front |
| 253 |
// once it reaches the end. |
| 254 |
#[test] |
| 255 |
fn left_over_buffer_back_fill() { |
| 256 |
let seed = Seed::generate().unwrap(); |
| 257 |
|
| 258 |
let mut prng: Prng<Field64, SeedStreamTurboShake128> = |
| 259 |
Prng::from_seed_stream(XofTurboShake128::seed_stream(&seed, b"", b"")); |
| 260 |
|
| 261 |
// Construct a `Prng` with a longer-than-usual buffer. |
| 262 |
let mut prng_weird_buffer_size: Prng<Field64, SeedStreamTurboShake128> = |
| 263 |
Prng::from_seed_stream(XofTurboShake128::seed_stream(&seed, b"", b"")); |
| 264 |
let mut extra = [0; 7]; |
| 265 |
prng_weird_buffer_size.seed_stream.fill_bytes(&mut extra); |
| 266 |
prng_weird_buffer_size.buffer.extend_from_slice(&extra); |
| 267 |
|
| 268 |
// Check that the next several outputs match. We need to check enough outputs to ensure |
| 269 |
// that we have to refill the buffer. |
| 270 |
for _ in 0..BUFFER_SIZE_IN_ELEMENTS * 2 { |
| 271 |
assert_eq!(prng.next().unwrap(), prng_weird_buffer_size.next().unwrap()); |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
#[cfg(feature = "experimental")] |
| 276 |
#[test] |
| 277 |
fn into_different_field() { |
| 278 |
let seed = Seed::generate().unwrap(); |
| 279 |
let want: Prng<Field64, SeedStreamTurboShake128> = |
| 280 |
Prng::from_seed_stream(XofTurboShake128::seed_stream(&seed, b"", b"")); |
| 281 |
let want_buffer = want.buffer.clone(); |
| 282 |
|
| 283 |
let got: Prng<Field128, _> = want.into_new_field(); |
| 284 |
assert_eq!(got.buffer_index, 0); |
| 285 |
assert_eq!(got.buffer, want_buffer); |
| 286 |
} |
| 287 |
} |