arnaucube
arnaucube/testudoPublic Self-hosted repository
testudo/src/nizk/bullet.rs
src/nizk/bullet.rsRaw
  1//! This module is an adaptation of code from the bulletproofs crate.
  2//! See NOTICE.md for more details
  3#![allow(non_snake_case)]
  4#![allow(clippy::type_complexity)]
  5#![allow(clippy::too_many_arguments)]
  6use crate::math::Math;
  7use crate::poseidon_transcript::PoseidonTranscript;
  8
  9use super::super::errors::ProofVerifyError;
 10use super::super::group::{
 11  CompressGroupElement, CompressedGroup, DecompressGroupElement, GroupElement,
 12  VartimeMultiscalarMul,
 13};
 14use super::super::math::Math;
 15use super::super::scalar::Scalar;
 16use super::super::transcript::ProofTranscript;
 17use ark_ff::{fields, Field};
 18use ark_serialize::*;
 19use ark_std::{One, Zero};
 20use core::iter;
 21use merlin::Transcript;
 22use std::ops::MulAssign;
 23
 24#[derive(Debug, CanonicalSerialize, CanonicalDeserialize)]
 25pub struct BulletReductionProof {
 26  L_vec: Vec<CompressedGroup>,
 27  R_vec: Vec<CompressedGroup>,
 28}
 29
 30impl BulletReductionProof {
 31  /// Create an inner-product proof.
 32  ///
 33  /// The proof is created with respect to the bases \\(G\\).
 34  ///
 35  /// The `transcript` is passed in as a parameter so that the
 36  /// challenges depend on the *entire* transcript (including parent
 37  /// protocols).
 38  ///
 39  /// The lengths of the vectors must all be the same, and must all be
 40  /// either 0 or a power of 2.
 41  pub fn prove(
 42    transcript: &mut PoseidonTranscript,
 43    Q: &GroupElement,
 44    G_vec: &[GroupElement],
 45    H: &GroupElement,
 46    a_vec: &[Scalar],
 47    b_vec: &[Scalar],
 48    blind: &Scalar,
 49    blinds_vec: &[(Scalar, Scalar)],
 50  ) -> (
 51    BulletReductionProof,
 52    GroupElement,
 53    Scalar,
 54    Scalar,
 55    GroupElement,
 56    Scalar,
 57  ) {
 58    // Create slices G, H, a, b backed by their respective
 59    // vectors.  This lets us reslice as we compress the lengths
 60    // of the vectors in the main loop below.
 61    let mut G = &mut G_vec.to_owned()[..];
 62    let mut a = &mut a_vec.to_owned()[..];
 63    let mut b = &mut b_vec.to_owned()[..];
 64
 65    // All of the input vectors must have a length that is a power of two.
 66    let mut n = G.len();
 67    assert!(n.is_power_of_two());
 68    let lg_n = n.log_2();
 69
 70    // All of the input vectors must have the same length.
 71    assert_eq!(G.len(), n);
 72    assert_eq!(a.len(), n);
 73    assert_eq!(b.len(), n);
 74    assert_eq!(blinds_vec.len(), 2 * lg_n);
 75
 76    let mut L_vec = Vec::with_capacity(lg_n);
 77    let mut R_vec = Vec::with_capacity(lg_n);
 78    let mut blinds_iter = blinds_vec.iter();
 79    let mut blind_fin = *blind;
 80
 81    while n != 1 {
 82      n /= 2;
 83      let (a_L, a_R) = a.split_at_mut(n);
 84      let (b_L, b_R) = b.split_at_mut(n);
 85      let (G_L, G_R) = G.split_at_mut(n);
 86
 87      let c_L = inner_product(a_L, b_R);
 88      let c_R = inner_product(a_R, b_L);
 89
 90      let (blind_L, blind_R) = blinds_iter.next().unwrap();
 91
 92      let L = GroupElement::vartime_multiscalar_mul(
 93        a_L
 94          .iter()
 95          .chain(iter::once(&c_L))
 96          .chain(iter::once(blind_L))
 97          .map(|s| *s)
 98          .collect::<Vec<Scalar>>()
 99          .as_slice(),
100        G_R
101          .iter()
102          .chain(iter::once(Q))
103          .chain(iter::once(H))
104          .map(|p| *p)
105          .collect::<Vec<GroupElement>>()
106          .as_slice(),
107      );
108
109      let R = GroupElement::vartime_multiscalar_mul(
110        a_R
111          .iter()
112          .chain(iter::once(&c_R))
113          .chain(iter::once(blind_R))
114          .map(|s| *s)
115          .collect::<Vec<Scalar>>()
116          .as_slice(),
117        G_L
118          .iter()
119          .chain(iter::once(Q))
120          .chain(iter::once(H))
121          .map(|p| *p)
122          .collect::<Vec<GroupElement>>()
123          .as_slice(),
124      );
125
126      transcript.append_point(&L.compress());
127      transcript.append_point(&R.compress());
128
129      let u = transcript.challenge_scalar();
130      let u_inv = u.inverse().unwrap();
131
132      for i in 0..n {
133        a_L[i] = a_L[i] * u + u_inv * a_R[i];
134        b_L[i] = b_L[i] * u_inv + u * b_R[i];
135        G_L[i] = GroupElement::vartime_multiscalar_mul(&[u_inv, u], &[G_L[i], G_R[i]]);
136      }
137
138      blind_fin = blind_fin + u * u * blind_L + u_inv * u_inv * blind_R;
139
140      L_vec.push(L.compress());
141      R_vec.push(R.compress());
142
143      a = a_L;
144      b = b_L;
145      G = G_L;
146    }
147
148    let Gamma_hat =
149      GroupElement::vartime_multiscalar_mul(&[a[0], a[0] * b[0], blind_fin], &[G[0], *Q, *H]);
150
151    (
152      BulletReductionProof { L_vec, R_vec },
153      Gamma_hat,
154      a[0],
155      b[0],
156      G[0],
157      blind_fin,
158    )
159  }
160
161  /// Computes three vectors of verification scalars \\([u\_{i}^{2}]\\), \\([u\_{i}^{-2}]\\) and \\([s\_{i}]\\) for combined multiscalar multiplication
162  /// in a parent protocol. See [inner product protocol notes](index.html#verification-equation) for details.
163  /// The verifier must provide the input length \\(n\\) explicitly to avoid unbounded allocation within the inner product proof.
164  fn verification_scalars(
165    &self,
166    n: usize,
167    transcript: &mut PoseidonTranscript,
168  ) -> Result<(Vec<Scalar>, Vec<Scalar>, Vec<Scalar>), ProofVerifyError> {
169    let lg_n = self.L_vec.len();
170    if lg_n >= 32 {
171      // 4 billion multiplications should be enough for anyone
172      // and this check prevents overflow in 1<<lg_n below.
173      return Err(ProofVerifyError::InternalError);
174    }
175    if n != (1 << lg_n) {
176      return Err(ProofVerifyError::InternalError);
177    }
178
179    // 1. Recompute x_k,...,x_1 based on the proof transcript
180    let mut challenges = Vec::with_capacity(lg_n);
181    for (L, R) in self.L_vec.iter().zip(self.R_vec.iter()) {
182      transcript.append_point(L);
183      transcript.append_point(R);
184      challenges.push(transcript.challenge_scalar());
185    }
186
187    // 2. Compute 1/(u_k...u_1) and 1/u_k, ..., 1/u_1
188    let mut challenges_inv: Vec<Scalar> = challenges.clone();
189
190    ark_ff::fields::batch_inversion(&mut challenges_inv);
191    let mut allinv: Scalar = Scalar::one();
192    for c in challenges.iter().filter(|s| !s.is_zero()) {
193      allinv.mul_assign(c);
194    }
195    allinv = allinv.inverse().unwrap();
196
197    // 3. Compute u_i^2 and (1/u_i)^2
198    for i in 0..lg_n {
199      challenges[i] = challenges[i].square();
200      challenges_inv[i] = challenges_inv[i].square();
201    }
202    let challenges_sq = challenges;
203    let challenges_inv_sq = challenges_inv;
204
205    // 4. Compute s values inductively.
206    let mut s = Vec::with_capacity(n);
207    s.push(allinv);
208    for i in 1..n {
209      let lg_i = (32 - 1 - (i as u32).leading_zeros()) as usize;
210      let k = 1 << lg_i;
211      // The challenges are stored in "creation order" as [u_k,...,u_1],
212      // so u_{lg(i)+1} = is indexed by (lg_n-1) - lg_i
213      let u_lg_i_sq = challenges_sq[(lg_n - 1) - lg_i];
214      s.push(s[i - k] * u_lg_i_sq);
215    }
216
217    Ok((challenges_sq, challenges_inv_sq, s))
218  }
219
220  /// This method is for testing that proof generation work,
221  /// but for efficiency the actual protocols would use `verification_scalars`
222  /// method to combine inner product verification with other checks
223  /// in a single multiscalar multiplication.
224  pub fn verify(
225    &self,
226    n: usize,
227    a: &[Scalar],
228    transcript: &mut PoseidonTranscript,
229    Gamma: &GroupElement,
230    G: &[GroupElement],
231  ) -> Result<(GroupElement, GroupElement, Scalar), ProofVerifyError> {
232    let (u_sq, u_inv_sq, s) = self.verification_scalars(n, transcript)?;
233
234    let Ls = self
235      .L_vec
236      .iter()
237      .map(|p| GroupElement::decompress(p).ok_or(ProofVerifyError::InternalError))
238      .collect::<Result<Vec<_>, _>>()?;
239
240    let Rs = self
241      .R_vec
242      .iter()
243      .map(|p| GroupElement::decompress(p).ok_or(ProofVerifyError::InternalError))
244      .collect::<Result<Vec<_>, _>>()?;
245
246    let G_hat = GroupElement::vartime_multiscalar_mul(s.as_slice(), G);
247    let a_hat = inner_product(a, &s);
248
249    let Gamma_hat = GroupElement::vartime_multiscalar_mul(
250      u_sq
251        .iter()
252        .chain(u_inv_sq.iter())
253        .chain(iter::once(&Scalar::one()))
254        .map(|s| *s)
255        .collect::<Vec<Scalar>>()
256        .as_slice(),
257      Ls.iter()
258        .chain(Rs.iter())
259        .chain(iter::once(Gamma))
260        .map(|p| *p)
261        .collect::<Vec<GroupElement>>()
262        .as_slice(),
263    );
264
265    Ok((G_hat, Gamma_hat, a_hat))
266  }
267}
268
269/// Computes an inner product of two vectors
270/// \\[
271///    {\langle {\mathbf{a}}, {\mathbf{b}} \rangle} = \sum\_{i=0}^{n-1} a\_i \cdot b\_i.
272/// \\]
273/// Panics if the lengths of \\(\mathbf{a}\\) and \\(\mathbf{b}\\) are not equal.
274pub fn inner_product(a: &[Scalar], b: &[Scalar]) -> Scalar {
275  assert!(
276    a.len() == b.len(),
277    "inner_product(a,b): lengths of vectors do not match"
278  );
279  let mut out = Scalar::zero();
280  for i in 0..a.len() {
281    out += a[i] * b[i];
282  }
283  out
284}