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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use super::*;
impl<E: Environment, const RATE: usize> HashToGroup for Poseidon<E, RATE> {
type Input = Field<E>;
type Output = Group<E>;
#[inline]
fn hash_to_group(&self, input: &[Self::Input]) -> Result<Self::Output> {
ensure!(!input.is_empty(), "Input to hash to group cannot be empty");
match self.hash_many(input, 2).iter().map(Elligator2::<E>::encode).collect_tuple() {
Some((Ok((h0, _)), Ok((h1, _)))) => Ok(h0 + h1),
_ => bail!("Poseidon failed to compute hash to group on the given input"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use snarkvm_console_types::environment::Console;
type CurrentEnvironment = Console;
const ITERATIONS: u64 = 1000;
macro_rules! check_hash_to_group {
($poseidon:ident) => {{
let poseidon = $poseidon::<CurrentEnvironment>::setup("HashToGroupTest")?;
assert!(poseidon.hash_to_group(&[]).is_err());
let mut rng = TestRng::default();
for _ in 0..ITERATIONS {
for num_inputs in 1..8 {
let inputs = (0..num_inputs).map(|_| Uniform::rand(&mut rng)).collect::<Vec<_>>();
let candidate = poseidon.hash_to_group(&inputs)?;
assert!((*candidate).to_affine().is_on_curve());
assert!((*candidate).to_affine().is_in_correct_subgroup_assuming_on_curve());
assert_ne!(Group::<CurrentEnvironment>::zero(), candidate);
assert_ne!(Group::<CurrentEnvironment>::generator(), candidate);
let candidate_cofactor_inv = candidate.div_by_cofactor();
assert_eq!(candidate, candidate_cofactor_inv.mul_by_cofactor());
}
}
Ok(())
}};
}
#[test]
fn test_poseidon2_hash_to_group() -> Result<()> {
check_hash_to_group!(Poseidon2)
}
#[test]
fn test_poseidon4_hash_to_group() -> Result<()> {
check_hash_to_group!(Poseidon4)
}
#[test]
fn test_poseidon8_hash_to_group() -> Result<()> {
check_hash_to_group!(Poseidon8)
}
}