shine.rs 9.6 KB

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