field.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. use crate::fixed_key_aes::FixedKeyAes;
  2. use bincode;
  3. use blake3;
  4. use ff::{Field, PrimeField};
  5. use num;
  6. use rand::{thread_rng, Rng};
  7. #[allow(non_upper_case_globals)]
  8. pub const p: u128 = 340282366920938462946865773367900766209;
  9. /// Prime field with modulus
  10. /// p = 340282366920938462946865773367900766209.
  11. #[derive(PrimeField, bincode::Encode, bincode::Decode)]
  12. #[PrimeFieldModulus = "340282366920938462946865773367900766209"]
  13. #[PrimeFieldGenerator = "7"]
  14. #[PrimeFieldReprEndianness = "little"]
  15. pub struct Fp([u64; 3]);
  16. impl num::traits::Zero for Fp {
  17. fn zero() -> Self {
  18. Self::ZERO
  19. }
  20. fn is_zero(&self) -> bool {
  21. *self == Self::ZERO
  22. }
  23. }
  24. pub trait FromPrf {
  25. type PrfKey: Copy;
  26. /// PRF key generation
  27. fn prf_key_gen() -> Self::PrfKey;
  28. /// PRF into Fp
  29. fn prf(key: &Self::PrfKey, input: u64) -> Self;
  30. /// PRF into vector of Fp
  31. fn prf_vector(key: &Self::PrfKey, input: u64, size: usize) -> Vec<Self>
  32. where
  33. Self: Sized;
  34. }
  35. pub trait FromPrg {
  36. fn expand(input: u128) -> Self;
  37. fn expand_bytes(input: &[u8]) -> Self;
  38. }
  39. pub trait FromLimbs {
  40. const NUM_LIMBS: usize;
  41. type Limbs;
  42. fn from_limbs(limbs: &[u64]) -> Self;
  43. }
  44. impl FromLimbs for Fp {
  45. const NUM_LIMBS: usize = 3;
  46. type Limbs = [u64; 3];
  47. fn from_limbs(limbs: &[u64]) -> Self {
  48. eprintln!("FromLimbs might be broken ...");
  49. Self(
  50. limbs
  51. .try_into()
  52. .expect(&format!("slice needs to have length {}", Self::NUM_LIMBS)),
  53. )
  54. }
  55. }
  56. pub trait Modulus128 {
  57. /// Modulus of the prime field
  58. const MOD: u128;
  59. }
  60. impl Modulus128 for Fp {
  61. const MOD: u128 = p;
  62. }
  63. pub trait FromHash {
  64. /// Hash into Fp
  65. fn hash(input: u64) -> Self;
  66. fn hash_bytes(input: &[u8]) -> Self;
  67. }
  68. pub trait LegendreSymbol: PrimeField {
  69. /// Return an arbitrary QNR.
  70. fn get_non_random_qnr() -> Self;
  71. /// Compute the Legendre Symbol (p/a)
  72. fn legendre_symbol(a: Self) -> Self;
  73. }
  74. impl LegendreSymbol for Fp {
  75. // (p-1)/ 2 = 0b11111111111111111111111111111111111111111111111111111111111 00 1
  76. // 00000000000000000000000000000000000000000000000000000000000000000
  77. // (59x '1', 2x '9', 1x '1', 65x '0')
  78. /// 7 is not a square mod p.
  79. fn get_non_random_qnr() -> Self {
  80. Self::ONE + Self::ONE + Self::ONE + Self::ONE + Self::ONE + Self::ONE + Self::ONE
  81. }
  82. /// Compute the Legendre Symbol (p/a)
  83. fn legendre_symbol(a: Self) -> Self {
  84. // handle 65x even
  85. let mut x = a;
  86. for _ in 0..65 {
  87. x = x.square();
  88. }
  89. // handle 1x odd
  90. let mut y = x;
  91. x = x.square();
  92. // handle 2x even
  93. x = x.square();
  94. x = x.square();
  95. // handle 59x odd
  96. for _ in 0..58 {
  97. y = x * y;
  98. x = x.square();
  99. }
  100. let z = x * y;
  101. assert!(
  102. (z == -Fp::ONE || z == Fp::ONE || z == Fp::ZERO) && (z != Fp::ZERO || a == Fp::ZERO)
  103. );
  104. z
  105. }
  106. }
  107. impl Fp {
  108. fn from_xof(xof: &mut blake3::OutputReader) -> Self {
  109. assert_eq!(Self::NUM_BITS, 128);
  110. loop {
  111. let tmp = {
  112. let mut repr = [0u64; 3];
  113. for i in 0..2 {
  114. let mut bytes = [0u8; 8];
  115. xof.fill(&mut bytes);
  116. repr[i] = u64::from_le_bytes(bytes);
  117. }
  118. Self(repr)
  119. };
  120. if tmp.is_valid() {
  121. return tmp;
  122. }
  123. }
  124. }
  125. }
  126. impl FromPrf for Fp {
  127. type PrfKey = [u8; blake3::KEY_LEN];
  128. /// PRF key generation
  129. fn prf_key_gen() -> Self::PrfKey {
  130. thread_rng().gen()
  131. }
  132. /// PRF into Fp
  133. fn prf(key: &Self::PrfKey, input: u64) -> Self {
  134. let mut hasher = blake3::Hasher::new_keyed(&key);
  135. hasher.update(&input.to_be_bytes());
  136. let mut xof = hasher.finalize_xof();
  137. Self::from_xof(&mut xof)
  138. }
  139. /// PRF into vector of Fp
  140. fn prf_vector(key: &Self::PrfKey, input: u64, size: usize) -> Vec<Self> {
  141. let mut hasher = blake3::Hasher::new_keyed(&key);
  142. hasher.update(&input.to_be_bytes());
  143. let mut xof = hasher.finalize_xof();
  144. (0..size).map(|_| Self::from_xof(&mut xof)).collect()
  145. }
  146. }
  147. impl FromPrg for Fp {
  148. fn expand(input: u128) -> Self {
  149. Self::expand_bytes(&input.to_be_bytes())
  150. }
  151. fn expand_bytes(input: &[u8]) -> Self {
  152. assert_eq!(input.len(), 16);
  153. // not really "fixed-key"
  154. let aes = FixedKeyAes::new(input.try_into().unwrap());
  155. let mut i = 0;
  156. loop {
  157. let val = aes.pi(i);
  158. if val < Fp::MOD {
  159. return Fp::from_limbs(&[
  160. (val & 0xffffffffffffffff) as u64,
  161. (val >> 64) as u64,
  162. 0u64,
  163. ]);
  164. }
  165. i += 1;
  166. }
  167. }
  168. }
  169. impl FromHash for Fp {
  170. /// Hash into Fp
  171. fn hash(input: u64) -> Self {
  172. Self::hash_bytes(&input.to_be_bytes())
  173. }
  174. fn hash_bytes(input: &[u8]) -> Self {
  175. let mut hasher = blake3::Hasher::new();
  176. hasher.update(input);
  177. let mut xof = hasher.finalize_xof();
  178. Self::from_xof(&mut xof)
  179. }
  180. }
  181. #[cfg(test)]
  182. mod tests {
  183. use super::*;
  184. #[test]
  185. fn test_lagrange_symbol() {
  186. const INPUTS: [u128; 20] = [
  187. 0,
  188. 1,
  189. 2,
  190. 35122421919063474048031845924062067909,
  191. 61212839083344548205786527436063227216,
  192. 108886203898319005744174078164860101674,
  193. 112160854746794802432264095652132979488,
  194. 142714630766673706362679167860844911107,
  195. 144328356835331043954321695814395383527,
  196. 149714699338443771695584577213555322897,
  197. 162837698983268132975860461485836731565,
  198. 185920817468766357617527011469055960606,
  199. 207479253861772423381237297118907360324,
  200. 220976947578297059190439898234224764278,
  201. 225624737240143795963751467909724695007,
  202. 230022448309092634504744292546382561960,
  203. 284649339713848098295138218361935151979,
  204. 293856596737329296797721884860187281734,
  205. 315840344961299616831836711745928570660,
  206. 340282366920938462946865773367900766208,
  207. ];
  208. const OUTPUTS: [u128; 20] = [
  209. 0,
  210. 1,
  211. 1,
  212. 1,
  213. 1,
  214. 1,
  215. 340282366920938462946865773367900766208,
  216. 1,
  217. 1,
  218. 340282366920938462946865773367900766208,
  219. 1,
  220. 340282366920938462946865773367900766208,
  221. 1,
  222. 1,
  223. 1,
  224. 340282366920938462946865773367900766208,
  225. 340282366920938462946865773367900766208,
  226. 1,
  227. 1,
  228. 1,
  229. ];
  230. for (&x, &y) in INPUTS.iter().zip(OUTPUTS.iter()) {
  231. assert_eq!(Fp::legendre_symbol(Fp::from_u128(x)), Fp::from_u128(y));
  232. }
  233. assert_eq!(Fp::legendre_symbol(Fp::get_non_random_qnr()), -Fp::ONE);
  234. }
  235. #[test]
  236. fn test_serialization() {
  237. for _ in 0..100 {
  238. let x = Fp::random(thread_rng());
  239. let x_bytes = bincode::encode_to_vec(x, bincode::config::standard()).unwrap();
  240. let (y, bytes_read): (Fp, usize) =
  241. bincode::decode_from_slice(&x_bytes, bincode::config::standard()).unwrap();
  242. assert_eq!(bytes_read, x_bytes.len());
  243. assert_eq!(y, x);
  244. }
  245. }
  246. }