Skip to content
Snippets Groups Projects
Commit 4a8b2d84 authored by Pratyush Mishra's avatar Pratyush Mishra
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
target
Cargo.lock
.DS_Store
.idea
*.iml
*.ipynb_checkpoints
*.pyc
*.sage.py
params
[package]
name = "poly-commit"
version = "0.1.0"
authors = [
"Alessandro Chiesa <alexch@berkeley.edu>",
"Mary Maller <mary.maller.15@ucl.ac.uk>",
"Yuncong Hu <huyuncongh@gmail.com>",
"Pratyush Mishra <pratyush@berkeley.edu>",
"Noah Vesely <noah.vesely.18@ucl.ac.uk>",
"Nicholas Ward <npward@berkeley.edu>",
]
description = "A library for constructing polynomial commitment schemes for use in zkSNARKs"
homepage = "https://libzexe.org"
repository = "https://github.com/scipr/poly-commit"
documentation = "https://docs.rs/poly-commit/"
keywords = ["cryptography", "polynomial commitments", "elliptic curves", "pairing"]
categories = ["cryptography"]
include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
license = "MIT/Apache-2.0"
edition = "2018"
[dependencies]
algebra = { git = "https://github.com/scipr-lab/zexe/", features = [ "parallel" ] }
ff-fft = { git = "https://github.com/scipr-lab/zexe/" }
bench-utils = { git = "https://github.com/scipr-lab/zexe/" }
rand = { version = "0.4" }
rayon = { version = "1" }
derivative = { version = "1" }
[features]
timer = [ "bench-utils/timer" ]
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.
The MIT 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.
<h1 align="center">`poly-commit`</h1>
<p align="center">
<a href="https://travis-ci.org/scipr-lab/poly-commit"><img src="https://travis-ci.org/scipr-lab/poly-commit.svg?branch=master"></a>
<a href="https://github.com/scipr-lab/poly-commit/blob/master/AUTHORS"><img src="https://img.shields.io/badge/authors-SCIPR%20Lab-orange.svg"></a>
<a href="https://github.com/scipr-lab/poly-commit/blob/master/LICENSE-APACHE"><img src="https://img.shields.io/badge/license-APACHE-blue.svg"></a>
<a href="https://github.com/scipr-lab/poly-commit/blob/master/LICENSE-MIT"><img src="https://img.shields.io/badge/license-MIT-blue.svg"></a>
</p>
`poly-commit` is a Rust library that implements *polynomial commitment schemes*, a cryptographic primitive that enables parties to "commit" to polynomials and then provide proofs of correct evaluation for these commitments.
This library was initially developed as part of the paper *"[<span style="font-variant:small-caps;">Marlin</span>: Preprocessing zkSNARKs with Universal and Updatable SRS][marlin]"*, and it is released under the MIT License and the Apache v2 License (see [License](#license)).
**WARNING:** This is an academic proof-of-concept prototype, and in particular has not received careful code review. This implementation is NOT ready for production use.
## Overview
This library provides traits for *polynomial commitment schemes*, as well as constructions of these based on the paper *"[Polynomial Commitments][kzg10]"*. Polynomial commitment (PC) schemes allow a user to first commit to polynomials, and to then provide proofs of correct evaluation for the committed polynomials. PC schemes satisfy the following properties:
- **Hiding** - commitments and proofs should reveal no information about the committed polynomial.
- **Succinctness** - commitment and proof size should scale sublinearly with the degree of the committed polynomial. Optionally, verification time should also scale sublinearly.
- **Extractability** - there should exist an extractor *E*, which when given a commitment and a valid evaluation proof, should be able to extract a polynomial that agrees with the evaluation.
[kzg10]: http://cacr.uwaterloo.ca/techreports/2010/cacr2010-10.pdf
## Build guide
The library compiles on the `stable` toolchain of the Rust compiler. To install the latest version of Rust, first install `rustup` by following the instructions [here](https://rustup.rs/), or via your platform's package manager. Once `rustup` is installed, install the Rust toolchain by invoking:
```bash
rustup install stable
```
After that, use `cargo`, the standard Rust build tool, to build the library:
```bash
git clone https://github.com/scipr-lab/poly-commit.git
cd poly-commit
cargo build --release
```
This library comes with some unit and integration tests. Run these tests with:
```bash
cargo test
```
Lastly, this library is instrumented with profiling infrastructure that prints detailed
profiles of execution time; to enables this, compile with `cargo build --features timer`.
## License
`poly-commit` is licensed under either of the following licenses, at your discretion.
* 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)
Unless you explicitly state otherwise, any contribution submitted for inclusion in `poly-commit` by you shall be dual licensed as above (as defined in the Apache v2 License), without any additional terms or conditions.
[marlin]: https://ia.cr/2019/xxx
## Reference paper
[_<span style="font-variant:small-caps;">Marlin</span>: Preprocessing zkSNARKs with Universal and Updatable SRS_][marlin]
Alessandro Chiesa, Yuncong Hu, Mary Maller, [Pratyush Mishra](https://www.github.com/pratyush), Noah Vesely, [Nicholas Ward](https://www.github.com/npwardberkeley)
*IACR ePrint Report 2019/XXX*
## Acknowledgements
This work was supported by:
an Engineering and Physical Sciences Research Council grant (EP/N028104/1),
a Google Faculty Award,
the RISELab at UC Berkeley,
and
donations from the Ethereum Foundation and the Interchain Foundation.
//! A crate for polynomial commitment schemes.
#![deny(unused_import_braces, unused_qualifications, trivial_casts)]
#![deny(trivial_numeric_casts, private_in_public, variant_size_differences)]
#![deny(stable_features, unreachable_pub, non_shorthand_field_patterns)]
#![deny(unused_attributes, unused_imports, unused_mut, missing_docs)]
#![deny(renamed_and_removed_lints, stable_features, unused_allocation)]
#![deny(unused_comparisons, bare_trait_objects, unused_must_use, const_err)]
#![forbid(unsafe_code)]
#[macro_use]
extern crate algebra;
#[macro_use]
extern crate derivative;
#[macro_use]
extern crate bench_utils;
use rand::Rng;
use algebra::Field;
use std::borrow::Cow;
pub use ff_fft::DensePolynomial as Polynomial;
/// Defines `SinglePolynomialCommitment` schemes that allow one to commit to
/// a single polynomial, and then provide an evaluation proof for that polynomial
/// at a single point.
pub mod single_pc;
/// Defines `MultiPolynomialCommitment` schemes that allow one to commit to
/// multiple polynomials, and then provide evaluation proofs for these polynomials
/// at many points.
pub mod multi_pc;
pub use multi_pc::MultiPolynomialCommitment;
pub use single_pc::SinglePolynomialCommitment;
/// Defines the minimal interface of committer keys for any polynomial
/// commitment scheme.
pub trait PCCommitterKey: Clone {
/// Outputs the maximum degree supported by the committer key.
fn max_degree(&self) -> usize;
}
/// Defines the minimal interface of verifier keys for any polynomial
/// commitment scheme.
pub trait PCVerifierKey: Clone {
/// Outputs the maximum degree supported by the verifier key.
fn max_degree(&self) -> usize;
}
/// Defines the minimal interface of commitments for any polynomial
/// commitment scheme.
pub trait PCCommitment: Clone + algebra::ToBytes {
/// Outputs a non-hiding commitment to the zero polynomial.
fn empty() -> Self;
/// Does this commitment have a degree bound?
fn has_degree_bound(&self) -> bool;
/// Size in bytes
fn size_in_bytes(&self) -> usize;
}
/// Defines the minimal interface of commitment randomness for any polynomial
/// commitment scheme.
pub trait PCRandomness: Clone {
/// Outputs empty randomness that does not hide the commitment.
fn empty() -> Self;
/// Outputs empty randomness that does not hide the commitment, with no degree bound.
fn empty_no_degree_bound() -> Self;
/// Samples randomness for commitments;
/// `num_queries` specifies the number of queries that the commitment will be opened at.
fn rand<R: Rng>(num_queries: usize, rng: &mut R) -> Self;
}
/// A polynomial along with other information necessary for the HIOP protocol
/// and for the polynomial commitment scheme.
#[derive(Clone)]
pub struct LabeledPolynomial<'a, F: Field> {
polynomial: Cow<'a, Polynomial<F>>,
degree_bound: Option<usize>,
hiding_bound: Option<usize>,
}
impl<'a, F: Field> std::ops::Deref for LabeledPolynomial<'a, F> {
type Target = Polynomial<F>;
fn deref(&self) -> &Self::Target {
&self.polynomial
}
}
impl<'a, F: Field> LabeledPolynomial<'a, F> {
/// Instantiate a new polynomial_context.
pub fn new_owned(polynomial: Polynomial<F>, degree_bound: Option<usize>, hiding_bound: Option<usize>) -> Self {
Self {
polynomial: Cow::Owned(polynomial),
degree_bound,
hiding_bound,
}
}
/// Instantiate a new polynomial_context.
pub fn new(polynomial: &'a Polynomial<F>, degree_bound: Option<usize>, hiding_bound: Option<usize>) -> Self {
Self {
polynomial: Cow::Borrowed(polynomial),
degree_bound,
hiding_bound,
}
}
/// Retrieve the polynomial from `self`.
pub fn polynomial(&self) -> &Polynomial<F> {
&self.polynomial
}
/// Evaluate the polynomial in `self`.
pub fn evaluate(&self, point: F) -> F {
self.polynomial.evaluate(point)
}
/// Retrieve the degree bound in `self`.
pub fn degree_bound(&self) -> Option<usize> {
self.degree_bound
}
/// Retrieve whether the polynomial in `self` should be hidden.
pub fn is_hiding(&self) -> bool {
self.hiding_bound.is_some()
}
/// Retrieve the hiding bound for the polynomial in `self`.
pub fn hiding_bound(&self) -> Option<usize> {
self.hiding_bound
}
}
use algebra::Field;
use rand::Rng;
use std::borrow::Borrow;
use std::collections::{BTreeMap, BTreeSet};
use crate::*;
/// `QuerySet` is the set of queries that are to be made to a list of polynomials
/// `p` that have previously been committed. Each element of a `QuerySet` is a `(index, query)`
/// pair, where `index` is the index into `p`, and `query` is the field element
/// that `p[index]` is to be queried at.
pub type QuerySet<F> = BTreeSet<(usize, F)>;
/// `Evaluations` is the result of querying a list of polynomials `p` at a `QuerySet`
/// `Q`. It maps each element of `Q` to the resulting evaluation. That is,
/// if `(index, query)` is an element of `Q`, then `evaluation.get((index, query))`
/// should equal `p[index].evaluate(query)`.
pub type Evaluations<F> = BTreeMap<(usize, F), F>;
/// Describes the interface for a polynomial commitment scheme that allows
/// a sender to commit to multiple polynomials and later provide a succinct proof
/// of evaluation for the corresponding commitments at a query set `Q`, while
/// enforcing per-polynomial degree bounds.
pub trait MultiPolynomialCommitment<F: Field> {
/// The committer key for the scheme; used to commit to a polynomial and then
/// open the commitment to produce an evaluation proof.
type CommitterKey: PCCommitterKey;
/// The verifier key for the scheme; used to check an evaluation proof.
type VerifierKey: PCVerifierKey;
/// The commitment to a polynomial.
type Commitment: PCCommitment;
/// The commitment randomness.
type Randomness: PCRandomness;
/// The evaluation proof.
type Proof: Clone;
/// The error type for the scheme.
type Error: std::error::Error;
/// Constructs public parameters when given as input the maximum degree `degree`
/// for the polynomial commitment scheme.
fn setup<R: Rng>(degree: usize, rng: &mut R) -> Result<(Self::CommitterKey, Self::VerifierKey), Self::Error>;
/// Outputs a commitments to `polynomials`. If `hiding_bounds[i].is_some()`,
/// then the `i`-th commitment is hiding up to `hiding_bounds[i]` number of queries.
/// `rng` should not be `None` if `hiding_bounds[i].is_some()`
/// is true.
///
/// If `hiding_bounds[i].is_none()`, then the `i`-th randomness is
/// `Self::Randomness::empty()`.
// TODO: technically each iterator below can have different lifetimes, but
// that becomes quite noisy. Also, lifetime elision in argument position
// should fix this (https://github.com/rust-lang/rust/issues/49287)
fn commit<'a>(
ck: &Self::CommitterKey,
polynomials: impl IntoIterator<Item = &'a Polynomial<F>>,
degree_bounds: impl IntoIterator<Item = &'a Option<usize>>,
hiding_bounds: impl IntoIterator<Item = &'a Option<usize>>,
rng: Option<&mut dyn Rng>,
) -> Result<(Vec<Self::Commitment>, Vec<Self::Randomness>), Self::Error>;
/// On input a list of polynomials and a query set, `open` outputs a proof of evaluation
/// of the polynomials at the points in the query set.
fn open(
ck: &Self::CommitterKey,
polynomials: &[impl Borrow<Polynomial<F>>],
degree_bounds: &[Option<usize>],
query_set: &QuerySet<F>,
opening_challenge: F,
r: &[impl Borrow<Self::Randomness>],
) -> Result<Self::Proof, Self::Error>;
/// Checks that `values` are the true evaluations at `query_set` of the polynomials
/// committed in `comm`.
fn check<R: Rng>(
vk: &Self::VerifierKey,
comm: &[Self::Commitment],
degree_bounds: &[Option<usize>],
query_set: &QuerySet<F>,
values: &Evaluations<F>,
proof: &Self::Proof,
opening_challenge: F,
rng: &mut R,
) -> Result<bool, Self::Error>;
/// Commit to labeled polynomials.
fn commit_labeled<'a>(
ck: &Self::CommitterKey,
labeled_polynomials: impl Iterator<Item = &'a LabeledPolynomial<'a, F>>,
rng: Option<&mut dyn Rng>,
) -> Result<(Vec<Self::Commitment>, Vec<Self::Randomness>), Self::Error> {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
let mut hiding_bounds = Vec::new();
for labeled_poly in labeled_polynomials {
polynomials.push(labeled_poly.polynomial());
degree_bounds.push(labeled_poly.degree_bound());
hiding_bounds.push(labeled_poly.hiding_bound());
}
Self::commit(
ck,
polynomials,
&degree_bounds,
&hiding_bounds,
rng,
)
}
/// Open labeled polynomials.
fn open_labeled<'a>(
ck: &Self::CommitterKey,
labeled_polynomials: impl Iterator<Item = &'a LabeledPolynomial<'a, F>>,
query_set: &QuerySet<F>,
opening_challenge: F,
rands: &[Self::Randomness],
) -> Result<Self::Proof, Self::Error> {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
let mut hiding_bounds = Vec::new();
for labeled_poly in labeled_polynomials {
polynomials.push(labeled_poly.polynomial());
degree_bounds.push(labeled_poly.degree_bound());
hiding_bounds.push(labeled_poly.hiding_bound());
}
Self::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)
}
}
/// Generic construction of a `MultiPolynomialCommitment` scheme from a
/// `SinglePolynomialCommitment` scheme whenever the commitment and randomness of the
/// `SinglePolynomialCommitment` scheme are additively homomorphic.
/// Specifically, we require `C = MultiPolynomialCommitment::Commitment`
/// to satisfy `for<'a> C: AddAssign<(F, &'a C)>.
///
/// The construction follows the blueprint laid out in [CHMMVW19](insert eprint link).
pub mod mpc_from_spc;
#[cfg(test)]
pub mod tests {
use crate::multi_pc::*;
use algebra::Field;
use rand::{distributions::Sample, thread_rng, Rand};
pub fn single_poly_test<F, MultiPC>() -> Result<(), MultiPC::Error>
where
F: Field,
MultiPC: MultiPolynomialCommitment<F>,
{
let rng = &mut thread_rng();
let max_degree = rand::distributions::Range::new(1, 64).sample(rng);;
let (ck, vk) = MultiPC::setup(max_degree, rng)?;
for _ in 0..100 {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
// Generate polynomials
for _ in 0..1 {
let degree = max_degree;
polynomials.push(Polynomial::rand(degree, rng));
degree_bounds.push(None);
}
let num_points_in_query_set = 1;
let hiding_bounds = vec![Some(num_points_in_query_set); 1];
let (comms, rands) = MultiPC::commit(
&ck,
&polynomials,
&degree_bounds,
&hiding_bounds,
Some(rng),
)?;
// Construct query set
let mut query_set = QuerySet::new();
let mut values = Evaluations::new();
for _ in 0..num_points_in_query_set {
let point = F::rand(rng);
for i in 0..1 {
query_set.insert((i, point));
let value = polynomials[i].evaluate(point);
values.insert((i, point), value);
}
}
let opening_challenge = F::rand(rng);
let proof = MultiPC::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)?;
assert!(
MultiPC::check(
&vk,
&comms,
&degree_bounds,
&query_set,
&values,
&proof,
opening_challenge,
rng
)?,
"proof was incorrect"
);
}
Ok(())
}
pub fn single_poly_degree_bound_test<F, MultiPC>() -> Result<(), MultiPC::Error>
where
F: Field,
MultiPC: MultiPolynomialCommitment<F>,
{
let rng = &mut thread_rng();
let max_degree = rand::distributions::Range::new(1, 64).sample(rng);;
let (ck, vk) = MultiPC::setup(max_degree, rng)?;
for _ in 0..100 {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
// Generate polynomials
for _ in 0..1 {
let degree = rand::distributions::Range::new(1, max_degree).sample(rng);
polynomials.push(Polynomial::rand(degree, rng));
let mut range = rand::distributions::Range::new(degree, max_degree);
let degree_bound = Some(range.sample(rng));
degree_bounds.push(degree_bound);
}
let num_points_in_query_set = 1;
let hiding_bounds = vec![Some(num_points_in_query_set); 1];
let (comms, rands) = MultiPC::commit(
&ck,
&polynomials,
&degree_bounds,
&hiding_bounds,
Some(rng),
)?;
println!("Committed");
// Construct query set
let mut query_set = QuerySet::new();
let mut values = Evaluations::new();
for _ in 0..num_points_in_query_set {
let point = F::rand(rng);
for i in 0..1 {
query_set.insert((i, point));
let value = polynomials[i].evaluate(point);
values.insert((i, point), value);
}
}
println!("Generated query set");
let opening_challenge = F::rand(rng);
let proof = MultiPC::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)?;
println!("Opened");
assert!(
MultiPC::check(
&vk,
&comms,
&degree_bounds,
&query_set,
&values,
&proof,
opening_challenge,
rng
)?,
"proof was incorrect"
);
}
Ok(())
}
pub fn single_poly_degree_bound_multiple_queries_test<F, MultiPC>() -> Result<(), MultiPC::Error>
where
F: Field,
MultiPC: MultiPolynomialCommitment<F>,
{
let rng = &mut thread_rng();
let max_degree = rand::distributions::Range::new(1, 64).sample(rng);;
let (ck, vk) = MultiPC::setup(max_degree, rng)?;
for _ in 0..100 {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
// Generate polynomials
for _ in 0..1 {
let degree = rand::distributions::Range::new(1, max_degree).sample(rng);
polynomials.push(Polynomial::rand(degree, rng));
let mut range = rand::distributions::Range::new(degree, max_degree);
let degree_bound = Some(range.sample(rng));
degree_bounds.push(degree_bound);
}
let num_points_in_query_set = 2;
let hiding_bounds = vec![Some(num_points_in_query_set); 1];
let (comms, rands) = MultiPC::commit(
&ck,
&polynomials,
&degree_bounds,
&hiding_bounds,
Some(rng),
)?;
// Construct query set
let mut query_set = QuerySet::new();
let mut values = Evaluations::new();
for _ in 0..num_points_in_query_set {
let point = F::rand(rng);
for i in 0..1 {
query_set.insert((i, point));
let value = polynomials[i].evaluate(point);
values.insert((i, point), value);
}
}
let opening_challenge = F::rand(rng);
let proof = MultiPC::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)?;
assert!(
MultiPC::check(
&vk,
&comms,
&degree_bounds,
&query_set,
&values,
&proof,
opening_challenge,
rng
)?,
"proof was incorrect"
);
}
Ok(())
}
pub fn two_polys_degree_bound_single_query_test<F, MultiPC>() -> Result<(), MultiPC::Error>
where
F: Field,
MultiPC: MultiPolynomialCommitment<F>,
{
let rng = &mut thread_rng();
let max_degree = 10;
let (ck, vk) = MultiPC::setup(max_degree, rng)?;
for _ in 0..100 {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
// Generate polynomials
for _ in 0..2 {
let degree = rand::distributions::Range::new(1, max_degree).sample(rng);
polynomials.push(Polynomial::rand(degree, rng));
let mut range = rand::distributions::Range::new(degree, max_degree);
let degree_bound = Some(range.sample(rng));
degree_bounds.push(degree_bound);
}
let num_points_in_query_set = 1;
let hiding_bounds = vec![Some(num_points_in_query_set); 2];
let (comms, rands) = MultiPC::commit(
&ck,
&polynomials,
&degree_bounds,
&hiding_bounds,
Some(rng),
)?;
// Construct query set
let mut query_set = QuerySet::new();
let mut values = Evaluations::new();
for _ in 0..num_points_in_query_set {
let point = F::rand(rng);
for i in 0..2 {
query_set.insert((i, point));
let value = polynomials[i].evaluate(point);
values.insert((i, point), value);
}
}
let opening_challenge = F::rand(rng);
let proof = MultiPC::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)?;
assert!(
MultiPC::check(
&vk,
&comms,
&degree_bounds,
&query_set,
&values,
&proof,
opening_challenge,
rng
)?,
"proof was incorrect"
);
}
Ok(())
}
pub fn full_end_to_end_test<F, MultiPC>() -> Result<(), MultiPC::Error>
where
F: Field,
MultiPC: MultiPolynomialCommitment<F>,
{
let rng = &mut thread_rng();
let max_degree = rand::distributions::Range::new(2, 64).sample(rng);;
let (ck, vk) = MultiPC::setup(max_degree, rng)?;
for _ in 0..10 {
let mut polynomials = Vec::new();
let mut degree_bounds = Vec::new();
// Generate polynomials
for _ in 0..10 {
let degree = rand::distributions::Range::new(1, max_degree).sample(rng);
polynomials.push(Polynomial::rand(degree, rng));
let mut range = rand::distributions::Range::new(degree, max_degree);
let degree_bound = Some(range.sample(rng));
degree_bounds.push(degree_bound);
}
let num_points_in_query_set = rand::distributions::Range::new(1, 5).sample(rng);
let hiding_bounds = vec![Some(num_points_in_query_set); 10];
let (comms, rands) = MultiPC::commit(
&ck,
&polynomials,
&degree_bounds,
&hiding_bounds,
Some(rng),
)?;
// Construct query set
let mut query_set = QuerySet::new();
let mut values = Evaluations::new();
for _ in 0..num_points_in_query_set {
let point = F::rand(rng);
for i in 0..10 {
let should_be_queried = bool::rand(rng);
if should_be_queried {
query_set.insert((i, point));
let value = polynomials[i].evaluate(point);
values.insert((i, point), value);
}
}
}
let opening_challenge = F::rand(rng);
let proof = MultiPC::open(
&ck,
&polynomials,
&degree_bounds,
&query_set,
opening_challenge,
&rands,
)?;
let result = MultiPC::check(
&vk,
&comms,
&degree_bounds,
&query_set,
&values,
&proof,
opening_challenge,
rng
)?;
if !result {
println!("Failed with 10 polynomials, num_points_in_query_set: {:?}", num_points_in_query_set);
}
assert!(result, "proof was incorrect");
}
Ok(())
}
}
This diff is collapsed.
This diff is collapsed.
use crate::*;
use algebra::Field;
use rand::Rng;
/// Describes the interface for a polynomial commitment scheme that allows
/// a sender to commit to a single polynomial and later provide a succinct proof
/// of evaluation for that commitment.
/// ```compile_fail
///
/// let rng = &mut thread_rng();
/// // Generate committer and verifier keys for a maximum polynomial degree
/// // of 10.
/// let degree = 10;
/// let (ck, vk) = SinglePC::setup(degree, rng);
///
/// // Generate a random degree-10 polynomial.
/// let p = Polynomial::rand(degree, rng);;
/// let hiding_bound = Some(1);
///
/// // Commit to this polynomial
/// let (comm, rand) = SinglePC::commit(&ck, &p, hiding_bound, rng)?;
///
/// // Evaluate the polynomial at a random point, and generate an evaluation
/// // proof.
/// let point = F::rand(rng);
/// let value = p.evaluate(point);
/// let proof = SinglePC::open(&ck, &p, point, &rand)?;
///
/// // Verify the evaluation proof.
/// assert!(SinglePC::check(&vk, &comm, point, value, &proof)?, "proof was incorrect");
/// ```
pub trait SinglePolynomialCommitment<F: Field> {
/// The committer key for the scheme; used to commit to a polynomial and then
/// open the commitment to produce an evaluation proof.
type CommitterKey: PCCommitterKey;
/// The verifier key for the scheme; used to check an evaluation proof.
type VerifierKey: PCVerifierKey;
/// The commitment to a polynomial.
type Commitment: PCCommitment;
/// The commitment randomness.
type Randomness: PCRandomness;
/// The evaluation proof.
type Proof: Clone;
/// The error type for the scheme.
type Error: std::error::Error;
/// Constructs public parameters when given as input the maximum degree `degree`
/// for the polynomial commitment scheme.
fn setup<R: Rng>(degree: usize, rng: &mut R) -> Result<(Self::CommitterKey, Self::VerifierKey), Self::Error>;
/// Outputs a commitment to `polynomial`. If `hiding_bound.is_some()`, then the
/// resulting commitment is hiding up to `hiding_bound.unwrap()` number of queries.
/// `rng` should not be `None` if `hiding_bound.is_some()`.
/// If `hiding_bound.is_none()`, then the randomness is `Self::Randomness::empty()`.
fn commit(
ck: &Self::CommitterKey,
polynomial: &Polynomial<F>,
hiding_bound: Option<usize>,
rng: Option<&mut dyn Rng>,
) -> Result<(Self::Commitment, Self::Randomness), Self::Error>;
/// On input a polynomial `p` and a point `point` in the field `F`,
/// `open` outputs an evaluation proof for `p` at `point`.
fn open(
ck: &Self::CommitterKey,
p: &Polynomial<F>,
point: F,
r: &Self::Randomness,
) -> Result<Self::Proof, Self::Error>;
/// Verifies that `value` is the evaluation at `point` of the polynomial
/// committed inside `comm`.
fn check(
vk: &Self::VerifierKey,
comm: &Self::Commitment,
point: F,
value: F,
proof: &Self::Proof,
) -> Result<bool, Self::Error>;
/// Check a batch of proofs
fn batch_check<R: Rng>(
vk: &Self::VerifierKey,
commitments: &[Self::Commitment],
points: &[F],
values: &[F],
proofs: &[Self::Proof],
rng: &mut R,
) -> Result<bool, Self::Error>;
/// Commit to a labeled polynomial.
fn commit_labeled(
ck: &Self::CommitterKey,
labeled_polynomial: &LabeledPolynomial<F>,
rng: Option<&mut dyn Rng>,
) -> Result<(Self::Commitment, Self::Randomness), Self::Error> {
Self::commit(
ck,
labeled_polynomial.polynomial(),
labeled_polynomial.hiding_bound(),
rng,
)
}
/// Open a labeled polynomial.
fn open_labeled<'a>(
ck: &Self::CommitterKey,
labeled_polynomial: &LabeledPolynomial<F>,
point: F,
rand: &Self::Randomness,
) -> Result<Self::Proof, Self::Error> {
Self::open(
&ck,
labeled_polynomial.polynomial(),
point,
&rand,
)
}
}
/// Implements the [KZG10](kzg10) construction that satisfies the `SinglePolynomialCommitment`
/// trait.
///
/// [kzg10]: http://cacr.uwaterloo.ca/techreports/2010/cacr2010-10.pdf
pub mod kzg10;
#[cfg(test)]
pub mod tests {
use crate::*;
use algebra::Field;
use rand::{thread_rng, Rand};
pub fn end_to_end_test<F, SinglePC>() -> Result<(), SinglePC::Error>
where
F: Field,
SinglePC: SinglePolynomialCommitment<F>,
{
let rng = &mut thread_rng();
for _ in 0..100 {
let mut degree = 0;
while degree <= 1 {
degree = usize::rand(rng) % 20;
}
let (ck, vk) = SinglePC::setup(degree, rng)?;
let p = Polynomial::rand(degree, rng);;
let hiding_bound = Some(1);
let (comm, rand) = SinglePC::commit(&ck, &p, hiding_bound, Some(rng))?;
let point = F::rand(rng);
let value = p.evaluate(point);
let proof = SinglePC::open(&ck, &p, point, &rand)?;
assert!(
SinglePC::check(&vk, &comm, point, value, &proof)?,
"proof was incorrect for max_degree = {}, polynomial_degree = {}, hiding_bound = {:?}",
degree,
p.degree(),
hiding_bound,
);
}
Ok(())
}
pub fn batch_check_test<F, SinglePC>() -> Result<(), SinglePC::Error>
where
F: Field,
SinglePC: SinglePolynomialCommitment<F>,
{
let rng = &mut thread_rng();
for _ in 0..10 {
let mut degree = 0;
while degree <= 1 {
degree = usize::rand(rng) % 20;
}
let (ck, vk) = SinglePC::setup(degree, rng)?;
let mut comms = Vec::new();
let mut values = Vec::new();
let mut points = Vec::new();
let mut proofs = Vec::new();
for _ in 0..10 {
let p = Polynomial::rand(degree, rng);;
let hiding_bound = Some(1);
let (comm, rand) = SinglePC::commit(&ck, &p, hiding_bound, Some(rng))?;
let point = F::rand(rng);
let value = p.evaluate(point);
let proof = SinglePC::open(&ck, &p, point, &rand)?;
assert!(SinglePC::check(&vk, &comm, point, value, &proof)?);
comms.push(comm);
values.push(value);
points.push(point);
proofs.push(proof);
}
assert!(SinglePC::batch_check(&vk, &comms, &points, &values, &proofs, rng)?);
}
Ok(())
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment