monero_bulletproofs/original/
mod.rs

1use std_shims::{sync::LazyLock, vec::Vec};
2
3use rand_core::{RngCore, CryptoRng};
4
5use zeroize::Zeroize;
6
7use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, Scalar, EdwardsPoint};
8
9use monero_generators::{H as MONERO_H, Generators, COMMITMENT_BITS};
10use monero_primitives::{Commitment, INV_EIGHT, keccak256_to_scalar};
11use monero_io::CompressedPoint;
12
13use crate::{
14  core::{MAX_COMMITMENTS, multiexp},
15  scalar_vector::ScalarVector,
16  BulletproofsBatchVerifier,
17};
18
19pub(crate) mod inner_product;
20use inner_product::*;
21pub(crate) use inner_product::IpProof;
22
23include!(concat!(env!("OUT_DIR"), "/generators.rs"));
24
25#[derive(Clone, Debug)]
26pub(crate) struct AggregateRangeStatement<'a> {
27  commitments: &'a [EdwardsPoint],
28}
29
30#[derive(Clone, Debug)]
31pub(crate) struct AggregateRangeWitness {
32  commitments: Vec<Commitment>,
33}
34
35#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
36pub struct AggregateRangeProof {
37  pub(crate) A: CompressedPoint,
38  pub(crate) S: CompressedPoint,
39  pub(crate) T1: CompressedPoint,
40  pub(crate) T2: CompressedPoint,
41  pub(crate) tau_x: Scalar,
42  pub(crate) mu: Scalar,
43  pub(crate) t_hat: Scalar,
44  pub(crate) ip: IpProof,
45}
46
47impl<'a> AggregateRangeStatement<'a> {
48  pub(crate) fn new(commitments: &'a [EdwardsPoint]) -> Option<Self> {
49    if commitments.is_empty() || (commitments.len() > MAX_COMMITMENTS) {
50      None?;
51    }
52    Some(Self { commitments })
53  }
54}
55
56impl AggregateRangeWitness {
57  pub(crate) fn new(commitments: Vec<Commitment>) -> Option<Self> {
58    if commitments.is_empty() || (commitments.len() > MAX_COMMITMENTS) {
59      None?;
60    }
61    Some(Self { commitments })
62  }
63}
64
65impl<'a> AggregateRangeStatement<'a> {
66  fn initial_transcript(&self) -> (Scalar, Vec<EdwardsPoint>) {
67    let V = self.commitments.iter().map(|c| c * INV_EIGHT()).collect::<Vec<_>>();
68    (keccak256_to_scalar(V.iter().flat_map(|V| V.compress().to_bytes()).collect::<Vec<_>>()), V)
69  }
70
71  fn transcript_A_S(
72    transcript: Scalar,
73    A: CompressedPoint,
74    S: CompressedPoint,
75  ) -> (Scalar, Scalar) {
76    let mut buf = Vec::with_capacity(96);
77    buf.extend(transcript.to_bytes());
78    buf.extend_from_slice(A.as_bytes());
79    buf.extend_from_slice(S.as_bytes());
80    let y = keccak256_to_scalar(buf);
81    let z = keccak256_to_scalar(y.to_bytes());
82    (y, z)
83  }
84
85  fn transcript_T12(transcript: Scalar, T1: CompressedPoint, T2: CompressedPoint) -> Scalar {
86    let mut buf = Vec::with_capacity(128);
87    buf.extend_from_slice(transcript.as_bytes());
88    buf.extend_from_slice(transcript.as_bytes());
89    buf.extend_from_slice(T1.as_bytes());
90    buf.extend_from_slice(T2.as_bytes());
91    keccak256_to_scalar(buf)
92  }
93
94  fn transcript_tau_x_mu_t_hat(
95    transcript: Scalar,
96    tau_x: Scalar,
97    mu: Scalar,
98    t_hat: Scalar,
99  ) -> Scalar {
100    let mut buf = Vec::with_capacity(128);
101    buf.extend(transcript.to_bytes());
102    buf.extend(transcript.to_bytes());
103    buf.extend(tau_x.to_bytes());
104    buf.extend(mu.to_bytes());
105    buf.extend(t_hat.to_bytes());
106    keccak256_to_scalar(buf)
107  }
108
109  #[allow(clippy::needless_pass_by_value)]
110  pub(crate) fn prove(
111    self,
112    rng: &mut (impl RngCore + CryptoRng),
113    witness: AggregateRangeWitness,
114  ) -> Option<AggregateRangeProof> {
115    if self.commitments != witness.commitments.iter().map(Commitment::calculate).collect::<Vec<_>>()
116    {
117      None?
118    };
119
120    let generators = &GENERATORS;
121
122    let (mut transcript, _) = self.initial_transcript();
123
124    // Find out the padded amount of commitments
125    let mut padded_pow_of_2 = 1;
126    while padded_pow_of_2 < witness.commitments.len() {
127      padded_pow_of_2 <<= 1;
128    }
129
130    let mut aL = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
131    for (i, commitment) in witness.commitments.iter().enumerate() {
132      let mut amount = commitment.amount;
133      for j in 0 .. COMMITMENT_BITS {
134        aL[(i * COMMITMENT_BITS) + j] = Scalar::from(amount & 1);
135        amount >>= 1;
136      }
137    }
138    let aR = aL.clone() - Scalar::ONE;
139
140    let alpha = Scalar::random(&mut *rng);
141
142    let A = CompressedPoint::from(
143      {
144        let mut terms = Vec::with_capacity(1 + (2 * aL.len()));
145        terms.push((alpha, ED25519_BASEPOINT_POINT));
146        for (aL, G) in aL.0.iter().zip(&generators.G) {
147          terms.push((*aL, *G));
148        }
149        for (aR, H) in aR.0.iter().zip(&generators.H) {
150          terms.push((*aR, *H));
151        }
152        let res = multiexp(&terms) * INV_EIGHT();
153        terms.zeroize();
154        res
155      }
156      .compress(),
157    );
158
159    let mut sL = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
160    let mut sR = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
161    for i in 0 .. (padded_pow_of_2 * COMMITMENT_BITS) {
162      sL[i] = Scalar::random(&mut *rng);
163      sR[i] = Scalar::random(&mut *rng);
164    }
165    let rho = Scalar::random(&mut *rng);
166
167    let S = CompressedPoint::from(
168      {
169        let mut terms = Vec::with_capacity(1 + (2 * sL.len()));
170        terms.push((rho, ED25519_BASEPOINT_POINT));
171        for (sL, G) in sL.0.iter().zip(&generators.G) {
172          terms.push((*sL, *G));
173        }
174        for (sR, H) in sR.0.iter().zip(&generators.H) {
175          terms.push((*sR, *H));
176        }
177        let res = multiexp(&terms) * INV_EIGHT();
178        terms.zeroize();
179        res
180      }
181      .compress(),
182    );
183
184    let (y, z) = Self::transcript_A_S(transcript, A, S);
185    transcript = z;
186    let z = ScalarVector::powers(z, 3 + padded_pow_of_2);
187
188    let twos = ScalarVector::powers(Scalar::from(2u8), COMMITMENT_BITS);
189
190    let l = [aL - z[1], sL];
191    let y_pow_n = ScalarVector::powers(y, aR.len());
192    let mut r = [((aR + z[1]) * &y_pow_n), sR * &y_pow_n];
193    {
194      for j in 0 .. padded_pow_of_2 {
195        for i in 0 .. COMMITMENT_BITS {
196          r[0].0[(j * COMMITMENT_BITS) + i] += z[2 + j] * twos[i];
197        }
198      }
199    }
200    let t1 = (l[0].clone().inner_product(&r[1])) + (r[0].clone().inner_product(&l[1]));
201    let t2 = l[1].clone().inner_product(&r[1]);
202
203    let tau_1 = Scalar::random(&mut *rng);
204    let T1 = CompressedPoint::from(
205      {
206        let mut T1_terms = [(t1, *MONERO_H), (tau_1, ED25519_BASEPOINT_POINT)];
207        for term in &mut T1_terms {
208          term.0 *= INV_EIGHT();
209        }
210        let T1 = multiexp(&T1_terms);
211        T1_terms.zeroize();
212        T1
213      }
214      .compress(),
215    );
216    let tau_2 = Scalar::random(&mut *rng);
217    let T2 = CompressedPoint::from(
218      {
219        let mut T2_terms = [(t2, *MONERO_H), (tau_2, ED25519_BASEPOINT_POINT)];
220        for term in &mut T2_terms {
221          term.0 *= INV_EIGHT();
222        }
223        let T2 = multiexp(&T2_terms);
224        T2_terms.zeroize();
225        T2
226      }
227      .compress(),
228    );
229
230    transcript = Self::transcript_T12(transcript, T1, T2);
231    let x = transcript;
232
233    let [l0, l1] = l;
234    let l = l0 + &(l1 * x);
235    let [r0, r1] = r;
236    let r = r0 + &(r1 * x);
237    let t_hat = l.clone().inner_product(&r);
238    let mut tau_x = ((tau_2 * x) + tau_1) * x;
239    {
240      for (i, commitment) in witness.commitments.iter().enumerate() {
241        tau_x += z[2 + i] * commitment.mask;
242      }
243    }
244    let mu = alpha + (rho * x);
245
246    let y_inv_pow_n = ScalarVector::powers(y.invert(), l.len());
247
248    transcript = Self::transcript_tau_x_mu_t_hat(transcript, tau_x, mu, t_hat);
249    let x_ip = transcript;
250
251    let ip = IpStatement::new_without_P_transcript(y_inv_pow_n, x_ip)
252      .prove(
253        transcript,
254        IpWitness::new(l, r).expect("Bulletproofs::Original created an invalid IpWitness"),
255      )
256      .expect("Bulletproofs::Original failed to prove the inner-product");
257
258    let res = AggregateRangeProof { A, S, T1, T2, tau_x, mu, t_hat, ip };
259    #[cfg(debug_assertions)]
260    {
261      let mut verifier = BulletproofsBatchVerifier::default();
262      debug_assert!(self.verify(rng, &mut verifier, res.clone()));
263      debug_assert!(verifier.verify());
264    }
265    Some(res)
266  }
267
268  #[must_use]
269  pub(crate) fn verify(
270    self,
271    rng: &mut (impl RngCore + CryptoRng),
272    verifier: &mut BulletproofsBatchVerifier,
273    AggregateRangeProof { A, S, T1, T2, tau_x, mu, t_hat, ip }: AggregateRangeProof,
274  ) -> bool {
275    let mut padded_pow_of_2 = 1;
276    while padded_pow_of_2 < self.commitments.len() {
277      padded_pow_of_2 <<= 1;
278    }
279    let ip_rows = padded_pow_of_2 * COMMITMENT_BITS;
280
281    while verifier.0.g_bold.len() < ip_rows {
282      verifier.0.g_bold.push(Scalar::ZERO);
283      verifier.0.h_bold.push(Scalar::ZERO);
284    }
285
286    let (mut transcript, mut commitments) = self.initial_transcript();
287    for commitment in &mut commitments {
288      *commitment = commitment.mul_by_cofactor();
289    }
290
291    let (y, z) = Self::transcript_A_S(transcript, A, S);
292    transcript = z;
293    let z = ScalarVector::powers(z, 3 + padded_pow_of_2);
294    transcript = Self::transcript_T12(transcript, T1, T2);
295    let x = transcript;
296    transcript = Self::transcript_tau_x_mu_t_hat(transcript, tau_x, mu, t_hat);
297    let x_ip = transcript;
298
299    let decomp_mul_cofactor =
300      |p| CompressedPoint::decompress(&p).map(|p| EdwardsPoint::mul_by_cofactor(&p));
301
302    let (Some(A), Some(S), Some(T1), Some(T2)) = (
303      decomp_mul_cofactor(A),
304      decomp_mul_cofactor(S),
305      decomp_mul_cofactor(T1),
306      decomp_mul_cofactor(T2),
307    ) else {
308      return false;
309    };
310
311    let y_pow_n = ScalarVector::powers(y, ip_rows);
312    let y_inv_pow_n = ScalarVector::powers(y.invert(), ip_rows);
313
314    let twos = ScalarVector::powers(Scalar::from(2u8), COMMITMENT_BITS);
315
316    // 65
317    {
318      let weight = Scalar::random(&mut *rng);
319      verifier.0.h += weight * t_hat;
320      verifier.0.g += weight * tau_x;
321
322      // Now that we've accumulated the lhs, negate the weight and accumulate the rhs
323      // These will now sum to 0 if equal
324      let weight = -weight;
325
326      verifier.0.h += weight * (z[1] - (z[2])) * y_pow_n.sum();
327
328      for (i, commitment) in commitments.iter().enumerate() {
329        verifier.0.other.push((weight * z[2 + i], *commitment));
330      }
331
332      for i in 0 .. padded_pow_of_2 {
333        verifier.0.h -= weight * z[3 + i] * twos.clone().sum();
334      }
335      verifier.0.other.push((weight * x, T1));
336      verifier.0.other.push((weight * (x * x), T2));
337    }
338
339    let ip_weight = Scalar::random(&mut *rng);
340
341    // 66
342    verifier.0.other.push((ip_weight, A));
343    verifier.0.other.push((ip_weight * x, S));
344    // We can replace these with a g_sum, h_sum scalar in the batch verifier
345    // It'd trade `2 * ip_rows` scalar additions (per proof) for one scalar addition and an
346    // additional term in the MSM
347    let ip_z = ip_weight * z[1];
348    for i in 0 .. ip_rows {
349      verifier.0.h_bold[i] += ip_z;
350    }
351    let neg_ip_z = -ip_z;
352    for i in 0 .. ip_rows {
353      verifier.0.g_bold[i] += neg_ip_z;
354    }
355    {
356      for j in 0 .. padded_pow_of_2 {
357        for i in 0 .. COMMITMENT_BITS {
358          let full_i = (j * COMMITMENT_BITS) + i;
359          verifier.0.h_bold[full_i] += ip_weight * y_inv_pow_n[full_i] * z[2 + j] * twos[i];
360        }
361      }
362    }
363    verifier.0.h += ip_weight * x_ip * t_hat;
364
365    // 67, 68
366    verifier.0.g += ip_weight * -mu;
367    let res = IpStatement::new_without_P_transcript(y_inv_pow_n, x_ip)
368      .verify(verifier, ip_rows, transcript, ip_weight, ip);
369    res.is_ok()
370  }
371}