You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

466 lines
12 KiB

4 years ago
4 years ago
4 years ago
  1. #![allow(unused)]
  2. use ark_ff::fields::{FftField, FftParameters, Field, LegendreSymbol, PrimeField, SquareRootField};
  3. use ark_serialize::{buffer_bit_byte_size, Flags, SWFlags};
  4. use ark_std::io::Cursor;
  5. use rand::{Rng, SeedableRng};
  6. use rand_xorshift::XorShiftRng;
  7. pub const ITERATIONS: u32 = 40;
  8. fn random_negation_tests<F: Field, R: Rng>(rng: &mut R) {
  9. for _ in 0..ITERATIONS {
  10. let a = F::rand(rng);
  11. let mut b = -a;
  12. b += &a;
  13. assert!(b.is_zero());
  14. }
  15. }
  16. fn random_addition_tests<F: Field, R: Rng>(rng: &mut R) {
  17. for _ in 0..ITERATIONS {
  18. let a = F::rand(rng);
  19. let b = F::rand(rng);
  20. let c = F::rand(rng);
  21. let t0 = (a + &b) + &c; // (a + b) + c
  22. let t1 = (a + &c) + &b; // (a + c) + b
  23. let t2 = (b + &c) + &a; // (b + c) + a
  24. assert_eq!(t0, t1);
  25. assert_eq!(t1, t2);
  26. }
  27. }
  28. fn random_subtraction_tests<F: Field, R: Rng>(rng: &mut R) {
  29. for _ in 0..ITERATIONS {
  30. let a = F::rand(rng);
  31. let b = F::rand(rng);
  32. let t0 = a - &b; // (a - b)
  33. let mut t1 = b; // (b - a)
  34. t1 -= &a;
  35. let mut t2 = t0; // (a - b) + (b - a) = 0
  36. t2 += &t1;
  37. assert!(t2.is_zero());
  38. }
  39. }
  40. fn random_multiplication_tests<F: Field, R: Rng>(rng: &mut R) {
  41. for _ in 0..ITERATIONS {
  42. let a = F::rand(rng);
  43. let b = F::rand(rng);
  44. let c = F::rand(rng);
  45. let mut t0 = a; // (a * b) * c
  46. t0 *= &b;
  47. t0 *= &c;
  48. let mut t1 = a; // (a * c) * b
  49. t1 *= &c;
  50. t1 *= &b;
  51. let mut t2 = b; // (b * c) * a
  52. t2 *= &c;
  53. t2 *= &a;
  54. assert_eq!(t0, t1);
  55. assert_eq!(t1, t2);
  56. }
  57. }
  58. fn random_inversion_tests<F: Field, R: Rng>(rng: &mut R) {
  59. assert!(F::zero().inverse().is_none());
  60. for _ in 0..ITERATIONS {
  61. let mut a = F::rand(rng);
  62. let b = a.inverse().unwrap(); // probablistically nonzero
  63. a *= &b;
  64. assert_eq!(a, F::one());
  65. }
  66. }
  67. fn random_doubling_tests<F: Field, R: Rng>(rng: &mut R) {
  68. for _ in 0..ITERATIONS {
  69. let mut a = F::rand(rng);
  70. let mut b = a;
  71. a += &b;
  72. b.double_in_place();
  73. assert_eq!(a, b);
  74. }
  75. }
  76. fn random_squaring_tests<F: Field, R: Rng>(rng: &mut R) {
  77. for _ in 0..ITERATIONS {
  78. let mut a = F::rand(rng);
  79. let mut b = a;
  80. a *= &b;
  81. b.square_in_place();
  82. assert_eq!(a, b);
  83. }
  84. }
  85. fn random_expansion_tests<F: Field, R: Rng>(rng: &mut R) {
  86. for _ in 0..ITERATIONS {
  87. // Compare (a + b)(c + d) and (a*c + b*c + a*d + b*d)
  88. let a = F::rand(rng);
  89. let b = F::rand(rng);
  90. let c = F::rand(rng);
  91. let d = F::rand(rng);
  92. let mut t0 = a;
  93. t0 += &b;
  94. let mut t1 = c;
  95. t1 += &d;
  96. t0 *= &t1;
  97. let mut t2 = a;
  98. t2 *= &c;
  99. let mut t3 = b;
  100. t3 *= &c;
  101. let mut t4 = a;
  102. t4 *= &d;
  103. let mut t5 = b;
  104. t5 *= &d;
  105. t2 += &t3;
  106. t2 += &t4;
  107. t2 += &t5;
  108. assert_eq!(t0, t2);
  109. }
  110. for _ in 0..ITERATIONS {
  111. // Compare (a + b)c and (a*c + b*c)
  112. let a = F::rand(rng);
  113. let b = F::rand(rng);
  114. let c = F::rand(rng);
  115. let t0 = (a + &b) * &c;
  116. let t2 = a * &c + &(b * &c);
  117. assert_eq!(t0, t2);
  118. }
  119. }
  120. fn random_field_tests<F: Field>() {
  121. let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
  122. random_negation_tests::<F, _>(&mut rng);
  123. random_addition_tests::<F, _>(&mut rng);
  124. random_subtraction_tests::<F, _>(&mut rng);
  125. random_multiplication_tests::<F, _>(&mut rng);
  126. random_inversion_tests::<F, _>(&mut rng);
  127. random_doubling_tests::<F, _>(&mut rng);
  128. random_squaring_tests::<F, _>(&mut rng);
  129. random_expansion_tests::<F, _>(&mut rng);
  130. assert!(F::zero().is_zero());
  131. {
  132. let z = -F::zero();
  133. assert!(z.is_zero());
  134. }
  135. assert!(F::zero().inverse().is_none());
  136. // Multiplication by zero
  137. {
  138. let a = F::rand(&mut rng) * &F::zero();
  139. assert!(a.is_zero());
  140. }
  141. // Addition by zero
  142. {
  143. let mut a = F::rand(&mut rng);
  144. let copy = a;
  145. a += &F::zero();
  146. assert_eq!(a, copy);
  147. }
  148. }
  149. fn random_sqrt_tests<F: SquareRootField>() {
  150. let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
  151. for _ in 0..ITERATIONS {
  152. let a = F::rand(&mut rng);
  153. let b = a.square();
  154. assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
  155. let b = b.sqrt().unwrap();
  156. assert!(a == b || a == -b);
  157. }
  158. let mut c = F::one();
  159. for _ in 0..ITERATIONS {
  160. let mut b = c.square();
  161. assert_eq!(b.legendre(), LegendreSymbol::QuadraticResidue);
  162. b = b.sqrt().unwrap();
  163. if b != c {
  164. b = -b;
  165. }
  166. assert_eq!(b, c);
  167. c += &F::one();
  168. }
  169. }
  170. pub fn from_str_test<F: PrimeField>() {
  171. {
  172. let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
  173. for _ in 0..ITERATIONS {
  174. let n: u64 = rng.gen();
  175. let a = F::from_str(&ark_std::format!("{}", n))
  176. .map_err(|_| ())
  177. .unwrap();
  178. let b = F::from_repr(n.into()).unwrap();
  179. assert_eq!(a, b);
  180. }
  181. }
  182. assert!(F::from_str("").is_err());
  183. assert!(F::from_str("0").map_err(|_| ()).unwrap().is_zero());
  184. assert!(F::from_str("00").is_err());
  185. assert!(F::from_str("00000000000").is_err());
  186. }
  187. pub fn field_test<F: Field>(a: F, b: F) {
  188. let zero = F::zero();
  189. assert_eq!(zero, zero);
  190. assert_eq!(zero.is_zero(), true);
  191. assert_eq!(zero.is_one(), false);
  192. let one = F::one();
  193. assert_eq!(one, one);
  194. assert_eq!(one.is_zero(), false);
  195. assert_eq!(one.is_one(), true);
  196. assert_eq!(zero + &one, one);
  197. let two = one + &one;
  198. assert_eq!(two, two);
  199. assert_ne!(zero, two);
  200. assert_ne!(one, two);
  201. // a == a
  202. assert_eq!(a, a);
  203. // a + 0 = a
  204. assert_eq!(a + &zero, a);
  205. // a - 0 = a
  206. assert_eq!(a - &zero, a);
  207. // a - a = 0
  208. assert_eq!(a - &a, zero);
  209. // 0 - a = -a
  210. assert_eq!(zero - &a, -a);
  211. // a.double() = a + a
  212. assert_eq!(a.double(), a + &a);
  213. // b.double() = b + b
  214. assert_eq!(b.double(), b + &b);
  215. // a + b = b + a
  216. assert_eq!(a + &b, b + &a);
  217. // a - b = -(b - a)
  218. assert_eq!(a - &b, -(b - &a));
  219. // (a + b) + a = a + (b + a)
  220. assert_eq!((a + &b) + &a, a + &(b + &a));
  221. // (a + b).double() = (a + b) + (b + a)
  222. assert_eq!((a + &b).double(), (a + &b) + &(b + &a));
  223. // a * 0 = 0
  224. assert_eq!(a * &zero, zero);
  225. // a * 1 = a
  226. assert_eq!(a * &one, a);
  227. // a * 2 = a.double()
  228. assert_eq!(a * &two, a.double());
  229. // a * a^-1 = 1
  230. assert_eq!(a * &a.inverse().unwrap(), one);
  231. // a * a = a^2
  232. assert_eq!(a * &a, a.square());
  233. // a * a * a = a^3
  234. assert_eq!(a * &(a * &a), a.pow([0x3, 0x0, 0x0, 0x0]));
  235. // a * b = b * a
  236. assert_eq!(a * &b, b * &a);
  237. // (a * b) * a = a * (b * a)
  238. assert_eq!((a * &b) * &a, a * &(b * &a));
  239. // (a + b)^2 = a^2 + 2ab + b^2
  240. assert_eq!(
  241. (a + &b).square(),
  242. a.square() + &((a * &b) + &(a * &b)) + &b.square()
  243. );
  244. // (a - b)^2 = (-(b - a))^2
  245. assert_eq!((a - &b).square(), (-(b - &a)).square());
  246. random_field_tests::<F>();
  247. }
  248. pub fn fft_field_test<F: FftField>() {
  249. assert_eq!(
  250. F::two_adic_root_of_unity().pow([1 << F::FftParams::TWO_ADICITY]),
  251. F::one()
  252. );
  253. if let Some(small_subgroup_base) = F::FftParams::SMALL_SUBGROUP_BASE {
  254. let small_subgroup_base_adicity = F::FftParams::SMALL_SUBGROUP_BASE_ADICITY.unwrap();
  255. let large_subgroup_root_of_unity = F::large_subgroup_root_of_unity().unwrap();
  256. assert_eq!(
  257. large_subgroup_root_of_unity.pow([(1 << F::FftParams::TWO_ADICITY)
  258. * (small_subgroup_base as u64).pow(small_subgroup_base_adicity)]),
  259. F::one()
  260. );
  261. for i in 0..F::FftParams::TWO_ADICITY {
  262. for j in 0..small_subgroup_base_adicity {
  263. use core::convert::TryFrom;
  264. let size = usize::try_from(1 << i as usize).unwrap()
  265. * usize::try_from((small_subgroup_base as u64).pow(j)).unwrap();
  266. let root = F::get_root_of_unity(size).unwrap();
  267. assert_eq!(root.pow([size as u64]), F::one());
  268. }
  269. }
  270. } else {
  271. for i in 0..F::FftParams::TWO_ADICITY {
  272. let size = 1 << i;
  273. let root = F::get_root_of_unity(size).unwrap();
  274. assert_eq!(root.pow([size as u64]), F::one());
  275. }
  276. }
  277. }
  278. pub fn primefield_test<F: PrimeField>() {
  279. from_str_test::<F>();
  280. let one = F::one();
  281. assert_eq!(F::from(one.into_repr()), one);
  282. fft_field_test::<F>();
  283. }
  284. pub fn sqrt_field_test<F: SquareRootField>(elem: F) {
  285. let square = elem.square();
  286. let sqrt = square.sqrt().unwrap();
  287. assert!(sqrt == elem || sqrt == -elem);
  288. if let Some(sqrt) = elem.sqrt() {
  289. assert!(sqrt.square() == elem || sqrt.square() == -elem);
  290. }
  291. random_sqrt_tests::<F>();
  292. }
  293. pub fn frobenius_test<F: Field, C: AsRef<[u64]>>(characteristic: C, maxpower: usize) {
  294. let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
  295. for _ in 0..ITERATIONS {
  296. let a = F::rand(&mut rng);
  297. let mut a_0 = a;
  298. a_0.frobenius_map(0);
  299. assert_eq!(a, a_0);
  300. let mut a_q = a.pow(&characteristic);
  301. for power in 1..maxpower {
  302. let mut a_qi = a;
  303. a_qi.frobenius_map(power);
  304. assert_eq!(a_qi, a_q, "failed on power {}", power);
  305. a_q = a_q.pow(&characteristic);
  306. }
  307. }
  308. }
  309. pub fn field_serialization_test<F: Field>(buf_size: usize) {
  310. let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
  311. for _ in 0..ITERATIONS {
  312. let a = F::rand(&mut rng);
  313. {
  314. let mut serialized = vec![0u8; buf_size];
  315. let mut cursor = Cursor::new(&mut serialized[..]);
  316. a.serialize(&mut cursor).unwrap();
  317. let mut cursor = Cursor::new(&serialized[..]);
  318. let b = F::deserialize(&mut cursor).unwrap();
  319. assert_eq!(a, b);
  320. }
  321. {
  322. let mut serialized = vec![0u8; a.uncompressed_size()];
  323. let mut cursor = Cursor::new(&mut serialized[..]);
  324. a.serialize_uncompressed(&mut cursor).unwrap();
  325. let mut cursor = Cursor::new(&serialized[..]);
  326. let b = F::deserialize_uncompressed(&mut cursor).unwrap();
  327. assert_eq!(a, b);
  328. }
  329. {
  330. let mut serialized = vec![0u8; buf_size];
  331. let mut cursor = Cursor::new(&mut serialized[..]);
  332. a.serialize_with_flags(&mut cursor, SWFlags::from_y_sign(true))
  333. .unwrap();
  334. let mut cursor = Cursor::new(&serialized[..]);
  335. let (b, flags) = F::deserialize_with_flags::<_, SWFlags>(&mut cursor).unwrap();
  336. assert_eq!(flags.is_positive(), Some(true));
  337. assert!(!flags.is_infinity());
  338. assert_eq!(a, b);
  339. }
  340. #[derive(Default, Clone, Copy, Debug)]
  341. struct DummyFlags;
  342. impl Flags for DummyFlags {
  343. fn u8_bitmask(&self) -> u8 {
  344. 0
  345. }
  346. fn from_u8(_value: u8) -> Self {
  347. DummyFlags
  348. }
  349. fn from_u8_remove_flags(_value: &mut u8) -> Self {
  350. DummyFlags
  351. }
  352. fn len() -> usize {
  353. 200
  354. }
  355. }
  356. use ark_serialize::SerializationError;
  357. {
  358. let mut serialized = vec![0; buf_size];
  359. assert!(if let SerializationError::NotEnoughSpace = a
  360. .serialize_with_flags(&mut &mut serialized[..], DummyFlags)
  361. .unwrap_err()
  362. {
  363. true
  364. } else {
  365. false
  366. });
  367. assert!(if let SerializationError::NotEnoughSpace =
  368. F::deserialize_with_flags::<_, DummyFlags>(&mut &serialized[..]).unwrap_err()
  369. {
  370. true
  371. } else {
  372. false
  373. });
  374. }
  375. {
  376. let mut serialized = vec![0; buf_size - 1];
  377. let mut cursor = Cursor::new(&mut serialized[..]);
  378. a.serialize(&mut cursor).unwrap_err();
  379. let mut cursor = Cursor::new(&serialized[..]);
  380. F::deserialize(&mut cursor).unwrap_err();
  381. }
  382. }
  383. }