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
use crate::MontFelt;
impl MontFelt {
/// Tonelli-Shanks algorithm to compute the square root
///
/// Based on arkwork which is based on <https://eprint.iacr.org/2012/685.pdf> (p.12, alg.5).
pub fn sqrt(&self) -> Option<MontFelt> {
if self.is_zero() {
return Some(MontFelt::ZERO);
}
let mut z = MontFelt::SQRT_Z;
let mut w = self.pow(MontFelt::SQRT_T_MINUS_ONE_DIV2);
let mut x = w * self;
let mut b = x * w;
let mut v = MontFelt::SQRT_S;
while !b.is_one() {
let mut k = 0;
// Search for minimum k such that b^(2^k) = 1
let mut b2k = b;
while !b2k.is_one() {
b2k = b2k.square();
k += 1;
}
// If k = s, then a square root does not exist (QNR)
if k == MontFelt::SQRT_S {
return None;
}
let j = v - k;
w = z;
for _ in 1..j {
w = w.square();
}
z = w.square();
b *= z;
x *= w;
v = k;
}
// A square root always exists, since QNR's were filtered out
Some(x)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sqrt_base() {
// Test sqrt(9) = 3 or -3
let nine = MontFelt::from(9u64);
let three = MontFelt::from(3u64);
let sqrt = nine.sqrt().unwrap();
assert!(sqrt == three || sqrt == -three);
}
#[test]
fn test_sqrt_random() {
let mut rng = rand::thread_rng();
for _ in 0..100 {
let x = MontFelt::random(&mut rng);
let sqrt = x.sqrt();
if let Some(sqrt) = sqrt {
assert_eq!(sqrt.square(), x);
}
}
}
}