[
  {
    "path": ".gitignore",
    "content": "target\nCargo.lock\n*.rs.bk\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: rust\nrust:\n    - stable\n    - beta\n    - nightly\nmatrix:\n  allow_failures:\n    - rust: nightly\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"threshold-secret-sharing\"\nversion = \"0.2.3-pre\"\nauthors = [\n  \"Morten Dahl <morten.dahl@snips.ai>\",\n  \"Mathieu Poumeyrol <mathieu.poumeyrol@snips.ai>\"\n]\ndescription = \"A pure-Rust implementation of various threshold secret sharing schemes\"\nkeywords = [\n  \"secret-sharing\",\n  \"Shamir\",\n  \"cryptography\",\n  \"secure-computation\",\n  \"mpc\"\n]\nhomepage = \"https://github.com/snipsco/rust-threshold-secret-sharing\"\ndocumentation = \"https://docs.rs/threshold-secret-sharing\"\nlicense = \"MIT/Apache-2.0\"\ncategories = [ \"cryptography\" ]\n\n[badges]\ntravis-ci = { repository = \"snipsco/rust-threshold-secret-sharing\" }\n\n[features]\nparamgen = [\"primal\"]\n\n[dependencies]\nrand = \"0.3.*\"\nprimal = { version = \"0.2\", optional = true }\n\n[dev-dependencies]\nbencher = \"0.1\"\n\n[[bench]]\nname = \"packed\"\nharness = false\n"
  },
  {
    "path": "LICENSE",
    "content": "## License\n\nLicensed under either of\n * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\nat your option.\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall\nbe dual licensed as above, without any additional terms or conditions.\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Threshold Secret Sharing\n\n[![Build Status](https://travis-ci.org/snipsco/rust-threshold-secret-sharing.svg?branch=master)](https://travis-ci.org/snipsco/rust-threshold-secret-sharing)\n[![Latest version](https://img.shields.io/crates/v/threshold-secret-sharing.svg)](https://img.shields.io/crates/v/threshold-secret-sharing.svg)\n[![License: MIT/Apache2](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg)](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg)\n\nEfficient pure-Rust library for [secret sharing](https://en.wikipedia.org/wiki/Secret_sharing), offering efficient share generation and reconstruction for both traditional Shamir sharing and packet sharing. For now, secrets and shares are fixed as prime field elements represented by `i64` values.\n\n\n# Installation\n\n\n## Cargo\n```toml\n[dependencies]\nthreshold-secret-sharing = \"0.2\"\n```\n\n\n## GitHub\n```bash\ngit clone https://github.com/snipsco/rust-threshold-secret-sharing\ncd rust-threshold-secret-sharing\ncargo build --release\n```\n\n\n# Examples\nSeveral examples are included in the `examples/` directory. Run each with `cargo` using e.g.\n```sh\ncargo run --example shamir\n```\nfor the Shamir example below.\n\n\n## Shamir sharing\nUsing the Shamir scheme is relatively straight-forward.\n\nWhen choosing parameters, `threshold` and `share_count` must be chosen to satisfy security requirements, and `prime` must be large enough to correctly encode the value to be shared (and such that `prime >= share_count + 1`).\n\nWhen reconstructing the secret, indices must be explicitly provided to identify the shares; these correspond to the indices the shares had in the vector returned by `share()`.\n\n```rust\nextern crate threshold_secret_sharing as tss;\n\nfn main() {\n  // create instance of the Shamir scheme\n  let ref tss = tss::shamir::ShamirSecretSharing {\n    threshold: 8,           // privacy threshold\n    share_count: 20,        // total number of shares to generate\n    prime: 41               // prime field to use\n  };\n\n  let secret = 5;\n\n  // generate shares for secret\n  let all_shares = tss.share(secret);\n\n  // artificially remove some of the shares\n  let number_of_recovered_shared = 10;\n  assert!(number_of_recovered_shared >= tss.reconstruct_limit());\n  let recovered_indices: Vec<usize> = (0..number_of_recovered_shared).collect();\n  let recovered_shares: &[i64] = &all_shares[0..number_of_recovered_shared];\n\n  // reconstruct using remaining subset of shares\n  let reconstructed_secret = tss.reconstruct(&recovered_indices, recovered_shares);\n  assert_eq!(reconstructed_secret, secret);\n}\n```\n\n\n## Packed sharing\nIf many secrets are to be secret shared, it may be beneficial to use the packed scheme where several secrets are packed into each share. While still very computational efficient, one downside is that the parameters are somewhat restricted.\n\nSpecifically, the parameters are split in *scheme parameters* and *implementation parameters*:\n- the former, like in Shamir sharing, determines the abstract properties of the scheme, yet now also with a `secret_count` specifying how many secrets are to be packed into each share; the reconstruction limit is implicitly defined as `secret_count + threshold + 1`\n- the latter is related to the implementation (currently based on the Fast Fourier Transform) and requires not only a `prime` specifying the field, but also two principal roots of unity within that field, which must be respectively a power of 2 and a power of 3\n\nDue to this increased complexity, providing helper functions for finding suitable parameters are in progress. For now, a few fixed fields are included in the `packed` module as illustrated in the example below:\n\n- `PSS_4_8_3`, `PSS_4_26_3`, `PSS_155_728_100`, `PSS_155_19682_100`\n\nwith format `PSS_T_N_D` for sharing `D` secrets into `N` shares with a threshold of `T`.\n\n```rust\nextern crate threshold_secret_sharing as tss;\n\nfn main() {\n  // use predefined parameters\n  let ref tss = tss::packed::PSS_4_26_3;\n\n  // generate shares for a vector of secrets\n  let secrets = [1, 2, 3];\n  let all_shares = tss.share(&secrets);\n\n  // artificially remove some of the shares; keep only the first 8\n  let indices: Vec<usize> = (0..8).collect();\n  let shares = &all_shares[0..8];\n\n  // reconstruct using remaining subset of shares\n  let recovered_secrets = tss.reconstruct(&indices, shares);\n  assert_eq!(recovered_secrets, vec![1, 2, 3]);\n}\n```\n\n\n## Homomorphic properties\nBoth the Shamir and the packed scheme enjoy certain homomorphic properties: shared secrets can be transformed by manipulating the shares. Both addition and multiplications work, yet notice that the reconstruction limit in the case of multiplication goes up by a factor of two for each application.\n\n```rust\nextern crate threshold_secret_sharing as tss;\n\nfn main() {\n  // use predefined parameters\n  let ref tss = tss::PSS_4_26_3;\n\n  // generate shares for first vector of secrets\n  let secrets_1 = [1, 2, 3];\n  let shares_1 = tss.share(&secrets_1);\n\n  // generate shares for second vector of secrets\n  let secrets_2 = [4, 5, 6];\n  let shares_2 = tss.share(&secrets_2);\n\n  // combine shares pointwise to get shares of the sum of the secrets\n  let shares_sum: Vec<i64> = shares_1.iter().zip(&shares_2)\n    .map(|(a, b)| (a + b) % tss.prime).collect();\n\n  // artificially remove some of the shares; keep only the first 8\n  let indices: Vec<usize> = (0..8).collect();\n  let shares = &shares_sum[0..8];\n\n  // reconstruct using remaining subset of shares\n  let recovered_secrets = tss.reconstruct(&indices, shares);\n  assert_eq!(recovered_secrets, vec![5, 7, 9]);\n}\n```\n\n# Parameter generation\nWhile it's straight-forward to instantiate the Shamir scheme, as mentioned above the packed scheme is more tricky and a few helper methods are provided as a result. Since some applications needs only a fixed choice of parameters, these helper methods are optional and only included if the `paramgen` feature is activated during compilation:\n```\ncargo build --features paramgen\n```\nwhich also adds several extra dependencies.\n\n\n# Performance\nSo far most performance efforts has been focused on share generation for the packed scheme, with some obvious enhancements for reconstruction in the process of being implemented. As an example, sharing 100 secrets into approximately 20,000 shares with the packed scheme runs in around 31ms on a recent laptop, and in around 590ms on a Raspberry Pi 3.\n\nThese numbers were obtained by running\n```\ncargo bench\n```\nusing the nightly toolchain.\n\n# License\n\nLicensed under either of\n * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\nat your option.\n\n## Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall\nbe dual licensed as above, without any additional terms or conditions.\n"
  },
  {
    "path": "benches/packed.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n#[macro_use]\nextern crate bencher;\nextern crate threshold_secret_sharing as tss;\n\nmod shamir_vs_packed {\n\n    use bencher::Bencher;\n    use tss::shamir::*;\n\n    pub fn bench_100_shamir(b: &mut Bencher) {\n        let ref tss = ShamirSecretSharing {\n            threshold: 155 / 3,\n            parts: 728 / 3,\n            prime: 746497,\n        };\n\n        let all_secrets: Vec<i64> = vec![5 ; 100 ];\n        b.iter(|| {\n            let _shares: Vec<Vec<i64>> = all_secrets.iter()\n                .map(|&secret| tss.share(secret))\n                .collect();\n        });\n    }\n\n    pub fn bench_100_packed(b: &mut Bencher) {\n        use tss::packed::*;\n        let ref pss = PSS_155_728_100;\n        let all_secrets: Vec<i64> = vec![5 ; 100];\n        b.iter(|| {\n            let _shares = pss.share(&all_secrets);\n        })\n    }\n\n}\n\nbenchmark_group!(shamir_vs_packed,\n                 shamir_vs_packed::bench_100_shamir,\n                 shamir_vs_packed::bench_100_packed);\n\n\nmod packed {\n\n    use bencher::Bencher;\n    use tss::packed::*;\n\n    pub fn bench_large_secret_count(b: &mut Bencher) {\n        let ref pss = PSS_155_728_100;\n        let all_secrets = vec![5 ; pss.secret_count * 100];\n        b.iter(|| {\n            let _shares: Vec<Vec<i64>> = all_secrets.chunks(pss.secret_count)\n                .map(|secrets| pss.share(&secrets))\n                .collect();\n        });\n    }\n\n    pub fn bench_large_share_count(b: &mut Bencher) {\n        let ref pss = PSS_155_19682_100;\n        let secrets = vec![5 ; pss.secret_count];\n        b.iter(|| {\n            let _shares = pss.share(&secrets);\n        });\n    }\n\n    pub fn bench_large_reconstruct(b: &mut Bencher) {\n        let ref pss = PSS_155_19682_100;\n        let secrets = vec![5 ; pss.secret_count];\n        let all_shares = pss.share(&secrets);\n\n        // reconstruct using minimum number of shares required\n        let indices: Vec<usize> = (0..pss.reconstruct_limit()).collect();\n        let shares = &all_shares[0..pss.reconstruct_limit()];\n\n        b.iter(|| {\n            let _recovered_secrets = pss.reconstruct(&indices, &shares);\n        });\n    }\n\n}\n\nbenchmark_group!(packed,\n                 packed::bench_large_secret_count,\n                 packed::bench_large_share_count,\n                 packed::bench_large_reconstruct);\n\nbenchmark_main!(shamir_vs_packed, packed);\n"
  },
  {
    "path": "examples/homomorphic.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\nextern crate threshold_secret_sharing as tss;\n\nfn main() {\n\n    let ref pss = tss::packed::PSS_4_26_3;\n    println!(\"\\\n    Using parameters that: \\n \\\n     - allow {} values to be packed together \\n \\\n     - give a security threshold of {} \\n \\\n     - require {} of the {} shares to reconstruct in the basic case\",\n        pss.secret_count,\n        pss.threshold,\n        pss.reconstruct_limit(),\n        pss.share_count\n    );\n\n    // define inputs\n    let secrets_1 = vec![1, 2, 3];\n    println!(\"\\nFirst input vector:  {:?}\", &secrets_1);\n    let secrets_2 = vec![4, 5, 6];\n    println!(\"Second input vector: {:?}\", &secrets_2);\n    let secrets_3 = vec![3, 2, 1];\n    println!(\"Third input vector:  {:?}\", &secrets_3);\n    let secrets_4 = vec![6, 5, 4];\n    println!(\"Fourth input vector: {:?}\", &secrets_4);\n\n    // secret share inputs\n    let shares_1 = pss.share(&secrets_1);\n    println!(\"\\nSharing of first vector gives random shares S1:\\n{:?}\", &shares_1);\n    let shares_2 = pss.share(&secrets_2);\n    println!(\"\\nSharing of second vector gives random shares S2:\\n{:?}\", &shares_2);\n    let shares_3 = pss.share(&secrets_3);\n    println!(\"\\nSharing of third vector gives random shares S3:\\n{:?}\", &shares_3);\n    let shares_4 = pss.share(&secrets_4);\n    println!(\"\\nSharing of fourth vector gives random shares S4:\\n{:?}\", &shares_4);\n\n    // in the following, 'positivise' is used to map (potentially negative)\n    // values to their equivalent positive representation in Z_p for usability\n    use tss::positivise;\n\n    // multiply shares_1 and shares_2 point-wise\n    let shares_12: Vec<i64> = shares_1.iter().zip(&shares_2).map(|(a, b)| (a * b) % pss.prime).collect();\n    // ... and reconstruct product, using double reconstruction limit\n    let shares_12_reconstruct_limit = pss.reconstruct_limit() * 2;\n    let foo: Vec<usize> = (0..shares_12_reconstruct_limit).collect();\n    let bar = &shares_12[0..shares_12_reconstruct_limit];\n    let secrets_12 = pss.reconstruct(&foo, bar);\n    println!(\n        \"\\nMultiplying shares S1 and S2 point-wise gives new shares S12 which \\\n        can be reconstructed (using {} of them) to give output vector: {:?}\",\n        shares_12_reconstruct_limit,\n        positivise(&secrets_12, pss.prime)\n    );\n\n    // multiply shares_3 and shares_4 point-wise\n    let shares_34: Vec<i64> = shares_3.iter().zip(&shares_4).map(|(a, b)| (a * b) % pss.prime).collect();\n    // ... and reconstruct product, using double reconstruction limit\n    let shares_34_reconstruct_limit = pss.reconstruct_limit() * 2;\n    let foo: Vec<usize> = (0..shares_34_reconstruct_limit).collect();\n    let bar = &shares_34[0..shares_34_reconstruct_limit];\n    let secrets_34 = pss.reconstruct(&foo, bar);\n    println!(\n        \"\\nLikewise, multiplying shares S3 and S4 point-wise gives new shares S34 \\\n        which can be reconstructed (using {} of them) to give output vector: {:?}\",\n        shares_34_reconstruct_limit,\n        positivise(&secrets_34, pss.prime)\n    );\n\n    // multiply shares_sum12 and shares_34 point-wise\n    let shares_1234product: Vec<i64> = shares_12.iter().zip(&shares_34).map(|(a, b)| (a * b) % pss.prime).collect();\n    // ... and reconstruct product, using double reconstruction limit\n    let shares_1234product_reconstruct_limit = shares_1234product.len();\n    let foo: Vec<usize> = (0..shares_1234product_reconstruct_limit).collect();\n    let bar = &shares_1234product[0..shares_1234product_reconstruct_limit];\n    let secrets_1234product = pss.reconstruct(&foo, bar);\n    println!(\n        \"\\nIf we continue multiplying these new shares S12 and S34 then we no longer \\\n        have enough shares to reconstruct correctly; using all {} shares gives incorrect (random) \\\n        output: {:?}\",\n        shares_1234product_reconstruct_limit,\n        positivise(&secrets_1234product, pss.prime)\n    );\n\n    // add shares_12 and shares_34 point-wise\n    let shares_1234sum: Vec<i64> = shares_12.iter().zip(&shares_34).map(|(a, b)| (a + b) % pss.prime).collect();\n    // ... and reconstruct sum, using same reconstruction limit as inputs\n    let shares_1234sum_reconstruct_limit = pss.reconstruct_limit() * 2;\n    let foo: Vec<usize> = (0..shares_1234sum_reconstruct_limit).collect();\n    let bar = &shares_1234sum[0..shares_1234sum_reconstruct_limit];\n    let secrets_1234sum = pss.reconstruct(&foo, bar);\n    println!(\n        \"\\nHowever, adding shares S12 and S34 point-wise doesn't increase the \\\n        reconstruction limit and hence using {} shares we can still recover their sum: {:?}\",\n        shares_1234sum_reconstruct_limit,\n        positivise(&secrets_1234sum, pss.prime)\n    );\n\n}\n"
  },
  {
    "path": "examples/shamir.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\nextern crate threshold_secret_sharing as tss;\n\nfn main() {\n\n    let ref tss = tss::shamir::ShamirSecretSharing {\n        threshold: 9,\n        share_count: 20,\n        prime: 41  // any large enough prime will do\n    };\n\n    let secret = 5;\n    let all_shares = tss.share(secret);\n\n    let reconstruct_share_count = 10;\n    assert!(reconstruct_share_count >= tss.reconstruct_limit());\n\n    let indices: Vec<usize> = (0..reconstruct_share_count).collect();\n    let shares: &[i64] = &all_shares[0..reconstruct_share_count];\n    let recovered_secret = tss.reconstruct(&indices, shares);\n\n    println!(\"The recovered secret is {}\", recovered_secret);\n    assert_eq!(recovered_secret, secret);\n\n}\n"
  },
  {
    "path": "src/fields/fft.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! FFT by in-place Cooley-Tukey algorithms.\n\nuse super::Field;\n\n/// 2-radix FFT.\n///\n/// * zp is the modular field\n/// * data is the data to transform\n/// * omega is the root-of-unity to use\n///\n/// `data.len()` must be a power of 2. omega must be a root of unity of order\n/// `data.len()`\npub fn fft2<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    fft2_in_place_rearrange(zp, &mut *data);\n    fft2_in_place_compute(zp, &mut *data, omega);\n}\n\n/// 2-radix inverse FFT.\n///\n/// * zp is the modular field\n/// * data is the data to transform\n/// * omega is the root-of-unity to use\n///\n/// `data.len()` must be a power of 2. omega must be a root of unity of order\n/// `data.len()`\npub fn fft2_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    let omega_inv = zp.inv(omega);\n    let len = data.len();\n    let len_inv = zp.inv(zp.from_u64(len as u64));\n    fft2(zp, data, omega_inv);\n    for mut x in data {\n        *x = zp.mul(*x, len_inv);\n    }\n}\n\nfn fft2_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {\n    let mut target = 0;\n    for pos in 0..data.len() {\n        if target > pos {\n            data.swap(target, pos)\n        }\n        let mut mask = data.len() >> 1;\n        while target & mask != 0 {\n            target &= !mask;\n            mask >>= 1;\n        }\n        target |= mask;\n    }\n}\n\nfn fft2_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    let mut depth = 0usize;\n    while 1usize << depth < data.len() {\n        let step = 1usize << depth;\n        let jump = 2 * step;\n        let factor_stride = zp.qpow(omega, (data.len() / step / 2) as u32);\n        let mut factor = zp.one();\n        for group in 0usize..step {\n            let mut pair = group;\n            while pair < data.len() {\n                let (x, y) = (data[pair], zp.mul(data[pair + step], factor));\n\n                data[pair] = zp.add(x, y);\n                data[pair + step] = zp.sub(x, y);\n\n                pair += jump;\n            }\n            factor = zp.mul(factor, factor_stride);\n        }\n        depth += 1;\n    }\n}\n\nfn trigits_len(n: usize) -> usize {\n    let mut result = 1;\n    let mut value = 3;\n    while value < n + 1 {\n        result += 1;\n        value *= 3;\n    }\n    result\n}\n\nfn fft3_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {\n    let mut target = 0isize;\n    let trigits_len = trigits_len(data.len() - 1);\n    let mut trigits: Vec<u8> = ::std::iter::repeat(0).take(trigits_len).collect();\n    let powers: Vec<isize> = (0..trigits_len).map(|x| 3isize.pow(x as u32)).rev().collect();\n    for pos in 0..data.len() {\n        if target as usize > pos {\n            data.swap(target as usize, pos)\n        }\n        for pow in 0..trigits_len {\n            if trigits[pow] < 2 {\n                trigits[pow] += 1;\n                target += powers[pow];\n                break;\n            } else {\n                trigits[pow] = 0;\n                target -= 2 * powers[pow];\n            }\n        }\n    }\n}\n\nfn fft3_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    let mut step = 1;\n    let big_omega = zp.qpow(omega, (data.len() as u32 / 3));\n    let big_omega_sq = zp.mul(big_omega, big_omega);\n    while step < data.len() {\n        let jump = 3 * step;\n        let factor_stride = zp.qpow(omega, (data.len() / step / 3) as u32);\n        let mut factor = zp.one();\n        for group in 0usize..step {\n            let factor_sq = zp.mul(factor, factor);\n            let mut pair = group;\n            while pair < data.len() {\n                let (x, y, z) = (data[pair],\n                                 zp.mul(data[pair + step], factor),\n                                 zp.mul(data[pair + 2 * step], factor_sq));\n\n                data[pair] = zp.add(zp.add(x, y), z);\n                data[pair + step] =\n                    zp.add(zp.add(x, zp.mul(big_omega, y)), zp.mul(big_omega_sq, z));\n                data[pair + 2 * step] =\n                    zp.add(zp.add(x, zp.mul(big_omega_sq, y)), zp.mul(big_omega, z));\n\n                pair += jump;\n            }\n            factor = zp.mul(factor, factor_stride);\n        }\n        step = jump;\n    }\n}\n\n/// 3-radix FFT.\n///\n/// * zp is the modular field\n/// * data is the data to transform\n/// * omega is the root-of-unity to use\n///\n/// `data.len()` must be a power of 2. omega must be a root of unity of order\n/// `data.len()`\npub fn fft3<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    fft3_in_place_rearrange(zp, &mut *data);\n    fft3_in_place_compute(zp, &mut *data, omega);\n}\n\n/// 3-radix inverse FFT.\n///\n/// * zp is the modular field\n/// * data is the data to transform\n/// * omega is the root-of-unity to use\n///\n/// `data.len()` must be a power of 2. omega must be a root of unity of order\n/// `data.len()`\npub fn fft3_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {\n    let omega_inv = zp.inv(omega);\n    let len_inv = zp.inv(zp.from_u64(data.len() as u64));\n    fft3(zp, data, omega_inv);\n    for mut x in data {\n        *x = zp.mul(*x, len_inv);\n    }\n}\n\n#[cfg(test)]\npub mod test {\n    use super::*;\n    use fields::Field;\n\n    pub fn from<F: Field>(zp: &F, data: &[u64]) -> Vec<F::U> {\n        data.iter().map(|&x| zp.from_u64(x)).collect()\n    }\n\n    pub fn back<F: Field>(zp: &F, data: &[F::U]) -> Vec<u64> {\n        data.iter().map(|&x| zp.to_u64(x)).collect()\n    }\n\n    pub fn test_fft2<F: Field>() {\n        // field is Z_433 in which 354 is an 8th root of unity\n        let zp = F::new(433);\n        let omega = zp.from_u64(354);\n\n        let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8]);\n        fft2(&zp, &mut data, omega);\n        assert_eq!(back(&zp, &data), [36, 303, 146, 3, 429, 422, 279, 122]);\n    }\n\n    pub fn test_fft2_inverse<F: Field>() {\n        // field is Z_433 in which 354 is an 8th root of unity\n        let zp = F::new(433);\n        let omega = zp.from_u64(354);\n\n        let mut data = from(&zp, &[36, 303, 146, 3, 429, 422, 279, 122]);\n        fft2_inverse(&zp, &mut *data, omega);\n        assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8])\n    }\n\n    pub fn test_fft2_big<F: Field>() {\n        let zp = F::new(5038849);\n        let omega = zp.from_u64(4318906);\n\n        let mut data: Vec<_> = (0..256).map(|a| zp.from_u64(a)).collect();\n        fft2(&zp, &mut *data, omega);\n        fft2_inverse(&zp, &mut data, omega);\n\n        assert_eq!(back(&zp, &data), (0..256).collect::<Vec<_>>());\n    }\n\n    pub fn test_fft3<F: Field>() {\n        // field is Z_433 in which 150 is an 9th root of unity\n        let zp = F::new(433);\n        let omega = zp.from_u64(150);\n\n        let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);\n        fft3(&zp, &mut data, omega);\n        assert_eq!(back(&zp, &data), [45, 404, 407, 266, 377, 47, 158, 17, 20]);\n    }\n\n    pub fn test_fft3_inverse<F: Field>() {\n        // field is Z_433 in which 150 is an 9th root of unity\n        let zp = F::new(433);\n        let omega = zp.from_u64(150);\n\n        let mut data = from(&zp, &[45, 404, 407, 266, 377, 47, 158, 17, 20]);\n        fft3_inverse(&zp, &mut *data, omega);\n        assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8, 9])\n    }\n\n    pub fn test_fft3_big<F: Field>() {\n        let zp = F::new(5038849);\n        let omega = zp.from_u64(1814687);\n\n        let mut data: Vec<_> = (0..19683).map(|a| zp.from_u64(a)).collect();\n        fft3(&zp, &mut data, omega);\n        fft3_inverse(&zp, &mut data, omega);\n\n        assert_eq!(back(&zp, &data), (0..19683).collect::<Vec<_>>());\n    }\n}\n"
  },
  {
    "path": "src/fields/mod.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! This module implements in-place 2-radix and 3-radix numeric theory\n//! transformations (FFT on modular fields).\n\npub mod fft;\n\n/// Abstract Field definition.\n///\n/// This trait is not meant to represent a general field in the strict\n/// mathematical sense but it has everything we need to make the FFT to work.\npub trait Field {\n    type U: Copy;\n\n    /// Create a modular field for the given prime.\n    ///\n    /// In the current state of implementation, only values in the u32 range\n    /// should be used.\n    fn new(prime: u64) -> Self;\n\n    /// Get the modulus.\n    fn modulus(&self) -> u64;\n\n    /// Convert a u64 to a modular integer.\n    fn from_u64(&self, a: u64) -> Self::U;\n\n    /// Convert a modular integer to u64 in the 0..modulus range.\n    fn to_u64(&self, a: Self::U) -> u64;\n\n    /// Convert a i64 to a modular integer.\n    fn from_i64(&self, a: i64) -> Self::U {\n        let a = a % self.modulus() as i64;\n        if a >= 0 {\n            self.from_u64(a as u64)\n        } else {\n            self.from_u64((a + self.modulus() as i64) as u64)\n        }\n    }\n\n    /// Convert a modular integer to i64 in the -modulus/2..+modulus/2 range.\n    fn to_i64(&self, a: Self::U) -> i64 {\n        let a = self.to_u64(a);\n        if a > self.modulus() / 2 {\n            a as i64 - self.modulus() as i64\n        } else {\n            a as i64\n        }\n    }\n\n    /// Get the Zero value.\n    fn zero(&self) -> Self::U {\n        self.from_u64(0)\n    }\n\n    /// Get the One value.\n    fn one(&self) -> Self::U {\n        self.from_u64(1)\n    }\n\n    /// Perfoms a modular addition.\n    fn add(&self, a: Self::U, b: Self::U) -> Self::U;\n\n    /// Perfoms a modular substraction.\n    fn sub(&self, a: Self::U, b: Self::U) -> Self::U;\n\n    /// Perfoms a modular multiplication.\n    fn mul(&self, a: Self::U, b: Self::U) -> Self::U;\n\n    /// Perfoms a modular inverse.\n    fn inv(&self, a: Self::U) -> Self::U;\n\n    /// Perfoms a modular exponentiation (x^e % modulus).\n    ///\n    /// Implements exponentiation by squaring.\n    fn qpow(&self, mut x: Self::U, mut e: u32) -> Self::U {\n        let mut acc = self.one();\n        while e > 0 {\n            if e % 2 == 0 {\n                // even\n                // no-op\n            } else {\n                // odd\n                acc = self.mul(acc, x);\n            }\n            x = self.mul(x, x);  // waste one of these by having it here but code is simpler (tiny bit)\n            e = e >> 1;\n        }\n        acc\n    }\n}\n\nmacro_rules! all_fields_test {\n    ($field:ty) => {\n        #[test] fn test_convert() { ::fields::test::test_convert::<$field>(); }\n        #[test] fn test_add() { ::fields::test::test_add::<$field>(); }\n        #[test] fn test_sub() { ::fields::test::test_sub::<$field>(); }\n        #[test] fn test_mul() { ::fields::test::test_mul::<$field>(); }\n        #[test] fn test_qpow() { ::fields::test::test_qpow::<$field>(); }\n        #[test] fn test_fft2() { ::fields::fft::test::test_fft2::<$field>(); }\n        #[test] fn test_fft2_inverse() { ::fields::fft::test::test_fft2_inverse::<$field>(); }\n        #[test] fn test_fft2_big() { ::fields::fft::test::test_fft2_big::<$field>(); }\n        #[test] fn test_fft3() { ::fields::fft::test::test_fft3::<$field>(); }\n        #[test] fn test_fft3_inverse() { ::fields::fft::test::test_fft3_inverse::<$field>(); }\n        #[test] fn test_fft3_big() { ::fields::fft::test::test_fft3_big::<$field>(); }\n    }\n}\n\npub mod native;\npub mod montgomery;\n\n#[cfg(test)]\npub mod test {\n    use super::Field;\n\n    pub fn test_convert<F: Field>() {\n        let zp = F::new(17);\n        for i in 0u64..20 {\n            assert_eq!(zp.to_u64(zp.from_u64(i)), i % 17);\n        }\n    }\n\n    pub fn test_add<F: Field>() {\n        let zp = F::new(17);\n        assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(2))), 10);\n        assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(13))), 4);\n    }\n\n    pub fn test_sub<F: Field>() {\n        let zp = F::new(17);\n        assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(2))), 6);\n        assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(13))),\n                   (17 + 8 - 13) % 17);\n    }\n\n    pub fn test_mul<F: Field>() {\n        let zp = F::new(17);\n        assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(2))),\n                   (8 * 2) % 17);\n        assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(5))),\n                   (8 * 5) % 17);\n    }\n\n    pub fn test_qpow<F: Field>() {\n        let zp = F::new(17);\n        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 0)), 1);\n        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 3)), 8);\n        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 6)), 13);\n    }\n}\n"
  },
  {
    "path": "src/fields/montgomery.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! Montgomery modular multiplication field.\n\nuse super::Field;\n\n/// MontgomeryField32 Value (wraps an u32 for type-safety).\n#[derive(Copy,Clone,Debug)]\npub struct Value(u32);\n\n/// Implementation of Field with Montgomery modular multiplication.\n///\n/// See https://en.wikipedia.org/wiki/Montgomery_modular_multiplication\n/// for general description of the scheme, or\n/// http://www.hackersdelight.org/MontgomeryMultiplication.pdf for\n/// implementation notes.\n///\n/// This implementation assumes R=2^32. In other terms, the modulus must be\n/// in the u32 range. All values will be positive, in the 0..modulus range,\n/// and represented by a u32.\npub struct MontgomeryField32 {\n    pub n: u32, // the prime\n    pub n_quote: u32,\n    pub r_inv: u32, // r = 2^32\n    pub r_cube: u32, // r^3 is used by inv()\n}\n\nimpl MontgomeryField32 {\n    pub fn new(prime: u32) -> MontgomeryField32 {\n        let r = 1u64 << 32;\n        let tmp = ::numtheory::mod_inverse(r as i64, prime as i64);\n        let r_inv = if tmp < 0 {\n            (tmp + prime as i64) as u32\n        } else {\n            tmp as u32\n        };\n        let tmp = ::numtheory::mod_inverse(prime as i64, r as i64);\n        let n_quote = if tmp > 0 {\n            (r as i64 - tmp) as u32\n        } else {\n            (r as i64 - tmp) as u32\n        };\n        let r_cube = ::numtheory::mod_pow(r as i64 % prime as i64, 3u32, prime as i64);\n        MontgomeryField32 {\n            n: prime,\n            r_inv: r_inv,\n            n_quote: n_quote,\n            r_cube: r_cube as u32,\n        }\n    }\n\n    fn redc(&self, a: u64) -> Value {\n        let m: u64 = (a as u32).wrapping_mul(self.n_quote) as u64;\n        let t: u32 = ((a + m * (self.n as u64)) >> 32) as u32;\n        Value((if t >= (self.n) { t - (self.n) } else { t }))\n    }\n}\n\nimpl Field for MontgomeryField32 {\n    type U = Value;\n\n    fn modulus(&self) -> u64 {\n        self.n as u64\n    }\n\n    fn add(&self, a: Self::U, b: Self::U) -> Self::U {\n        let sum = a.0 as u64 + b.0 as u64;\n        if sum > self.n as u64 {\n            Value((sum - self.n as u64) as u32)\n        } else {\n            Value(sum as u32)\n        }\n    }\n\n    fn sub(&self, a: Self::U, b: Self::U) -> Self::U {\n        if a.0 > b.0 {\n            Value(a.0 - b.0)\n        } else {\n            Value((a.0 as u64 + self.n as u64 - b.0 as u64) as u32)\n        }\n    }\n\n    fn mul(&self, a: Self::U, b: Self::U) -> Self::U {\n        self.redc((a.0 as u64).wrapping_mul(b.0 as u64))\n    }\n\n    fn inv(&self, a: Self::U) -> Self::U {\n        let ar_modn_inv = ::numtheory::mod_inverse(a.0 as i64, self.n as i64);\n        self.redc((ar_modn_inv as u64).wrapping_mul(self.r_cube as u64))\n    }\n\n    fn new(prime: u64) -> MontgomeryField32 {\n        MontgomeryField32::new(prime as u32)\n    }\n\n    fn from_u64(&self, a: u64) -> Self::U {\n        Value(((a << 32) % self.n as u64) as u32)\n    }\n\n    fn to_u64(&self, a: Self::U) -> u64 {\n        a.0 as u64 * self.r_inv as u64 % self.n as u64\n    }\n}\n\n#[cfg(test)]\nall_fields_test!(MontgomeryField32);\n"
  },
  {
    "path": "src/fields/native.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! Trivial native modular field.\n\nuse super::Field;\n\n\n#[derive(Copy,Clone,Debug)]\npub struct Value(i64);\n\n/// Trivial implementaion of Field using i64 values and performing a native\n/// modulo reduction after each operation.\n///\n/// Actual values show not exceed the u32 or i32 ranges as multiplication\n/// are performed \"naively\".\n///\n/// The mais purpose of this struct is to serve as a test reference to the \n/// more challenging implementations.\npub struct NativeField(i64);\n\nimpl Field for NativeField {\n    type U = Value;\n\n    fn new(prime: u64) -> NativeField {\n        NativeField(prime as i64)\n    }\n\n    fn modulus(&self) -> u64 {\n        self.0 as u64\n    }\n\n    fn from_u64(&self, a: u64) -> Self::U {\n        Value(a as i64 % self.0)\n    }\n\n    fn to_u64(&self, a: Self::U) -> u64 {\n        a.0 as u64\n    }\n\n    fn add(&self, a: Self::U, b: Self::U) -> Self::U {\n        Value((a.0 + b.0) % self.0)\n    }\n\n    fn sub(&self, a: Self::U, b: Self::U) -> Self::U {\n        let tmp = a.0 - b.0;\n        if tmp > 0 {\n            Value(tmp)\n        } else {\n            Value(tmp + self.0)\n        }\n    }\n\n    fn mul(&self, a: Self::U, b: Self::U) -> Self::U {\n        Value((a.0 * b.0) % self.0)\n    }\n\n    fn inv(&self, a: Self::U) -> Self::U {\n        let tmp = ::numtheory::mod_inverse((a.0 % self.0) as i64, self.0 as i64);\n        self.from_i64(tmp)\n    }\n}\n\n#[cfg(test)]\nall_fields_test!(NativeField);\n"
  },
  {
    "path": "src/lib.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! # Threshold Secret Sharing\n//! Pure-Rust library for [secret sharing](https://en.wikipedia.org/wiki/Secret_sharing),\n//! offering efficient share generation and reconstruction for both\n//! traditional Shamir sharing and its packet (or ramp) variant.\n//! For now, secrets and shares are fixed as prime field elements\n//! represented by `i64` values.\n\nextern crate rand;\n\nmod fields;\nmod numtheory;\npub use numtheory::positivise;\n\npub mod shamir;\npub mod packed;\n"
  },
  {
    "path": "src/numtheory.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! Various number theoretic utility functions used in the library.\n\n/// Euclidean GCD implementation (recursive). The first member of the returned\n/// triplet is the GCD of `a` and `b`.\npub fn gcd(a: i64, b: i64) -> (i64, i64, i64) {\n    if b == 0 {\n        (a, 1, 0)\n    } else {\n        let n = a / b;\n        let c = a % b;\n        let r = gcd(b, c);\n        (r.0, r.2, r.1 - r.2 * n)\n    }\n}\n\n#[test]\nfn test_gcd() {\n    assert_eq!(gcd(12, 16), (4, -1, 1));\n}\n\n\n/// Inverse of `k` in the *Zp* field defined by `prime`.\npub fn mod_inverse(k: i64, prime: i64) -> i64 {\n    let k2 = k % prime;\n    let r = if k2 < 0 {\n        -gcd(prime, -k2).2\n    } else {\n        gcd(prime, k2).2\n    };\n    (prime + r) % prime\n}\n\n#[test]\nfn test_mod_inverse() {\n    assert_eq!(mod_inverse(3, 7), 5);\n}\n\n\n/// `x` to the power of `e` in the *Zp* field defined by `prime`.\npub fn mod_pow(mut x: i64, mut e: u32, prime: i64) -> i64 {\n    let mut acc = 1;\n    while e > 0 {\n        if e % 2 == 0 {\n            // even\n            // no-op\n        } else {\n            // odd\n            acc = (acc * x) % prime;\n        }\n        x = (x * x) % prime; // waste one of these by having it here but code is simpler (tiny bit)\n        e = e >> 1;\n    }\n    acc\n}\n\n#[test]\nfn test_mod_pow() {\n    assert_eq!(mod_pow(2, 0, 17), 1);\n    assert_eq!(mod_pow(2, 3, 17), 8);\n    assert_eq!(mod_pow(2, 6, 17), 13);\n\n    assert_eq!(mod_pow(-3, 0, 17), 1);\n    assert_eq!(mod_pow(-3, 1, 17), -3);\n    assert_eq!(mod_pow(-3, 15, 17), -6);\n}\n\n\n/// Compute the 2-radix FFT of `a_coef` in the *Zp* field defined by `prime`.\n///\n/// `omega` must be a `n`-th principal root of unity,\n/// where `n` is the lenght of `a_coef` as well as a power of 2.\n/// The result will contains the same number of elements.\n#[allow(dead_code)]\npub fn fft2(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {\n    use fields::Field;\n    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);\n\n    let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();\n    ::fields::fft::fft2(&zp, &mut *data, zp.from_i64(omega));\n    data.iter().map(|a| zp.to_i64(*a)).collect()\n}\n\n/// Inverse FFT for `fft2`.\npub fn fft2_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {\n    use fields::Field;\n    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);\n\n    let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();\n    ::fields::fft::fft2_inverse(&zp, &mut *data, zp.from_i64(omega));\n    data.iter().map(|a| zp.to_i64(*a)).collect()\n}\n\n#[test]\nfn test_fft2() {\n    // field is Z_433 in which 354 is an 8th root of unity\n    let prime = 433;\n    let omega = 354;\n\n    let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8];\n    let a_point = fft2(&a_coef, omega, prime);\n    assert_eq!(positivise(&a_point, prime),\n               positivise(&[36, -130, -287, 3, -4, 422, 279, -311], prime))\n}\n\n#[test]\nfn test_fft2_inverse() {\n    // field is Z_433 in which 354 is an 8th root of unity\n    let prime = 433;\n    let omega = 354;\n\n    let a_point = vec![36, -130, -287, 3, -4, 422, 279, -311];\n    let a_coef = fft2_inverse(&a_point, omega, prime);\n    assert_eq!(positivise(&a_coef, prime), vec![1, 2, 3, 4, 5, 6, 7, 8])\n}\n\n/// Compute the 3-radix FFT of `a_coef` in the *Zp* field defined by `prime`.\n///\n/// `omega` must be a `n`-th principal root of unity,\n/// where `n` is the lenght of `a_coef` as well as a power of 3.\n/// The result will contains the same number of elements.\npub fn fft3(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {\n    use fields::Field;\n    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);\n\n    let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();\n    ::fields::fft::fft3(&zp, &mut *data, zp.from_i64(omega));\n    data.iter().map(|a| zp.to_i64(*a)).collect()\n}\n\n/// Inverse FFT for `fft3`.\n#[allow(dead_code)]\npub fn fft3_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {\n    use fields::Field;\n    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);\n\n    let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();\n    ::fields::fft::fft3_inverse(&zp, &mut *data, zp.from_i64(omega));\n    data.iter().map(|a| zp.to_i64(*a)).collect()\n}\n\n#[test]\nfn test_fft3() {\n    // field is Z_433 in which 150 is an 9th root of unity\n    let prime = 433;\n    let omega = 150;\n\n    let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];\n    let a_point = positivise(&fft3(&a_coef, omega, prime), prime);\n    assert_eq!(a_point, vec![45, 404, 407, 266, 377, 47, 158, 17, 20])\n}\n\n#[test]\nfn test_fft3_inverse() {\n    // field is Z_433 in which 150 is an 9th root of unity\n    let prime = 433;\n    let omega = 150;\n\n    let a_point = vec![45, 404, 407, 266, 377, 47, 158, 17, 20];\n    let a_coef = positivise(&fft3_inverse(&a_point, omega, prime), prime);\n    assert_eq!(a_coef, vec![1, 2, 3, 4, 5, 6, 7, 8, 9])\n}\n\n/// Performs a Lagrange interpolation in field Zp at the origin\n/// for a polynomial defined by `points` and `values`.\n///\n/// `points` and `values` are expected to be two arrays of the same size, containing\n/// respectively the evaluation points (x) and the value of the polynomial at those point (p(x)).\n///\n/// The result is the value of the polynomial at x=0. It is also its zero-degree coefficient.\n///\n/// This is obviously less general than `newton_interpolation_general` as we\n/// only get a single value, but it is much faster.\npub fn lagrange_interpolation_at_zero(points: &[i64], values: &[i64], prime: i64) -> i64 {\n    assert_eq!(points.len(), values.len());\n    // Lagrange interpolation for point 0\n    let mut acc = 0i64;\n    for i in 0..values.len() {\n        let xi = points[i];\n        let yi = values[i];\n        let mut num = 1i64;\n        let mut denum = 1i64;\n        for j in 0..values.len() {\n            if j != i {\n                let xj = points[j];\n                num = (num * xj) % prime;\n                denum = (denum * (xj - xi)) % prime;\n            }\n        }\n        acc = (acc + yi * num * mod_inverse(denum, prime)) % prime;\n    }\n    acc\n}\n\n/// Holds together points and Newton-interpolated coefficients for fast evaluation.\npub struct NewtonPolynomial<'a> {\n    points: &'a [i64],\n    coefficients: Vec<i64>,\n}\n\n\n/// General case for Newton interpolation in field Zp.\n///\n/// Given enough `points` (x) and `values` (p(x)), find the coefficients for `p`.\npub fn newton_interpolation_general<'a>(points: &'a [i64],\n                                        values: &[i64],\n                                        prime: i64)\n                                        -> NewtonPolynomial<'a> {\n    let coefficients = compute_newton_coefficients(points, values, prime);\n    NewtonPolynomial {\n        points: points,\n        coefficients: coefficients,\n    }\n}\n\n#[test]\nfn test_newton_interpolation_general() {\n    let prime = 17;\n\n    let poly = [1, 2, 3, 4];\n    let points = vec![5, 6, 7, 8, 9];\n    let values: Vec<i64> =\n        points.iter().map(|&point| mod_evaluate_polynomial(&poly, point, prime)).collect();\n    assert_eq!(values, vec![8, 16, 4, 13, 16]);\n\n    let recovered_poly = newton_interpolation_general(&points, &values, prime);\n    let recovered_values: Vec<i64> =\n        points.iter().map(|&point| newton_evaluate(&recovered_poly, point, prime)).collect();\n    assert_eq!(recovered_values, values);\n\n    assert_eq!(newton_evaluate(&recovered_poly, 10, prime), 3);\n    assert_eq!(newton_evaluate(&recovered_poly, 11, prime), -2);\n    assert_eq!(newton_evaluate(&recovered_poly, 12, prime), 8);\n}\n\npub fn newton_evaluate(poly: &NewtonPolynomial, point: i64, prime: i64) -> i64 {\n    // compute Newton points\n    let mut newton_points = vec![1];\n    for i in 0..poly.points.len() - 1 {\n        let diff = (point - poly.points[i]) % prime;\n        let product = (newton_points[i] * diff) % prime;\n        newton_points.push(product);\n    }\n    let ref newton_coefs = poly.coefficients;\n    // sum up\n    newton_coefs.iter()\n        .zip(newton_points)\n        .map(|(coef, point)| (coef * point) % prime)\n        .fold(0, |a, b| (a + b) % prime)\n}\n\nfn compute_newton_coefficients(points: &[i64], values: &[i64], prime: i64) -> Vec<i64> {\n    assert_eq!(points.len(), values.len());\n\n    let mut store: Vec<(usize, usize, i64)> =\n        values.iter().enumerate().map(|(index, &value)| (index, index, value)).collect();\n\n    for j in 1..store.len() {\n        for i in (j..store.len()).rev() {\n            let index_lower = store[i - 1].0;\n            let index_upper = store[i].1;\n\n            let point_lower = points[index_lower];\n            let point_upper = points[index_upper];\n            let point_diff = (point_upper - point_lower) % prime;\n            let point_diff_inverse = mod_inverse(point_diff, prime);\n\n            let coef_lower = store[i - 1].2;\n            let coef_upper = store[i].2;\n            let coef_diff = (coef_upper - coef_lower) % prime;\n\n            let fraction = (coef_diff * point_diff_inverse) % prime;\n\n            store[i] = (index_lower, index_upper, fraction);\n        }\n    }\n\n    store.iter().map(|&(_, _, v)| v).collect()\n}\n\n#[test]\nfn test_compute_newton_coefficients() {\n    let points = vec![5, 6, 7, 8, 9];\n    let values = vec![8, 16, 4, 13, 16];\n    let prime = 17;\n\n    let coefficients = compute_newton_coefficients(&points, &values, prime);\n    assert_eq!(coefficients, vec![8, 8, -10, 4, 0]);\n}\n\n/// Map `values` from `[-n/2, n/2)` to `[0, n)`.\npub fn positivise(values: &[i64], n: i64) -> Vec<i64> {\n    values.iter()\n        .map(|&value| if value < 0 { value + n } else { value })\n        .collect()\n}\n\n// deprecated\n// fn mod_evaluate_polynomial_naive(coefficients: &[i64], point: i64, prime: i64) -> i64 {\n//     // evaluate naively\n//     coefficients.iter()\n//        .enumerate()\n//        .map(|(deg, coef)| (coef * mod_pow(point, deg as u32, prime)) % prime)\n//        .fold(0, |a, b| (a + b) % prime)\n// }\n//\n// #[test]\n// fn test_mod_evaluate_polynomial_naive() {\n//     let poly = vec![1,2,3,4,5,6];\n//     let point = 5;\n//     let prime = 17;\n//     assert_eq!(mod_evaluate_polynomial_naive(&poly, point, prime), 4);\n// }\n\n/// Evaluate polynomial given by `coefficients` at `point` in Zp using Horner's method.\npub fn mod_evaluate_polynomial(coefficients: &[i64], point: i64, prime: i64) -> i64 {\n    // evaluate using Horner's rule\n    //  - to combine with fold we consider the coefficients in reverse order\n    let mut reversed_coefficients = coefficients.iter().rev();\n    // manually split due to fold insisting on an initial value\n    let head = *reversed_coefficients.next().unwrap();\n    let tail = reversed_coefficients;\n    tail.fold(head, |partial, coef| (partial * point + coef) % prime)\n}\n\n#[test]\nfn test_mod_evaluate_polynomial() {\n    let poly = vec![1, 2, 3, 4, 5, 6];\n    let point = 5;\n    let prime = 17;\n    assert_eq!(mod_evaluate_polynomial(&poly, point, prime), 4);\n}\n"
  },
  {
    "path": "src/packed.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! Packed (or ramp) variant of Shamir secret sharing,\n//! allowing efficient sharing of several secrets together.\n\nuse numtheory::{mod_pow, fft2_inverse, fft3};\nuse rand;\n\n/// Parameters for the packed variant of Shamir secret sharing,\n/// specifying number of secrets shared together, total number of shares, and privacy threshold.\n///\n/// This scheme generalises\n/// [Shamir's scheme](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing)\n/// by simultaneously sharing several secrets, at the expense of leaving a gap\n/// between the privacy threshold and the reconstruction limit.\n///\n/// The Fast Fourier Transform is used for efficiency reasons,\n/// allowing most operations run to quasilinear time `O(n.log(n))` in `share_count`.\n/// An implication of this is that secrets and shares are positioned on positive powers of\n/// respectively an `n`-th and `m`-th principal root of unity,\n/// where `n` is a power of 2 and `m` a power of 3.\n///\n/// As a result there exist several constraints between the various parameters:\n///\n/// * `prime` must be a prime large enough to hold the secrets we plan to share\n/// * `share_count` must be at least `secret_count + threshold` (the reconstruction limit)\n/// * `secret_count + threshold + 1` must be a power of 2\n/// * `share_count + 1` must be a power of 3\n/// * `omega_secrets` must be a `(secret_count + threshold + 1)`-th root of unity\n/// * `omega_shares` must be a `(share_count + 1)`-th root of unity\n///\n/// An optional `paramgen` feature provides methods for finding suitable parameters satisfying\n/// these somewhat complex requirements, in addition to several fixed parameter choices.\n#[derive(Debug,Copy,Clone,PartialEq)]\npub struct PackedSecretSharing {\n\n    // abstract properties\n\n    /// Maximum number of shares that can be known without exposing the secrets\n    /// (privacy threshold).\n    pub threshold: usize,\n    /// Number of shares to split the secrets into.\n    pub share_count: usize,\n    /// Number of secrets to share together.\n    pub secret_count: usize,\n\n    // implementation configuration\n\n    /// Prime defining the Zp field in which computation is taking place.\n    pub prime: i64,\n    /// `m`-th principal root of unity in Zp, where `m = secret_count + threshold + 1`\n    /// must be a power of 2.\n    pub omega_secrets: i64,\n    /// `n`-th principal root of unity in Zp, where `n = share_count + 1` must be a power of 3.\n    pub omega_shares: i64,\n}\n\n/// Example of tiny PSS settings, for sharing 3 secrets into 8 shares, with\n/// a privacy threshold of 4.\npub static PSS_4_8_3: PackedSecretSharing = PackedSecretSharing {\n    threshold: 4,\n    share_count: 8,\n    secret_count: 3,\n    prime: 433,\n    omega_secrets: 354,\n    omega_shares: 150,\n};\n\n/// Example of small PSS settings, for sharing 3 secrets into 26 shares, with\n/// a privacy threshold of 4.\npub static PSS_4_26_3: PackedSecretSharing = PackedSecretSharing {\n    threshold: 4,\n    share_count: 26,\n    secret_count: 3,\n    prime: 433,\n    omega_secrets: 354,\n    omega_shares: 17,\n};\n\n/// Example of PSS settings, for sharing 100 secrets into 728 shares, with\n/// a privacy threshold of 155.\npub static PSS_155_728_100: PackedSecretSharing = PackedSecretSharing {\n    threshold: 155,\n    share_count: 728,\n    secret_count: 100,\n    prime: 746497,\n    omega_secrets: 95660,\n    omega_shares: 610121,\n};\n\n/// Example of PSS settings, for sharing 100 secrets into 19682 shares, with\n/// a privacy threshold of 155.\npub static PSS_155_19682_100: PackedSecretSharing = PackedSecretSharing {\n    threshold: 155,\n    share_count: 19682,\n    secret_count: 100,\n    prime: 5038849,\n    omega_secrets: 4318906,\n    omega_shares: 1814687,\n};\n\nimpl PackedSecretSharing {\n    /// Minimum number of shares required to reconstruct secrets.\n    ///\n    /// For this scheme this is always `secret_count + threshold`\n    pub fn reconstruct_limit(&self) -> usize {\n        self.threshold + self.secret_count\n    }\n\n    /// Generate `share_count` shares for the `secrets` vector.\n    ///\n    /// The length of `secrets` must be `secret_count`.\n    /// It is safe to pad with anything, including zeros.\n    pub fn share(&self, secrets: &[i64]) -> Vec<i64> {\n        assert_eq!(secrets.len(), self.secret_count);\n        // sample polynomial\n        let mut poly = self.sample_polynomial(secrets);\n        assert_eq!(poly.len(), self.reconstruct_limit() + 1);\n        // .. and extend it\n        poly.extend(vec![0; self.share_count - self.reconstruct_limit()]);\n        assert_eq!(poly.len(), self.share_count + 1);\n        // evaluate polynomial to generate shares\n        let mut shares = self.evaluate_polynomial(poly);\n        // .. but remove first element since it should not be used as a share (it's always zero)\n        assert_eq!(shares[0], 0);\n        shares.remove(0);\n        // return\n        assert_eq!(shares.len(), self.share_count);\n        shares\n    }\n\n    fn sample_polynomial(&self, secrets: &[i64]) -> Vec<i64> {\n        assert_eq!(secrets.len(), self.secret_count);\n        // sample randomness using secure randomness\n        use rand::distributions::Sample;\n        let mut range = rand::distributions::range::Range::new(0, self.prime - 1);\n        let mut rng = rand::OsRng::new().unwrap();\n        let randomness: Vec<i64> =\n            (0..self.threshold).map(|_| range.sample(&mut rng) as i64).collect();\n        // recover polynomial\n        let coefficients = self.recover_polynomial(secrets, randomness);\n        assert_eq!(coefficients.len(), self.reconstruct_limit() + 1);\n        coefficients\n    }\n\n    fn recover_polynomial(&self, secrets: &[i64], randomness: Vec<i64>) -> Vec<i64> {\n        // fix the value corresponding to point 1 (zero)\n        let mut values: Vec<i64> = vec![0];\n        // let the subsequent values correspond to the secrets\n        values.extend(secrets);\n        // fill in with random values\n        values.extend(randomness);\n        // run backward FFT to recover polynomial in coefficient representation\n        assert_eq!(values.len(), self.reconstruct_limit() + 1);\n        let coefficients = fft2_inverse(&values, self.omega_secrets, self.prime);\n        coefficients\n    }\n\n    fn evaluate_polynomial(&self, coefficients: Vec<i64>) -> Vec<i64> {\n        assert_eq!(coefficients.len(), self.share_count + 1);\n        let points = fft3(&coefficients, self.omega_shares, self.prime);\n        points\n    }\n\n    /// Reconstruct the secrets from a large enough subset of the shares.\n    ///\n    /// `indices` are the ranks of the known shares as output by the `share` method,\n    ///  while `values` are the actual values of these shares.\n    /// Both must have the same number of elements, and at least `reconstruct_limit`.\n    ///\n    /// The resulting vector is of length `secret_count`.\n    pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> Vec<i64> {\n        assert!(shares.len() == indices.len());\n        assert!(shares.len() >= self.reconstruct_limit());\n        let mut points: Vec<i64> =\n            indices.iter()\n            .map(|&x| mod_pow(self.omega_shares, x as u32 + 1, self.prime))\n            .collect();\n        let mut values = shares.to_vec();\n        // insert missing value for point 1 (zero)\n        points.insert(0, 1);\n        values.insert(0, 0);\n        // interpolate using Newton's method\n        use numtheory::{newton_interpolation_general, newton_evaluate};\n        // TODO optimise by using Newton-equally-space variant\n        let poly = newton_interpolation_general(&points, &values, self.prime);\n        // evaluate at omega_secrets points to recover secrets\n        // TODO optimise to avoid re-computation of power\n        let secrets = (1..self.reconstruct_limit())\n            .map(|e| mod_pow(self.omega_secrets, e as u32, self.prime))\n            .map(|point| newton_evaluate(&poly, point, self.prime))\n            .take(self.secret_count)\n            .collect();\n        secrets\n    }\n}\n\n\n#[cfg(test)]\nmod tests {\n\n    use super::*;\n    use numtheory::*;\n\n    #[test]\n    fn test_recover_polynomial() {\n        let ref pss = PSS_4_8_3;\n        let secrets = vec![1, 2, 3];\n        let randomness = vec![8, 8, 8, 8];  // use fixed randomness\n        let poly = pss.recover_polynomial(&secrets, randomness);\n        assert_eq!(\n            positivise(&poly, pss.prime),\n            positivise(&[113, -382, -172, 267, -325, 432, 388, -321], pss.prime)\n        );\n    }\n\n    #[test]\n    #[cfg_attr(rustfmt, rustfmt_skip)]\n    fn test_evaluate_polynomial() {\n        let ref pss = PSS_4_26_3;\n        let poly = vec![113,  51, 261, 267, 108, 432, 388, 112,   0,\n                          0,   0,   0,   0,   0,   0,   0,   0,   0,\n                          0,   0,   0,   0,   0,   0,   0,   0,   0];\n        let points = &pss.evaluate_polynomial(poly);\n        assert_eq!(\n            positivise(points, pss.prime),\n            vec![   0, 77, 230,  91, 286, 179, 337,  83, 212,\n                   88, 406, 58, 425, 345, 350, 336, 430, 404,\n                   51, 60, 305, 395,  84, 156, 160, 112, 422]\n        );\n    }\n\n    #[test]\n    #[cfg_attr(rustfmt, rustfmt_skip)]\n    fn test_share() {\n        let ref pss = PSS_4_26_3;\n\n        // do sharing\n        let secrets = vec![5, 6, 7];\n        let mut shares = pss.share(&secrets);\n\n        // manually recover secrets\n        use numtheory::{fft3_inverse, mod_evaluate_polynomial};\n        shares.insert(0, 0);\n        let poly = fft3_inverse(&shares, PSS_4_26_3.omega_shares, PSS_4_26_3.prime);\n        let recovered_secrets: Vec<i64> = (1..secrets.len() + 1)\n            .map(|i| {\n                mod_evaluate_polynomial(&poly,\n                                        mod_pow(PSS_4_26_3.omega_secrets,\n                                                i as u32,\n                                                PSS_4_26_3.prime),\n                                        PSS_4_26_3.prime)\n            })\n            .collect();\n\n        use numtheory::positivise;\n        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);\n    }\n\n    #[test]\n    fn test_large_share() {\n        let ref pss = PSS_155_19682_100;\n        let secrets = vec![5 ; pss.secret_count];\n        let shares = pss.share(&secrets);\n        assert_eq!(shares.len(), pss.share_count);\n    }\n\n    #[test]\n    fn test_share_reconstruct() {\n        let ref pss = PSS_4_26_3;\n        let secrets = vec![5, 6, 7];\n        let shares = pss.share(&secrets);\n\n        use numtheory::positivise;\n\n        // reconstruction must work for all shares\n        let indices: Vec<usize> = (0..shares.len()).collect();\n        let recovered_secrets = pss.reconstruct(&indices, &shares);\n        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);\n\n        // .. and for only sufficient shares\n        let indices: Vec<usize> = (0..pss.reconstruct_limit()).collect();\n        let recovered_secrets = pss.reconstruct(&indices, &shares[0..pss.reconstruct_limit()]);\n        print!(\"lenght is {:?}\", indices.len());\n        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);\n    }\n\n    #[test]\n    fn test_share_additive_homomorphism() {\n        let ref pss = PSS_4_26_3;\n\n        let secrets_1 = vec![1, 2, 3];\n        let secrets_2 = vec![4, 5, 6];\n        let shares_1 = pss.share(&secrets_1);\n        let shares_2 = pss.share(&secrets_2);\n\n        // add shares pointwise\n        let shares_sum: Vec<i64> =\n            shares_1.iter().zip(shares_2).map(|(a, b)| (a + b) % pss.prime).collect();\n\n        // reconstruct sum, using same reconstruction limit\n        let reconstruct_limit = pss.reconstruct_limit();\n        let indices: Vec<usize> = (0..reconstruct_limit).collect();\n        let shares = &shares_sum[0..reconstruct_limit];\n        let recovered_secrets = pss.reconstruct(&indices, shares);\n\n        use numtheory::positivise;\n        assert_eq!(positivise(&recovered_secrets, pss.prime), vec![5, 7, 9]);\n    }\n\n    #[test]\n    fn test_share_multiplicative_homomorphism() {\n        let ref pss = PSS_4_26_3;\n\n        let secrets_1 = vec![1, 2, 3];\n        let secrets_2 = vec![4, 5, 6];\n        let shares_1 = pss.share(&secrets_1);\n        let shares_2 = pss.share(&secrets_2);\n\n        // multiply shares pointwise\n        let shares_product: Vec<i64> =\n            shares_1.iter().zip(shares_2).map(|(a, b)| (a * b) % pss.prime).collect();\n\n        // reconstruct product, using double reconstruction limit\n        let reconstruct_limit = pss.reconstruct_limit() * 2;\n        let indices: Vec<usize> = (0..reconstruct_limit).collect();\n        let shares = &shares_product[0..reconstruct_limit];\n        let recovered_secrets = pss.reconstruct(&indices, shares);\n\n        use numtheory::positivise;\n        assert_eq!(positivise(&recovered_secrets, pss.prime), vec![4, 10, 18]);\n    }\n\n}\n\n\n#[doc(hidden)]\n#[cfg(feature = \"paramgen\")]\npub mod paramgen {\n\n    //! Optional helper methods for parameter generation\n\n    extern crate primal;\n\n    #[cfg_attr(rustfmt, rustfmt_skip)]\n    fn check_prime_form(min_p: usize, n: usize, m: usize, p: usize) -> bool {\n        if p < min_p { return false; }\n\n        let q = p - 1;\n        if q % n != 0 { return false; }\n        if q % m != 0 { return false; }\n\n        let q = q / (n * m);\n        if q % n == 0 { return false; }\n        if q % m == 0 { return false; }\n\n        return true;\n    }\n\n    #[test]\n    fn test_check_prime_form() {\n        assert_eq!(primal::Primes::all().find(|p| check_prime_form(198, 8, 9, *p)).unwrap(), 433);\n    }\n\n    fn factor(p: usize) -> Vec<usize> {\n        let mut factors = vec![];\n        let bound = (p as f64).sqrt().ceil() as usize;\n        for f in 2..bound + 1 {\n            if p % f == 0 {\n                factors.push(f);\n                factors.push(p / f);\n            }\n        }\n        factors\n    }\n\n    #[test]\n    fn test_factor() {\n        assert_eq!(factor(40), [2, 20, 4, 10, 5, 8]);\n        assert_eq!(factor(41), []);\n    }\n\n    fn find_field(min_p: usize, n: usize, m: usize) -> Option<(i64, i64)> {\n        // find prime of right form\n        let p = primal::Primes::all().find(|p| check_prime_form(min_p, n, m, *p)).unwrap();\n        // find (any) generator\n        let factors = factor(p - 1);\n        for g in 2..p {\n            // test generator against all factors of p-1\n            let is_generator = factors.iter().all(|f| {\n                use numtheory::mod_pow;\n                let e = (p - 1) / f;\n                mod_pow(g as i64, e as u32, p as i64) != 1  // TODO check for negative value\n            });\n            // return\n            if is_generator {\n                return Some((p as i64, g as i64));\n            }\n        }\n        // didn't find any\n        None\n    }\n\n    #[test]\n    fn test_find_field() {\n        assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(2)).unwrap(),\n                   (433, 5));\n        assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(3)).unwrap(),\n                   (433, 5));\n        assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(6)).unwrap(),\n                   (746497, 5));\n        assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(9)).unwrap(),\n                   (5038849, 29));\n\n        // assert_eq!(find_field(198, 2usize.pow(11), 3usize.pow(8)).unwrap(), (120932353, 5));\n        // assert_eq!(find_field(198, 2usize.pow(13), 3usize.pow(9)).unwrap(), (483729409, 23));\n    }\n\n    fn find_roots(n: usize, m: usize, p: i64, g: i64) -> (i64, i64) {\n        use numtheory::mod_pow;\n        let omega_secrets = mod_pow(g, ((p - 1) / n as i64) as u32, p);\n        let omega_shares = mod_pow(g, ((p - 1) / m as i64) as u32, p);\n        (omega_secrets, omega_shares)\n    }\n\n    #[test]\n    fn test_find_roots() {\n        assert_eq!(find_roots(2usize.pow(3), 3usize.pow(2), 433, 5), (354, 150));\n        assert_eq!(find_roots(2usize.pow(3), 3usize.pow(3), 433, 5), (354, 17));\n    }\n\n    #[doc(hidden)]\n    pub fn generate_parameters(min_size: usize, n: usize, m: usize) -> (i64, i64, i64) {\n        // TODO settle option business once and for all (don't remember it as needed)\n        let (prime, g) = find_field(min_size, n, m).unwrap();\n        let (omega_secrets, omega_shares) = find_roots(n, m, prime, g);\n        (prime, omega_secrets, omega_shares)\n    }\n\n    #[test]\n    fn test_generate_parameters() {\n        assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(2)),\n                   (433, 354, 150));\n        assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(3)),\n                   (433, 354, 17));\n    }\n\n    fn is_power_of(x: usize, e: usize) -> bool {\n        let power = (x as f64).log(e as f64).floor() as u32;\n        e.pow(power) == x\n    }\n\n    #[test]\n    fn test_is_power_of() {\n        assert_eq!(is_power_of(4, 2), true);\n        assert_eq!(is_power_of(5, 2), false);\n        assert_eq!(is_power_of(6, 2), false);\n        assert_eq!(is_power_of(7, 2), false);\n        assert_eq!(is_power_of(8, 2), true);\n\n        assert_eq!(is_power_of(4, 3), false);\n        assert_eq!(is_power_of(5, 3), false);\n        assert_eq!(is_power_of(6, 3), false);\n        assert_eq!(is_power_of(7, 3), false);\n        assert_eq!(is_power_of(8, 3), false);\n        assert_eq!(is_power_of(9, 3), true);\n    }\n\n    use super::PackedSecretSharing;\n\n    impl PackedSecretSharing {\n\n        /// Find suitable parameters with as small a prime field as possible.\n        pub fn new(threshold: usize,\n                   secret_count: usize,\n                   share_count: usize)\n                   -> PackedSecretSharing {\n            let min_size = share_count + secret_count + threshold + 1;\n            Self::new_with_min_size(threshold, secret_count, share_count, min_size)\n        }\n\n        /// Find suitable parameters with a prime field of at least the specified size.\n        pub fn new_with_min_size(threshold: usize,\n                                 secret_count: usize,\n                                 share_count: usize,\n                                 min_size: usize)\n                                 -> PackedSecretSharing {\n\n            let m = threshold + secret_count + 1;\n            let n = share_count + 1;\n            assert!(is_power_of(m, 2));\n            assert!(is_power_of(n, 3));\n            assert!(min_size >= share_count + secret_count + threshold + 1);\n\n            let (prime, omega_secrets, omega_shares) = generate_parameters(min_size, m, n);\n\n            PackedSecretSharing {\n                threshold: threshold,\n                share_count: share_count,\n                secret_count: secret_count,\n                prime: prime,\n                omega_secrets: omega_secrets,\n                omega_shares: omega_shares,\n            }\n        }\n    }\n\n    #[test]\n    fn test_new() {\n        assert_eq!(PackedSecretSharing::new(155, 100, 728),\n                   super::PSS_155_728_100);\n        assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 8, 200),\n                   super::PSS_4_8_3);\n        assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 26, 200),\n                   super::PSS_4_26_3);\n    }\n\n}\n"
  },
  {
    "path": "src/shamir.rs",
    "content": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT\n// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. All files in the project carrying such notice may not be copied,\n// modified, or distributed except according to those terms.\n\n//! Standard [Shamir secret sharing](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing)\n//! for a single secret.\n\nuse rand;\nuse numtheory::*;\n\n/// Parameters for the Shamir scheme, specifying privacy threshold and total number of shares.\n///\n/// There are very few constraints except for the obvious ones:\n///\n/// * `prime` must be a prime large enough to hold the secrets we plan to share\n/// * `share_count` must be at least `threshold + 1` (the reconstruction limit)\n///\n/// # Example:\n///\n/// ```\n///    use threshold_secret_sharing::shamir;\n///    let tss = shamir::ShamirSecretSharing {\n///        threshold: 9,\n///        share_count: 20,\n///        prime: 41\n///    };\n///\n///    let secret = 5;\n///    let all_shares = tss.share(secret);\n///\n///    let reconstruct_share_count = tss.reconstruct_limit();\n///\n///    let indices: Vec<usize> = (0..reconstruct_share_count).collect();\n///    let shares: &[i64] = &all_shares[0..reconstruct_share_count];\n///    let recovered_secret = tss.reconstruct(&indices, shares);\n///\n///    println!(\"The recovered secret is {}\", recovered_secret);\n///    assert_eq!(recovered_secret, secret);\n/// ```\n#[derive(Debug)]\npub struct ShamirSecretSharing {\n    /// Maximum number of shares that can be known without exposing the secret.\n    pub threshold: usize,\n    /// Number of shares to split the secret into.\n    pub share_count: usize,\n    /// Prime defining the Zp field in which computation is taking place.\n    pub prime: i64,\n}\n\n/// Small preset parameters for tests.\npub static SHAMIR_5_20: ShamirSecretSharing = ShamirSecretSharing {\n    threshold: 5,\n    share_count: 20,\n    prime: 41,\n};\n\nimpl ShamirSecretSharing {\n    /// Minimum number of shares required to reconstruct secret.\n    ///\n    /// For this scheme this is always `threshold + 1`.\n    pub fn reconstruct_limit(&self) -> usize {\n        self.threshold + 1\n    }\n\n    /// Generate `share_count` shares from `secret`.\n    pub fn share(&self, secret: i64) -> Vec<i64> {\n        let poly = self.sample_polynomial(secret);\n        self.evaluate_polynomial(&poly)\n    }\n\n    /// Reconstruct `secret` from a large enough subset of the shares.\n    ///\n    /// `indices` are the ranks of the known shares as output by the `share` method,\n    /// while `values` are the actual values of these shares.\n    /// Both must have the same number of elements, and at least `reconstruct_limit`.\n    pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> i64 {\n        assert!(shares.len() == indices.len());\n        assert!(shares.len() >= self.reconstruct_limit());\n        // add one to indices to get points\n        let points: Vec<i64> = indices.iter().map(|&i| (i as i64) + 1i64).collect();\n        lagrange_interpolation_at_zero(&*points, &shares, self.prime)\n    }\n\n    fn sample_polynomial(&self, zero_value: i64) -> Vec<i64> {\n        // fix the first coefficient (corresponding to the evaluation at zero)\n        let mut coefficients = vec![zero_value];\n        // sample the remaining coefficients randomly using secure randomness\n        use rand::distributions::Sample;\n        let mut range = rand::distributions::range::Range::new(0, self.prime - 1);\n        let mut rng = rand::OsRng::new().unwrap();\n        let random_coefficients: Vec<i64> =\n            (0..self.threshold).map(|_| range.sample(&mut rng)).collect();\n        coefficients.extend(random_coefficients);\n        // return\n        coefficients\n    }\n\n    fn evaluate_polynomial(&self, coefficients: &[i64]) -> Vec<i64> {\n        // evaluate at all points\n        (1..self.share_count + 1)\n            .map(|point| mod_evaluate_polynomial(coefficients, point as i64, self.prime))\n            .collect()\n    }\n}\n\n\n#[test]\nfn test_evaluate_polynomial() {\n    let ref tss = SHAMIR_5_20;\n    let poly = vec![1, 2, 0];\n    let values = tss.evaluate_polynomial(&poly);\n    assert_eq!(*values,\n               [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 0]);\n}\n\n#[test]\nfn wikipedia_example() {\n    let tss = ShamirSecretSharing {\n        threshold: 2,\n        share_count: 6,\n        prime: 1613,\n    };\n\n    let shares = tss.evaluate_polynomial(&[1234, 166, 94]);\n    assert_eq!(&*shares, &[1494, 329, 965, 176, 1188, 775]);\n\n    assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), 1234);\n    assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), 1234);\n    assert_eq!(tss.reconstruct(&[2, 3, 4], &shares[2..5]), 1234);\n}\n\n#[test]\nfn test_shamir() {\n    let tss = ShamirSecretSharing {\n        threshold: 2,\n        share_count: 6,\n        prime: 41,\n    };\n    let secret = 1;\n    let shares = tss.share(secret);\n    assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), secret);\n    assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), secret);\n    assert_eq!(tss.reconstruct(&[2, 3, 4, 5], &shares[2..6]), secret);\n}\n"
  }
]