vss.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. use curve25519_dalek::edwards::EdwardsPoint;
  2. use curve25519_dalek::traits::Identity;
  3. use curve25519_dalek::scalar::Scalar;
  4. use curve25519_dalek::constants::ED25519_BASEPOINT_POINT;
  5. use rand::rngs::ThreadRng;
  6. pub type Secret = Scalar;
  7. #[derive(Copy, Clone)]
  8. pub struct Share {
  9. index: u32,
  10. value: Scalar,
  11. }
  12. pub struct Commitment {
  13. coms: Vec<EdwardsPoint>,
  14. }
  15. /// Create secret shares for a given secret.
  16. pub fn generate_shares(secret: Secret, numshares: u32, threshold: u32) -> Result<(Commitment, Vec<Share>), &'static str> {
  17. if threshold < 1 { return Err("Threshold cannot be 0") }
  18. if numshares < 1 { return Err("Number of shares cannot be 0") }
  19. if threshold > numshares { return Err("Threshold cannot exceed numshares") }
  20. let numcoeffs = (threshold-1) as usize;
  21. let mut coeffs: Vec<Scalar> = Vec::with_capacity(numcoeffs);
  22. let mut rng: ThreadRng = rand::thread_rng();
  23. let mut shares: Vec<Share> = Vec::with_capacity(numshares as usize);
  24. let mut comm: Commitment = Commitment { coms: Vec::with_capacity(threshold as usize) };
  25. for _ in 0..numcoeffs {
  26. coeffs.push(Scalar::random(&mut rng));
  27. }
  28. for share_index in 1..numshares+1 {
  29. // Evaluate the polynomial with `secret` as the constant term
  30. // and `coeffs` as the other coefficients at the point x=share_index
  31. // using Horner's method
  32. let scalar_index = Scalar::from(share_index);
  33. let mut value = Scalar::zero();
  34. for i in (0..numcoeffs).rev() {
  35. value += coeffs[i];
  36. value *= scalar_index;
  37. }
  38. value += secret;
  39. shares.push(Share{ index: share_index, value: value });
  40. }
  41. comm.coms.push(ED25519_BASEPOINT_POINT * secret);
  42. for c in coeffs {
  43. comm.coms.push(ED25519_BASEPOINT_POINT * c);
  44. }
  45. Ok((comm, shares))
  46. }
  47. /// Verify that a share is consistent with a commitment.
  48. pub fn verify_share(share: &Share, commitment: &Commitment) -> Result<bool, &'static str> {
  49. let f_result = ED25519_BASEPOINT_POINT * share.value;
  50. let x = Scalar::from(share.index);
  51. let (_, result) = commitment.coms.iter().fold(
  52. (Scalar::one(), EdwardsPoint::identity()),
  53. |(x_to_the_i, sum_so_far), comm_i|
  54. (x_to_the_i * x, sum_so_far + x_to_the_i * comm_i));
  55. let is_valid = f_result == result;
  56. Ok(is_valid)
  57. }
  58. /// Reconstruct the secret from enough (at least the threshold) already-verified shares.
  59. pub fn reconstruct_secret(shares: &Vec<Share>) -> Result<Secret, &'static str> {
  60. let numshares = shares.len();
  61. if numshares < 1 { return Err("No shares provided"); }
  62. let mut lagrange_coeffs: Vec<Scalar> = Vec::with_capacity(numshares);
  63. for i in 0..numshares {
  64. let mut num = Scalar::one();
  65. let mut den = Scalar::one();
  66. for j in 0..numshares {
  67. if j==i { continue; }
  68. num *= Scalar::from(shares[j].index);
  69. den *= Scalar::from(shares[j].index) - Scalar::from(shares[i].index);
  70. }
  71. if den == Scalar::zero() {
  72. return Err("Duplicate shares provided");
  73. }
  74. lagrange_coeffs.push(num * den.invert());
  75. }
  76. let mut secret = Scalar::zero();
  77. for i in 0..numshares {
  78. secret += lagrange_coeffs[i] * shares[i].value;
  79. }
  80. Ok(secret)
  81. }
  82. /// Create a proactive update.
  83. pub fn create_update(num_shares: u32, threshold: u32) -> Result<(Commitment, Vec<Share>), &'static str> {
  84. generate_shares(Scalar::zero(), num_shares, threshold)
  85. }
  86. /// Apply the commitment for the update to the master commitment.
  87. pub fn apply_commitment_update(old_commitment: &Commitment, update: &Commitment) -> Result<Commitment, &'static str> {
  88. let mut new_commitments: Commitment = Commitment { coms: Vec::with_capacity(old_commitment.coms.len()) };
  89. for i in 0..old_commitment.coms.len() {
  90. let new_commitment = old_commitment.coms[i] + update.coms[i];
  91. new_commitments.coms.push(new_commitment);
  92. }
  93. Ok(new_commitments)
  94. }
  95. /// Apply the share update to an existing share
  96. pub fn apply_share_update(old_share: &Share, update: &Share, updated_commitment: &Commitment) -> Result<Share, &'static str> {
  97. let updated_share = Share{
  98. index: old_share.index,
  99. value: old_share.value + update.value,
  100. };
  101. let share_is_valid = match verify_share(&updated_share, updated_commitment) {
  102. Ok(n) => n,
  103. Err(_) => return Err("Error when validating share"),
  104. };
  105. if !share_is_valid {
  106. return Err("Share is invalid");
  107. }
  108. Ok(updated_share)
  109. }
  110. #[cfg(test)]
  111. mod tests {
  112. use crate::vss::*;
  113. #[test]
  114. fn share_simple() {
  115. let s = Secret::from(42u32);
  116. let res = generate_shares(s, 5, 2);
  117. assert!(res.is_ok());
  118. let (com, shares) = res.unwrap();
  119. assert!(shares.len() == 5);
  120. assert!(com.coms.len() == 2);
  121. let mut recshares: Vec<Share> = Vec::new();
  122. recshares.push(shares[1]);
  123. recshares.push(shares[3]);
  124. let recres = reconstruct_secret(&recshares);
  125. assert!(recres.is_ok());
  126. assert_eq!(recres.unwrap(), s);
  127. }
  128. #[test]
  129. fn share_not_enough() {
  130. let s = Secret::from(42u32);
  131. let res = generate_shares(s, 5, 2);
  132. assert!(res.is_ok());
  133. let (_, shares) = res.unwrap();
  134. let mut recshares: Vec<Share> = Vec::new();
  135. recshares.push(shares[1]);
  136. let recres = reconstruct_secret(&recshares);
  137. assert!(recres.is_ok());
  138. assert_ne!(recres.unwrap(), s);
  139. }
  140. #[test]
  141. fn share_dup() {
  142. let s = Secret::from(42u32);
  143. let res = generate_shares(s, 5, 2);
  144. assert!(res.is_ok());
  145. let (_, shares) = res.unwrap();
  146. let mut recshares: Vec<Share> = Vec::new();
  147. recshares.push(shares[1]);
  148. recshares.push(shares[1]);
  149. let recres = reconstruct_secret(&recshares);
  150. assert!(recres.is_err());
  151. assert_eq!(recres.err(), Some("Duplicate shares provided"));
  152. }
  153. #[test]
  154. fn share_badparams() {
  155. let s = Secret::from(42u32);
  156. {
  157. let res = generate_shares(s, 5, 0);
  158. assert!(res.is_err());
  159. assert_eq!(res.err(), Some("Threshold cannot be 0"));
  160. }
  161. {
  162. let res = generate_shares(s, 0, 3);
  163. assert!(res.is_err());
  164. assert_eq!(res.err(), Some("Number of shares cannot be 0"));
  165. }
  166. {
  167. let res = generate_shares(s, 1, 3);
  168. assert!(res.is_err());
  169. assert_eq!(res.err(), Some("Threshold cannot exceed numshares"));
  170. }
  171. }
  172. #[test]
  173. fn share_commitment_valid() {
  174. let s = Secret::from(42u32);
  175. let res = generate_shares(s, 8, 3);
  176. assert!(res.is_ok());
  177. let (com, shares) = res.unwrap();
  178. for share in shares {
  179. let is_valid = verify_share(&share, &com);
  180. assert!(is_valid.is_ok());
  181. assert!(is_valid.unwrap());
  182. }
  183. }
  184. #[test]
  185. fn share_commitment_invalid() {
  186. let s1 = Secret::from(42u32);
  187. let s2 = Secret::from(42u32);
  188. let res1 = generate_shares(s1, 8, 3);
  189. assert!(res1.is_ok());
  190. let (_, shares1) = res1.unwrap();
  191. let res2 = generate_shares(s2, 8, 3);
  192. assert!(res2.is_ok());
  193. let (com2, _) = res2.unwrap();
  194. for share in shares1 {
  195. // test that commitments to a different set of shares fails
  196. let is_valid = verify_share(&share, &com2);
  197. assert!(is_valid.is_ok());
  198. assert_ne!(is_valid.unwrap(), true);
  199. }
  200. }
  201. #[test]
  202. fn share_update_valid() {
  203. let s = Secret::from(42u32);
  204. let res = generate_shares(s, 5, 2);
  205. assert!(res.is_ok());
  206. let (com, shares) = res.unwrap();
  207. // Create a new update
  208. let update_comm_res = create_update(5, 2);
  209. assert!(update_comm_res.is_ok());
  210. let (com_update, shares_update) = update_comm_res.unwrap();
  211. // Apply the update to previously-created committment
  212. let updated_commitment_res = apply_commitment_update(&com, &com_update);
  213. assert!(updated_commitment_res.is_ok());
  214. let updated_commitment = updated_commitment_res.unwrap();
  215. // Distribute the update to all owners of shares
  216. // Verify and apply the update
  217. // Collect updated shares to test secret reconstruction after
  218. let mut updates_to_shares = shares_update.iter();
  219. let mut updated_shares: Vec<Share> = Vec::with_capacity(5);
  220. for share in &shares {
  221. let share_update = updates_to_shares.next().unwrap();
  222. let update_share_res = apply_share_update(&share, &share_update, &updated_commitment);
  223. assert!(update_share_res.is_ok());
  224. let updated_share = update_share_res.unwrap();
  225. updated_shares.push(updated_share);
  226. }
  227. // assert that we can recover the original secret using the updated shares
  228. let recres = reconstruct_secret(&updated_shares);
  229. assert!(recres.is_ok());
  230. assert_eq!(recres.unwrap(), s);
  231. // test that the old shares are not valid with the updated commitment
  232. for share in &shares {
  233. let is_valid = verify_share(&share, &updated_commitment);
  234. assert!(is_valid.is_ok());
  235. assert!(!is_valid.unwrap());
  236. }
  237. }
  238. #[test]
  239. fn share_update_valid_multiple_updates() {
  240. let s = Secret::from(42u32);
  241. let res = generate_shares(s, 5, 2);
  242. assert!(res.is_ok());
  243. let (com, shares) = res.unwrap();
  244. // final shares to test at the end
  245. let mut updated_shares: Vec<Share> = Vec::with_capacity(5);
  246. // override these each time in the loop
  247. let mut next_shares = shares;
  248. let mut next_com = com;
  249. for i in 0..5 {
  250. // Create a new update
  251. let update_comm_res = create_update(5, 2);
  252. assert!(update_comm_res.is_ok());
  253. let (com_update, shares_update) = update_comm_res.unwrap();
  254. // Apply the update to previously-created committment
  255. let updated_commitment_res = apply_commitment_update(&next_com, &com_update);
  256. assert!(updated_commitment_res.is_ok());
  257. let updated_commitment = updated_commitment_res.unwrap();
  258. let mut iterim_shares: Vec<Share> = Vec::with_capacity(5);
  259. let mut updates_to_shares = shares_update.iter();
  260. for share in &next_shares {
  261. let share_update = updates_to_shares.next().unwrap();
  262. let update_share_res = apply_share_update(&share, &share_update, &updated_commitment);
  263. assert!(update_share_res.is_ok());
  264. let updated_share = update_share_res.unwrap();
  265. // only collect the last round of updated shares
  266. if i == 4 {
  267. updated_shares.push(updated_share);
  268. }
  269. iterim_shares.push(updated_share);
  270. }
  271. next_shares = iterim_shares;
  272. next_com = updated_commitment;
  273. }
  274. // assert that we can recover the original secret using the updated shares
  275. let recres = reconstruct_secret(&updated_shares);
  276. assert!(recres.is_ok());
  277. assert_eq!(recres.unwrap(), s);
  278. }
  279. }