field.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. //! Implementation of the prime field used in Ramen.
  2. #![allow(missing_docs)] // Otherwise, there will be a warning originating from the PrimeField
  3. // derive macro ...
  4. use crate::fixed_key_aes::FixedKeyAes;
  5. use bincode;
  6. use blake3;
  7. use ff::{Field, PrimeField};
  8. use num;
  9. use rand::{thread_rng, Rng};
  10. use rug;
  11. /// Prime number `p` defining [`Fp`].
  12. #[allow(non_upper_case_globals)]
  13. pub const p: u128 = 340282366920938462946865773367900766209;
  14. /// Prime field with modulus [`p`].
  15. #[derive(PrimeField)]
  16. #[PrimeFieldModulus = "340282366920938462946865773367900766209"]
  17. #[PrimeFieldGenerator = "7"]
  18. #[PrimeFieldReprEndianness = "little"]
  19. pub struct Fp([u64; 3]);
  20. impl bincode::Encode for Fp {
  21. fn encode<E: bincode::enc::Encoder>(
  22. &self,
  23. encoder: &mut E,
  24. ) -> core::result::Result<(), bincode::error::EncodeError> {
  25. bincode::Encode::encode(&self.to_le_bytes(), encoder)?;
  26. Ok(())
  27. }
  28. }
  29. impl bincode::Decode for Fp {
  30. fn decode<D: bincode::de::Decoder>(
  31. decoder: &mut D,
  32. ) -> core::result::Result<Self, bincode::error::DecodeError> {
  33. let bytes: [u8; 16] = bincode::Decode::decode(decoder)?;
  34. Self::from_le_bytes_vartime(&bytes).ok_or_else(|| {
  35. bincode::error::DecodeError::OtherString(format!(
  36. "{bytes:?} does not encode a valid Fp element"
  37. ))
  38. })
  39. }
  40. }
  41. impl num::traits::Zero for Fp {
  42. fn zero() -> Self {
  43. Self::ZERO
  44. }
  45. fn is_zero(&self) -> bool {
  46. *self == Self::ZERO
  47. }
  48. }
  49. /// Specifies that Self is the range of a PRF.
  50. pub trait FromPrf {
  51. /// Key type of the PRF.
  52. type PrfKey: Copy;
  53. /// PRF key generation.
  54. fn prf_key_gen() -> Self::PrfKey;
  55. /// PRF: `[u64] -> Self`.
  56. fn prf(key: &Self::PrfKey, input: u64) -> Self;
  57. /// PRF into vector of Self.
  58. fn prf_vector(key: &Self::PrfKey, input: u64, size: usize) -> Vec<Self>
  59. where
  60. Self: Sized;
  61. }
  62. /// Specifies that Self can be obtained from a PRG.
  63. pub trait FromPrg {
  64. /// Expand a seed given as 128 bit integer.
  65. fn expand(input: u128) -> Self;
  66. /// Expand a seed given as byte slice of length 16.
  67. fn expand_bytes(input: &[u8]) -> Self;
  68. }
  69. /// Trait for prime fields where the modulus can be provided as a 128 bit integer.
  70. pub trait Modulus128 {
  71. /// Modulus of the prime field
  72. const MOD: u128;
  73. }
  74. impl Modulus128 for Fp {
  75. const MOD: u128 = p;
  76. }
  77. /// Specifies that Self can be hashed into.
  78. pub trait FromHash {
  79. /// Hash a 64 bit integer into Self.
  80. fn hash(input: u64) -> Self;
  81. /// Hash a byte slice into Self.
  82. fn hash_bytes(input: &[u8]) -> Self;
  83. }
  84. /// Definies the Legendre symbol in a prime field.
  85. pub trait LegendreSymbol: PrimeField {
  86. /// Return an arbitrary QNR.
  87. fn get_non_random_qnr() -> Self;
  88. /// Compute the Legendre Symbol (p/a)
  89. fn legendre_symbol(a: Self) -> i8;
  90. }
  91. /// Simple implementation of the legendre symbol using exponentiation.
  92. pub fn legendre_symbol_exp(a: Fp) -> i8 {
  93. // handle 65x even
  94. let mut x = a;
  95. for _ in 0..65 {
  96. x = x.square();
  97. }
  98. // handle 1x odd
  99. let mut y = x;
  100. x = x.square();
  101. // handle 2x even
  102. x = x.square();
  103. x = x.square();
  104. // handle 59x odd
  105. for _ in 0..58 {
  106. y = x * y;
  107. x = x.square();
  108. }
  109. let z = x * y;
  110. debug_assert!(
  111. (z == -Fp::ONE || z == Fp::ONE || z == Fp::ZERO) && (z != Fp::ZERO || a == Fp::ZERO)
  112. );
  113. if z == Fp::ONE {
  114. 1
  115. } else if z == -Fp::ONE {
  116. -1
  117. } else if z == Fp::ZERO {
  118. 0
  119. } else {
  120. panic!("something went wrong during Legendre Symbol computation")
  121. }
  122. }
  123. /// Faster implementation of the legendre symbol using the `rug` library.
  124. pub fn legendre_symbol_rug(a: Fp) -> i8 {
  125. let bytes = a.to_le_bytes();
  126. let a_int = rug::Integer::from_digits(&bytes, rug::integer::Order::LsfLe);
  127. let p_int = rug::Integer::from(p);
  128. a_int.legendre(&p_int) as i8
  129. }
  130. impl LegendreSymbol for Fp {
  131. // (p-1)/ 2 = 0b11111111111111111111111111111111111111111111111111111111111 00 1
  132. // 00000000000000000000000000000000000000000000000000000000000000000
  133. // (59x '1', 2x '9', 1x '1', 65x '0')
  134. /// 7 is not a square mod p.
  135. fn get_non_random_qnr() -> Self {
  136. Self::from_u128(7)
  137. }
  138. /// Compute the Legendre Symbol (p/a)
  139. fn legendre_symbol(a: Self) -> i8 {
  140. legendre_symbol_rug(a)
  141. }
  142. }
  143. impl Fp {
  144. fn from_xof(xof: &mut blake3::OutputReader) -> Self {
  145. assert_eq!(Self::NUM_BITS, 128);
  146. loop {
  147. let tmp = {
  148. let mut repr = [0u64; 3];
  149. for limb in repr.iter_mut().take(2) {
  150. let mut bytes = [0u8; 8];
  151. xof.fill(&mut bytes);
  152. *limb = u64::from_le_bytes(bytes);
  153. }
  154. Self(repr)
  155. };
  156. if tmp.is_valid() {
  157. return tmp;
  158. }
  159. }
  160. }
  161. /// Convert a field element into 16 bytes using little endian byte order.
  162. pub fn to_le_bytes(&self) -> [u8; 16] {
  163. let mut bytes = [0u8; 16];
  164. let repr = self.to_repr();
  165. debug_assert_eq!(&repr.as_ref()[16..], &[0u8; 8]);
  166. bytes.copy_from_slice(&repr.as_ref()[0..16]);
  167. bytes
  168. }
  169. /// Create a field element from 16 bytes using little endian byte order.
  170. pub fn from_le_bytes_vartime(bytes: &[u8; 16]) -> Option<Self> {
  171. let mut repr = <Self as PrimeField>::Repr::default();
  172. debug_assert_eq!(repr.as_ref(), &[0u8; 24]);
  173. repr.as_mut()[0..16].copy_from_slice(bytes);
  174. Self::from_repr_vartime(repr)
  175. }
  176. }
  177. impl FromPrf for Fp {
  178. type PrfKey = [u8; blake3::KEY_LEN];
  179. /// PRF key generation
  180. fn prf_key_gen() -> Self::PrfKey {
  181. thread_rng().gen()
  182. }
  183. /// PRF into Fp
  184. fn prf(key: &Self::PrfKey, input: u64) -> Self {
  185. let mut hasher = blake3::Hasher::new_keyed(key);
  186. hasher.update(&input.to_be_bytes());
  187. let mut xof = hasher.finalize_xof();
  188. Self::from_xof(&mut xof)
  189. }
  190. /// PRF into vector of Fp
  191. fn prf_vector(key: &Self::PrfKey, input: u64, size: usize) -> Vec<Self> {
  192. let mut hasher = blake3::Hasher::new_keyed(key);
  193. hasher.update(&input.to_be_bytes());
  194. let mut xof = hasher.finalize_xof();
  195. (0..size).map(|_| Self::from_xof(&mut xof)).collect()
  196. }
  197. }
  198. impl FromPrg for Fp {
  199. fn expand(input: u128) -> Self {
  200. Self::expand_bytes(&input.to_be_bytes())
  201. }
  202. fn expand_bytes(input: &[u8]) -> Self {
  203. assert_eq!(input.len(), 16);
  204. // not really "fixed-key"
  205. let aes = FixedKeyAes::new(input.try_into().unwrap());
  206. let mut i = 0;
  207. loop {
  208. let val = aes.pi(i);
  209. if val < Fp::MOD {
  210. return Fp::from_u128(val);
  211. }
  212. i += 1;
  213. }
  214. }
  215. }
  216. impl FromHash for Fp {
  217. /// Hash into Fp
  218. fn hash(input: u64) -> Self {
  219. Self::hash_bytes(&input.to_be_bytes())
  220. }
  221. fn hash_bytes(input: &[u8]) -> Self {
  222. let mut hasher = blake3::Hasher::new();
  223. hasher.update(input);
  224. let mut xof = hasher.finalize_xof();
  225. Self::from_xof(&mut xof)
  226. }
  227. }
  228. #[cfg(test)]
  229. mod tests {
  230. use super::*;
  231. #[test]
  232. fn test_legendre_symbol() {
  233. const INPUTS: [u128; 20] = [
  234. 0,
  235. 1,
  236. 2,
  237. 35122421919063474048031845924062067909,
  238. 61212839083344548205786527436063227216,
  239. 108886203898319005744174078164860101674,
  240. 112160854746794802432264095652132979488,
  241. 142714630766673706362679167860844911107,
  242. 144328356835331043954321695814395383527,
  243. 149714699338443771695584577213555322897,
  244. 162837698983268132975860461485836731565,
  245. 185920817468766357617527011469055960606,
  246. 207479253861772423381237297118907360324,
  247. 220976947578297059190439898234224764278,
  248. 225624737240143795963751467909724695007,
  249. 230022448309092634504744292546382561960,
  250. 284649339713848098295138218361935151979,
  251. 293856596737329296797721884860187281734,
  252. 315840344961299616831836711745928570660,
  253. 340282366920938462946865773367900766208,
  254. ];
  255. const OUTPUTS: [i8; 20] = [
  256. 0, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1,
  257. ];
  258. for (&x, &y) in INPUTS.iter().zip(OUTPUTS.iter()) {
  259. assert_eq!(Fp::legendre_symbol(Fp::from_u128(x)), y);
  260. assert_eq!(legendre_symbol_exp(Fp::from_u128(x)), y);
  261. assert_eq!(legendre_symbol_rug(Fp::from_u128(x)), y);
  262. }
  263. assert_eq!(Fp::legendre_symbol(Fp::get_non_random_qnr()), -1);
  264. assert_eq!(legendre_symbol_exp(Fp::get_non_random_qnr()), -1);
  265. assert_eq!(legendre_symbol_rug(Fp::get_non_random_qnr()), -1);
  266. }
  267. #[test]
  268. fn test_serialization() {
  269. for _ in 0..100 {
  270. let x = Fp::random(thread_rng());
  271. let x_bytes =
  272. bincode::encode_to_vec(x, bincode::config::standard().skip_fixed_array_length())
  273. .unwrap();
  274. assert_eq!(x_bytes.len(), 16);
  275. let (y, bytes_read): (Fp, usize) = bincode::decode_from_slice(
  276. &x_bytes,
  277. bincode::config::standard().skip_fixed_array_length(),
  278. )
  279. .unwrap();
  280. assert_eq!(bytes_read, x_bytes.len());
  281. assert_eq!(y, x);
  282. }
  283. }
  284. #[test]
  285. fn test_to_bytes() {
  286. for _ in 0..100 {
  287. let x = Fp::random(thread_rng());
  288. let x_bytes = x.to_le_bytes();
  289. assert_eq!(x_bytes.len(), 16);
  290. let y = Fp::from_le_bytes_vartime(&x_bytes).expect("from_le_bytes_vartime failed");
  291. assert_eq!(x, y);
  292. }
  293. }
  294. }