forked from arkworks-rs/poly-commit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structures.rs
418 lines (354 loc) · 11.8 KB
/
data_structures.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::{Rc, String, Vec};
pub use algebra::DensePolynomial as Polynomial;
use algebra::{
serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError},
Field, SemanticallyValid, ToBytes,
};
use rand_core::RngCore;
use std::{
borrow::Borrow,
fmt::Debug,
io::{Error as IoError, ErrorKind, Read, Result as IoResult, Write},
ops::{AddAssign, MulAssign, SubAssign},
};
/// Labels a `LabeledPolynomial` or a `LabeledCommitment`.
pub type PolynomialLabel = String;
/// Defines the minimal interface for public params for any polynomial
/// commitment scheme.
pub trait PCUniversalParams:
Clone + Debug + CanonicalSerialize + CanonicalDeserialize + Eq + PartialEq
{
/// Outputs the maximum degree supported by the committer key.
fn max_degree(&self) -> usize;
/// Returns the hash of `self` instance.
fn get_hash(&self) -> &[u8];
/// Copy other instance params into this. Used for testing purposes.
fn copy_params(&mut self, other: &Self);
}
/// Defines the minimal interface of committer keys for any polynomial
/// commitment scheme.
pub trait PCCommitterKey:
Clone + Debug + Eq + PartialEq + CanonicalSerialize + CanonicalDeserialize + SemanticallyValid
{
/// Outputs the maximum degree supported by the universal parameters
/// `Self` was derived from.
fn max_degree(&self) -> usize;
/// Outputs the maximum degree supported by the committer key.
fn supported_degree(&self) -> usize;
/// Returns the hash of `self` instance.
fn get_hash(&self) -> &[u8];
/// Randomize key for testing purpose
fn randomize(&mut self);
}
/// Defines the minimal interface of verifier keys for any polynomial
/// commitment scheme.
pub trait PCVerifierKey:
Clone + Debug + Eq + PartialEq + CanonicalSerialize + CanonicalDeserialize + SemanticallyValid
{
/// Outputs the maximum degree supported by the universal parameters
/// `Self` was derived from.
fn max_degree(&self) -> usize;
/// Outputs the maximum degree supported by the verifier key.
fn supported_degree(&self) -> usize;
/// Returns the hash of `self` instance.
fn get_hash(&self) -> &[u8];
/// Randomize key for testing purpose
fn randomize(&mut self);
}
/// Defines the minimal interface of prepared verifier keys for any polynomial
/// commitment scheme.
pub trait PCPreparedVerifierKey<Unprepared: PCVerifierKey> {
/// prepare
fn prepare(vk: &Unprepared) -> Self;
}
/// Defines the minimal interface of commitments for any polynomial
/// commitment scheme.
pub trait PCCommitment:
Clone + CanonicalSerialize + CanonicalDeserialize + ToBytes + SemanticallyValid
{
/// 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;
/// Randomize commiment values for testing purpose
fn randomize(&mut self);
}
/// Defines the minimal interface of prepared commitments for any polynomial
/// commitment scheme.
pub trait PCPreparedCommitment<UNPREPARED: PCCommitment>: Clone {
/// prepare
fn prepare(comm: &UNPREPARED) -> Self;
}
/// Defines the minimal interface of commitment randomness for any polynomial
/// commitment scheme.
pub trait PCRandomness:
Clone + Debug + Eq + PartialEq + CanonicalSerialize + CanonicalDeserialize
{
/// Outputs empty randomness that does not hide the commitment.
fn empty(segments_count: usize) -> Self;
/// Samples randomness for commitments;
/// `num_queries` specifies the number of queries that the commitment will be opened at.
/// `has_degree_bound` indicates that the corresponding commitment has an enforced
/// strict degree bound.
fn rand<R: RngCore>(num_queries: usize, has_degree_bound: bool, rng: &mut R) -> Self;
}
/// A polynomial along with information about its degree bound (if any), and the
/// maximum number of queries that will be made to it. This latter number determines
/// the amount of protection that will be provided to a commitment for this polynomial.
#[derive(Debug, Clone, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)]
pub struct LabeledPolynomial<F: Field> {
label: PolynomialLabel,
polynomial: Rc<Polynomial<F>>,
degree_bound: Option<usize>,
hiding_bound: Option<usize>,
}
impl<'a, F: Field> std::ops::Deref for LabeledPolynomial<F> {
type Target = Polynomial<F>;
fn deref(&self) -> &Self::Target {
&self.polynomial
}
}
impl<'a, F: Field> LabeledPolynomial<F> {
/// Construct a new labeled polynomial.
pub fn new(
label: PolynomialLabel,
polynomial: Polynomial<F>,
degree_bound: Option<usize>,
hiding_bound: Option<usize>,
) -> Self {
Self {
label,
polynomial: Rc::new(polynomial),
degree_bound,
hiding_bound,
}
}
/// Return the label for `self`.
pub fn label(&self) -> &String {
&self.label
}
/// 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
}
}
/// A commitment along with information about its degree bound (if any).
#[derive(Clone)]
pub struct LabeledCommitment<C: PCCommitment> {
label: PolynomialLabel,
commitment: C,
degree_bound: Option<usize>,
}
impl<C: PCCommitment> LabeledCommitment<C> {
/// Instantiate a new commitment_context.
pub fn new(label: PolynomialLabel, commitment: C, degree_bound: Option<usize>) -> Self {
Self {
label,
commitment,
degree_bound,
}
}
/// Return the label for `self`.
pub fn label(&self) -> &String {
&self.label
}
/// Retrieve the commitment from `self`.
pub fn commitment(&self) -> &C {
&self.commitment
}
/// Retrieve the degree bound in `self`.
pub fn degree_bound(&self) -> Option<usize> {
self.degree_bound
}
/// Randomize commitment for test purpose
pub fn randomize(&mut self) {
self.commitment.randomize();
}
}
impl<C: PCCommitment> SemanticallyValid for LabeledCommitment<C> {
fn is_valid(&self) -> bool {
self.commitment.is_valid()
}
}
impl<C: PCCommitment> ToBytes for LabeledCommitment<C> {
#[inline]
fn write<W: Write>(&self, writer: W) -> IoResult<()> {
self.commitment
.serialize_without_metadata(writer)
.map_err(|e| IoError::new(ErrorKind::Other, format! {"{:?}", e}))
}
}
/// A labeled randomness.
#[derive(Clone, Debug, Eq, PartialEq, CanonicalSerialize, CanonicalDeserialize)]
pub struct LabeledRandomness<Rand: PCRandomness> {
label: PolynomialLabel,
randomness: Rand,
}
impl<Rand: PCRandomness> LabeledRandomness<Rand> {
/// Instantiate a new randomness_context.
pub fn new(label: PolynomialLabel, randomness: Rand) -> Self {
Self { label, randomness }
}
/// Return the label for `self`.
pub fn label(&self) -> &String {
&self.label
}
/// Retrieve the commitment from `self`.
pub fn randomness(&self) -> &Rand {
&self.randomness
}
}
/// A term in a linear combination.
#[derive(Hash, Ord, PartialOrd, Clone, Eq, PartialEq, Debug)]
pub enum LCTerm {
/// The constant term representing `one`.
One,
/// Label for a polynomial.
PolyLabel(String),
}
impl LCTerm {
/// Returns `true` if `self == LCTerm::One`
#[inline]
pub fn is_one(&self) -> bool {
if let LCTerm::One = self {
true
} else {
false
}
}
}
impl From<PolynomialLabel> for LCTerm {
fn from(other: PolynomialLabel) -> Self {
Self::PolyLabel(other)
}
}
impl<'a> From<&'a str> for LCTerm {
fn from(other: &str) -> Self {
Self::PolyLabel(other.into())
}
}
impl std::convert::TryInto<PolynomialLabel> for LCTerm {
type Error = ();
fn try_into(self) -> Result<PolynomialLabel, ()> {
match self {
Self::One => Err(()),
Self::PolyLabel(l) => Ok(l),
}
}
}
impl<'a> std::convert::TryInto<&'a PolynomialLabel> for &'a LCTerm {
type Error = ();
fn try_into(self) -> Result<&'a PolynomialLabel, ()> {
match self {
LCTerm::One => Err(()),
LCTerm::PolyLabel(l) => Ok(l),
}
}
}
impl<B: Borrow<String>> PartialEq<B> for LCTerm {
fn eq(&self, other: &B) -> bool {
match self {
Self::One => false,
Self::PolyLabel(l) => l == other.borrow(),
}
}
}
/// A labeled linear combinations of polynomials.
#[derive(Clone, Debug)]
pub struct LinearCombination<F> {
/// The label.
pub label: String,
/// The linear combination of `(coeff, poly_label)` pairs.
pub terms: Vec<(F, LCTerm)>,
}
impl<F: Field> LinearCombination<F> {
/// Construct an empty labeled linear combination.
pub fn empty(label: impl Into<String>) -> Self {
Self {
label: label.into(),
terms: Vec::new(),
}
}
/// Construct a new labeled linear combination.
/// with the terms specified in `term`.
pub fn new(label: impl Into<String>, terms: Vec<(F, impl Into<LCTerm>)>) -> Self {
let terms = terms.into_iter().map(|(c, t)| (c, t.into())).collect();
Self {
label: label.into(),
terms,
}
}
/// Returns the label of the linear combination.
pub fn label(&self) -> &String {
&self.label
}
/// Returns `true` if the linear combination has no terms.
pub fn is_empty(&self) -> bool {
self.terms.is_empty()
}
/// Add a term to the linear combination.
pub fn push(&mut self, term: (F, LCTerm)) -> &mut Self {
self.terms.push(term);
self
}
}
impl<'a, F: Field> AddAssign<(F, &'a LinearCombination<F>)> for LinearCombination<F> {
fn add_assign(&mut self, (coeff, other): (F, &'a LinearCombination<F>)) {
self.terms
.extend(other.terms.iter().map(|(c, t)| (coeff * c, t.clone())));
}
}
impl<'a, F: Field> SubAssign<(F, &'a LinearCombination<F>)> for LinearCombination<F> {
fn sub_assign(&mut self, (coeff, other): (F, &'a LinearCombination<F>)) {
self.terms
.extend(other.terms.iter().map(|(c, t)| (-coeff * c, t.clone())));
}
}
impl<'a, F: Field> AddAssign<&'a LinearCombination<F>> for LinearCombination<F> {
fn add_assign(&mut self, other: &'a LinearCombination<F>) {
self.terms.extend(other.terms.iter().cloned());
}
}
impl<'a, F: Field> SubAssign<&'a LinearCombination<F>> for LinearCombination<F> {
fn sub_assign(&mut self, other: &'a LinearCombination<F>) {
self.terms
.extend(other.terms.iter().map(|(c, t)| (-*c, t.clone())));
}
}
impl<F: Field> AddAssign<F> for LinearCombination<F> {
fn add_assign(&mut self, coeff: F) {
self.terms.push((coeff, LCTerm::One));
}
}
impl<F: Field> SubAssign<F> for LinearCombination<F> {
fn sub_assign(&mut self, coeff: F) {
self.terms.push((-coeff, LCTerm::One));
}
}
impl<F: Field> MulAssign<F> for LinearCombination<F> {
fn mul_assign(&mut self, coeff: F) {
self.terms.iter_mut().for_each(|(c, _)| *c *= coeff);
}
}
impl<F: Field> std::ops::Deref for LinearCombination<F> {
type Target = [(F, LCTerm)];
fn deref(&self) -> &Self::Target {
&self.terms
}
}