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