shine.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. use crate::lagrange::*;
  2. use curve25519_dalek::constants as dalek_constants;
  3. use curve25519_dalek::ristretto::RistrettoPoint;
  4. use curve25519_dalek::ristretto::VartimeRistrettoPrecomputation;
  5. use curve25519_dalek::scalar::Scalar;
  6. use curve25519_dalek::traits::Identity;
  7. use curve25519_dalek::traits::VartimePrecomputedMultiscalarMul;
  8. use itertools::Itertools;
  9. use rand::RngCore;
  10. use sha2::digest::FixedOutput;
  11. use sha2::Digest;
  12. use sha2::Sha256;
  13. // Compute (m choose k) when m^k < 2^64
  14. fn binom(m: u32, k: u32) -> u64 {
  15. let mut numer = 1u64;
  16. let mut denom = 1u64;
  17. for i in 0u64..(k as u64) {
  18. numer *= (m as u64) - i;
  19. denom *= i + 1;
  20. }
  21. numer / denom
  22. }
  23. // The hash function used to create the coefficients for the
  24. // pseudorandom secret sharing.
  25. fn hash1(phi: &[u8; 32], w: &[u8]) -> Scalar {
  26. let mut hash = Sha256::new();
  27. hash.update(phi);
  28. hash.update(w);
  29. let mut hashval = [0u8; 32];
  30. hash.finalize_into((&mut hashval).into());
  31. Scalar::from_bytes_mod_order(hashval)
  32. }
  33. // The key for player k will consist of a vector of (v, phi) tuples,
  34. // where the v values enumerate all lists of t-1 player numbers (from
  35. // 1 to n) that do _not_ include k
  36. #[derive(Debug)]
  37. pub struct Key {
  38. pub n: u32,
  39. pub t: u32,
  40. pub k: u32,
  41. pub secrets: Vec<(Vec<u32>, [u8; 32])>,
  42. }
  43. impl Key {
  44. pub fn keygen(n: u32, t: u32) -> Vec<Self> {
  45. let mut rng = rand::thread_rng();
  46. let mut res: Vec<Self> = Vec::new();
  47. for k in 1..=n {
  48. res.push(Self {
  49. n,
  50. t,
  51. k,
  52. secrets: Vec::new(),
  53. });
  54. }
  55. let si = (1..=n).combinations((t - 1) as usize);
  56. for v in si {
  57. // For each subset of size t-1, pick a random secret, and
  58. // give it to all players _not_ in that subset
  59. let mut phi: [u8; 32] = [0; 32];
  60. rng.fill_bytes(&mut phi);
  61. let mut vnextind = 0usize;
  62. let mut vnext = v[0];
  63. for i in 1..=n {
  64. if i < vnext {
  65. res[(i - 1) as usize]
  66. .secrets
  67. .push((v.clone(), phi));
  68. } else {
  69. vnextind += 1;
  70. vnext = if vnextind < ((t - 1) as usize) {
  71. v[vnextind]
  72. } else {
  73. n + 1
  74. };
  75. }
  76. }
  77. }
  78. res
  79. }
  80. }
  81. #[test]
  82. pub fn test_keygen() {
  83. let keys = Key::keygen(7, 4);
  84. println!("key for player 3: {:?}", keys[2]);
  85. println!("key for player 7: {:?}", keys[6]);
  86. }
  87. #[derive(Debug)]
  88. pub struct PreprocKey {
  89. pub n: u32,
  90. pub t: u32,
  91. pub k: u32,
  92. pub secrets: Vec<([u8; 32], Scalar)>,
  93. }
  94. impl PreprocKey {
  95. pub fn preproc(key: &Key) -> Self {
  96. Self {
  97. n: key.n,
  98. t: key.t,
  99. k: key.k,
  100. secrets: key
  101. .secrets
  102. .iter()
  103. .map(|(v, phi)| (*phi, lagrange(v, 0, key.k)))
  104. .collect(),
  105. }
  106. }
  107. pub fn rand(n: u32, t: u32) -> Self {
  108. let delta = binom(n - 1, t - 1);
  109. let mut secrets: Vec<([u8; 32], Scalar)> = Vec::new();
  110. let mut rng = rand::thread_rng();
  111. for _ in 0u64..delta {
  112. let mut phi = [0u8; 32];
  113. rng.fill_bytes(&mut phi);
  114. let lagrange: Scalar = Scalar::random(&mut rng);
  115. secrets.push((phi, lagrange));
  116. }
  117. Self {
  118. n,
  119. t,
  120. k: 1,
  121. secrets,
  122. }
  123. }
  124. pub fn gen(&self, w: &[u8]) -> (Scalar, RistrettoPoint) {
  125. let d = self.secrets
  126. .iter()
  127. .map(|&(phi, lagrange)| hash1(&phi, w) * lagrange)
  128. .sum();
  129. (d, &d * &dalek_constants::RISTRETTO_BASEPOINT_TABLE)
  130. }
  131. pub fn delta(&self) -> usize {
  132. self.secrets.len()
  133. }
  134. }
  135. pub fn commit(evaluation: &Scalar) -> RistrettoPoint {
  136. evaluation * &dalek_constants::RISTRETTO_BASEPOINT_TABLE
  137. }
  138. // Verify that a set of commitments are consistent with a given t, using
  139. // precomputed Lagrange polynomials. Return false if the commitments
  140. // are not consistent with the given t, or true if they are. You must
  141. // pass at least 2t-1 commitments, and the same number of lag_polys.
  142. pub fn verify_polys(
  143. t: u32,
  144. lag_polys: &[ScalarPoly],
  145. commitments: &[RistrettoPoint],
  146. ) -> bool {
  147. // Check if the commitments are consistent: when interpolating the
  148. // polys in the exponent, the low t coefficients can be non-0 but
  149. // the ones above that must be 0
  150. let coalition_size = commitments.len();
  151. assert!(t >= 1);
  152. assert!(coalition_size >= 2 * (t as usize) - 1);
  153. assert!(coalition_size == lag_polys.len());
  154. assert!(coalition_size == lag_polys[0].coeffs.len());
  155. // Use this to compute the multiscalar multiplications
  156. let multiscalar = VartimeRistrettoPrecomputation::new(Vec::<RistrettoPoint>::new());
  157. // Compute the B_i for i from t to coalition_size-1. All of them
  158. // should be the identity; otherwise, the commitments are
  159. // inconsistent.
  160. ((t as usize)..coalition_size)
  161. .map(|i| {
  162. // B_i = \sum_j lag_polys[j].coeffs[i] * commitments[j]
  163. multiscalar.vartime_mixed_multiscalar_mul(
  164. &Vec::<Scalar>::new(),
  165. (0..coalition_size).map(|j| lag_polys[j].coeffs[i]),
  166. commitments,
  167. )
  168. })
  169. .all(|bi: RistrettoPoint| bi == RistrettoPoint::identity())
  170. }
  171. // Verify that a set of commitments are consistent with a given t.
  172. // Return false if the commitments are not consistent with the given t,
  173. // or true if they are. You must pass at least 2t-1 commitments, and the
  174. // same number of lag_polys.
  175. pub fn verify(
  176. t: u32,
  177. coalition: &[u32],
  178. commitments: &[RistrettoPoint],
  179. ) -> bool {
  180. let polys = lagrange_polys(coalition);
  181. verify_polys(t, &polys, commitments)
  182. }
  183. // Combine commitments using precomputed Lagrange polynomials. Return
  184. // None if the commitments are not consistent with the given t. You
  185. // must pass at least 2t-1 commitments, and the same number of
  186. // lag_polys.
  187. pub fn combinecomm_polys(
  188. t: u32,
  189. lag_polys: &[ScalarPoly],
  190. commitments: &[RistrettoPoint],
  191. ) -> Option<RistrettoPoint> {
  192. let coalition_size = commitments.len();
  193. assert!(t >= 1);
  194. assert!(coalition_size >= 2 * (t as usize) - 1);
  195. assert!(coalition_size == lag_polys.len());
  196. assert!(coalition_size == lag_polys[0].coeffs.len());
  197. // Check if the commitments are consistent: when interpolating the
  198. // polys in the exponent, the low t coefficients can be non-0 but
  199. // the ones above that must be 0
  200. if ! verify_polys(t, lag_polys, commitments) {
  201. return None;
  202. }
  203. // Use this to compute the multiscalar multiplications
  204. let multiscalar = VartimeRistrettoPrecomputation::new(Vec::<RistrettoPoint>
  205. ::new());
  206. // Compute B_0 (which is the combined commitment) and return
  207. // Some(B_0)
  208. Some(multiscalar.vartime_mixed_multiscalar_mul(
  209. &Vec::<Scalar>::new(),
  210. (0..coalition_size).map(|j| lag_polys[j].coeffs[0]),
  211. commitments,
  212. ))
  213. }
  214. // Combine commitments. Return None if the commitments are not
  215. // consistent with the given t. You must pass at least 2t-1
  216. // commitments, and the same size of coalition.
  217. pub fn combinecomm(
  218. t: u32,
  219. coalition: &[u32],
  220. commitments: &[RistrettoPoint],
  221. ) -> Option<RistrettoPoint> {
  222. let polys = lagrange_polys(coalition);
  223. combinecomm_polys(t, &polys, commitments)
  224. }
  225. // Combine already-verified commitments using precomputed Lagrange
  226. // polynomials. You must pass at least 2t-1 commitments, and the same
  227. // number of lag_polys.
  228. pub fn agg_polys(
  229. t: u32,
  230. lag_polys: &[ScalarPoly],
  231. commitments: &[RistrettoPoint],
  232. ) -> RistrettoPoint {
  233. let coalition_size = commitments.len();
  234. assert!(t >= 1);
  235. assert!(coalition_size >= 2 * (t as usize) - 1);
  236. assert!(coalition_size == lag_polys.len());
  237. assert!(coalition_size == lag_polys[0].coeffs.len());
  238. // Use this to compute the multiscalar multiplications
  239. let multiscalar = VartimeRistrettoPrecomputation::new(Vec::<RistrettoPoint>::new());
  240. // Compute B_0 (which is the combined commitment) and return it
  241. multiscalar.vartime_mixed_multiscalar_mul(
  242. &Vec::<Scalar>::new(),
  243. (0..coalition_size).map(|j| lag_polys[j].coeffs[0]),
  244. commitments,
  245. )
  246. }
  247. // Combine already-verified commitments. You must pass at least 2t-1
  248. // commitments, and the same number of lag_polys.
  249. pub fn agg(
  250. t: u32,
  251. coalition: &[u32],
  252. commitments: &[RistrettoPoint],
  253. ) -> RistrettoPoint {
  254. let polys = lagrange_polys(coalition);
  255. agg_polys(t, &polys, commitments)
  256. }
  257. #[test]
  258. pub fn test_preproc() {
  259. let keys = Key::keygen(7, 4);
  260. let ppkey3 = PreprocKey::preproc(&keys[2]);
  261. let ppkey7 = PreprocKey::preproc(&keys[6]);
  262. println!("preproc key for player 3: {:?}", ppkey3);
  263. println!("preproc key for player 7: {:?}", ppkey7);
  264. }
  265. #[test]
  266. pub fn test_gen() {
  267. let keys = Key::keygen(7, 3);
  268. let ppkeys: Vec<PreprocKey> = keys.iter().map(|x| PreprocKey::preproc(x)).collect();
  269. let mut rng = rand::thread_rng();
  270. let mut w = [0u8; 32];
  271. rng.fill_bytes(&mut w);
  272. let evals: Vec<Scalar> = ppkeys.iter().map(|k| k.gen(&w).0).collect();
  273. // Try interpolating different subsets and check that the answer is
  274. // the same
  275. let interp1 = interpolate(&vec![1, 2, 3, 4, 5], &evals[0..=4], 0);
  276. let interp2 = interpolate(&vec![3, 4, 5, 6, 7], &evals[2..=6], 0);
  277. println!("interp1 = {:?}", interp1);
  278. println!("interp2 = {:?}", interp2);
  279. assert!(interp1 == interp2);
  280. }
  281. #[test]
  282. pub fn test_combinecomm() {
  283. let keys = Key::keygen(7, 3);
  284. let ppkeys: Vec<PreprocKey> = keys.iter().map(|x| PreprocKey::preproc(x)).collect();
  285. let mut rng = rand::thread_rng();
  286. let mut w = [0u8; 32];
  287. rng.fill_bytes(&mut w);
  288. let commitments: Vec<RistrettoPoint> =
  289. ppkeys.iter().map(|k| k.gen(&w).1).collect();
  290. let comm1 = combinecomm(3, &vec![1, 2, 3, 4, 5], &commitments[0..=4]);
  291. let comm2 = combinecomm(3, &vec![3, 4, 5, 6, 7], &commitments[2..=6]);
  292. assert_ne!(comm1, None);
  293. assert_ne!(comm2, None);
  294. // Test a failure case
  295. let comm3 = combinecomm(3, &vec![1, 2, 3, 4, 6], &commitments[0..=4]);
  296. assert_eq!(comm3, None);
  297. }