field.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. use crate::fixed_key_aes::FixedKeyAes;
  2. use blake3;
  3. use communicator::{traits::Serializable, Error};
  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)]
  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. Self(
  49. limbs
  50. .try_into()
  51. .expect(&format!("slice needs to have length {}", Self::NUM_LIMBS)),
  52. )
  53. }
  54. }
  55. pub trait Modulus128 {
  56. /// Modulus of the prime field
  57. const MOD: u128;
  58. }
  59. impl Modulus128 for Fp {
  60. const MOD: u128 = p;
  61. }
  62. pub trait FromHash {
  63. /// Hash into Fp
  64. fn hash(input: u64) -> Self;
  65. fn hash_bytes(input: &[u8]) -> Self;
  66. }
  67. pub trait LegendreSymbol: PrimeField {
  68. /// Compute the Legendre Symbol (p/a)
  69. fn legendre_symbol(a: Self) -> Self;
  70. }
  71. impl LegendreSymbol for Fp {
  72. // (p-1)/ 2 = 0b11111111111111111111111111111111111111111111111111111111111 00 1
  73. // 00000000000000000000000000000000000000000000000000000000000000000
  74. // (59x '1', 2x '9', 1x '1', 65x '0')
  75. /// Compute the Legendre Symbol (p/a)
  76. fn legendre_symbol(a: Self) -> Self {
  77. // handle 65x even
  78. let mut x = a;
  79. for _ in 0..65 {
  80. x = x.square();
  81. }
  82. // handle 1x odd
  83. let mut y = x;
  84. x = x.square();
  85. // handle 2x even
  86. x = x.square();
  87. x = x.square();
  88. // handle 59x odd
  89. for _ in 0..58 {
  90. y = x * y;
  91. x = x.square();
  92. }
  93. let z = x * y;
  94. assert!(
  95. (z == -Fp::ONE || z == Fp::ONE || z == Fp::ZERO) && (z != Fp::ZERO || a == Fp::ZERO)
  96. );
  97. z
  98. }
  99. }
  100. impl Fp {
  101. fn from_xof(xof: &mut blake3::OutputReader) -> Self {
  102. assert_eq!(Self::NUM_BITS, 128);
  103. loop {
  104. let tmp = {
  105. let mut repr = [0u64; 3];
  106. for i in 0..2 {
  107. let mut bytes = [0u8; 8];
  108. xof.fill(&mut bytes);
  109. repr[i] = u64::from_le_bytes(bytes);
  110. }
  111. Self(repr)
  112. };
  113. if tmp.is_valid() {
  114. return tmp;
  115. }
  116. }
  117. }
  118. }
  119. impl FromPrf for Fp {
  120. type PrfKey = [u8; blake3::KEY_LEN];
  121. /// PRF key generation
  122. fn prf_key_gen() -> Self::PrfKey {
  123. thread_rng().gen()
  124. }
  125. /// PRF into Fp
  126. fn prf(key: &Self::PrfKey, input: u64) -> Self {
  127. let mut hasher = blake3::Hasher::new_keyed(&key);
  128. hasher.update(&input.to_be_bytes());
  129. let mut xof = hasher.finalize_xof();
  130. Self::from_xof(&mut xof)
  131. }
  132. /// PRF into vector of Fp
  133. fn prf_vector(key: &Self::PrfKey, input: u64, size: usize) -> Vec<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. (0..size).map(|_| Self::from_xof(&mut xof)).collect()
  138. }
  139. }
  140. impl FromPrg for Fp {
  141. fn expand(input: u128) -> Self {
  142. Self::expand_bytes(&input.to_be_bytes())
  143. }
  144. fn expand_bytes(input: &[u8]) -> Self {
  145. assert_eq!(input.len(), 16);
  146. // not really "fixed-key"
  147. let aes = FixedKeyAes::new(input.try_into().unwrap());
  148. let mut i = 0;
  149. loop {
  150. let val = aes.pi(i);
  151. if val < Fp::MOD {
  152. return Fp::from_limbs(&[
  153. (val & 0xffffffffffffffff) as u64,
  154. (val >> 64) as u64,
  155. 0u64,
  156. ]);
  157. }
  158. i += 1;
  159. }
  160. }
  161. }
  162. impl FromHash for Fp {
  163. /// Hash into Fp
  164. fn hash(input: u64) -> Self {
  165. Self::hash_bytes(&input.to_be_bytes())
  166. }
  167. fn hash_bytes(input: &[u8]) -> Self {
  168. let mut hasher = blake3::Hasher::new();
  169. hasher.update(input);
  170. let mut xof = hasher.finalize_xof();
  171. Self::from_xof(&mut xof)
  172. }
  173. }
  174. impl Serializable for Fp {
  175. fn bytes_required() -> usize {
  176. 16
  177. }
  178. fn to_bytes(&self) -> Vec<u8> {
  179. let mut buf = vec![0u8; 16];
  180. self.into_bytes(&mut buf).unwrap();
  181. buf
  182. }
  183. fn into_bytes(&self, buf: &mut [u8]) -> Result<(), Error> {
  184. if buf.len() != 16 {
  185. return Err(Error::SerializationError("wrong buffer size".to_owned()));
  186. }
  187. buf.chunks_mut(8).enumerate().for_each(|(i, c)| {
  188. c.copy_from_slice(&self.0[i].to_be_bytes());
  189. });
  190. Ok(())
  191. }
  192. fn from_bytes(buf: &[u8]) -> Result<Self, Error> {
  193. if buf.len() != 16 {
  194. return Err(Error::DeserializationError("wrong buffer size".to_owned()));
  195. }
  196. let mut output = Self::ZERO;
  197. buf.chunks(8).enumerate().for_each(|(i, c)| {
  198. output.0[i] = u64::from_be_bytes(c.try_into().unwrap());
  199. });
  200. Ok(output)
  201. }
  202. }
  203. #[cfg(test)]
  204. mod tests {
  205. use super::*;
  206. #[test]
  207. fn test_lagrange_symbol() {
  208. const INPUTS: [u128; 20] = [
  209. 0,
  210. 1,
  211. 2,
  212. 35122421919063474048031845924062067909,
  213. 61212839083344548205786527436063227216,
  214. 108886203898319005744174078164860101674,
  215. 112160854746794802432264095652132979488,
  216. 142714630766673706362679167860844911107,
  217. 144328356835331043954321695814395383527,
  218. 149714699338443771695584577213555322897,
  219. 162837698983268132975860461485836731565,
  220. 185920817468766357617527011469055960606,
  221. 207479253861772423381237297118907360324,
  222. 220976947578297059190439898234224764278,
  223. 225624737240143795963751467909724695007,
  224. 230022448309092634504744292546382561960,
  225. 284649339713848098295138218361935151979,
  226. 293856596737329296797721884860187281734,
  227. 315840344961299616831836711745928570660,
  228. 340282366920938462946865773367900766208,
  229. ];
  230. const OUTPUTS: [u128; 20] = [
  231. 0,
  232. 1,
  233. 1,
  234. 1,
  235. 1,
  236. 1,
  237. 340282366920938462946865773367900766208,
  238. 1,
  239. 1,
  240. 340282366920938462946865773367900766208,
  241. 1,
  242. 340282366920938462946865773367900766208,
  243. 1,
  244. 1,
  245. 1,
  246. 340282366920938462946865773367900766208,
  247. 340282366920938462946865773367900766208,
  248. 1,
  249. 1,
  250. 1,
  251. ];
  252. for (&x, &y) in INPUTS.iter().zip(OUTPUTS.iter()) {
  253. assert_eq!(Fp::legendre_symbol(Fp::from_u128(x)), Fp::from_u128(y));
  254. }
  255. }
  256. #[test]
  257. fn test_serialization() {
  258. assert_eq!(Fp::bytes_required(), 16);
  259. for _ in 0..100 {
  260. let x = Fp::random(thread_rng());
  261. let x_bytes = x.to_bytes();
  262. let y = Fp::from_bytes(&x_bytes).unwrap();
  263. assert_eq!(y, x);
  264. }
  265. }
  266. }