1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use ark_ff::UniformRand;
use ark_serialize::CanonicalSerialize;
use ark_std::rand::{
    distributions::{Distribution, Standard},
    Rng,
};

use crate::{element::EdwardsProjective, AffineElement, Element, Encoding};

impl Distribution<Element> for Standard {
    #[inline]
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Element {
        loop {
            // 1. Generate random underlying elliptic curve point.
            let test_point = EdwardsProjective::rand(rng);
            let mut bytes = [0u8; 32];
            test_point
                .serialize_compressed(&mut bytes[..])
                .expect("serialization into array should be infallible");

            // 2. Check if valid decaf point. If not continue.
            if let Ok(p) = Encoding(bytes).vartime_decompress() {
                return p;
            }
        }
    }
}

impl Distribution<AffineElement> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> AffineElement {
        let point: Element = self.sample(rng);
        point.into()
    }
}