master b6d110fba65d cached
18 files
82.4 KB
23.3k tokens
129 symbols
1 requests
Download .txt
Repository: snipsco/rust-threshold-secret-sharing
Branch: master
Commit: b6d110fba65d
Files: 18
Total size: 82.4 KB

Directory structure:
gitextract_iu92y051/

├── .gitignore
├── .travis.yml
├── Cargo.toml
├── LICENSE
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── benches/
│   └── packed.rs
├── examples/
│   ├── homomorphic.rs
│   └── shamir.rs
└── src/
    ├── fields/
    │   ├── fft.rs
    │   ├── mod.rs
    │   ├── montgomery.rs
    │   └── native.rs
    ├── lib.rs
    ├── numtheory.rs
    ├── packed.rs
    └── shamir.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
target
Cargo.lock
*.rs.bk


================================================
FILE: .travis.yml
================================================
language: rust
rust:
    - stable
    - beta
    - nightly
matrix:
  allow_failures:
    - rust: nightly


================================================
FILE: Cargo.toml
================================================
[package]
name = "threshold-secret-sharing"
version = "0.2.3-pre"
authors = [
  "Morten Dahl <morten.dahl@snips.ai>",
  "Mathieu Poumeyrol <mathieu.poumeyrol@snips.ai>"
]
description = "A pure-Rust implementation of various threshold secret sharing schemes"
keywords = [
  "secret-sharing",
  "Shamir",
  "cryptography",
  "secure-computation",
  "mpc"
]
homepage = "https://github.com/snipsco/rust-threshold-secret-sharing"
documentation = "https://docs.rs/threshold-secret-sharing"
license = "MIT/Apache-2.0"
categories = [ "cryptography" ]

[badges]
travis-ci = { repository = "snipsco/rust-threshold-secret-sharing" }

[features]
paramgen = ["primal"]

[dependencies]
rand = "0.3.*"
primal = { version = "0.2", optional = true }

[dev-dependencies]
bencher = "0.1"

[[bench]]
name = "packed"
harness = false


================================================
FILE: LICENSE
================================================
## License

Licensed under either of
 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.


================================================
FILE: LICENSE-APACHE
================================================
                              Apache License
                        Version 2.0, January 2004
                     http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

   To apply the Apache License to your work, attach the following
   boilerplate notice, with the fields enclosed by brackets "[]"
   replaced with your own identifying information. (Don't include
   the brackets!)  The text should be enclosed in the appropriate
   comment syntax for the file format. We also recommend that a
   file or class name and description of purpose be included on the
   same "printed page" as the copyright notice for easier
   identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: LICENSE-MIT
================================================
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# Threshold Secret Sharing

[![Build Status](https://travis-ci.org/snipsco/rust-threshold-secret-sharing.svg?branch=master)](https://travis-ci.org/snipsco/rust-threshold-secret-sharing)
[![Latest version](https://img.shields.io/crates/v/threshold-secret-sharing.svg)](https://img.shields.io/crates/v/threshold-secret-sharing.svg)
[![License: MIT/Apache2](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg)](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg)

Efficient 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.


# Installation


## Cargo
```toml
[dependencies]
threshold-secret-sharing = "0.2"
```


## GitHub
```bash
git clone https://github.com/snipsco/rust-threshold-secret-sharing
cd rust-threshold-secret-sharing
cargo build --release
```


# Examples
Several examples are included in the `examples/` directory. Run each with `cargo` using e.g.
```sh
cargo run --example shamir
```
for the Shamir example below.


## Shamir sharing
Using the Shamir scheme is relatively straight-forward.

When 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`).

When 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()`.

```rust
extern crate threshold_secret_sharing as tss;

fn main() {
  // create instance of the Shamir scheme
  let ref tss = tss::shamir::ShamirSecretSharing {
    threshold: 8,           // privacy threshold
    share_count: 20,        // total number of shares to generate
    prime: 41               // prime field to use
  };

  let secret = 5;

  // generate shares for secret
  let all_shares = tss.share(secret);

  // artificially remove some of the shares
  let number_of_recovered_shared = 10;
  assert!(number_of_recovered_shared >= tss.reconstruct_limit());
  let recovered_indices: Vec<usize> = (0..number_of_recovered_shared).collect();
  let recovered_shares: &[i64] = &all_shares[0..number_of_recovered_shared];

  // reconstruct using remaining subset of shares
  let reconstructed_secret = tss.reconstruct(&recovered_indices, recovered_shares);
  assert_eq!(reconstructed_secret, secret);
}
```


## Packed sharing
If 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.

Specifically, the parameters are split in *scheme parameters* and *implementation parameters*:
- 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`
- 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

Due 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:

- `PSS_4_8_3`, `PSS_4_26_3`, `PSS_155_728_100`, `PSS_155_19682_100`

with format `PSS_T_N_D` for sharing `D` secrets into `N` shares with a threshold of `T`.

```rust
extern crate threshold_secret_sharing as tss;

fn main() {
  // use predefined parameters
  let ref tss = tss::packed::PSS_4_26_3;

  // generate shares for a vector of secrets
  let secrets = [1, 2, 3];
  let all_shares = tss.share(&secrets);

  // artificially remove some of the shares; keep only the first 8
  let indices: Vec<usize> = (0..8).collect();
  let shares = &all_shares[0..8];

  // reconstruct using remaining subset of shares
  let recovered_secrets = tss.reconstruct(&indices, shares);
  assert_eq!(recovered_secrets, vec![1, 2, 3]);
}
```


## Homomorphic properties
Both 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.

```rust
extern crate threshold_secret_sharing as tss;

fn main() {
  // use predefined parameters
  let ref tss = tss::PSS_4_26_3;

  // generate shares for first vector of secrets
  let secrets_1 = [1, 2, 3];
  let shares_1 = tss.share(&secrets_1);

  // generate shares for second vector of secrets
  let secrets_2 = [4, 5, 6];
  let shares_2 = tss.share(&secrets_2);

  // combine shares pointwise to get shares of the sum of the secrets
  let shares_sum: Vec<i64> = shares_1.iter().zip(&shares_2)
    .map(|(a, b)| (a + b) % tss.prime).collect();

  // artificially remove some of the shares; keep only the first 8
  let indices: Vec<usize> = (0..8).collect();
  let shares = &shares_sum[0..8];

  // reconstruct using remaining subset of shares
  let recovered_secrets = tss.reconstruct(&indices, shares);
  assert_eq!(recovered_secrets, vec![5, 7, 9]);
}
```

# Parameter generation
While 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:
```
cargo build --features paramgen
```
which also adds several extra dependencies.


# Performance
So 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.

These numbers were obtained by running
```
cargo bench
```
using the nightly toolchain.

# License

Licensed under either of
 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.


================================================
FILE: benches/packed.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

#[macro_use]
extern crate bencher;
extern crate threshold_secret_sharing as tss;

mod shamir_vs_packed {

    use bencher::Bencher;
    use tss::shamir::*;

    pub fn bench_100_shamir(b: &mut Bencher) {
        let ref tss = ShamirSecretSharing {
            threshold: 155 / 3,
            parts: 728 / 3,
            prime: 746497,
        };

        let all_secrets: Vec<i64> = vec![5 ; 100 ];
        b.iter(|| {
            let _shares: Vec<Vec<i64>> = all_secrets.iter()
                .map(|&secret| tss.share(secret))
                .collect();
        });
    }

    pub fn bench_100_packed(b: &mut Bencher) {
        use tss::packed::*;
        let ref pss = PSS_155_728_100;
        let all_secrets: Vec<i64> = vec![5 ; 100];
        b.iter(|| {
            let _shares = pss.share(&all_secrets);
        })
    }

}

benchmark_group!(shamir_vs_packed,
                 shamir_vs_packed::bench_100_shamir,
                 shamir_vs_packed::bench_100_packed);


mod packed {

    use bencher::Bencher;
    use tss::packed::*;

    pub fn bench_large_secret_count(b: &mut Bencher) {
        let ref pss = PSS_155_728_100;
        let all_secrets = vec![5 ; pss.secret_count * 100];
        b.iter(|| {
            let _shares: Vec<Vec<i64>> = all_secrets.chunks(pss.secret_count)
                .map(|secrets| pss.share(&secrets))
                .collect();
        });
    }

    pub fn bench_large_share_count(b: &mut Bencher) {
        let ref pss = PSS_155_19682_100;
        let secrets = vec![5 ; pss.secret_count];
        b.iter(|| {
            let _shares = pss.share(&secrets);
        });
    }

    pub fn bench_large_reconstruct(b: &mut Bencher) {
        let ref pss = PSS_155_19682_100;
        let secrets = vec![5 ; pss.secret_count];
        let all_shares = pss.share(&secrets);

        // reconstruct using minimum number of shares required
        let indices: Vec<usize> = (0..pss.reconstruct_limit()).collect();
        let shares = &all_shares[0..pss.reconstruct_limit()];

        b.iter(|| {
            let _recovered_secrets = pss.reconstruct(&indices, &shares);
        });
    }

}

benchmark_group!(packed,
                 packed::bench_large_secret_count,
                 packed::bench_large_share_count,
                 packed::bench_large_reconstruct);

benchmark_main!(shamir_vs_packed, packed);


================================================
FILE: examples/homomorphic.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
extern crate threshold_secret_sharing as tss;

fn main() {

    let ref pss = tss::packed::PSS_4_26_3;
    println!("\
    Using parameters that: \n \
     - allow {} values to be packed together \n \
     - give a security threshold of {} \n \
     - require {} of the {} shares to reconstruct in the basic case",
        pss.secret_count,
        pss.threshold,
        pss.reconstruct_limit(),
        pss.share_count
    );

    // define inputs
    let secrets_1 = vec![1, 2, 3];
    println!("\nFirst input vector:  {:?}", &secrets_1);
    let secrets_2 = vec![4, 5, 6];
    println!("Second input vector: {:?}", &secrets_2);
    let secrets_3 = vec![3, 2, 1];
    println!("Third input vector:  {:?}", &secrets_3);
    let secrets_4 = vec![6, 5, 4];
    println!("Fourth input vector: {:?}", &secrets_4);

    // secret share inputs
    let shares_1 = pss.share(&secrets_1);
    println!("\nSharing of first vector gives random shares S1:\n{:?}", &shares_1);
    let shares_2 = pss.share(&secrets_2);
    println!("\nSharing of second vector gives random shares S2:\n{:?}", &shares_2);
    let shares_3 = pss.share(&secrets_3);
    println!("\nSharing of third vector gives random shares S3:\n{:?}", &shares_3);
    let shares_4 = pss.share(&secrets_4);
    println!("\nSharing of fourth vector gives random shares S4:\n{:?}", &shares_4);

    // in the following, 'positivise' is used to map (potentially negative)
    // values to their equivalent positive representation in Z_p for usability
    use tss::positivise;

    // multiply shares_1 and shares_2 point-wise
    let shares_12: Vec<i64> = shares_1.iter().zip(&shares_2).map(|(a, b)| (a * b) % pss.prime).collect();
    // ... and reconstruct product, using double reconstruction limit
    let shares_12_reconstruct_limit = pss.reconstruct_limit() * 2;
    let foo: Vec<usize> = (0..shares_12_reconstruct_limit).collect();
    let bar = &shares_12[0..shares_12_reconstruct_limit];
    let secrets_12 = pss.reconstruct(&foo, bar);
    println!(
        "\nMultiplying shares S1 and S2 point-wise gives new shares S12 which \
        can be reconstructed (using {} of them) to give output vector: {:?}",
        shares_12_reconstruct_limit,
        positivise(&secrets_12, pss.prime)
    );

    // multiply shares_3 and shares_4 point-wise
    let shares_34: Vec<i64> = shares_3.iter().zip(&shares_4).map(|(a, b)| (a * b) % pss.prime).collect();
    // ... and reconstruct product, using double reconstruction limit
    let shares_34_reconstruct_limit = pss.reconstruct_limit() * 2;
    let foo: Vec<usize> = (0..shares_34_reconstruct_limit).collect();
    let bar = &shares_34[0..shares_34_reconstruct_limit];
    let secrets_34 = pss.reconstruct(&foo, bar);
    println!(
        "\nLikewise, multiplying shares S3 and S4 point-wise gives new shares S34 \
        which can be reconstructed (using {} of them) to give output vector: {:?}",
        shares_34_reconstruct_limit,
        positivise(&secrets_34, pss.prime)
    );

    // multiply shares_sum12 and shares_34 point-wise
    let shares_1234product: Vec<i64> = shares_12.iter().zip(&shares_34).map(|(a, b)| (a * b) % pss.prime).collect();
    // ... and reconstruct product, using double reconstruction limit
    let shares_1234product_reconstruct_limit = shares_1234product.len();
    let foo: Vec<usize> = (0..shares_1234product_reconstruct_limit).collect();
    let bar = &shares_1234product[0..shares_1234product_reconstruct_limit];
    let secrets_1234product = pss.reconstruct(&foo, bar);
    println!(
        "\nIf we continue multiplying these new shares S12 and S34 then we no longer \
        have enough shares to reconstruct correctly; using all {} shares gives incorrect (random) \
        output: {:?}",
        shares_1234product_reconstruct_limit,
        positivise(&secrets_1234product, pss.prime)
    );

    // add shares_12 and shares_34 point-wise
    let shares_1234sum: Vec<i64> = shares_12.iter().zip(&shares_34).map(|(a, b)| (a + b) % pss.prime).collect();
    // ... and reconstruct sum, using same reconstruction limit as inputs
    let shares_1234sum_reconstruct_limit = pss.reconstruct_limit() * 2;
    let foo: Vec<usize> = (0..shares_1234sum_reconstruct_limit).collect();
    let bar = &shares_1234sum[0..shares_1234sum_reconstruct_limit];
    let secrets_1234sum = pss.reconstruct(&foo, bar);
    println!(
        "\nHowever, adding shares S12 and S34 point-wise doesn't increase the \
        reconstruction limit and hence using {} shares we can still recover their sum: {:?}",
        shares_1234sum_reconstruct_limit,
        positivise(&secrets_1234sum, pss.prime)
    );

}


================================================
FILE: examples/shamir.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
extern crate threshold_secret_sharing as tss;

fn main() {

    let ref tss = tss::shamir::ShamirSecretSharing {
        threshold: 9,
        share_count: 20,
        prime: 41  // any large enough prime will do
    };

    let secret = 5;
    let all_shares = tss.share(secret);

    let reconstruct_share_count = 10;
    assert!(reconstruct_share_count >= tss.reconstruct_limit());

    let indices: Vec<usize> = (0..reconstruct_share_count).collect();
    let shares: &[i64] = &all_shares[0..reconstruct_share_count];
    let recovered_secret = tss.reconstruct(&indices, shares);

    println!("The recovered secret is {}", recovered_secret);
    assert_eq!(recovered_secret, secret);

}


================================================
FILE: src/fields/fft.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! FFT by in-place Cooley-Tukey algorithms.

use super::Field;

/// 2-radix FFT.
///
/// * zp is the modular field
/// * data is the data to transform
/// * omega is the root-of-unity to use
///
/// `data.len()` must be a power of 2. omega must be a root of unity of order
/// `data.len()`
pub fn fft2<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    fft2_in_place_rearrange(zp, &mut *data);
    fft2_in_place_compute(zp, &mut *data, omega);
}

/// 2-radix inverse FFT.
///
/// * zp is the modular field
/// * data is the data to transform
/// * omega is the root-of-unity to use
///
/// `data.len()` must be a power of 2. omega must be a root of unity of order
/// `data.len()`
pub fn fft2_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    let omega_inv = zp.inv(omega);
    let len = data.len();
    let len_inv = zp.inv(zp.from_u64(len as u64));
    fft2(zp, data, omega_inv);
    for mut x in data {
        *x = zp.mul(*x, len_inv);
    }
}

fn fft2_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {
    let mut target = 0;
    for pos in 0..data.len() {
        if target > pos {
            data.swap(target, pos)
        }
        let mut mask = data.len() >> 1;
        while target & mask != 0 {
            target &= !mask;
            mask >>= 1;
        }
        target |= mask;
    }
}

fn fft2_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    let mut depth = 0usize;
    while 1usize << depth < data.len() {
        let step = 1usize << depth;
        let jump = 2 * step;
        let factor_stride = zp.qpow(omega, (data.len() / step / 2) as u32);
        let mut factor = zp.one();
        for group in 0usize..step {
            let mut pair = group;
            while pair < data.len() {
                let (x, y) = (data[pair], zp.mul(data[pair + step], factor));

                data[pair] = zp.add(x, y);
                data[pair + step] = zp.sub(x, y);

                pair += jump;
            }
            factor = zp.mul(factor, factor_stride);
        }
        depth += 1;
    }
}

fn trigits_len(n: usize) -> usize {
    let mut result = 1;
    let mut value = 3;
    while value < n + 1 {
        result += 1;
        value *= 3;
    }
    result
}

fn fft3_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {
    let mut target = 0isize;
    let trigits_len = trigits_len(data.len() - 1);
    let mut trigits: Vec<u8> = ::std::iter::repeat(0).take(trigits_len).collect();
    let powers: Vec<isize> = (0..trigits_len).map(|x| 3isize.pow(x as u32)).rev().collect();
    for pos in 0..data.len() {
        if target as usize > pos {
            data.swap(target as usize, pos)
        }
        for pow in 0..trigits_len {
            if trigits[pow] < 2 {
                trigits[pow] += 1;
                target += powers[pow];
                break;
            } else {
                trigits[pow] = 0;
                target -= 2 * powers[pow];
            }
        }
    }
}

fn fft3_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    let mut step = 1;
    let big_omega = zp.qpow(omega, (data.len() as u32 / 3));
    let big_omega_sq = zp.mul(big_omega, big_omega);
    while step < data.len() {
        let jump = 3 * step;
        let factor_stride = zp.qpow(omega, (data.len() / step / 3) as u32);
        let mut factor = zp.one();
        for group in 0usize..step {
            let factor_sq = zp.mul(factor, factor);
            let mut pair = group;
            while pair < data.len() {
                let (x, y, z) = (data[pair],
                                 zp.mul(data[pair + step], factor),
                                 zp.mul(data[pair + 2 * step], factor_sq));

                data[pair] = zp.add(zp.add(x, y), z);
                data[pair + step] =
                    zp.add(zp.add(x, zp.mul(big_omega, y)), zp.mul(big_omega_sq, z));
                data[pair + 2 * step] =
                    zp.add(zp.add(x, zp.mul(big_omega_sq, y)), zp.mul(big_omega, z));

                pair += jump;
            }
            factor = zp.mul(factor, factor_stride);
        }
        step = jump;
    }
}

/// 3-radix FFT.
///
/// * zp is the modular field
/// * data is the data to transform
/// * omega is the root-of-unity to use
///
/// `data.len()` must be a power of 2. omega must be a root of unity of order
/// `data.len()`
pub fn fft3<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    fft3_in_place_rearrange(zp, &mut *data);
    fft3_in_place_compute(zp, &mut *data, omega);
}

/// 3-radix inverse FFT.
///
/// * zp is the modular field
/// * data is the data to transform
/// * omega is the root-of-unity to use
///
/// `data.len()` must be a power of 2. omega must be a root of unity of order
/// `data.len()`
pub fn fft3_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
    let omega_inv = zp.inv(omega);
    let len_inv = zp.inv(zp.from_u64(data.len() as u64));
    fft3(zp, data, omega_inv);
    for mut x in data {
        *x = zp.mul(*x, len_inv);
    }
}

#[cfg(test)]
pub mod test {
    use super::*;
    use fields::Field;

    pub fn from<F: Field>(zp: &F, data: &[u64]) -> Vec<F::U> {
        data.iter().map(|&x| zp.from_u64(x)).collect()
    }

    pub fn back<F: Field>(zp: &F, data: &[F::U]) -> Vec<u64> {
        data.iter().map(|&x| zp.to_u64(x)).collect()
    }

    pub fn test_fft2<F: Field>() {
        // field is Z_433 in which 354 is an 8th root of unity
        let zp = F::new(433);
        let omega = zp.from_u64(354);

        let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8]);
        fft2(&zp, &mut data, omega);
        assert_eq!(back(&zp, &data), [36, 303, 146, 3, 429, 422, 279, 122]);
    }

    pub fn test_fft2_inverse<F: Field>() {
        // field is Z_433 in which 354 is an 8th root of unity
        let zp = F::new(433);
        let omega = zp.from_u64(354);

        let mut data = from(&zp, &[36, 303, 146, 3, 429, 422, 279, 122]);
        fft2_inverse(&zp, &mut *data, omega);
        assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8])
    }

    pub fn test_fft2_big<F: Field>() {
        let zp = F::new(5038849);
        let omega = zp.from_u64(4318906);

        let mut data: Vec<_> = (0..256).map(|a| zp.from_u64(a)).collect();
        fft2(&zp, &mut *data, omega);
        fft2_inverse(&zp, &mut data, omega);

        assert_eq!(back(&zp, &data), (0..256).collect::<Vec<_>>());
    }

    pub fn test_fft3<F: Field>() {
        // field is Z_433 in which 150 is an 9th root of unity
        let zp = F::new(433);
        let omega = zp.from_u64(150);

        let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
        fft3(&zp, &mut data, omega);
        assert_eq!(back(&zp, &data), [45, 404, 407, 266, 377, 47, 158, 17, 20]);
    }

    pub fn test_fft3_inverse<F: Field>() {
        // field is Z_433 in which 150 is an 9th root of unity
        let zp = F::new(433);
        let omega = zp.from_u64(150);

        let mut data = from(&zp, &[45, 404, 407, 266, 377, 47, 158, 17, 20]);
        fft3_inverse(&zp, &mut *data, omega);
        assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8, 9])
    }

    pub fn test_fft3_big<F: Field>() {
        let zp = F::new(5038849);
        let omega = zp.from_u64(1814687);

        let mut data: Vec<_> = (0..19683).map(|a| zp.from_u64(a)).collect();
        fft3(&zp, &mut data, omega);
        fft3_inverse(&zp, &mut data, omega);

        assert_eq!(back(&zp, &data), (0..19683).collect::<Vec<_>>());
    }
}


================================================
FILE: src/fields/mod.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! This module implements in-place 2-radix and 3-radix numeric theory
//! transformations (FFT on modular fields).

pub mod fft;

/// Abstract Field definition.
///
/// This trait is not meant to represent a general field in the strict
/// mathematical sense but it has everything we need to make the FFT to work.
pub trait Field {
    type U: Copy;

    /// Create a modular field for the given prime.
    ///
    /// In the current state of implementation, only values in the u32 range
    /// should be used.
    fn new(prime: u64) -> Self;

    /// Get the modulus.
    fn modulus(&self) -> u64;

    /// Convert a u64 to a modular integer.
    fn from_u64(&self, a: u64) -> Self::U;

    /// Convert a modular integer to u64 in the 0..modulus range.
    fn to_u64(&self, a: Self::U) -> u64;

    /// Convert a i64 to a modular integer.
    fn from_i64(&self, a: i64) -> Self::U {
        let a = a % self.modulus() as i64;
        if a >= 0 {
            self.from_u64(a as u64)
        } else {
            self.from_u64((a + self.modulus() as i64) as u64)
        }
    }

    /// Convert a modular integer to i64 in the -modulus/2..+modulus/2 range.
    fn to_i64(&self, a: Self::U) -> i64 {
        let a = self.to_u64(a);
        if a > self.modulus() / 2 {
            a as i64 - self.modulus() as i64
        } else {
            a as i64
        }
    }

    /// Get the Zero value.
    fn zero(&self) -> Self::U {
        self.from_u64(0)
    }

    /// Get the One value.
    fn one(&self) -> Self::U {
        self.from_u64(1)
    }

    /// Perfoms a modular addition.
    fn add(&self, a: Self::U, b: Self::U) -> Self::U;

    /// Perfoms a modular substraction.
    fn sub(&self, a: Self::U, b: Self::U) -> Self::U;

    /// Perfoms a modular multiplication.
    fn mul(&self, a: Self::U, b: Self::U) -> Self::U;

    /// Perfoms a modular inverse.
    fn inv(&self, a: Self::U) -> Self::U;

    /// Perfoms a modular exponentiation (x^e % modulus).
    ///
    /// Implements exponentiation by squaring.
    fn qpow(&self, mut x: Self::U, mut e: u32) -> Self::U {
        let mut acc = self.one();
        while e > 0 {
            if e % 2 == 0 {
                // even
                // no-op
            } else {
                // odd
                acc = self.mul(acc, x);
            }
            x = self.mul(x, x);  // waste one of these by having it here but code is simpler (tiny bit)
            e = e >> 1;
        }
        acc
    }
}

macro_rules! all_fields_test {
    ($field:ty) => {
        #[test] fn test_convert() { ::fields::test::test_convert::<$field>(); }
        #[test] fn test_add() { ::fields::test::test_add::<$field>(); }
        #[test] fn test_sub() { ::fields::test::test_sub::<$field>(); }
        #[test] fn test_mul() { ::fields::test::test_mul::<$field>(); }
        #[test] fn test_qpow() { ::fields::test::test_qpow::<$field>(); }
        #[test] fn test_fft2() { ::fields::fft::test::test_fft2::<$field>(); }
        #[test] fn test_fft2_inverse() { ::fields::fft::test::test_fft2_inverse::<$field>(); }
        #[test] fn test_fft2_big() { ::fields::fft::test::test_fft2_big::<$field>(); }
        #[test] fn test_fft3() { ::fields::fft::test::test_fft3::<$field>(); }
        #[test] fn test_fft3_inverse() { ::fields::fft::test::test_fft3_inverse::<$field>(); }
        #[test] fn test_fft3_big() { ::fields::fft::test::test_fft3_big::<$field>(); }
    }
}

pub mod native;
pub mod montgomery;

#[cfg(test)]
pub mod test {
    use super::Field;

    pub fn test_convert<F: Field>() {
        let zp = F::new(17);
        for i in 0u64..20 {
            assert_eq!(zp.to_u64(zp.from_u64(i)), i % 17);
        }
    }

    pub fn test_add<F: Field>() {
        let zp = F::new(17);
        assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(2))), 10);
        assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(13))), 4);
    }

    pub fn test_sub<F: Field>() {
        let zp = F::new(17);
        assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(2))), 6);
        assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(13))),
                   (17 + 8 - 13) % 17);
    }

    pub fn test_mul<F: Field>() {
        let zp = F::new(17);
        assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(2))),
                   (8 * 2) % 17);
        assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(5))),
                   (8 * 5) % 17);
    }

    pub fn test_qpow<F: Field>() {
        let zp = F::new(17);
        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 0)), 1);
        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 3)), 8);
        assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 6)), 13);
    }
}


================================================
FILE: src/fields/montgomery.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Montgomery modular multiplication field.

use super::Field;

/// MontgomeryField32 Value (wraps an u32 for type-safety).
#[derive(Copy,Clone,Debug)]
pub struct Value(u32);

/// Implementation of Field with Montgomery modular multiplication.
///
/// See https://en.wikipedia.org/wiki/Montgomery_modular_multiplication
/// for general description of the scheme, or
/// http://www.hackersdelight.org/MontgomeryMultiplication.pdf for
/// implementation notes.
///
/// This implementation assumes R=2^32. In other terms, the modulus must be
/// in the u32 range. All values will be positive, in the 0..modulus range,
/// and represented by a u32.
pub struct MontgomeryField32 {
    pub n: u32, // the prime
    pub n_quote: u32,
    pub r_inv: u32, // r = 2^32
    pub r_cube: u32, // r^3 is used by inv()
}

impl MontgomeryField32 {
    pub fn new(prime: u32) -> MontgomeryField32 {
        let r = 1u64 << 32;
        let tmp = ::numtheory::mod_inverse(r as i64, prime as i64);
        let r_inv = if tmp < 0 {
            (tmp + prime as i64) as u32
        } else {
            tmp as u32
        };
        let tmp = ::numtheory::mod_inverse(prime as i64, r as i64);
        let n_quote = if tmp > 0 {
            (r as i64 - tmp) as u32
        } else {
            (r as i64 - tmp) as u32
        };
        let r_cube = ::numtheory::mod_pow(r as i64 % prime as i64, 3u32, prime as i64);
        MontgomeryField32 {
            n: prime,
            r_inv: r_inv,
            n_quote: n_quote,
            r_cube: r_cube as u32,
        }
    }

    fn redc(&self, a: u64) -> Value {
        let m: u64 = (a as u32).wrapping_mul(self.n_quote) as u64;
        let t: u32 = ((a + m * (self.n as u64)) >> 32) as u32;
        Value((if t >= (self.n) { t - (self.n) } else { t }))
    }
}

impl Field for MontgomeryField32 {
    type U = Value;

    fn modulus(&self) -> u64 {
        self.n as u64
    }

    fn add(&self, a: Self::U, b: Self::U) -> Self::U {
        let sum = a.0 as u64 + b.0 as u64;
        if sum > self.n as u64 {
            Value((sum - self.n as u64) as u32)
        } else {
            Value(sum as u32)
        }
    }

    fn sub(&self, a: Self::U, b: Self::U) -> Self::U {
        if a.0 > b.0 {
            Value(a.0 - b.0)
        } else {
            Value((a.0 as u64 + self.n as u64 - b.0 as u64) as u32)
        }
    }

    fn mul(&self, a: Self::U, b: Self::U) -> Self::U {
        self.redc((a.0 as u64).wrapping_mul(b.0 as u64))
    }

    fn inv(&self, a: Self::U) -> Self::U {
        let ar_modn_inv = ::numtheory::mod_inverse(a.0 as i64, self.n as i64);
        self.redc((ar_modn_inv as u64).wrapping_mul(self.r_cube as u64))
    }

    fn new(prime: u64) -> MontgomeryField32 {
        MontgomeryField32::new(prime as u32)
    }

    fn from_u64(&self, a: u64) -> Self::U {
        Value(((a << 32) % self.n as u64) as u32)
    }

    fn to_u64(&self, a: Self::U) -> u64 {
        a.0 as u64 * self.r_inv as u64 % self.n as u64
    }
}

#[cfg(test)]
all_fields_test!(MontgomeryField32);


================================================
FILE: src/fields/native.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Trivial native modular field.

use super::Field;


#[derive(Copy,Clone,Debug)]
pub struct Value(i64);

/// Trivial implementaion of Field using i64 values and performing a native
/// modulo reduction after each operation.
///
/// Actual values show not exceed the u32 or i32 ranges as multiplication
/// are performed "naively".
///
/// The mais purpose of this struct is to serve as a test reference to the 
/// more challenging implementations.
pub struct NativeField(i64);

impl Field for NativeField {
    type U = Value;

    fn new(prime: u64) -> NativeField {
        NativeField(prime as i64)
    }

    fn modulus(&self) -> u64 {
        self.0 as u64
    }

    fn from_u64(&self, a: u64) -> Self::U {
        Value(a as i64 % self.0)
    }

    fn to_u64(&self, a: Self::U) -> u64 {
        a.0 as u64
    }

    fn add(&self, a: Self::U, b: Self::U) -> Self::U {
        Value((a.0 + b.0) % self.0)
    }

    fn sub(&self, a: Self::U, b: Self::U) -> Self::U {
        let tmp = a.0 - b.0;
        if tmp > 0 {
            Value(tmp)
        } else {
            Value(tmp + self.0)
        }
    }

    fn mul(&self, a: Self::U, b: Self::U) -> Self::U {
        Value((a.0 * b.0) % self.0)
    }

    fn inv(&self, a: Self::U) -> Self::U {
        let tmp = ::numtheory::mod_inverse((a.0 % self.0) as i64, self.0 as i64);
        self.from_i64(tmp)
    }
}

#[cfg(test)]
all_fields_test!(NativeField);


================================================
FILE: src/lib.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! # Threshold Secret Sharing
//! 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 its packet (or ramp) variant.
//! For now, secrets and shares are fixed as prime field elements
//! represented by `i64` values.

extern crate rand;

mod fields;
mod numtheory;
pub use numtheory::positivise;

pub mod shamir;
pub mod packed;


================================================
FILE: src/numtheory.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Various number theoretic utility functions used in the library.

/// Euclidean GCD implementation (recursive). The first member of the returned
/// triplet is the GCD of `a` and `b`.
pub fn gcd(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let n = a / b;
        let c = a % b;
        let r = gcd(b, c);
        (r.0, r.2, r.1 - r.2 * n)
    }
}

#[test]
fn test_gcd() {
    assert_eq!(gcd(12, 16), (4, -1, 1));
}


/// Inverse of `k` in the *Zp* field defined by `prime`.
pub fn mod_inverse(k: i64, prime: i64) -> i64 {
    let k2 = k % prime;
    let r = if k2 < 0 {
        -gcd(prime, -k2).2
    } else {
        gcd(prime, k2).2
    };
    (prime + r) % prime
}

#[test]
fn test_mod_inverse() {
    assert_eq!(mod_inverse(3, 7), 5);
}


/// `x` to the power of `e` in the *Zp* field defined by `prime`.
pub fn mod_pow(mut x: i64, mut e: u32, prime: i64) -> i64 {
    let mut acc = 1;
    while e > 0 {
        if e % 2 == 0 {
            // even
            // no-op
        } else {
            // odd
            acc = (acc * x) % prime;
        }
        x = (x * x) % prime; // waste one of these by having it here but code is simpler (tiny bit)
        e = e >> 1;
    }
    acc
}

#[test]
fn test_mod_pow() {
    assert_eq!(mod_pow(2, 0, 17), 1);
    assert_eq!(mod_pow(2, 3, 17), 8);
    assert_eq!(mod_pow(2, 6, 17), 13);

    assert_eq!(mod_pow(-3, 0, 17), 1);
    assert_eq!(mod_pow(-3, 1, 17), -3);
    assert_eq!(mod_pow(-3, 15, 17), -6);
}


/// Compute the 2-radix FFT of `a_coef` in the *Zp* field defined by `prime`.
///
/// `omega` must be a `n`-th principal root of unity,
/// where `n` is the lenght of `a_coef` as well as a power of 2.
/// The result will contains the same number of elements.
#[allow(dead_code)]
pub fn fft2(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {
    use fields::Field;
    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);

    let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();
    ::fields::fft::fft2(&zp, &mut *data, zp.from_i64(omega));
    data.iter().map(|a| zp.to_i64(*a)).collect()
}

/// Inverse FFT for `fft2`.
pub fn fft2_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {
    use fields::Field;
    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);

    let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();
    ::fields::fft::fft2_inverse(&zp, &mut *data, zp.from_i64(omega));
    data.iter().map(|a| zp.to_i64(*a)).collect()
}

#[test]
fn test_fft2() {
    // field is Z_433 in which 354 is an 8th root of unity
    let prime = 433;
    let omega = 354;

    let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8];
    let a_point = fft2(&a_coef, omega, prime);
    assert_eq!(positivise(&a_point, prime),
               positivise(&[36, -130, -287, 3, -4, 422, 279, -311], prime))
}

#[test]
fn test_fft2_inverse() {
    // field is Z_433 in which 354 is an 8th root of unity
    let prime = 433;
    let omega = 354;

    let a_point = vec![36, -130, -287, 3, -4, 422, 279, -311];
    let a_coef = fft2_inverse(&a_point, omega, prime);
    assert_eq!(positivise(&a_coef, prime), vec![1, 2, 3, 4, 5, 6, 7, 8])
}

/// Compute the 3-radix FFT of `a_coef` in the *Zp* field defined by `prime`.
///
/// `omega` must be a `n`-th principal root of unity,
/// where `n` is the lenght of `a_coef` as well as a power of 3.
/// The result will contains the same number of elements.
pub fn fft3(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {
    use fields::Field;
    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);

    let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();
    ::fields::fft::fft3(&zp, &mut *data, zp.from_i64(omega));
    data.iter().map(|a| zp.to_i64(*a)).collect()
}

/// Inverse FFT for `fft3`.
#[allow(dead_code)]
pub fn fft3_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {
    use fields::Field;
    let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32);

    let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::<Vec<_>>();
    ::fields::fft::fft3_inverse(&zp, &mut *data, zp.from_i64(omega));
    data.iter().map(|a| zp.to_i64(*a)).collect()
}

#[test]
fn test_fft3() {
    // field is Z_433 in which 150 is an 9th root of unity
    let prime = 433;
    let omega = 150;

    let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
    let a_point = positivise(&fft3(&a_coef, omega, prime), prime);
    assert_eq!(a_point, vec![45, 404, 407, 266, 377, 47, 158, 17, 20])
}

#[test]
fn test_fft3_inverse() {
    // field is Z_433 in which 150 is an 9th root of unity
    let prime = 433;
    let omega = 150;

    let a_point = vec![45, 404, 407, 266, 377, 47, 158, 17, 20];
    let a_coef = positivise(&fft3_inverse(&a_point, omega, prime), prime);
    assert_eq!(a_coef, vec![1, 2, 3, 4, 5, 6, 7, 8, 9])
}

/// Performs a Lagrange interpolation in field Zp at the origin
/// for a polynomial defined by `points` and `values`.
///
/// `points` and `values` are expected to be two arrays of the same size, containing
/// respectively the evaluation points (x) and the value of the polynomial at those point (p(x)).
///
/// The result is the value of the polynomial at x=0. It is also its zero-degree coefficient.
///
/// This is obviously less general than `newton_interpolation_general` as we
/// only get a single value, but it is much faster.
pub fn lagrange_interpolation_at_zero(points: &[i64], values: &[i64], prime: i64) -> i64 {
    assert_eq!(points.len(), values.len());
    // Lagrange interpolation for point 0
    let mut acc = 0i64;
    for i in 0..values.len() {
        let xi = points[i];
        let yi = values[i];
        let mut num = 1i64;
        let mut denum = 1i64;
        for j in 0..values.len() {
            if j != i {
                let xj = points[j];
                num = (num * xj) % prime;
                denum = (denum * (xj - xi)) % prime;
            }
        }
        acc = (acc + yi * num * mod_inverse(denum, prime)) % prime;
    }
    acc
}

/// Holds together points and Newton-interpolated coefficients for fast evaluation.
pub struct NewtonPolynomial<'a> {
    points: &'a [i64],
    coefficients: Vec<i64>,
}


/// General case for Newton interpolation in field Zp.
///
/// Given enough `points` (x) and `values` (p(x)), find the coefficients for `p`.
pub fn newton_interpolation_general<'a>(points: &'a [i64],
                                        values: &[i64],
                                        prime: i64)
                                        -> NewtonPolynomial<'a> {
    let coefficients = compute_newton_coefficients(points, values, prime);
    NewtonPolynomial {
        points: points,
        coefficients: coefficients,
    }
}

#[test]
fn test_newton_interpolation_general() {
    let prime = 17;

    let poly = [1, 2, 3, 4];
    let points = vec![5, 6, 7, 8, 9];
    let values: Vec<i64> =
        points.iter().map(|&point| mod_evaluate_polynomial(&poly, point, prime)).collect();
    assert_eq!(values, vec![8, 16, 4, 13, 16]);

    let recovered_poly = newton_interpolation_general(&points, &values, prime);
    let recovered_values: Vec<i64> =
        points.iter().map(|&point| newton_evaluate(&recovered_poly, point, prime)).collect();
    assert_eq!(recovered_values, values);

    assert_eq!(newton_evaluate(&recovered_poly, 10, prime), 3);
    assert_eq!(newton_evaluate(&recovered_poly, 11, prime), -2);
    assert_eq!(newton_evaluate(&recovered_poly, 12, prime), 8);
}

pub fn newton_evaluate(poly: &NewtonPolynomial, point: i64, prime: i64) -> i64 {
    // compute Newton points
    let mut newton_points = vec![1];
    for i in 0..poly.points.len() - 1 {
        let diff = (point - poly.points[i]) % prime;
        let product = (newton_points[i] * diff) % prime;
        newton_points.push(product);
    }
    let ref newton_coefs = poly.coefficients;
    // sum up
    newton_coefs.iter()
        .zip(newton_points)
        .map(|(coef, point)| (coef * point) % prime)
        .fold(0, |a, b| (a + b) % prime)
}

fn compute_newton_coefficients(points: &[i64], values: &[i64], prime: i64) -> Vec<i64> {
    assert_eq!(points.len(), values.len());

    let mut store: Vec<(usize, usize, i64)> =
        values.iter().enumerate().map(|(index, &value)| (index, index, value)).collect();

    for j in 1..store.len() {
        for i in (j..store.len()).rev() {
            let index_lower = store[i - 1].0;
            let index_upper = store[i].1;

            let point_lower = points[index_lower];
            let point_upper = points[index_upper];
            let point_diff = (point_upper - point_lower) % prime;
            let point_diff_inverse = mod_inverse(point_diff, prime);

            let coef_lower = store[i - 1].2;
            let coef_upper = store[i].2;
            let coef_diff = (coef_upper - coef_lower) % prime;

            let fraction = (coef_diff * point_diff_inverse) % prime;

            store[i] = (index_lower, index_upper, fraction);
        }
    }

    store.iter().map(|&(_, _, v)| v).collect()
}

#[test]
fn test_compute_newton_coefficients() {
    let points = vec![5, 6, 7, 8, 9];
    let values = vec![8, 16, 4, 13, 16];
    let prime = 17;

    let coefficients = compute_newton_coefficients(&points, &values, prime);
    assert_eq!(coefficients, vec![8, 8, -10, 4, 0]);
}

/// Map `values` from `[-n/2, n/2)` to `[0, n)`.
pub fn positivise(values: &[i64], n: i64) -> Vec<i64> {
    values.iter()
        .map(|&value| if value < 0 { value + n } else { value })
        .collect()
}

// deprecated
// fn mod_evaluate_polynomial_naive(coefficients: &[i64], point: i64, prime: i64) -> i64 {
//     // evaluate naively
//     coefficients.iter()
//        .enumerate()
//        .map(|(deg, coef)| (coef * mod_pow(point, deg as u32, prime)) % prime)
//        .fold(0, |a, b| (a + b) % prime)
// }
//
// #[test]
// fn test_mod_evaluate_polynomial_naive() {
//     let poly = vec![1,2,3,4,5,6];
//     let point = 5;
//     let prime = 17;
//     assert_eq!(mod_evaluate_polynomial_naive(&poly, point, prime), 4);
// }

/// Evaluate polynomial given by `coefficients` at `point` in Zp using Horner's method.
pub fn mod_evaluate_polynomial(coefficients: &[i64], point: i64, prime: i64) -> i64 {
    // evaluate using Horner's rule
    //  - to combine with fold we consider the coefficients in reverse order
    let mut reversed_coefficients = coefficients.iter().rev();
    // manually split due to fold insisting on an initial value
    let head = *reversed_coefficients.next().unwrap();
    let tail = reversed_coefficients;
    tail.fold(head, |partial, coef| (partial * point + coef) % prime)
}

#[test]
fn test_mod_evaluate_polynomial() {
    let poly = vec![1, 2, 3, 4, 5, 6];
    let point = 5;
    let prime = 17;
    assert_eq!(mod_evaluate_polynomial(&poly, point, prime), 4);
}


================================================
FILE: src/packed.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Packed (or ramp) variant of Shamir secret sharing,
//! allowing efficient sharing of several secrets together.

use numtheory::{mod_pow, fft2_inverse, fft3};
use rand;

/// Parameters for the packed variant of Shamir secret sharing,
/// specifying number of secrets shared together, total number of shares, and privacy threshold.
///
/// This scheme generalises
/// [Shamir's scheme](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing)
/// by simultaneously sharing several secrets, at the expense of leaving a gap
/// between the privacy threshold and the reconstruction limit.
///
/// The Fast Fourier Transform is used for efficiency reasons,
/// allowing most operations run to quasilinear time `O(n.log(n))` in `share_count`.
/// An implication of this is that secrets and shares are positioned on positive powers of
/// respectively an `n`-th and `m`-th principal root of unity,
/// where `n` is a power of 2 and `m` a power of 3.
///
/// As a result there exist several constraints between the various parameters:
///
/// * `prime` must be a prime large enough to hold the secrets we plan to share
/// * `share_count` must be at least `secret_count + threshold` (the reconstruction limit)
/// * `secret_count + threshold + 1` must be a power of 2
/// * `share_count + 1` must be a power of 3
/// * `omega_secrets` must be a `(secret_count + threshold + 1)`-th root of unity
/// * `omega_shares` must be a `(share_count + 1)`-th root of unity
///
/// An optional `paramgen` feature provides methods for finding suitable parameters satisfying
/// these somewhat complex requirements, in addition to several fixed parameter choices.
#[derive(Debug,Copy,Clone,PartialEq)]
pub struct PackedSecretSharing {

    // abstract properties

    /// Maximum number of shares that can be known without exposing the secrets
    /// (privacy threshold).
    pub threshold: usize,
    /// Number of shares to split the secrets into.
    pub share_count: usize,
    /// Number of secrets to share together.
    pub secret_count: usize,

    // implementation configuration

    /// Prime defining the Zp field in which computation is taking place.
    pub prime: i64,
    /// `m`-th principal root of unity in Zp, where `m = secret_count + threshold + 1`
    /// must be a power of 2.
    pub omega_secrets: i64,
    /// `n`-th principal root of unity in Zp, where `n = share_count + 1` must be a power of 3.
    pub omega_shares: i64,
}

/// Example of tiny PSS settings, for sharing 3 secrets into 8 shares, with
/// a privacy threshold of 4.
pub static PSS_4_8_3: PackedSecretSharing = PackedSecretSharing {
    threshold: 4,
    share_count: 8,
    secret_count: 3,
    prime: 433,
    omega_secrets: 354,
    omega_shares: 150,
};

/// Example of small PSS settings, for sharing 3 secrets into 26 shares, with
/// a privacy threshold of 4.
pub static PSS_4_26_3: PackedSecretSharing = PackedSecretSharing {
    threshold: 4,
    share_count: 26,
    secret_count: 3,
    prime: 433,
    omega_secrets: 354,
    omega_shares: 17,
};

/// Example of PSS settings, for sharing 100 secrets into 728 shares, with
/// a privacy threshold of 155.
pub static PSS_155_728_100: PackedSecretSharing = PackedSecretSharing {
    threshold: 155,
    share_count: 728,
    secret_count: 100,
    prime: 746497,
    omega_secrets: 95660,
    omega_shares: 610121,
};

/// Example of PSS settings, for sharing 100 secrets into 19682 shares, with
/// a privacy threshold of 155.
pub static PSS_155_19682_100: PackedSecretSharing = PackedSecretSharing {
    threshold: 155,
    share_count: 19682,
    secret_count: 100,
    prime: 5038849,
    omega_secrets: 4318906,
    omega_shares: 1814687,
};

impl PackedSecretSharing {
    /// Minimum number of shares required to reconstruct secrets.
    ///
    /// For this scheme this is always `secret_count + threshold`
    pub fn reconstruct_limit(&self) -> usize {
        self.threshold + self.secret_count
    }

    /// Generate `share_count` shares for the `secrets` vector.
    ///
    /// The length of `secrets` must be `secret_count`.
    /// It is safe to pad with anything, including zeros.
    pub fn share(&self, secrets: &[i64]) -> Vec<i64> {
        assert_eq!(secrets.len(), self.secret_count);
        // sample polynomial
        let mut poly = self.sample_polynomial(secrets);
        assert_eq!(poly.len(), self.reconstruct_limit() + 1);
        // .. and extend it
        poly.extend(vec![0; self.share_count - self.reconstruct_limit()]);
        assert_eq!(poly.len(), self.share_count + 1);
        // evaluate polynomial to generate shares
        let mut shares = self.evaluate_polynomial(poly);
        // .. but remove first element since it should not be used as a share (it's always zero)
        assert_eq!(shares[0], 0);
        shares.remove(0);
        // return
        assert_eq!(shares.len(), self.share_count);
        shares
    }

    fn sample_polynomial(&self, secrets: &[i64]) -> Vec<i64> {
        assert_eq!(secrets.len(), self.secret_count);
        // sample randomness using secure randomness
        use rand::distributions::Sample;
        let mut range = rand::distributions::range::Range::new(0, self.prime - 1);
        let mut rng = rand::OsRng::new().unwrap();
        let randomness: Vec<i64> =
            (0..self.threshold).map(|_| range.sample(&mut rng) as i64).collect();
        // recover polynomial
        let coefficients = self.recover_polynomial(secrets, randomness);
        assert_eq!(coefficients.len(), self.reconstruct_limit() + 1);
        coefficients
    }

    fn recover_polynomial(&self, secrets: &[i64], randomness: Vec<i64>) -> Vec<i64> {
        // fix the value corresponding to point 1 (zero)
        let mut values: Vec<i64> = vec![0];
        // let the subsequent values correspond to the secrets
        values.extend(secrets);
        // fill in with random values
        values.extend(randomness);
        // run backward FFT to recover polynomial in coefficient representation
        assert_eq!(values.len(), self.reconstruct_limit() + 1);
        let coefficients = fft2_inverse(&values, self.omega_secrets, self.prime);
        coefficients
    }

    fn evaluate_polynomial(&self, coefficients: Vec<i64>) -> Vec<i64> {
        assert_eq!(coefficients.len(), self.share_count + 1);
        let points = fft3(&coefficients, self.omega_shares, self.prime);
        points
    }

    /// Reconstruct the secrets from a large enough subset of the shares.
    ///
    /// `indices` are the ranks of the known shares as output by the `share` method,
    ///  while `values` are the actual values of these shares.
    /// Both must have the same number of elements, and at least `reconstruct_limit`.
    ///
    /// The resulting vector is of length `secret_count`.
    pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> Vec<i64> {
        assert!(shares.len() == indices.len());
        assert!(shares.len() >= self.reconstruct_limit());
        let mut points: Vec<i64> =
            indices.iter()
            .map(|&x| mod_pow(self.omega_shares, x as u32 + 1, self.prime))
            .collect();
        let mut values = shares.to_vec();
        // insert missing value for point 1 (zero)
        points.insert(0, 1);
        values.insert(0, 0);
        // interpolate using Newton's method
        use numtheory::{newton_interpolation_general, newton_evaluate};
        // TODO optimise by using Newton-equally-space variant
        let poly = newton_interpolation_general(&points, &values, self.prime);
        // evaluate at omega_secrets points to recover secrets
        // TODO optimise to avoid re-computation of power
        let secrets = (1..self.reconstruct_limit())
            .map(|e| mod_pow(self.omega_secrets, e as u32, self.prime))
            .map(|point| newton_evaluate(&poly, point, self.prime))
            .take(self.secret_count)
            .collect();
        secrets
    }
}


#[cfg(test)]
mod tests {

    use super::*;
    use numtheory::*;

    #[test]
    fn test_recover_polynomial() {
        let ref pss = PSS_4_8_3;
        let secrets = vec![1, 2, 3];
        let randomness = vec![8, 8, 8, 8];  // use fixed randomness
        let poly = pss.recover_polynomial(&secrets, randomness);
        assert_eq!(
            positivise(&poly, pss.prime),
            positivise(&[113, -382, -172, 267, -325, 432, 388, -321], pss.prime)
        );
    }

    #[test]
    #[cfg_attr(rustfmt, rustfmt_skip)]
    fn test_evaluate_polynomial() {
        let ref pss = PSS_4_26_3;
        let poly = vec![113,  51, 261, 267, 108, 432, 388, 112,   0,
                          0,   0,   0,   0,   0,   0,   0,   0,   0,
                          0,   0,   0,   0,   0,   0,   0,   0,   0];
        let points = &pss.evaluate_polynomial(poly);
        assert_eq!(
            positivise(points, pss.prime),
            vec![   0, 77, 230,  91, 286, 179, 337,  83, 212,
                   88, 406, 58, 425, 345, 350, 336, 430, 404,
                   51, 60, 305, 395,  84, 156, 160, 112, 422]
        );
    }

    #[test]
    #[cfg_attr(rustfmt, rustfmt_skip)]
    fn test_share() {
        let ref pss = PSS_4_26_3;

        // do sharing
        let secrets = vec![5, 6, 7];
        let mut shares = pss.share(&secrets);

        // manually recover secrets
        use numtheory::{fft3_inverse, mod_evaluate_polynomial};
        shares.insert(0, 0);
        let poly = fft3_inverse(&shares, PSS_4_26_3.omega_shares, PSS_4_26_3.prime);
        let recovered_secrets: Vec<i64> = (1..secrets.len() + 1)
            .map(|i| {
                mod_evaluate_polynomial(&poly,
                                        mod_pow(PSS_4_26_3.omega_secrets,
                                                i as u32,
                                                PSS_4_26_3.prime),
                                        PSS_4_26_3.prime)
            })
            .collect();

        use numtheory::positivise;
        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);
    }

    #[test]
    fn test_large_share() {
        let ref pss = PSS_155_19682_100;
        let secrets = vec![5 ; pss.secret_count];
        let shares = pss.share(&secrets);
        assert_eq!(shares.len(), pss.share_count);
    }

    #[test]
    fn test_share_reconstruct() {
        let ref pss = PSS_4_26_3;
        let secrets = vec![5, 6, 7];
        let shares = pss.share(&secrets);

        use numtheory::positivise;

        // reconstruction must work for all shares
        let indices: Vec<usize> = (0..shares.len()).collect();
        let recovered_secrets = pss.reconstruct(&indices, &shares);
        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);

        // .. and for only sufficient shares
        let indices: Vec<usize> = (0..pss.reconstruct_limit()).collect();
        let recovered_secrets = pss.reconstruct(&indices, &shares[0..pss.reconstruct_limit()]);
        print!("lenght is {:?}", indices.len());
        assert_eq!(positivise(&recovered_secrets, pss.prime), secrets);
    }

    #[test]
    fn test_share_additive_homomorphism() {
        let ref pss = PSS_4_26_3;

        let secrets_1 = vec![1, 2, 3];
        let secrets_2 = vec![4, 5, 6];
        let shares_1 = pss.share(&secrets_1);
        let shares_2 = pss.share(&secrets_2);

        // add shares pointwise
        let shares_sum: Vec<i64> =
            shares_1.iter().zip(shares_2).map(|(a, b)| (a + b) % pss.prime).collect();

        // reconstruct sum, using same reconstruction limit
        let reconstruct_limit = pss.reconstruct_limit();
        let indices: Vec<usize> = (0..reconstruct_limit).collect();
        let shares = &shares_sum[0..reconstruct_limit];
        let recovered_secrets = pss.reconstruct(&indices, shares);

        use numtheory::positivise;
        assert_eq!(positivise(&recovered_secrets, pss.prime), vec![5, 7, 9]);
    }

    #[test]
    fn test_share_multiplicative_homomorphism() {
        let ref pss = PSS_4_26_3;

        let secrets_1 = vec![1, 2, 3];
        let secrets_2 = vec![4, 5, 6];
        let shares_1 = pss.share(&secrets_1);
        let shares_2 = pss.share(&secrets_2);

        // multiply shares pointwise
        let shares_product: Vec<i64> =
            shares_1.iter().zip(shares_2).map(|(a, b)| (a * b) % pss.prime).collect();

        // reconstruct product, using double reconstruction limit
        let reconstruct_limit = pss.reconstruct_limit() * 2;
        let indices: Vec<usize> = (0..reconstruct_limit).collect();
        let shares = &shares_product[0..reconstruct_limit];
        let recovered_secrets = pss.reconstruct(&indices, shares);

        use numtheory::positivise;
        assert_eq!(positivise(&recovered_secrets, pss.prime), vec![4, 10, 18]);
    }

}


#[doc(hidden)]
#[cfg(feature = "paramgen")]
pub mod paramgen {

    //! Optional helper methods for parameter generation

    extern crate primal;

    #[cfg_attr(rustfmt, rustfmt_skip)]
    fn check_prime_form(min_p: usize, n: usize, m: usize, p: usize) -> bool {
        if p < min_p { return false; }

        let q = p - 1;
        if q % n != 0 { return false; }
        if q % m != 0 { return false; }

        let q = q / (n * m);
        if q % n == 0 { return false; }
        if q % m == 0 { return false; }

        return true;
    }

    #[test]
    fn test_check_prime_form() {
        assert_eq!(primal::Primes::all().find(|p| check_prime_form(198, 8, 9, *p)).unwrap(), 433);
    }

    fn factor(p: usize) -> Vec<usize> {
        let mut factors = vec![];
        let bound = (p as f64).sqrt().ceil() as usize;
        for f in 2..bound + 1 {
            if p % f == 0 {
                factors.push(f);
                factors.push(p / f);
            }
        }
        factors
    }

    #[test]
    fn test_factor() {
        assert_eq!(factor(40), [2, 20, 4, 10, 5, 8]);
        assert_eq!(factor(41), []);
    }

    fn find_field(min_p: usize, n: usize, m: usize) -> Option<(i64, i64)> {
        // find prime of right form
        let p = primal::Primes::all().find(|p| check_prime_form(min_p, n, m, *p)).unwrap();
        // find (any) generator
        let factors = factor(p - 1);
        for g in 2..p {
            // test generator against all factors of p-1
            let is_generator = factors.iter().all(|f| {
                use numtheory::mod_pow;
                let e = (p - 1) / f;
                mod_pow(g as i64, e as u32, p as i64) != 1  // TODO check for negative value
            });
            // return
            if is_generator {
                return Some((p as i64, g as i64));
            }
        }
        // didn't find any
        None
    }

    #[test]
    fn test_find_field() {
        assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(2)).unwrap(),
                   (433, 5));
        assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(3)).unwrap(),
                   (433, 5));
        assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(6)).unwrap(),
                   (746497, 5));
        assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(9)).unwrap(),
                   (5038849, 29));

        // assert_eq!(find_field(198, 2usize.pow(11), 3usize.pow(8)).unwrap(), (120932353, 5));
        // assert_eq!(find_field(198, 2usize.pow(13), 3usize.pow(9)).unwrap(), (483729409, 23));
    }

    fn find_roots(n: usize, m: usize, p: i64, g: i64) -> (i64, i64) {
        use numtheory::mod_pow;
        let omega_secrets = mod_pow(g, ((p - 1) / n as i64) as u32, p);
        let omega_shares = mod_pow(g, ((p - 1) / m as i64) as u32, p);
        (omega_secrets, omega_shares)
    }

    #[test]
    fn test_find_roots() {
        assert_eq!(find_roots(2usize.pow(3), 3usize.pow(2), 433, 5), (354, 150));
        assert_eq!(find_roots(2usize.pow(3), 3usize.pow(3), 433, 5), (354, 17));
    }

    #[doc(hidden)]
    pub fn generate_parameters(min_size: usize, n: usize, m: usize) -> (i64, i64, i64) {
        // TODO settle option business once and for all (don't remember it as needed)
        let (prime, g) = find_field(min_size, n, m).unwrap();
        let (omega_secrets, omega_shares) = find_roots(n, m, prime, g);
        (prime, omega_secrets, omega_shares)
    }

    #[test]
    fn test_generate_parameters() {
        assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(2)),
                   (433, 354, 150));
        assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(3)),
                   (433, 354, 17));
    }

    fn is_power_of(x: usize, e: usize) -> bool {
        let power = (x as f64).log(e as f64).floor() as u32;
        e.pow(power) == x
    }

    #[test]
    fn test_is_power_of() {
        assert_eq!(is_power_of(4, 2), true);
        assert_eq!(is_power_of(5, 2), false);
        assert_eq!(is_power_of(6, 2), false);
        assert_eq!(is_power_of(7, 2), false);
        assert_eq!(is_power_of(8, 2), true);

        assert_eq!(is_power_of(4, 3), false);
        assert_eq!(is_power_of(5, 3), false);
        assert_eq!(is_power_of(6, 3), false);
        assert_eq!(is_power_of(7, 3), false);
        assert_eq!(is_power_of(8, 3), false);
        assert_eq!(is_power_of(9, 3), true);
    }

    use super::PackedSecretSharing;

    impl PackedSecretSharing {

        /// Find suitable parameters with as small a prime field as possible.
        pub fn new(threshold: usize,
                   secret_count: usize,
                   share_count: usize)
                   -> PackedSecretSharing {
            let min_size = share_count + secret_count + threshold + 1;
            Self::new_with_min_size(threshold, secret_count, share_count, min_size)
        }

        /// Find suitable parameters with a prime field of at least the specified size.
        pub fn new_with_min_size(threshold: usize,
                                 secret_count: usize,
                                 share_count: usize,
                                 min_size: usize)
                                 -> PackedSecretSharing {

            let m = threshold + secret_count + 1;
            let n = share_count + 1;
            assert!(is_power_of(m, 2));
            assert!(is_power_of(n, 3));
            assert!(min_size >= share_count + secret_count + threshold + 1);

            let (prime, omega_secrets, omega_shares) = generate_parameters(min_size, m, n);

            PackedSecretSharing {
                threshold: threshold,
                share_count: share_count,
                secret_count: secret_count,
                prime: prime,
                omega_secrets: omega_secrets,
                omega_shares: omega_shares,
            }
        }
    }

    #[test]
    fn test_new() {
        assert_eq!(PackedSecretSharing::new(155, 100, 728),
                   super::PSS_155_728_100);
        assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 8, 200),
                   super::PSS_4_8_3);
        assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 26, 200),
                   super::PSS_4_26_3);
    }

}


================================================
FILE: src/shamir.rs
================================================
// Copyright (c) 2016 rust-threshold-secret-sharing developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Standard [Shamir secret sharing](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing)
//! for a single secret.

use rand;
use numtheory::*;

/// Parameters for the Shamir scheme, specifying privacy threshold and total number of shares.
///
/// There are very few constraints except for the obvious ones:
///
/// * `prime` must be a prime large enough to hold the secrets we plan to share
/// * `share_count` must be at least `threshold + 1` (the reconstruction limit)
///
/// # Example:
///
/// ```
///    use threshold_secret_sharing::shamir;
///    let tss = shamir::ShamirSecretSharing {
///        threshold: 9,
///        share_count: 20,
///        prime: 41
///    };
///
///    let secret = 5;
///    let all_shares = tss.share(secret);
///
///    let reconstruct_share_count = tss.reconstruct_limit();
///
///    let indices: Vec<usize> = (0..reconstruct_share_count).collect();
///    let shares: &[i64] = &all_shares[0..reconstruct_share_count];
///    let recovered_secret = tss.reconstruct(&indices, shares);
///
///    println!("The recovered secret is {}", recovered_secret);
///    assert_eq!(recovered_secret, secret);
/// ```
#[derive(Debug)]
pub struct ShamirSecretSharing {
    /// Maximum number of shares that can be known without exposing the secret.
    pub threshold: usize,
    /// Number of shares to split the secret into.
    pub share_count: usize,
    /// Prime defining the Zp field in which computation is taking place.
    pub prime: i64,
}

/// Small preset parameters for tests.
pub static SHAMIR_5_20: ShamirSecretSharing = ShamirSecretSharing {
    threshold: 5,
    share_count: 20,
    prime: 41,
};

impl ShamirSecretSharing {
    /// Minimum number of shares required to reconstruct secret.
    ///
    /// For this scheme this is always `threshold + 1`.
    pub fn reconstruct_limit(&self) -> usize {
        self.threshold + 1
    }

    /// Generate `share_count` shares from `secret`.
    pub fn share(&self, secret: i64) -> Vec<i64> {
        let poly = self.sample_polynomial(secret);
        self.evaluate_polynomial(&poly)
    }

    /// Reconstruct `secret` from a large enough subset of the shares.
    ///
    /// `indices` are the ranks of the known shares as output by the `share` method,
    /// while `values` are the actual values of these shares.
    /// Both must have the same number of elements, and at least `reconstruct_limit`.
    pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> i64 {
        assert!(shares.len() == indices.len());
        assert!(shares.len() >= self.reconstruct_limit());
        // add one to indices to get points
        let points: Vec<i64> = indices.iter().map(|&i| (i as i64) + 1i64).collect();
        lagrange_interpolation_at_zero(&*points, &shares, self.prime)
    }

    fn sample_polynomial(&self, zero_value: i64) -> Vec<i64> {
        // fix the first coefficient (corresponding to the evaluation at zero)
        let mut coefficients = vec![zero_value];
        // sample the remaining coefficients randomly using secure randomness
        use rand::distributions::Sample;
        let mut range = rand::distributions::range::Range::new(0, self.prime - 1);
        let mut rng = rand::OsRng::new().unwrap();
        let random_coefficients: Vec<i64> =
            (0..self.threshold).map(|_| range.sample(&mut rng)).collect();
        coefficients.extend(random_coefficients);
        // return
        coefficients
    }

    fn evaluate_polynomial(&self, coefficients: &[i64]) -> Vec<i64> {
        // evaluate at all points
        (1..self.share_count + 1)
            .map(|point| mod_evaluate_polynomial(coefficients, point as i64, self.prime))
            .collect()
    }
}


#[test]
fn test_evaluate_polynomial() {
    let ref tss = SHAMIR_5_20;
    let poly = vec![1, 2, 0];
    let values = tss.evaluate_polynomial(&poly);
    assert_eq!(*values,
               [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 0]);
}

#[test]
fn wikipedia_example() {
    let tss = ShamirSecretSharing {
        threshold: 2,
        share_count: 6,
        prime: 1613,
    };

    let shares = tss.evaluate_polynomial(&[1234, 166, 94]);
    assert_eq!(&*shares, &[1494, 329, 965, 176, 1188, 775]);

    assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), 1234);
    assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), 1234);
    assert_eq!(tss.reconstruct(&[2, 3, 4], &shares[2..5]), 1234);
}

#[test]
fn test_shamir() {
    let tss = ShamirSecretSharing {
        threshold: 2,
        share_count: 6,
        prime: 41,
    };
    let secret = 1;
    let shares = tss.share(secret);
    assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), secret);
    assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), secret);
    assert_eq!(tss.reconstruct(&[2, 3, 4, 5], &shares[2..6]), secret);
}
Download .txt
gitextract_iu92y051/

├── .gitignore
├── .travis.yml
├── Cargo.toml
├── LICENSE
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── benches/
│   └── packed.rs
├── examples/
│   ├── homomorphic.rs
│   └── shamir.rs
└── src/
    ├── fields/
    │   ├── fft.rs
    │   ├── mod.rs
    │   ├── montgomery.rs
    │   └── native.rs
    ├── lib.rs
    ├── numtheory.rs
    ├── packed.rs
    └── shamir.rs
Download .txt
SYMBOL INDEX (129 symbols across 10 files)

FILE: benches/packed.rs
  function bench_100_shamir (line 18) | pub fn bench_100_shamir(b: &mut Bencher) {
  function bench_100_packed (line 33) | pub fn bench_100_packed(b: &mut Bencher) {
  function bench_large_secret_count (line 54) | pub fn bench_large_secret_count(b: &mut Bencher) {
  function bench_large_share_count (line 64) | pub fn bench_large_share_count(b: &mut Bencher) {
  function bench_large_reconstruct (line 72) | pub fn bench_large_reconstruct(b: &mut Bencher) {

FILE: examples/homomorphic.rs
  function main (line 10) | fn main() {

FILE: examples/shamir.rs
  function main (line 10) | fn main() {

FILE: src/fields/fft.rs
  function fft2 (line 21) | pub fn fft2<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
  function fft2_inverse (line 34) | pub fn fft2_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
  function fft2_in_place_rearrange (line 44) | fn fft2_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {
  function fft2_in_place_compute (line 59) | fn fft2_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::...
  function trigits_len (line 82) | fn trigits_len(n: usize) -> usize {
  function fft3_in_place_rearrange (line 92) | fn fft3_in_place_rearrange<F: Field>(_zp: &F, data: &mut [F::U]) {
  function fft3_in_place_compute (line 114) | fn fft3_in_place_compute<F: Field>(zp: &F, data: &mut [F::U], omega: F::...
  function fft3 (line 152) | pub fn fft3<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
  function fft3_inverse (line 165) | pub fn fft3_inverse<F: Field>(zp: &F, data: &mut [F::U], omega: F::U) {
  function from (line 179) | pub fn from<F: Field>(zp: &F, data: &[u64]) -> Vec<F::U> {
  function back (line 183) | pub fn back<F: Field>(zp: &F, data: &[F::U]) -> Vec<u64> {
  function test_fft2 (line 187) | pub fn test_fft2<F: Field>() {
  function test_fft2_inverse (line 197) | pub fn test_fft2_inverse<F: Field>() {
  function test_fft2_big (line 207) | pub fn test_fft2_big<F: Field>() {
  function test_fft3 (line 218) | pub fn test_fft3<F: Field>() {
  function test_fft3_inverse (line 228) | pub fn test_fft3_inverse<F: Field>() {
  function test_fft3_big (line 238) | pub fn test_fft3_big<F: Field>() {

FILE: src/fields/mod.rs
  type Field (line 18) | pub trait Field {
    method new (line 25) | fn new(prime: u64) -> Self;
    method modulus (line 28) | fn modulus(&self) -> u64;
    method from_u64 (line 31) | fn from_u64(&self, a: u64) -> Self::U;
    method to_u64 (line 34) | fn to_u64(&self, a: Self::U) -> u64;
    method from_i64 (line 37) | fn from_i64(&self, a: i64) -> Self::U {
    method to_i64 (line 47) | fn to_i64(&self, a: Self::U) -> i64 {
    method zero (line 57) | fn zero(&self) -> Self::U {
    method one (line 62) | fn one(&self) -> Self::U {
    method add (line 67) | fn add(&self, a: Self::U, b: Self::U) -> Self::U;
    method sub (line 70) | fn sub(&self, a: Self::U, b: Self::U) -> Self::U;
    method mul (line 73) | fn mul(&self, a: Self::U, b: Self::U) -> Self::U;
    method inv (line 76) | fn inv(&self, a: Self::U) -> Self::U;
    method qpow (line 81) | fn qpow(&self, mut x: Self::U, mut e: u32) -> Self::U {
  function test_convert (line 121) | pub fn test_convert<F: Field>() {
  function test_add (line 128) | pub fn test_add<F: Field>() {
  function test_sub (line 134) | pub fn test_sub<F: Field>() {
  function test_mul (line 141) | pub fn test_mul<F: Field>() {
  function test_qpow (line 149) | pub fn test_qpow<F: Field>() {

FILE: src/fields/montgomery.rs
  type Value (line 15) | pub struct Value(u32);
  type MontgomeryField32 (line 27) | pub struct MontgomeryField32 {
    method new (line 35) | pub fn new(prime: u32) -> MontgomeryField32 {
    method redc (line 58) | fn redc(&self, a: u64) -> Value {
  type U (line 66) | type U = Value;
  method modulus (line 68) | fn modulus(&self) -> u64 {
  method add (line 72) | fn add(&self, a: Self::U, b: Self::U) -> Self::U {
  method sub (line 81) | fn sub(&self, a: Self::U, b: Self::U) -> Self::U {
  method mul (line 89) | fn mul(&self, a: Self::U, b: Self::U) -> Self::U {
  method inv (line 93) | fn inv(&self, a: Self::U) -> Self::U {
  method new (line 98) | fn new(prime: u64) -> MontgomeryField32 {
  method from_u64 (line 102) | fn from_u64(&self, a: u64) -> Self::U {
  method to_u64 (line 106) | fn to_u64(&self, a: Self::U) -> u64 {

FILE: src/fields/native.rs
  type Value (line 15) | pub struct Value(i64);
  type NativeField (line 25) | pub struct NativeField(i64);
  type U (line 28) | type U = Value;
  method new (line 30) | fn new(prime: u64) -> NativeField {
  method modulus (line 34) | fn modulus(&self) -> u64 {
  method from_u64 (line 38) | fn from_u64(&self, a: u64) -> Self::U {
  method to_u64 (line 42) | fn to_u64(&self, a: Self::U) -> u64 {
  method add (line 46) | fn add(&self, a: Self::U, b: Self::U) -> Self::U {
  method sub (line 50) | fn sub(&self, a: Self::U, b: Self::U) -> Self::U {
  method mul (line 59) | fn mul(&self, a: Self::U, b: Self::U) -> Self::U {
  method inv (line 63) | fn inv(&self, a: Self::U) -> Self::U {

FILE: src/numtheory.rs
  function gcd (line 13) | pub fn gcd(a: i64, b: i64) -> (i64, i64, i64) {
  function test_gcd (line 25) | fn test_gcd() {
  function mod_inverse (line 31) | pub fn mod_inverse(k: i64, prime: i64) -> i64 {
  function test_mod_inverse (line 42) | fn test_mod_inverse() {
  function mod_pow (line 48) | pub fn mod_pow(mut x: i64, mut e: u32, prime: i64) -> i64 {
  function test_mod_pow (line 65) | fn test_mod_pow() {
  function fft2 (line 82) | pub fn fft2(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {
  function fft2_inverse (line 92) | pub fn fft2_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {
  function test_fft2 (line 102) | fn test_fft2() {
  function test_fft2_inverse (line 114) | fn test_fft2_inverse() {
  function fft3 (line 129) | pub fn fft3(a_coef: &[i64], omega: i64, prime: i64) -> Vec<i64> {
  function fft3_inverse (line 140) | pub fn fft3_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec<i64> {
  function test_fft3 (line 150) | fn test_fft3() {
  function test_fft3_inverse (line 161) | fn test_fft3_inverse() {
  function lagrange_interpolation_at_zero (line 181) | pub fn lagrange_interpolation_at_zero(points: &[i64], values: &[i64], pr...
  type NewtonPolynomial (line 203) | pub struct NewtonPolynomial<'a> {
  function newton_interpolation_general (line 212) | pub fn newton_interpolation_general<'a>(points: &'a [i64],
  function test_newton_interpolation_general (line 224) | fn test_newton_interpolation_general() {
  function newton_evaluate (line 243) | pub fn newton_evaluate(poly: &NewtonPolynomial, point: i64, prime: i64) ...
  function compute_newton_coefficients (line 259) | fn compute_newton_coefficients(points: &[i64], values: &[i64], prime: i6...
  function test_compute_newton_coefficients (line 289) | fn test_compute_newton_coefficients() {
  function positivise (line 299) | pub fn positivise(values: &[i64], n: i64) -> Vec<i64> {
  function mod_evaluate_polynomial (line 323) | pub fn mod_evaluate_polynomial(coefficients: &[i64], point: i64, prime: ...
  function test_mod_evaluate_polynomial (line 334) | fn test_mod_evaluate_polynomial() {

FILE: src/packed.rs
  type PackedSecretSharing (line 41) | pub struct PackedSecretSharing {
    method reconstruct_limit (line 112) | pub fn reconstruct_limit(&self) -> usize {
    method share (line 120) | pub fn share(&self, secrets: &[i64]) -> Vec<i64> {
    method sample_polynomial (line 138) | fn sample_polynomial(&self, secrets: &[i64]) -> Vec<i64> {
    method recover_polynomial (line 152) | fn recover_polynomial(&self, secrets: &[i64], randomness: Vec<i64>) ->...
    method evaluate_polynomial (line 165) | fn evaluate_polynomial(&self, coefficients: Vec<i64>) -> Vec<i64> {
    method reconstruct (line 178) | pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> Vec<i6...
    method new (line 480) | pub fn new(threshold: usize,
    method new_with_min_size (line 489) | pub fn new_with_min_size(threshold: usize,
  function test_recover_polynomial (line 212) | fn test_recover_polynomial() {
  function test_evaluate_polynomial (line 225) | fn test_evaluate_polynomial() {
  function test_share (line 241) | fn test_share() {
  function test_large_share (line 267) | fn test_large_share() {
  function test_share_reconstruct (line 275) | fn test_share_reconstruct() {
  function test_share_additive_homomorphism (line 295) | fn test_share_additive_homomorphism() {
  function test_share_multiplicative_homomorphism (line 318) | fn test_share_multiplicative_homomorphism() {
  function check_prime_form (line 352) | fn check_prime_form(min_p: usize, n: usize, m: usize, p: usize) -> bool {
  function test_check_prime_form (line 367) | fn test_check_prime_form() {
  function factor (line 371) | fn factor(p: usize) -> Vec<usize> {
  function test_factor (line 384) | fn test_factor() {
  function find_field (line 389) | fn find_field(min_p: usize, n: usize, m: usize) -> Option<(i64, i64)> {
  function test_find_field (line 411) | fn test_find_field() {
  function find_roots (line 425) | fn find_roots(n: usize, m: usize, p: i64, g: i64) -> (i64, i64) {
  function test_find_roots (line 433) | fn test_find_roots() {
  function generate_parameters (line 439) | pub fn generate_parameters(min_size: usize, n: usize, m: usize) -> (i64,...
  function test_generate_parameters (line 447) | fn test_generate_parameters() {
  function is_power_of (line 454) | fn is_power_of(x: usize, e: usize) -> bool {
  function test_is_power_of (line 460) | fn test_is_power_of() {
  function test_new (line 515) | fn test_new() {

FILE: src/shamir.rs
  type ShamirSecretSharing (line 45) | pub struct ShamirSecretSharing {
    method reconstruct_limit (line 65) | pub fn reconstruct_limit(&self) -> usize {
    method share (line 70) | pub fn share(&self, secret: i64) -> Vec<i64> {
    method reconstruct (line 80) | pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> i64 {
    method sample_polynomial (line 88) | fn sample_polynomial(&self, zero_value: i64) -> Vec<i64> {
    method evaluate_polynomial (line 102) | fn evaluate_polynomial(&self, coefficients: &[i64]) -> Vec<i64> {
  function test_evaluate_polynomial (line 112) | fn test_evaluate_polynomial() {
  function wikipedia_example (line 121) | fn wikipedia_example() {
  function test_shamir (line 137) | fn test_shamir() {
Condensed preview — 18 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (88K chars).
[
  {
    "path": ".gitignore",
    "chars": 26,
    "preview": "target\nCargo.lock\n*.rs.bk\n"
  },
  {
    "path": ".travis.yml",
    "chars": 105,
    "preview": "language: rust\nrust:\n    - stable\n    - beta\n    - nightly\nmatrix:\n  allow_failures:\n    - rust: nightly\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 812,
    "preview": "[package]\nname = \"threshold-secret-sharing\"\nversion = \"0.2.3-pre\"\nauthors = [\n  \"Morten Dahl <morten.dahl@snips.ai>\",\n  "
  },
  {
    "path": "LICENSE",
    "chars": 495,
    "preview": "## License\n\nLicensed under either of\n * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apac"
  },
  {
    "path": "LICENSE-APACHE",
    "chars": 10847,
    "preview": "                              Apache License\n                        Version 2.0, January 2004\n                     http"
  },
  {
    "path": "LICENSE-MIT",
    "chars": 1023,
    "preview": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentati"
  },
  {
    "path": "README.md",
    "chars": 6990,
    "preview": "# Threshold Secret Sharing\n\n[![Build Status](https://travis-ci.org/snipsco/rust-threshold-secret-sharing.svg?branch=mast"
  },
  {
    "path": "benches/packed.rs",
    "chars": 2755,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "examples/homomorphic.rs",
    "chars": 5045,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "examples/shamir.rs",
    "chars": 1094,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/fields/fft.rs",
    "chars": 7906,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/fields/mod.rs",
    "chars": 5102,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/fields/montgomery.rs",
    "chars": 3438,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/fields/native.rs",
    "chars": 1822,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/lib.rs",
    "chars": 868,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/numtheory.rs",
    "chars": 11323,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/packed.rs",
    "chars": 19470,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  },
  {
    "path": "src/shamir.rs",
    "chars": 5247,
    "preview": "// Copyright (c) 2016 rust-threshold-secret-sharing developers\n//\n// Licensed under the Apache License, Version 2.0\n// <"
  }
]

About this extraction

This page contains the full source code of the snipsco/rust-threshold-secret-sharing GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 18 files (82.4 KB), approximately 23.3k tokens, and a symbol index with 129 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!