| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
|
| 3 |
//! Implementation of the generic Fully Linear Proof (FLP) system specified in |
| 4 |
//! [[draft-irtf-cfrg-vdaf-08]]. This is the main building block of [`Prio3`](crate::vdaf::prio3). |
| 5 |
//! |
| 6 |
//! The FLP is derived for any implementation of the [`Type`] trait. Such an implementation |
| 7 |
//! specifies a validity circuit that defines the set of valid measurements, as well as the finite |
| 8 |
//! field in which the validity circuit is evaluated. It also determines how raw measurements are |
| 9 |
//! encoded as inputs to the validity circuit, and how aggregates are decoded from sums of |
| 10 |
//! measurements. |
| 11 |
//! |
| 12 |
//! # Overview |
| 13 |
//! |
| 14 |
//! The proof system is comprised of three algorithms. The first, `prove`, is run by the prover in |
| 15 |
//! order to generate a proof of a statement's validity. The second and third, `query` and |
| 16 |
//! `decide`, are run by the verifier in order to check the proof. The proof asserts that the input |
| 17 |
//! is an element of a language recognized by the arithmetic circuit. If an input is _not_ valid, |
| 18 |
//! then the verification step will fail with high probability: |
| 19 |
//! |
| 20 |
//! ``` |
| 21 |
//! use prio::flp::types::Count; |
| 22 |
//! use prio::flp::Type; |
| 23 |
//! use prio::field::{random_vector, FieldElement, Field64}; |
| 24 |
//! |
| 25 |
//! // The prover chooses a measurement. |
| 26 |
//! let count = Count::new(); |
| 27 |
//! let input: Vec<Field64> = count.encode_measurement(&false).unwrap(); |
| 28 |
//! |
| 29 |
//! // The prover and verifier agree on "joint randomness" used to generate and |
| 30 |
//! // check the proof. The application needs to ensure that the prover |
| 31 |
//! // "commits" to the input before this point. In Prio3, the joint |
| 32 |
//! // randomness is derived from additive shares of the input. |
| 33 |
//! let joint_rand = random_vector(count.joint_rand_len()).unwrap(); |
| 34 |
//! |
| 35 |
//! // The prover generates the proof. |
| 36 |
//! let prove_rand = random_vector(count.prove_rand_len()).unwrap(); |
| 37 |
//! let proof = count.prove(&input, &prove_rand, &joint_rand).unwrap(); |
| 38 |
//! |
| 39 |
//! // The verifier checks the proof. In the first step, the verifier "queries" |
| 40 |
//! // the input and proof, getting the "verifier message" in response. It then |
| 41 |
//! // inspects the verifier to decide if the input is valid. |
| 42 |
//! let query_rand = random_vector(count.query_rand_len()).unwrap(); |
| 43 |
//! let verifier = count.query(&input, &proof, &query_rand, &joint_rand, 1).unwrap(); |
| 44 |
//! assert!(count.decide(&verifier).unwrap()); |
| 45 |
//! ``` |
| 46 |
//! |
| 47 |
//! [draft-irtf-cfrg-vdaf-08]: https://datatracker.ietf.org/doc/draft-irtf-cfrg-vdaf/08/ |
| 48 |
|
| 49 |
#[cfg(feature = "experimental")] |
| 50 |
use crate::dp::DifferentialPrivacyStrategy; |
| 51 |
use crate::fft::{discrete_fourier_transform, discrete_fourier_transform_inv_finish, FftError}; |
| 52 |
use crate::field::{FftFriendlyFieldElement, FieldElement, FieldElementWithInteger, FieldError}; |
| 53 |
use crate::fp::log2; |
| 54 |
use crate::polynomial::poly_eval; |
| 55 |
use std::any::Any; |
| 56 |
use std::convert::TryFrom; |
| 57 |
use std::fmt::Debug; |
| 58 |
|
| 59 |
pub mod gadgets; |
| 60 |
pub mod types; |
| 61 |
|
| 62 |
/// Errors propagated by methods in this module. |
| 63 |
#[derive(Debug, thiserror::Error)] |
| 64 |
#[non_exhaustive] |
| 65 |
pub enum FlpError { |
| 66 |
/// Calling [`Type::prove`] returned an error. |
| 67 |
#[error("prove error: {0}")] |
| 68 |
Prove(String), |
| 69 |
|
| 70 |
/// Calling [`Type::query`] returned an error. |
| 71 |
#[error("query error: {0}")] |
| 72 |
Query(String), |
| 73 |
|
| 74 |
/// Calling [`Type::decide`] returned an error. |
| 75 |
#[error("decide error: {0}")] |
| 76 |
Decide(String), |
| 77 |
|
| 78 |
/// Calling a gadget returned an error. |
| 79 |
#[error("gadget error: {0}")] |
| 80 |
Gadget(String), |
| 81 |
|
| 82 |
/// Calling the validity circuit returned an error. |
| 83 |
#[error("validity circuit error: {0}")] |
| 84 |
Valid(String), |
| 85 |
|
| 86 |
/// Calling [`Type::encode_measurement`] returned an error. |
| 87 |
#[error("value error: {0}")] |
| 88 |
Encode(String), |
| 89 |
|
| 90 |
/// Calling [`Type::decode_result`] returned an error. |
| 91 |
#[error("value error: {0}")] |
| 92 |
Decode(String), |
| 93 |
|
| 94 |
/// Calling [`Type::truncate`] returned an error. |
| 95 |
#[error("truncate error: {0}")] |
| 96 |
Truncate(String), |
| 97 |
|
| 98 |
/// Generic invalid parameter. This may be returned when an FLP type cannot be constructed. |
| 99 |
#[error("invalid paramter: {0}")] |
| 100 |
InvalidParameter(String), |
| 101 |
|
| 102 |
/// Returned if an FFT operation propagates an error. |
| 103 |
#[error("FFT error: {0}")] |
| 104 |
Fft(#[from] FftError), |
| 105 |
|
| 106 |
/// Returned if a field operation encountered an error. |
| 107 |
#[error("Field error: {0}")] |
| 108 |
Field(#[from] FieldError), |
| 109 |
|
| 110 |
#[cfg(feature = "experimental")] |
| 111 |
/// An error happened during noising. |
| 112 |
#[error("differential privacy error: {0}")] |
| 113 |
DifferentialPrivacy(#[from] crate::dp::DpError), |
| 114 |
} |
| 115 |
|
| 116 |
/// A type. Implementations of this trait specify how a particular kind of measurement is encoded |
| 117 |
/// as a vector of field elements and how validity of the encoded measurement is determined. |
| 118 |
/// Validity is determined via an arithmetic circuit evaluated over the encoded measurement. |
| 119 |
pub trait Type: Sized + Eq + Clone + Debug { |
| 120 |
/// The type of raw measurement to be encoded. |
| 121 |
type Measurement: Clone + Debug; |
| 122 |
|
| 123 |
/// The type of aggregate result for this type. |
| 124 |
type AggregateResult: Clone + Debug; |
| 125 |
|
| 126 |
/// The finite field used for this type. |
| 127 |
type Field: FftFriendlyFieldElement; |
| 128 |
|
| 129 |
/// Encodes a measurement as a vector of [`Self::input_len`] field elements. |
| 130 |
fn encode_measurement( |
| 131 |
&self, |
| 132 |
measurement: &Self::Measurement, |
| 133 |
) -> Result<Vec<Self::Field>, FlpError>; |
| 134 |
|
| 135 |
/// Decode an aggregate result. |
| 136 |
fn decode_result( |
| 137 |
&self, |
| 138 |
data: &[Self::Field], |
| 139 |
num_measurements: usize, |
| 140 |
) -> Result<Self::AggregateResult, FlpError>; |
| 141 |
|
| 142 |
/// Returns the sequence of gadgets associated with the validity circuit. |
| 143 |
/// |
| 144 |
/// # Notes |
| 145 |
/// |
| 146 |
/// The construction of [[BBCG+19], Theorem 4.3] uses a single gadget rather than many. The |
| 147 |
/// idea to generalize the proof system to allow multiple gadgets is discussed briefly in |
| 148 |
/// [[BBCG+19], Remark 4.5], but no construction is given. The construction implemented here |
| 149 |
/// requires security analysis. |
| 150 |
/// |
| 151 |
/// [BBCG+19]: https://ia.cr/2019/188 |
| 152 |
fn gadget(&self) -> Vec<Box<dyn Gadget<Self::Field>>>; |
| 153 |
|
| 154 |
/// Evaluates the validity circuit on an input and returns the output. |
| 155 |
/// |
| 156 |
/// # Parameters |
| 157 |
/// |
| 158 |
/// * `gadgets` is the sequence of gadgets, presumably output by [`Self::gadget`]. |
| 159 |
/// * `input` is the input to be validated. |
| 160 |
/// * `joint_rand` is the joint randomness shared by the prover and verifier. |
| 161 |
/// * `num_shares` is the number of input shares. |
| 162 |
/// |
| 163 |
/// # Example usage |
| 164 |
/// |
| 165 |
/// Applications typically do not call this method directly. It is used internally by |
| 166 |
/// [`Self::prove`] and [`Self::query`] to generate and verify the proof respectively. |
| 167 |
/// |
| 168 |
/// ``` |
| 169 |
/// use prio::flp::types::Count; |
| 170 |
/// use prio::flp::Type; |
| 171 |
/// use prio::field::{random_vector, FieldElement, Field64}; |
| 172 |
/// |
| 173 |
/// let count = Count::new(); |
| 174 |
/// let input: Vec<Field64> = count.encode_measurement(&true).unwrap(); |
| 175 |
/// let joint_rand = random_vector(count.joint_rand_len()).unwrap(); |
| 176 |
/// let v = count.valid(&mut count.gadget(), &input, &joint_rand, 1).unwrap(); |
| 177 |
/// assert_eq!(v, Field64::zero()); |
| 178 |
/// ``` |
| 179 |
fn valid( |
| 180 |
&self, |
| 181 |
gadgets: &mut Vec<Box<dyn Gadget<Self::Field>>>, |
| 182 |
input: &[Self::Field], |
| 183 |
joint_rand: &[Self::Field], |
| 184 |
num_shares: usize, |
| 185 |
) -> Result<Self::Field, FlpError>; |
| 186 |
|
| 187 |
/// Constructs an aggregatable output from an encoded input. Calling this method is only safe |
| 188 |
/// once `input` has been validated. |
| 189 |
fn truncate(&self, input: Vec<Self::Field>) -> Result<Vec<Self::Field>, FlpError>; |
| 190 |
|
| 191 |
/// The length in field elements of the encoded input returned by [`Self::encode_measurement`]. |
| 192 |
fn input_len(&self) -> usize; |
| 193 |
|
| 194 |
/// The length in field elements of the proof generated for this type. |
| 195 |
fn proof_len(&self) -> usize; |
| 196 |
|
| 197 |
/// The length in field elements of the verifier message constructed by [`Self::query`]. |
| 198 |
fn verifier_len(&self) -> usize; |
| 199 |
|
| 200 |
/// The length of the truncated output (i.e., the output of [`Type::truncate`]). |
| 201 |
fn output_len(&self) -> usize; |
| 202 |
|
| 203 |
/// The length of the joint random input. |
| 204 |
fn joint_rand_len(&self) -> usize; |
| 205 |
|
| 206 |
/// The length in field elements of the random input consumed by the prover to generate a |
| 207 |
/// proof. This is the same as the sum of the arity of each gadget in the validity circuit. |
| 208 |
fn prove_rand_len(&self) -> usize; |
| 209 |
|
| 210 |
/// The length in field elements of the random input consumed by the verifier to make queries |
| 211 |
/// against inputs and proofs. This is the same as the number of gadgets in the validity |
| 212 |
/// circuit. |
| 213 |
fn query_rand_len(&self) -> usize; |
| 214 |
|
| 215 |
/// Generate a proof of an input's validity. The return value is a sequence of |
| 216 |
/// [`Self::proof_len`] field elements. |
| 217 |
/// |
| 218 |
/// # Parameters |
| 219 |
/// |
| 220 |
/// * `input` is the input. |
| 221 |
/// * `prove_rand` is the prover' randomness. |
| 222 |
/// * `joint_rand` is the randomness shared by the prover and verifier. |
| 223 |
fn prove( |
| 224 |
&self, |
| 225 |
input: &[Self::Field], |
| 226 |
prove_rand: &[Self::Field], |
| 227 |
joint_rand: &[Self::Field], |
| 228 |
) -> Result<Vec<Self::Field>, FlpError> { |
| 229 |
if input.len() != self.input_len() { |
| 230 |
return Err(FlpError::Prove(format!( |
| 231 |
"unexpected input length: got {}; want {}", |
| 232 |
input.len(), |
| 233 |
self.input_len() |
| 234 |
))); |
| 235 |
} |
| 236 |
|
| 237 |
if prove_rand.len() != self.prove_rand_len() { |
| 238 |
return Err(FlpError::Prove(format!( |
| 239 |
"unexpected prove randomness length: got {}; want {}", |
| 240 |
prove_rand.len(), |
| 241 |
self.prove_rand_len() |
| 242 |
))); |
| 243 |
} |
| 244 |
|
| 245 |
if joint_rand.len() != self.joint_rand_len() { |
| 246 |
return Err(FlpError::Prove(format!( |
| 247 |
"unexpected joint randomness length: got {}; want {}", |
| 248 |
joint_rand.len(), |
| 249 |
self.joint_rand_len() |
| 250 |
))); |
| 251 |
} |
| 252 |
|
| 253 |
let mut prove_rand_len = 0; |
| 254 |
let mut shims = self |
| 255 |
.gadget() |
| 256 |
.into_iter() |
| 257 |
.map(|inner| { |
| 258 |
let inner_arity = inner.arity(); |
| 259 |
if prove_rand_len + inner_arity > prove_rand.len() { |
| 260 |
return Err(FlpError::Prove(format!( |
| 261 |
"short prove randomness: got {}; want at least {}", |
| 262 |
prove_rand.len(), |
| 263 |
prove_rand_len + inner_arity |
| 264 |
))); |
| 265 |
} |
| 266 |
|
| 267 |
let gadget = Box::new(ProveShimGadget::new( |
| 268 |
inner, |
| 269 |
&prove_rand[prove_rand_len..prove_rand_len + inner_arity], |
| 270 |
)?) as Box<dyn Gadget<Self::Field>>; |
| 271 |
prove_rand_len += inner_arity; |
| 272 |
|
| 273 |
Ok(gadget) |
| 274 |
}) |
| 275 |
.collect::<Result<Vec<_>, FlpError>>()?; |
| 276 |
assert_eq!(prove_rand_len, self.prove_rand_len()); |
| 277 |
|
| 278 |
// Create a buffer for storing the proof. The buffer is longer than the proof itself; the extra |
| 279 |
// length is to accommodate the computation of each gadget polynomial. |
| 280 |
let data_len = shims |
| 281 |
.iter() |
| 282 |
.map(|shim| { |
| 283 |
let gadget_poly_len = gadget_poly_len(shim.degree(), wire_poly_len(shim.calls())); |
| 284 |
|
| 285 |
// Computing the gadget polynomial using FFT requires an amount of memory that is a |
| 286 |
// power of 2. Thus we choose the smallest power of 2 that is at least as large as |
| 287 |
// the gadget polynomial. The wire seeds are encoded in the proof, too, so we |
| 288 |
// include the arity of the gadget to ensure there is always enough room at the end |
| 289 |
// of the buffer to compute the next gadget polynomial. It's likely that the |
| 290 |
// memory footprint here can be reduced, with a bit of care. |
| 291 |
shim.arity() + gadget_poly_len.next_power_of_two() |
| 292 |
}) |
| 293 |
.sum(); |
| 294 |
let mut proof = vec![Self::Field::zero(); data_len]; |
| 295 |
|
| 296 |
// Run the validity circuit with a sequence of "shim" gadgets that record the value of each |
| 297 |
// input wire of each gadget evaluation. These values are used to construct the wire |
| 298 |
// polynomials for each gadget in the next step. |
| 299 |
let _ = self.valid(&mut shims, input, joint_rand, 1)?; |
| 300 |
|
| 301 |
// Construct the proof. |
| 302 |
let mut proof_len = 0; |
| 303 |
for shim in shims.iter_mut() { |
| 304 |
let gadget = shim |
| 305 |
.as_any() |
| 306 |
.downcast_mut::<ProveShimGadget<Self::Field>>() |
| 307 |
.unwrap(); |
| 308 |
|
| 309 |
// Interpolate the wire polynomials `f[0], ..., f[g_arity-1]` from the input wires of each |
| 310 |
// evaluation of the gadget. |
| 311 |
let m = wire_poly_len(gadget.calls()); |
| 312 |
let m_inv = Self::Field::from( |
| 313 |
<Self::Field as FieldElementWithInteger>::Integer::try_from(m).unwrap(), |
| 314 |
) |
| 315 |
.inv(); |
| 316 |
let mut f = vec![vec![Self::Field::zero(); m]; gadget.arity()]; |
| 317 |
for ((coefficients, values), proof_val) in f[..gadget.arity()] |
| 318 |
.iter_mut() |
| 319 |
.zip(gadget.f_vals[..gadget.arity()].iter()) |
| 320 |
.zip(proof[proof_len..proof_len + gadget.arity()].iter_mut()) |
| 321 |
{ |
| 322 |
discrete_fourier_transform(coefficients, values, m)?; |
| 323 |
discrete_fourier_transform_inv_finish(coefficients, m, m_inv); |
| 324 |
|
| 325 |
// The first point on each wire polynomial is a random value chosen by the prover. This |
| 326 |
// point is stored in the proof so that the verifier can reconstruct the wire |
| 327 |
// polynomials. |
| 328 |
*proof_val = values[0]; |
| 329 |
} |
| 330 |
|
| 331 |
// Construct the gadget polynomial `G(f[0], ..., f[g_arity-1])` and append it to `proof`. |
| 332 |
let gadget_poly_len = gadget_poly_len(gadget.degree(), m); |
| 333 |
let start = proof_len + gadget.arity(); |
| 334 |
let end = start + gadget_poly_len.next_power_of_two(); |
| 335 |
gadget.call_poly(&mut proof[start..end], &f)?; |
| 336 |
proof_len += gadget.arity() + gadget_poly_len; |
| 337 |
} |
| 338 |
|
| 339 |
// Truncate the buffer to the size of the proof. |
| 340 |
assert_eq!(proof_len, self.proof_len()); |
| 341 |
proof.truncate(proof_len); |
| 342 |
Ok(proof) |
| 343 |
} |
| 344 |
|
| 345 |
/// Query an input and proof and return the verifier message. The return value has length |
| 346 |
/// [`Self::verifier_len`]. |
| 347 |
/// |
| 348 |
/// # Parameters |
| 349 |
/// |
| 350 |
/// * `input` is the input or input share. |
| 351 |
/// * `proof` is the proof or proof share. |
| 352 |
/// * `query_rand` is the verifier's randomness. |
| 353 |
/// * `joint_rand` is the randomness shared by the prover and verifier. |
| 354 |
/// * `num_shares` is the total number of input shares. |
| 355 |
fn query( |
| 356 |
&self, |
| 357 |
input: &[Self::Field], |
| 358 |
proof: &[Self::Field], |
| 359 |
query_rand: &[Self::Field], |
| 360 |
joint_rand: &[Self::Field], |
| 361 |
num_shares: usize, |
| 362 |
) -> Result<Vec<Self::Field>, FlpError> { |
| 363 |
if input.len() != self.input_len() { |
| 364 |
return Err(FlpError::Query(format!( |
| 365 |
"unexpected input length: got {}; want {}", |
| 366 |
input.len(), |
| 367 |
self.input_len() |
| 368 |
))); |
| 369 |
} |
| 370 |
|
| 371 |
if proof.len() != self.proof_len() { |
| 372 |
return Err(FlpError::Query(format!( |
| 373 |
"unexpected proof length: got {}; want {}", |
| 374 |
proof.len(), |
| 375 |
self.proof_len() |
| 376 |
))); |
| 377 |
} |
| 378 |
|
| 379 |
if query_rand.len() != self.query_rand_len() { |
| 380 |
return Err(FlpError::Query(format!( |
| 381 |
"unexpected query randomness length: got {}; want {}", |
| 382 |
query_rand.len(), |
| 383 |
self.query_rand_len() |
| 384 |
))); |
| 385 |
} |
| 386 |
|
| 387 |
if joint_rand.len() != self.joint_rand_len() { |
| 388 |
return Err(FlpError::Query(format!( |
| 389 |
"unexpected joint randomness length: got {}; want {}", |
| 390 |
joint_rand.len(), |
| 391 |
self.joint_rand_len() |
| 392 |
))); |
| 393 |
} |
| 394 |
|
| 395 |
let mut proof_len = 0; |
| 396 |
let mut shims = self |
| 397 |
.gadget() |
| 398 |
.into_iter() |
| 399 |
.enumerate() |
| 400 |
.map(|(idx, gadget)| { |
| 401 |
let gadget_degree = gadget.degree(); |
| 402 |
let gadget_arity = gadget.arity(); |
| 403 |
let m = (1 + gadget.calls()).next_power_of_two(); |
| 404 |
let r = query_rand[idx]; |
| 405 |
|
| 406 |
// Make sure the query randomness isn't a root of unity. Evaluating the gadget |
| 407 |
// polynomial at any of these points would be a privacy violation, since these points |
| 408 |
// were used by the prover to construct the wire polynomials. |
| 409 |
if r.pow(<Self::Field as FieldElementWithInteger>::Integer::try_from(m).unwrap()) |
| 410 |
== Self::Field::one() |
| 411 |
{ |
| 412 |
return Err(FlpError::Query(format!( |
| 413 |
"invalid query randomness: encountered 2^{m}-th root of unity" |
| 414 |
))); |
| 415 |
} |
| 416 |
|
| 417 |
// Compute the length of the sub-proof corresponding to the `idx`-th gadget. |
| 418 |
let next_len = gadget_arity + gadget_degree * (m - 1) + 1; |
| 419 |
let proof_data = &proof[proof_len..proof_len + next_len]; |
| 420 |
proof_len += next_len; |
| 421 |
|
| 422 |
Ok(Box::new(QueryShimGadget::new(gadget, r, proof_data)?) |
| 423 |
as Box<dyn Gadget<Self::Field>>) |
| 424 |
}) |
| 425 |
.collect::<Result<Vec<_>, _>>()?; |
| 426 |
|
| 427 |
// Create a buffer for the verifier data. This includes the output of the validity circuit and, |
| 428 |
// for each gadget `shim[idx].inner`, the wire polynomials evaluated at the query randomness |
| 429 |
// `query_rand[idx]` and the gadget polynomial evaluated at `query_rand[idx]`. |
| 430 |
let data_len = 1 + shims.iter().map(|shim| shim.arity() + 1).sum::<usize>(); |
| 431 |
let mut verifier = Vec::with_capacity(data_len); |
| 432 |
|
| 433 |
// Run the validity circuit with a sequence of "shim" gadgets that record the inputs to each |
| 434 |
// wire for each gadget call. Record the output of the circuit and append it to the verifier |
| 435 |
// message. |
| 436 |
// |
| 437 |
// NOTE The proof of [BBC+19, Theorem 4.3] assumes that the output of the validity circuit is |
| 438 |
// equal to the output of the last gadget evaluation. Here we relax this assumption. This |
| 439 |
// should be OK, since it's possible to transform any circuit into one for which this is true. |
| 440 |
// (Needs security analysis.) |
| 441 |
let validity = self.valid(&mut shims, input, joint_rand, num_shares)?; |
| 442 |
verifier.push(validity); |
| 443 |
|
| 444 |
// Fill the buffer with the verifier message. |
| 445 |
for (query_rand_val, shim) in query_rand[..shims.len()].iter().zip(shims.iter_mut()) { |
| 446 |
let gadget = shim |
| 447 |
.as_any() |
| 448 |
.downcast_ref::<QueryShimGadget<Self::Field>>() |
| 449 |
.unwrap(); |
| 450 |
|
| 451 |
// Reconstruct the wire polynomials `f[0], ..., f[g_arity-1]` and evaluate each wire |
| 452 |
// polynomial at query randomness value. |
| 453 |
let m = (1 + gadget.calls()).next_power_of_two(); |
| 454 |
let m_inv = Self::Field::from( |
| 455 |
<Self::Field as FieldElementWithInteger>::Integer::try_from(m).unwrap(), |
| 456 |
) |
| 457 |
.inv(); |
| 458 |
let mut f = vec![Self::Field::zero(); m]; |
| 459 |
for wire in 0..gadget.arity() { |
| 460 |
discrete_fourier_transform(&mut f, &gadget.f_vals[wire], m)?; |
| 461 |
discrete_fourier_transform_inv_finish(&mut f, m, m_inv); |
| 462 |
verifier.push(poly_eval(&f, *query_rand_val)); |
| 463 |
} |
| 464 |
|
| 465 |
// Add the value of the gadget polynomial evaluated at the query randomness value. |
| 466 |
verifier.push(gadget.p_at_r); |
| 467 |
} |
| 468 |
|
| 469 |
assert_eq!(verifier.len(), self.verifier_len()); |
| 470 |
Ok(verifier) |
| 471 |
} |
| 472 |
|
| 473 |
/// Returns true if the verifier message indicates that the input from which it was generated is valid. |
| 474 |
fn decide(&self, verifier: &[Self::Field]) -> Result<bool, FlpError> { |
| 475 |
if verifier.len() != self.verifier_len() { |
| 476 |
return Err(FlpError::Decide(format!( |
| 477 |
"unexpected verifier length: got {}; want {}", |
| 478 |
verifier.len(), |
| 479 |
self.verifier_len() |
| 480 |
))); |
| 481 |
} |
| 482 |
|
| 483 |
// Check if the output of the circuit is 0. |
| 484 |
if verifier[0] != Self::Field::zero() { |
| 485 |
return Ok(false); |
| 486 |
} |
| 487 |
|
| 488 |
// Check that each of the proof polynomials are well-formed. |
| 489 |
let mut gadgets = self.gadget(); |
| 490 |
let mut verifier_len = 1; |
| 491 |
for gadget in gadgets.iter_mut() { |
| 492 |
let next_len = 1 + gadget.arity(); |
| 493 |
|
| 494 |
let e = gadget.call(&verifier[verifier_len..verifier_len + next_len - 1])?; |
| 495 |
if e != verifier[verifier_len + next_len - 1] { |
| 496 |
return Ok(false); |
| 497 |
} |
| 498 |
|
| 499 |
verifier_len += next_len; |
| 500 |
} |
| 501 |
|
| 502 |
Ok(true) |
| 503 |
} |
| 504 |
|
| 505 |
/// Check whether `input` and `joint_rand` have the length expected by `self`, |
| 506 |
/// return [`FlpError::Valid`] otherwise. |
| 507 |
fn valid_call_check( |
| 508 |
&self, |
| 509 |
input: &[Self::Field], |
| 510 |
joint_rand: &[Self::Field], |
| 511 |
) -> Result<(), FlpError> { |
| 512 |
if input.len() != self.input_len() { |
| 513 |
return Err(FlpError::Valid(format!( |
| 514 |
"unexpected input length: got {}; want {}", |
| 515 |
input.len(), |
| 516 |
self.input_len(), |
| 517 |
))); |
| 518 |
} |
| 519 |
|
| 520 |
if joint_rand.len() != self.joint_rand_len() { |
| 521 |
return Err(FlpError::Valid(format!( |
| 522 |
"unexpected joint randomness length: got {}; want {}", |
| 523 |
joint_rand.len(), |
| 524 |
self.joint_rand_len() |
| 525 |
))); |
| 526 |
} |
| 527 |
|
| 528 |
Ok(()) |
| 529 |
} |
| 530 |
|
| 531 |
/// Check if the length of `input` matches `self`'s `input_len()`, |
| 532 |
/// return [`FlpError::Truncate`] otherwise. |
| 533 |
fn truncate_call_check(&self, input: &[Self::Field]) -> Result<(), FlpError> { |
| 534 |
if input.len() != self.input_len() { |
| 535 |
return Err(FlpError::Truncate(format!( |
| 536 |
"Unexpected input length: got {}; want {}", |
| 537 |
input.len(), |
| 538 |
self.input_len() |
| 539 |
))); |
| 540 |
} |
| 541 |
|
| 542 |
Ok(()) |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
/// A type which supports adding noise to aggregate shares for Server Differential Privacy. |
| 547 |
#[cfg(feature = "experimental")] |
| 548 |
#[cfg_attr(docsrs, doc(cfg(feature = "experimental")))] |
| 549 |
pub trait TypeWithNoise<S>: Type |
| 550 |
where |
| 551 |
S: DifferentialPrivacyStrategy, |
| 552 |
{ |
| 553 |
/// Add noise to the aggregate share to obtain differential privacy. |
| 554 |
fn add_noise_to_result( |
| 555 |
&self, |
| 556 |
dp_strategy: &S, |
| 557 |
agg_result: &mut [Self::Field], |
| 558 |
num_measurements: usize, |
| 559 |
) -> Result<(), FlpError>; |
| 560 |
} |
| 561 |
|
| 562 |
/// A gadget, a non-affine arithmetic circuit that is called when evaluating a validity circuit. |
| 563 |
pub trait Gadget<F: FftFriendlyFieldElement>: Debug { |
| 564 |
/// Evaluates the gadget on input `inp` and returns the output. |
| 565 |
fn call(&mut self, inp: &[F]) -> Result<F, FlpError>; |
| 566 |
|
| 567 |
/// Evaluate the gadget on input of a sequence of polynomials. The output is written to `outp`. |
| 568 |
fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError>; |
| 569 |
|
| 570 |
/// Returns the arity of the gadget. This is the length of `inp` passed to `call` or |
| 571 |
/// `call_poly`. |
| 572 |
fn arity(&self) -> usize; |
| 573 |
|
| 574 |
/// Returns the circuit's arithmetic degree. This determines the minimum length the `outp` |
| 575 |
/// buffer passed to `call_poly`. |
| 576 |
fn degree(&self) -> usize; |
| 577 |
|
| 578 |
/// Returns the number of times the gadget is expected to be called. |
| 579 |
fn calls(&self) -> usize; |
| 580 |
|
| 581 |
/// This call is used to downcast a `Box<dyn Gadget<F>>` to a concrete type. |
| 582 |
fn as_any(&mut self) -> &mut dyn Any; |
| 583 |
} |
| 584 |
|
| 585 |
// A "shim" gadget used during proof generation to record the input wires each time a gadget is |
| 586 |
// evaluated. |
| 587 |
#[derive(Debug)] |
| 588 |
struct ProveShimGadget<F: FftFriendlyFieldElement> { |
| 589 |
inner: Box<dyn Gadget<F>>, |
| 590 |
|
| 591 |
/// Points at which the wire polynomials are interpolated. |
| 592 |
f_vals: Vec<Vec<F>>, |
| 593 |
|
| 594 |
/// The number of times the gadget has been called so far. |
| 595 |
ct: usize, |
| 596 |
} |
| 597 |
|
| 598 |
impl<F: FftFriendlyFieldElement> ProveShimGadget<F> { |
| 599 |
fn new(inner: Box<dyn Gadget<F>>, prove_rand: &[F]) -> Result<Self, FlpError> { |
| 600 |
let mut f_vals = vec![vec![F::zero(); 1 + inner.calls()]; inner.arity()]; |
| 601 |
|
| 602 |
for (prove_rand_val, wire_poly_vals) in |
| 603 |
prove_rand[..f_vals.len()].iter().zip(f_vals.iter_mut()) |
| 604 |
{ |
| 605 |
// Choose a random field element as the first point on the wire polynomial. |
| 606 |
wire_poly_vals[0] = *prove_rand_val; |
| 607 |
} |
| 608 |
|
| 609 |
Ok(Self { |
| 610 |
inner, |
| 611 |
f_vals, |
| 612 |
ct: 1, |
| 613 |
}) |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
impl<F: FftFriendlyFieldElement> Gadget<F> for ProveShimGadget<F> { |
| 618 |
fn call(&mut self, inp: &[F]) -> Result<F, FlpError> { |
| 619 |
for (wire_poly_vals, inp_val) in self.f_vals[..inp.len()].iter_mut().zip(inp.iter()) { |
| 620 |
wire_poly_vals[self.ct] = *inp_val; |
| 621 |
} |
| 622 |
self.ct += 1; |
| 623 |
self.inner.call(inp) |
| 624 |
} |
| 625 |
|
| 626 |
fn call_poly(&mut self, outp: &mut [F], inp: &[Vec<F>]) -> Result<(), FlpError> { |
| 627 |
self.inner.call_poly(outp, inp) |
| 628 |
} |
| 629 |
|
| 630 |
fn arity(&self) -> usize { |
| 631 |
self.inner.arity() |
| 632 |
} |
| 633 |
|
| 634 |
fn degree(&self) -> usize { |
| 635 |
self.inner.degree() |
| 636 |
} |
| 637 |
|
| 638 |
fn calls(&self) -> usize { |
| 639 |
self.inner.calls() |
| 640 |
} |
| 641 |
|
| 642 |
fn as_any(&mut self) -> &mut dyn Any { |
| 643 |
self |
| 644 |
} |
| 645 |
} |
| 646 |
|
| 647 |
// A "shim" gadget used during proof verification to record the points at which the intermediate |
| 648 |
// proof polynomials are evaluated. |
| 649 |
#[derive(Debug)] |
| 650 |
struct QueryShimGadget<F: FftFriendlyFieldElement> { |
| 651 |
inner: Box<dyn Gadget<F>>, |
| 652 |
|
| 653 |
/// Points at which intermediate proof polynomials are interpolated. |
| 654 |
f_vals: Vec<Vec<F>>, |
| 655 |
|
| 656 |
/// Points at which the gadget polynomial is interpolated. |
| 657 |
p_vals: Vec<F>, |
| 658 |
|
| 659 |
/// The gadget polynomial evaluated on a random input `r`. |
| 660 |
p_at_r: F, |
| 661 |
|
| 662 |
/// Used to compute an index into `p_val`. |
| 663 |
step: usize, |
| 664 |
|
| 665 |
/// The number of times the gadget has been called so far. |
| 666 |
ct: usize, |
| 667 |
} |
| 668 |
|
| 669 |
impl<F: FftFriendlyFieldElement> QueryShimGadget<F> { |
| 670 |
fn new(inner: Box<dyn Gadget<F>>, r: F, proof_data: &[F]) -> Result<Self, FlpError> { |
| 671 |
let gadget_degree = inner.degree(); |
| 672 |
let gadget_arity = inner.arity(); |
| 673 |
let m = (1 + inner.calls()).next_power_of_two(); |
| 674 |
let p = m * gadget_degree; |
| 675 |
|
| 676 |
// Each call to this gadget records the values at which intermediate proof polynomials were |
| 677 |
// interpolated. The first point was a random value chosen by the prover and transmitted in |
| 678 |
// the proof. |
| 679 |
let mut f_vals = vec![vec![F::zero(); 1 + inner.calls()]; gadget_arity]; |
| 680 |
for wire in 0..gadget_arity { |
| 681 |
f_vals[wire][0] = proof_data[wire]; |
| 682 |
} |
| 683 |
|
| 684 |
// Evaluate the gadget polynomial at roots of unity. |
| 685 |
let size = p.next_power_of_two(); |
| 686 |
let mut p_vals = vec![F::zero(); size]; |
| 687 |
discrete_fourier_transform(&mut p_vals, &proof_data[gadget_arity..], size)?; |
| 688 |
|
| 689 |
// The step is used to compute the element of `p_val` that will be returned by a call to |
| 690 |
// the gadget. |
| 691 |
let step = (1 << (log2(p as u128) - log2(m as u128))) as usize; |
| 692 |
|
| 693 |
// Evaluate the gadget polynomial `p` at query randomness `r`. |
| 694 |
let p_at_r = poly_eval(&proof_data[gadget_arity..], r); |
| 695 |
|
| 696 |
Ok(Self { |
| 697 |
inner, |
| 698 |
f_vals, |
| 699 |
p_vals, |
| 700 |
p_at_r, |
| 701 |
step, |
| 702 |
ct: 1, |
| 703 |
}) |
| 704 |
} |
| 705 |
} |
| 706 |
|
| 707 |
impl<F: FftFriendlyFieldElement> Gadget<F> for QueryShimGadget<F> { |
| 708 |
fn call(&mut self, inp: &[F]) -> Result<F, FlpError> { |
| 709 |
for (wire_poly_vals, inp_val) in self.f_vals[..inp.len()].iter_mut().zip(inp.iter()) { |
| 710 |
wire_poly_vals[self.ct] = *inp_val; |
| 711 |
} |
| 712 |
let outp = self.p_vals[self.ct * self.step]; |
| 713 |
self.ct += 1; |
| 714 |
Ok(outp) |
| 715 |
} |
| 716 |
|
| 717 |
fn call_poly(&mut self, _outp: &mut [F], _inp: &[Vec<F>]) -> Result<(), FlpError> { |
| 718 |
panic!("no-op"); |
| 719 |
} |
| 720 |
|
| 721 |
fn arity(&self) -> usize { |
| 722 |
self.inner.arity() |
| 723 |
} |
| 724 |
|
| 725 |
fn degree(&self) -> usize { |
| 726 |
self.inner.degree() |
| 727 |
} |
| 728 |
|
| 729 |
fn calls(&self) -> usize { |
| 730 |
self.inner.calls() |
| 731 |
} |
| 732 |
|
| 733 |
fn as_any(&mut self) -> &mut dyn Any { |
| 734 |
self |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
/// Compute the length of the wire polynomial constructed from the given number of gadget calls. |
| 739 |
#[inline] |
| 740 |
pub(crate) fn wire_poly_len(num_calls: usize) -> usize { |
| 741 |
(1 + num_calls).next_power_of_two() |
| 742 |
} |
| 743 |
|
| 744 |
/// Compute the length of the gadget polynomial for a gadget with the given degree and from wire |
| 745 |
/// polynomials of the given length. |
| 746 |
#[inline] |
| 747 |
pub(crate) fn gadget_poly_len(gadget_degree: usize, wire_poly_len: usize) -> usize { |
| 748 |
gadget_degree * (wire_poly_len - 1) + 1 |
| 749 |
} |
| 750 |
|
| 751 |
/// Utilities for testing FLPs. |
| 752 |
#[cfg(feature = "test-util")] |
| 753 |
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))] |
| 754 |
pub mod test_utils { |
| 755 |
use super::*; |
| 756 |
use crate::field::{random_vector, FieldElement, FieldElementWithInteger}; |
| 757 |
|
| 758 |
/// Various tests for an FLP. |
| 759 |
#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))] |
| 760 |
pub struct FlpTest<'a, T: Type> { |
| 761 |
/// The FLP. |
| 762 |
pub flp: &'a T, |
| 763 |
|
| 764 |
/// Optional test name. |
| 765 |
pub name: Option<&'a str>, |
| 766 |
|
| 767 |
/// The input to use for the tests. |
| 768 |
pub input: &'a [T::Field], |
| 769 |
|
| 770 |
/// If set, the expected result of truncating the input. |
| 771 |
pub expected_output: Option<&'a [T::Field]>, |
| 772 |
|
| 773 |
/// Whether the input is expected to be valid. |
| 774 |
pub expect_valid: bool, |
| 775 |
} |
| 776 |
|
| 777 |
impl<T: Type> FlpTest<'_, T> { |
| 778 |
/// Construct a test and run it. Expect the input to be valid and compare the truncated |
| 779 |
/// output to the provided value. |
| 780 |
pub fn expect_valid<const SHARES: usize>( |
| 781 |
flp: &T, |
| 782 |
input: &[T::Field], |
| 783 |
expected_output: &[T::Field], |
| 784 |
) { |
| 785 |
FlpTest { |
| 786 |
flp, |
| 787 |
name: None, |
| 788 |
input, |
| 789 |
expected_output: Some(expected_output), |
| 790 |
expect_valid: true, |
| 791 |
} |
| 792 |
.run::<SHARES>() |
| 793 |
} |
| 794 |
|
| 795 |
/// Construct a test and run it. Expect the input to be invalid. |
| 796 |
pub fn expect_invalid<const SHARES: usize>(flp: &T, input: &[T::Field]) { |
| 797 |
FlpTest { |
| 798 |
flp, |
| 799 |
name: None, |
| 800 |
input, |
| 801 |
expect_valid: false, |
| 802 |
expected_output: None, |
| 803 |
} |
| 804 |
.run::<SHARES>() |
| 805 |
} |
| 806 |
|
| 807 |
/// Construct a test and run it. Expect the input to be valid. |
| 808 |
pub fn expect_valid_no_output<const SHARES: usize>(flp: &T, input: &[T::Field]) { |
| 809 |
FlpTest { |
| 810 |
flp, |
| 811 |
name: None, |
| 812 |
input, |
| 813 |
expect_valid: true, |
| 814 |
expected_output: None, |
| 815 |
} |
| 816 |
.run::<SHARES>() |
| 817 |
} |
| 818 |
|
| 819 |
/// Run the tests. |
| 820 |
pub fn run<const SHARES: usize>(&self) { |
| 821 |
let name = self.name.unwrap_or("unnamed test"); |
| 822 |
|
| 823 |
assert_eq!( |
| 824 |
self.input.len(), |
| 825 |
self.flp.input_len(), |
| 826 |
"{name}: unexpected input length" |
| 827 |
); |
| 828 |
|
| 829 |
let mut gadgets = self.flp.gadget(); |
| 830 |
let joint_rand = random_vector(self.flp.joint_rand_len()).unwrap(); |
| 831 |
let prove_rand = random_vector(self.flp.prove_rand_len()).unwrap(); |
| 832 |
let query_rand = random_vector(self.flp.query_rand_len()).unwrap(); |
| 833 |
assert_eq!( |
| 834 |
self.flp.query_rand_len(), |
| 835 |
gadgets.len(), |
| 836 |
"{name}: unexpected number of gadgets" |
| 837 |
); |
| 838 |
assert_eq!( |
| 839 |
self.flp.joint_rand_len(), |
| 840 |
joint_rand.len(), |
| 841 |
"{name}: unexpected joint rand length" |
| 842 |
); |
| 843 |
assert_eq!( |
| 844 |
self.flp.prove_rand_len(), |
| 845 |
prove_rand.len(), |
| 846 |
"{name}: unexpected prove rand length", |
| 847 |
); |
| 848 |
assert_eq!( |
| 849 |
self.flp.query_rand_len(), |
| 850 |
query_rand.len(), |
| 851 |
"{name}: unexpected query rand length", |
| 852 |
); |
| 853 |
|
| 854 |
// Run the validity circuit. |
| 855 |
let v = self |
| 856 |
.flp |
| 857 |
.valid(&mut gadgets, self.input, &joint_rand, 1) |
| 858 |
.unwrap(); |
| 859 |
assert_eq!( |
| 860 |
v == T::Field::zero(), |
| 861 |
self.expect_valid, |
| 862 |
"{name}: unexpected output of valid() returned {v}", |
| 863 |
); |
| 864 |
|
| 865 |
// Generate the proof. |
| 866 |
let proof = self |
| 867 |
.flp |
| 868 |
.prove(self.input, &prove_rand, &joint_rand) |
| 869 |
.unwrap(); |
| 870 |
assert_eq!( |
| 871 |
proof.len(), |
| 872 |
self.flp.proof_len(), |
| 873 |
"{name}: unexpected proof length" |
| 874 |
); |
| 875 |
|
| 876 |
// Query the proof. |
| 877 |
let verifier = self |
| 878 |
.flp |
| 879 |
.query(self.input, &proof, &query_rand, &joint_rand, 1) |
| 880 |
.unwrap(); |
| 881 |
assert_eq!( |
| 882 |
verifier.len(), |
| 883 |
self.flp.verifier_len(), |
| 884 |
"{name}: unexpected verifier length" |
| 885 |
); |
| 886 |
|
| 887 |
// Decide if the input is valid. |
| 888 |
let res = self.flp.decide(&verifier).unwrap(); |
| 889 |
assert_eq!(res, self.expect_valid, "{name}: unexpected decision"); |
| 890 |
|
| 891 |
// Run distributed FLP. |
| 892 |
let input_shares = split_vector::<_, SHARES>(self.input); |
| 893 |
let proof_shares = split_vector::<_, SHARES>(&proof); |
| 894 |
let verifier: Vec<T::Field> = (0..SHARES) |
| 895 |
.map(|i| { |
| 896 |
self.flp |
| 897 |
.query( |
| 898 |
&input_shares[i], |
| 899 |
&proof_shares[i], |
| 900 |
&query_rand, |
| 901 |
&joint_rand, |
| 902 |
SHARES, |
| 903 |
) |
| 904 |
.unwrap() |
| 905 |
}) |
| 906 |
.reduce(|mut left, right| { |
| 907 |
for (x, y) in left.iter_mut().zip(right.iter()) { |
| 908 |
*x += *y; |
| 909 |
} |
| 910 |
left |
| 911 |
}) |
| 912 |
.unwrap(); |
| 913 |
|
| 914 |
let res = self.flp.decide(&verifier).unwrap(); |
| 915 |
assert_eq!( |
| 916 |
res, self.expect_valid, |
| 917 |
"{name}: unexpected distributed decision" |
| 918 |
); |
| 919 |
|
| 920 |
// Try verifying various proof mutants. |
| 921 |
for i in 0..std::cmp::min(proof.len(), 10) { |
| 922 |
let mut mutated_proof = proof.clone(); |
| 923 |
mutated_proof[i] *= T::Field::from( |
| 924 |
<T::Field as FieldElementWithInteger>::Integer::try_from(23).unwrap(), |
| 925 |
); |
| 926 |
let verifier = self |
| 927 |
.flp |
| 928 |
.query(self.input, &mutated_proof, &query_rand, &joint_rand, 1) |
| 929 |
.unwrap(); |
| 930 |
assert!( |
| 931 |
!self.flp.decide(&verifier).unwrap(), |
| 932 |
"{name}: proof mutant {} deemed valid", |
| 933 |
i |
| 934 |
); |
| 935 |
} |
| 936 |
|
| 937 |
// Try truncating the input. |
| 938 |
if let Some(ref expected_output) = self.expected_output { |
| 939 |
let output = self.flp.truncate(self.input.to_vec()).unwrap(); |
| 940 |
|
| 941 |
assert_eq!( |
| 942 |
output.len(), |
| 943 |
self.flp.output_len(), |
| 944 |
"{name}: unexpected output length of truncate()" |
| 945 |
); |
| 946 |
|
| 947 |
assert_eq!( |
| 948 |
&output, expected_output, |
| 949 |
"{name}: unexpected output of truncate()" |
| 950 |
); |
| 951 |
} |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
fn split_vector<F: FieldElement, const SHARES: usize>(inp: &[F]) -> [Vec<F>; SHARES] { |
| 956 |
let mut outp = Vec::with_capacity(SHARES); |
| 957 |
outp.push(inp.to_vec()); |
| 958 |
|
| 959 |
for _ in 1..SHARES { |
| 960 |
let share: Vec<F> = |
| 961 |
random_vector(inp.len()).expect("failed to generate a random vector"); |
| 962 |
for (x, y) in outp[0].iter_mut().zip(&share) { |
| 963 |
*x -= *y; |
| 964 |
} |
| 965 |
outp.push(share); |
| 966 |
} |
| 967 |
|
| 968 |
outp.try_into().unwrap() |
| 969 |
} |
| 970 |
} |
| 971 |
|
| 972 |
#[cfg(test)] |
| 973 |
mod tests { |
| 974 |
use super::*; |
| 975 |
use crate::field::{random_vector, split_vector, Field128}; |
| 976 |
use crate::flp::gadgets::{Mul, PolyEval}; |
| 977 |
use crate::polynomial::poly_range_check; |
| 978 |
|
| 979 |
use std::marker::PhantomData; |
| 980 |
|
| 981 |
// Simple integration test for the core FLP logic. You'll find more extensive unit tests for |
| 982 |
// each implemented data type in src/types.rs. |
| 983 |
#[test] |
| 984 |
fn test_flp() { |
| 985 |
const NUM_SHARES: usize = 2; |
| 986 |
|
| 987 |
let typ: TestType<Field128> = TestType::new(); |
| 988 |
let input = typ.encode_measurement(&3).unwrap(); |
| 989 |
assert_eq!(input.len(), typ.input_len()); |
| 990 |
|
| 991 |
let input_shares: Vec<Vec<Field128>> = split_vector(input.as_slice(), NUM_SHARES) |
| 992 |
.unwrap() |
| 993 |
.into_iter() |
| 994 |
.collect(); |
| 995 |
|
| 996 |
let joint_rand = random_vector(typ.joint_rand_len()).unwrap(); |
| 997 |
let prove_rand = random_vector(typ.prove_rand_len()).unwrap(); |
| 998 |
let query_rand = random_vector(typ.query_rand_len()).unwrap(); |
| 999 |
|
| 1000 |
let proof = typ.prove(&input, &prove_rand, &joint_rand).unwrap(); |
| 1001 |
assert_eq!(proof.len(), typ.proof_len()); |
| 1002 |
|
| 1003 |
let proof_shares: Vec<Vec<Field128>> = split_vector(&proof, NUM_SHARES) |
| 1004 |
.unwrap() |
| 1005 |
.into_iter() |
| 1006 |
.collect(); |
| 1007 |
|
| 1008 |
let verifier: Vec<Field128> = (0..NUM_SHARES) |
| 1009 |
.map(|i| { |
| 1010 |
typ.query( |
| 1011 |
&input_shares[i], |
| 1012 |
&proof_shares[i], |
| 1013 |
&query_rand, |
| 1014 |
&joint_rand, |
| 1015 |
NUM_SHARES, |
| 1016 |
) |
| 1017 |
.unwrap() |
| 1018 |
}) |
| 1019 |
.reduce(|mut left, right| { |
| 1020 |
for (x, y) in left.iter_mut().zip(right.iter()) { |
| 1021 |
*x += *y; |
| 1022 |
} |
| 1023 |
left |
| 1024 |
}) |
| 1025 |
.unwrap(); |
| 1026 |
assert_eq!(verifier.len(), typ.verifier_len()); |
| 1027 |
|
| 1028 |
assert!(typ.decide(&verifier).unwrap()); |
| 1029 |
} |
| 1030 |
|
| 1031 |
/// A toy type used for testing multiple gadgets. Valid inputs of this type consist of a pair |
| 1032 |
/// of field elements `(x, y)` where `2 <= x < 5` and `x^3 == y`. |
| 1033 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 1034 |
struct TestType<F>(PhantomData<F>); |
| 1035 |
|
| 1036 |
impl<F> TestType<F> { |
| 1037 |
fn new() -> Self { |
| 1038 |
Self(PhantomData) |
| 1039 |
} |
| 1040 |
} |
| 1041 |
|
| 1042 |
impl<F: FftFriendlyFieldElement> Type for TestType<F> { |
| 1043 |
type Measurement = F::Integer; |
| 1044 |
type AggregateResult = F::Integer; |
| 1045 |
type Field = F; |
| 1046 |
|
| 1047 |
fn valid( |
| 1048 |
&self, |
| 1049 |
g: &mut Vec<Box<dyn Gadget<F>>>, |
| 1050 |
input: &[F], |
| 1051 |
joint_rand: &[F], |
| 1052 |
_num_shares: usize, |
| 1053 |
) -> Result<F, FlpError> { |
| 1054 |
let r = joint_rand[0]; |
| 1055 |
let mut res = F::zero(); |
| 1056 |
|
| 1057 |
// Check that `data[0]^3 == data[1]`. |
| 1058 |
let mut inp = [input[0], input[0]]; |
| 1059 |
inp[0] = g[0].call(&inp)?; |
| 1060 |
inp[0] = g[0].call(&inp)?; |
| 1061 |
let x3_diff = inp[0] - input[1]; |
| 1062 |
res += r * x3_diff; |
| 1063 |
|
| 1064 |
// Check that `data[0]` is in the correct range. |
| 1065 |
let x_checked = g[1].call(&[input[0]])?; |
| 1066 |
res += (r * r) * x_checked; |
| 1067 |
|
| 1068 |
Ok(res) |
| 1069 |
} |
| 1070 |
|
| 1071 |
fn input_len(&self) -> usize { |
| 1072 |
2 |
| 1073 |
} |
| 1074 |
|
| 1075 |
fn proof_len(&self) -> usize { |
| 1076 |
// First chunk |
| 1077 |
let mul = 2 /* gadget arity */ + 2 /* gadget degree */ * ( |
| 1078 |
(1 + 2_usize /* gadget calls */).next_power_of_two() - 1) + 1; |
| 1079 |
|
| 1080 |
// Second chunk |
| 1081 |
let poly = 1 /* gadget arity */ + 3 /* gadget degree */ * ( |
| 1082 |
(1 + 1_usize /* gadget calls */).next_power_of_two() - 1) + 1; |
| 1083 |
|
| 1084 |
mul + poly |
| 1085 |
} |
| 1086 |
|
| 1087 |
fn verifier_len(&self) -> usize { |
| 1088 |
// First chunk |
| 1089 |
let mul = 1 + 2 /* gadget arity */; |
| 1090 |
|
| 1091 |
// Second chunk |
| 1092 |
let poly = 1 + 1 /* gadget arity */; |
| 1093 |
|
| 1094 |
1 + mul + poly |
| 1095 |
} |
| 1096 |
|
| 1097 |
fn output_len(&self) -> usize { |
| 1098 |
self.input_len() |
| 1099 |
} |
| 1100 |
|
| 1101 |
fn joint_rand_len(&self) -> usize { |
| 1102 |
1 |
| 1103 |
} |
| 1104 |
|
| 1105 |
fn prove_rand_len(&self) -> usize { |
| 1106 |
3 |
| 1107 |
} |
| 1108 |
|
| 1109 |
fn query_rand_len(&self) -> usize { |
| 1110 |
2 |
| 1111 |
} |
| 1112 |
|
| 1113 |
fn gadget(&self) -> Vec<Box<dyn Gadget<F>>> { |
| 1114 |
vec![ |
| 1115 |
Box::new(Mul::new(2)), |
| 1116 |
Box::new(PolyEval::new(poly_range_check(2, 5), 1)), |
| 1117 |
] |
| 1118 |
} |
| 1119 |
|
| 1120 |
fn encode_measurement(&self, measurement: &F::Integer) -> Result<Vec<F>, FlpError> { |
| 1121 |
Ok(vec![ |
| 1122 |
F::from(*measurement), |
| 1123 |
F::from(*measurement).pow(F::Integer::try_from(3).unwrap()), |
| 1124 |
]) |
| 1125 |
} |
| 1126 |
|
| 1127 |
fn truncate(&self, input: Vec<F>) -> Result<Vec<F>, FlpError> { |
| 1128 |
Ok(input) |
| 1129 |
} |
| 1130 |
|
| 1131 |
fn decode_result( |
| 1132 |
&self, |
| 1133 |
_data: &[F], |
| 1134 |
_num_measurements: usize, |
| 1135 |
) -> Result<F::Integer, FlpError> { |
| 1136 |
panic!("not implemented"); |
| 1137 |
} |
| 1138 |
} |
| 1139 |
|
| 1140 |
// In https://github.com/divviup/libprio-rs/issues/254 an out-of-bounds bug was reported that |
| 1141 |
// gets triggered when the size of the buffer passed to `gadget.call_poly()` is larger than |
| 1142 |
// needed for computing the gadget polynomial. |
| 1143 |
#[test] |
| 1144 |
fn issue254() { |
| 1145 |
let typ: Issue254Type<Field128> = Issue254Type::new(); |
| 1146 |
let input = typ.encode_measurement(&0).unwrap(); |
| 1147 |
assert_eq!(input.len(), typ.input_len()); |
| 1148 |
let joint_rand = random_vector(typ.joint_rand_len()).unwrap(); |
| 1149 |
let prove_rand = random_vector(typ.prove_rand_len()).unwrap(); |
| 1150 |
let query_rand = random_vector(typ.query_rand_len()).unwrap(); |
| 1151 |
let proof = typ.prove(&input, &prove_rand, &joint_rand).unwrap(); |
| 1152 |
let verifier = typ |
| 1153 |
.query(&input, &proof, &query_rand, &joint_rand, 1) |
| 1154 |
.unwrap(); |
| 1155 |
assert_eq!(verifier.len(), typ.verifier_len()); |
| 1156 |
assert!(typ.decide(&verifier).unwrap()); |
| 1157 |
} |
| 1158 |
|
| 1159 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 1160 |
struct Issue254Type<F> { |
| 1161 |
num_gadget_calls: [usize; 2], |
| 1162 |
phantom: PhantomData<F>, |
| 1163 |
} |
| 1164 |
|
| 1165 |
impl<F> Issue254Type<F> { |
| 1166 |
fn new() -> Self { |
| 1167 |
Self { |
| 1168 |
// The bug is triggered when there are two gadgets, but it doesn't matter how many |
| 1169 |
// times the second gadget is called. |
| 1170 |
num_gadget_calls: [100, 0], |
| 1171 |
phantom: PhantomData, |
| 1172 |
} |
| 1173 |
} |
| 1174 |
} |
| 1175 |
|
| 1176 |
impl<F: FftFriendlyFieldElement> Type for Issue254Type<F> { |
| 1177 |
type Measurement = F::Integer; |
| 1178 |
type AggregateResult = F::Integer; |
| 1179 |
type Field = F; |
| 1180 |
|
| 1181 |
fn valid( |
| 1182 |
&self, |
| 1183 |
g: &mut Vec<Box<dyn Gadget<F>>>, |
| 1184 |
input: &[F], |
| 1185 |
_joint_rand: &[F], |
| 1186 |
_num_shares: usize, |
| 1187 |
) -> Result<F, FlpError> { |
| 1188 |
// This is a useless circuit, as it only accepts "0". Its purpose is to exercise the |
| 1189 |
// use of multiple gadgets, each of which is called an arbitrary number of times. |
| 1190 |
let mut res = F::zero(); |
| 1191 |
for _ in 0..self.num_gadget_calls[0] { |
| 1192 |
res += g[0].call(&[input[0]])?; |
| 1193 |
} |
| 1194 |
for _ in 0..self.num_gadget_calls[1] { |
| 1195 |
res += g[1].call(&[input[0]])?; |
| 1196 |
} |
| 1197 |
Ok(res) |
| 1198 |
} |
| 1199 |
|
| 1200 |
fn input_len(&self) -> usize { |
| 1201 |
1 |
| 1202 |
} |
| 1203 |
|
| 1204 |
fn proof_len(&self) -> usize { |
| 1205 |
// First chunk |
| 1206 |
let first = 1 /* gadget arity */ + 2 /* gadget degree */ * ( |
| 1207 |
(1 + self.num_gadget_calls[0]).next_power_of_two() - 1) + 1; |
| 1208 |
|
| 1209 |
// Second chunk |
| 1210 |
let second = 1 /* gadget arity */ + 2 /* gadget degree */ * ( |
| 1211 |
(1 + self.num_gadget_calls[1]).next_power_of_two() - 1) + 1; |
| 1212 |
|
| 1213 |
first + second |
| 1214 |
} |
| 1215 |
|
| 1216 |
fn verifier_len(&self) -> usize { |
| 1217 |
// First chunk |
| 1218 |
let first = 1 + 1 /* gadget arity */; |
| 1219 |
|
| 1220 |
// Second chunk |
| 1221 |
let second = 1 + 1 /* gadget arity */; |
| 1222 |
|
| 1223 |
1 + first + second |
| 1224 |
} |
| 1225 |
|
| 1226 |
fn output_len(&self) -> usize { |
| 1227 |
self.input_len() |
| 1228 |
} |
| 1229 |
|
| 1230 |
fn joint_rand_len(&self) -> usize { |
| 1231 |
0 |
| 1232 |
} |
| 1233 |
|
| 1234 |
fn prove_rand_len(&self) -> usize { |
| 1235 |
// First chunk |
| 1236 |
let first = 1; // gadget arity |
| 1237 |
|
| 1238 |
// Second chunk |
| 1239 |
let second = 1; // gadget arity |
| 1240 |
|
| 1241 |
first + second |
| 1242 |
} |
| 1243 |
|
| 1244 |
fn query_rand_len(&self) -> usize { |
| 1245 |
2 // number of gadgets |
| 1246 |
} |
| 1247 |
|
| 1248 |
fn gadget(&self) -> Vec<Box<dyn Gadget<F>>> { |
| 1249 |
let poly = poly_range_check(0, 2); // A polynomial with degree 2 |
| 1250 |
vec![ |
| 1251 |
Box::new(PolyEval::new(poly.clone(), self.num_gadget_calls[0])), |
| 1252 |
Box::new(PolyEval::new(poly, self.num_gadget_calls[1])), |
| 1253 |
] |
| 1254 |
} |
| 1255 |
|
| 1256 |
fn encode_measurement(&self, measurement: &F::Integer) -> Result<Vec<F>, FlpError> { |
| 1257 |
Ok(vec![F::from(*measurement)]) |
| 1258 |
} |
| 1259 |
|
| 1260 |
fn truncate(&self, input: Vec<F>) -> Result<Vec<F>, FlpError> { |
| 1261 |
Ok(input) |
| 1262 |
} |
| 1263 |
|
| 1264 |
fn decode_result( |
| 1265 |
&self, |
| 1266 |
_data: &[F], |
| 1267 |
_num_measurements: usize, |
| 1268 |
) -> Result<F::Integer, FlpError> { |
| 1269 |
panic!("not implemented"); |
| 1270 |
} |
| 1271 |
} |
| 1272 |
} |