vss.rs 11 KB

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