use crate::guts::ChaCha;
use core::convert::Infallible;
use core::fmt;
use rand_core::block::{BlockRng, Generator};
use rand_core::{SeedableRng, TryCryptoRng, TryRng};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
const BUF_BLOCKS: u8 = 4;
const BLOCK_WORDS: u8 = 16;
macro_rules! chacha_impl {
($ChaChaXCore:ident, $ChaChaXRng:ident, $rounds:expr, $doc:expr, $abst:ident,) => {
#[doc=$doc]
#[derive(Clone, PartialEq, Eq)]
pub struct $ChaChaXCore {
state: ChaCha,
}
impl fmt::Debug for $ChaChaXCore {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ChaChaXCore {{}}")
}
}
impl Generator for $ChaChaXCore {
type Output = [u32; 64];
#[inline]
fn generate(&mut self, output: &mut Self::Output) {
self.state.refill4($rounds, output);
}
}
impl SeedableRng for $ChaChaXCore {
type Seed = [u8; 32];
#[inline]
fn from_seed(seed: Self::Seed) -> Self {
$ChaChaXCore {
state: ChaCha::new(&seed, &[0u8; 8]),
}
}
}
#[derive(Clone, Debug)]
pub struct $ChaChaXRng {
rng: BlockRng<$ChaChaXCore>,
}
impl SeedableRng for $ChaChaXRng {
type Seed = [u8; 32];
#[inline]
fn from_seed(seed: Self::Seed) -> Self {
let core = $ChaChaXCore::from_seed(seed);
Self {
rng: BlockRng::new(core),
}
}
}
impl TryRng for $ChaChaXRng {
type Error = Infallible;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Infallible> {
Ok(self.rng.next_word())
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Infallible> {
Ok(self.rng.next_u64_from_u32())
}
#[inline]
fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Infallible> {
Ok(self.rng.fill_bytes(bytes))
}
}
impl $ChaChaXRng {
#[inline]
pub fn get_word_pos(&self) -> u128 {
let mut block_counter = self.rng.core.state.get_block_pos();
if self.rng.word_offset() != 0 {
block_counter = block_counter.wrapping_sub(BUF_BLOCKS as u64);
}
let word_pos = u128::from(block_counter) * u128::from(BLOCK_WORDS);
word_pos + self.rng.word_offset() as u128
}
#[inline]
pub fn set_word_pos(&mut self, word_offset: u128) {
let block = (word_offset / u128::from(BLOCK_WORDS)) as u64;
self.rng.core.state.set_block_pos(block);
self.rng
.reset_and_skip((word_offset % u128::from(BLOCK_WORDS)) as usize);
}
#[inline]
pub fn set_stream(&mut self, stream: u64) {
self.rng.core.state.set_nonce(stream);
if self.rng.word_offset() != 0 {
let wp = self.get_word_pos();
self.set_word_pos(wp);
}
}
#[inline]
pub fn get_stream(&self) -> u64 {
self.rng.core.state.get_nonce()
}
#[inline]
pub fn get_seed(&self) -> [u8; 32] {
self.rng.core.state.get_seed()
}
}
impl TryCryptoRng for $ChaChaXRng {}
impl From<$ChaChaXCore> for $ChaChaXRng {
fn from(core: $ChaChaXCore) -> Self {
$ChaChaXRng {
rng: BlockRng::new(core),
}
}
}
impl PartialEq<$ChaChaXRng> for $ChaChaXRng {
fn eq(&self, rhs: &$ChaChaXRng) -> bool {
let a: $abst::$ChaChaXRng = self.into();
let b: $abst::$ChaChaXRng = rhs.into();
a == b
}
}
impl Eq for $ChaChaXRng {}
#[cfg(feature = "serde")]
impl Serialize for $ChaChaXRng {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
$abst::$ChaChaXRng::from(self).serialize(s)
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $ChaChaXRng {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
$abst::$ChaChaXRng::deserialize(d).map(|x| Self::from(&x))
}
}
mod $abst {
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub(crate) struct $ChaChaXRng {
seed: [u8; 32],
stream: u64,
word_pos: u128,
}
impl From<&super::$ChaChaXRng> for $ChaChaXRng {
fn from(r: &super::$ChaChaXRng) -> Self {
Self {
seed: r.get_seed(),
stream: r.get_stream(),
word_pos: r.get_word_pos(),
}
}
}
impl From<&$ChaChaXRng> for super::$ChaChaXRng {
fn from(a: &$ChaChaXRng) -> Self {
use rand_core::SeedableRng;
let mut r = Self::from_seed(a.seed);
r.set_stream(a.stream);
r.set_word_pos(a.word_pos);
r
}
}
}
};
}
chacha_impl!(
ChaCha20Core,
ChaCha20Rng,
10,
"ChaCha with 20 rounds",
abstract20,
);
chacha_impl!(
ChaCha12Core,
ChaCha12Rng,
6,
"ChaCha with 12 rounds",
abstract12,
);
chacha_impl!(
ChaCha8Core,
ChaCha8Rng,
4,
"ChaCha with 8 rounds",
abstract8,
);
#[cfg(test)]
mod test {
#[cfg(feature = "serde")]
use super::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng};
use rand_core::{Rng, SeedableRng};
type ChaChaRng = super::ChaCha20Rng;
#[cfg(feature = "serde")]
#[test]
fn test_chacha_serde_roundtrip() {
let seed = [
1, 0, 52, 0, 0, 0, 0, 0, 1, 0, 10, 0, 22, 32, 0, 0, 2, 0, 55, 49, 0, 11, 0, 0, 3, 0, 0,
0, 0, 0, 2, 92,
];
let mut rng1 = ChaCha20Rng::from_seed(seed);
let mut rng2 = ChaCha12Rng::from_seed(seed);
let mut rng3 = ChaCha8Rng::from_seed(seed);
let encoded1 = serde_json::to_string(&rng1).unwrap();
let encoded2 = serde_json::to_string(&rng2).unwrap();
let encoded3 = serde_json::to_string(&rng3).unwrap();
let mut decoded1: ChaCha20Rng = serde_json::from_str(&encoded1).unwrap();
let mut decoded2: ChaCha12Rng = serde_json::from_str(&encoded2).unwrap();
let mut decoded3: ChaCha8Rng = serde_json::from_str(&encoded3).unwrap();
assert_eq!(rng1, decoded1);
assert_eq!(rng2, decoded2);
assert_eq!(rng3, decoded3);
assert_eq!(rng1.next_u32(), decoded1.next_u32());
assert_eq!(rng2.next_u32(), decoded2.next_u32());
assert_eq!(rng3.next_u32(), decoded3.next_u32());
}
#[cfg(feature = "serde")]
#[test]
fn test_chacha_serde_format_stability() {
let j = r#"{"seed":[4,8,15,16,23,42,4,8,15,16,23,42,4,8,15,16,23,42,4,8,15,16,23,42,4,8,15,16,23,42,4,8],"stream":27182818284,"word_pos":314159265359}"#;
let r: ChaChaRng = serde_json::from_str(j).unwrap();
let j1 = serde_json::to_string(&r).unwrap();
assert_eq!(j, j1);
}
#[test]
fn test_chacha_construction() {
let seed = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
0, 0, 0,
];
let mut rng1 = ChaChaRng::from_seed(seed);
assert_eq!(rng1.next_u32(), 137206642);
let mut rng2 = ChaChaRng::from_rng(&mut rng1);
assert_eq!(rng2.next_u32(), 1325750369);
}
#[test]
fn test_chacha_true_values_a() {
let seed = [0u8; 32];
let mut rng = ChaChaRng::from_seed(seed);
let mut results = [0u32; 16];
for i in results.iter_mut() {
*i = rng.next_u32();
}
let expected = [
0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8,
0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815,
0x69b687c3, 0x8665eeb2,
];
assert_eq!(results, expected);
for i in results.iter_mut() {
*i = rng.next_u32();
}
let expected = [
0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612,
0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51,
0x1f0ae1ac, 0x6f4d794b,
];
assert_eq!(results, expected);
}
#[test]
fn test_chacha_true_values_b() {
let seed = [
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,
];
let mut rng = ChaChaRng::from_seed(seed);
for _ in 0..16 {
rng.next_u32();
}
let mut results = [0u32; 16];
for i in results.iter_mut() {
*i = rng.next_u32();
}
let expected = [
0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8,
0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8,
0xebdd4aa6, 0xa0136c00,
];
assert_eq!(results, expected);
}
#[test]
fn test_chacha_true_values_c() {
let seed = [
0, 0xff, 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,
];
let expected = [
0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1,
0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5,
0x87f47473, 0x96f0992e,
];
let expected_end = 3 * 16;
let mut results = [0u32; 16];
let mut rng1 = ChaChaRng::from_seed(seed);
for _ in 0..32 {
rng1.next_u32();
}
for i in results.iter_mut() {
*i = rng1.next_u32();
}
assert_eq!(results, expected);
assert_eq!(rng1.get_word_pos(), expected_end);
let mut rng2 = ChaChaRng::from_seed(seed);
rng2.set_word_pos(2 * 16);
for i in results.iter_mut() {
*i = rng2.next_u32();
}
assert_eq!(results, expected);
assert_eq!(rng2.get_word_pos(), expected_end);
let mut buf = [0u8; 32];
rng2.fill_bytes(&mut buf[..]);
assert_eq!(rng2.get_word_pos(), expected_end + 8);
rng2.fill_bytes(&mut buf[0..25]);
assert_eq!(rng2.get_word_pos(), expected_end + 15);
rng2.next_u64();
assert_eq!(rng2.get_word_pos(), expected_end + 17);
rng2.next_u32();
rng2.next_u64();
assert_eq!(rng2.get_word_pos(), expected_end + 20);
rng2.fill_bytes(&mut buf[0..1]);
assert_eq!(rng2.get_word_pos(), expected_end + 21);
}
#[test]
fn test_chacha_multiple_blocks() {
let seed = [
0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7,
0, 0, 0,
];
let mut rng = ChaChaRng::from_seed(seed);
let mut results = [0u32; 16];
for i in results.iter_mut() {
*i = rng.next_u32();
for _ in 0..16 {
rng.next_u32();
}
}
let expected = [
0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186,
0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc,
0x5f1c86d9, 0xc1f8e7f4,
];
assert_eq!(results, expected);
}
#[test]
fn test_chacha_true_bytes() {
let seed = [0u8; 32];
let mut rng = ChaChaRng::from_seed(seed);
let mut results = [0u8; 32];
rng.fill_bytes(&mut results);
let expected = [
118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 83, 134, 189, 40, 189, 210,
25, 184, 160, 141, 237, 26, 168, 54, 239, 204, 139, 119, 13, 199,
];
assert_eq!(results, expected);
}
#[test]
fn test_chacha_nonce() {
let seed = [0u8; 32];
let mut rng = ChaChaRng::from_seed(seed);
rng.set_stream(2u64 << (24 + 32));
let mut results = [0u32; 16];
for i in results.iter_mut() {
*i = rng.next_u32();
}
let expected = [
0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72,
0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8,
0x398a19fa, 0x6ded1b53,
];
assert_eq!(results, expected);
}
#[test]
fn test_chacha_clone_streams() {
let seed = [
0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7,
0, 0, 0,
];
let mut rng = ChaChaRng::from_seed(seed);
let mut clone = rng.clone();
for _ in 0..16 {
assert_eq!(rng.next_u64(), clone.next_u64());
}
rng.set_stream(51);
for _ in 0..7 {
assert!(rng.next_u32() != clone.next_u32());
}
clone.set_stream(51); for _ in 7..16 {
assert_eq!(rng.next_u32(), clone.next_u32());
}
}
#[test]
fn test_chacha_word_pos_wrap_exact() {
use super::{BLOCK_WORDS, BUF_BLOCKS};
let mut rng = ChaChaRng::from_seed(Default::default());
let last_block = (1 << 68) - u128::from(BUF_BLOCKS * BLOCK_WORDS);
rng.set_word_pos(last_block);
assert_eq!(rng.get_word_pos(), last_block);
}
#[test]
fn test_chacha_word_pos_wrap_excess() {
use super::BLOCK_WORDS;
let mut rng = ChaChaRng::from_seed(Default::default());
let last_block = (1 << 68) - u128::from(BLOCK_WORDS);
rng.set_word_pos(last_block);
assert_eq!(rng.get_word_pos(), last_block);
}
#[test]
fn test_chacha_word_pos_zero() {
let mut rng = ChaChaRng::from_seed(Default::default());
assert_eq!(rng.get_word_pos(), 0);
rng.set_word_pos(0);
assert_eq!(rng.get_word_pos(), 0);
}
#[test]
fn test_trait_objects() {
use rand_core::CryptoRng;
let mut rng1 = ChaChaRng::from_seed(Default::default());
let rng2 = &mut rng1.clone() as &mut dyn CryptoRng;
for _ in 0..1000 {
assert_eq!(rng1.next_u64(), rng2.next_u64());
}
}
}