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
use std_shims::{sync::LazyLock, vec::Vec};

use rand_core::{RngCore, CryptoRng};

use zeroize::Zeroize;

use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, Scalar, EdwardsPoint};

use monero_generators::{H as MONERO_H, Generators, MAX_COMMITMENTS, COMMITMENT_BITS};
use monero_primitives::{Commitment, INV_EIGHT, keccak256_to_scalar};
use crate::{core::multiexp, scalar_vector::ScalarVector, BulletproofsBatchVerifier};

pub(crate) mod inner_product;
use inner_product::*;
pub(crate) use inner_product::IpProof;

include!(concat!(env!("OUT_DIR"), "/generators.rs"));

#[derive(Clone, Debug)]
pub(crate) struct AggregateRangeStatement<'a> {
  commitments: &'a [EdwardsPoint],
}

#[derive(Clone, Debug)]
pub(crate) struct AggregateRangeWitness {
  commitments: Vec<Commitment>,
}

#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
pub struct AggregateRangeProof {
  pub(crate) A: EdwardsPoint,
  pub(crate) S: EdwardsPoint,
  pub(crate) T1: EdwardsPoint,
  pub(crate) T2: EdwardsPoint,
  pub(crate) tau_x: Scalar,
  pub(crate) mu: Scalar,
  pub(crate) t_hat: Scalar,
  pub(crate) ip: IpProof,
}

impl<'a> AggregateRangeStatement<'a> {
  pub(crate) fn new(commitments: &'a [EdwardsPoint]) -> Option<Self> {
    if commitments.is_empty() || (commitments.len() > MAX_COMMITMENTS) {
      None?;
    }
    Some(Self { commitments })
  }
}

impl AggregateRangeWitness {
  pub(crate) fn new(commitments: Vec<Commitment>) -> Option<Self> {
    if commitments.is_empty() || (commitments.len() > MAX_COMMITMENTS) {
      None?;
    }
    Some(Self { commitments })
  }
}

impl<'a> AggregateRangeStatement<'a> {
  fn initial_transcript(&self) -> (Scalar, Vec<EdwardsPoint>) {
    let V = self.commitments.iter().map(|c| c * INV_EIGHT()).collect::<Vec<_>>();
    (keccak256_to_scalar(V.iter().flat_map(|V| V.compress().to_bytes()).collect::<Vec<_>>()), V)
  }

  fn transcript_A_S(transcript: Scalar, A: EdwardsPoint, S: EdwardsPoint) -> (Scalar, Scalar) {
    let mut buf = Vec::with_capacity(96);
    buf.extend(transcript.to_bytes());
    buf.extend(A.compress().to_bytes());
    buf.extend(S.compress().to_bytes());
    let y = keccak256_to_scalar(buf);
    let z = keccak256_to_scalar(y.to_bytes());
    (y, z)
  }

  fn transcript_T12(transcript: Scalar, T1: EdwardsPoint, T2: EdwardsPoint) -> Scalar {
    let mut buf = Vec::with_capacity(128);
    buf.extend(transcript.to_bytes());
    buf.extend(transcript.to_bytes());
    buf.extend(T1.compress().to_bytes());
    buf.extend(T2.compress().to_bytes());
    keccak256_to_scalar(buf)
  }

  fn transcript_tau_x_mu_t_hat(
    transcript: Scalar,
    tau_x: Scalar,
    mu: Scalar,
    t_hat: Scalar,
  ) -> Scalar {
    let mut buf = Vec::with_capacity(128);
    buf.extend(transcript.to_bytes());
    buf.extend(transcript.to_bytes());
    buf.extend(tau_x.to_bytes());
    buf.extend(mu.to_bytes());
    buf.extend(t_hat.to_bytes());
    keccak256_to_scalar(buf)
  }

  #[allow(clippy::needless_pass_by_value)]
  pub(crate) fn prove(
    self,
    rng: &mut (impl RngCore + CryptoRng),
    witness: AggregateRangeWitness,
  ) -> Option<AggregateRangeProof> {
    if self.commitments != witness.commitments.iter().map(Commitment::calculate).collect::<Vec<_>>()
    {
      None?
    };

    let generators = &GENERATORS;

    let (mut transcript, _) = self.initial_transcript();

    // Find out the padded amount of commitments
    let mut padded_pow_of_2 = 1;
    while padded_pow_of_2 < witness.commitments.len() {
      padded_pow_of_2 <<= 1;
    }

    let mut aL = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
    for (i, commitment) in witness.commitments.iter().enumerate() {
      let mut amount = commitment.amount;
      for j in 0 .. COMMITMENT_BITS {
        aL[(i * COMMITMENT_BITS) + j] = Scalar::from(amount & 1);
        amount >>= 1;
      }
    }
    let aR = aL.clone() - Scalar::ONE;

    let alpha = Scalar::random(&mut *rng);

    let A = {
      let mut terms = Vec::with_capacity(1 + (2 * aL.len()));
      terms.push((alpha, ED25519_BASEPOINT_POINT));
      for (aL, G) in aL.0.iter().zip(&generators.G) {
        terms.push((*aL, *G));
      }
      for (aR, H) in aR.0.iter().zip(&generators.H) {
        terms.push((*aR, *H));
      }
      let res = multiexp(&terms) * INV_EIGHT();
      terms.zeroize();
      res
    };

    let mut sL = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
    let mut sR = ScalarVector::new(padded_pow_of_2 * COMMITMENT_BITS);
    for i in 0 .. (padded_pow_of_2 * COMMITMENT_BITS) {
      sL[i] = Scalar::random(&mut *rng);
      sR[i] = Scalar::random(&mut *rng);
    }
    let rho = Scalar::random(&mut *rng);

    let S = {
      let mut terms = Vec::with_capacity(1 + (2 * sL.len()));
      terms.push((rho, ED25519_BASEPOINT_POINT));
      for (sL, G) in sL.0.iter().zip(&generators.G) {
        terms.push((*sL, *G));
      }
      for (sR, H) in sR.0.iter().zip(&generators.H) {
        terms.push((*sR, *H));
      }
      let res = multiexp(&terms) * INV_EIGHT();
      terms.zeroize();
      res
    };

    let (y, z) = Self::transcript_A_S(transcript, A, S);
    transcript = z;
    let z = ScalarVector::powers(z, 3 + padded_pow_of_2);

    let twos = ScalarVector::powers(Scalar::from(2u8), COMMITMENT_BITS);

    let l = [aL - z[1], sL];
    let y_pow_n = ScalarVector::powers(y, aR.len());
    let mut r = [((aR + z[1]) * &y_pow_n), sR * &y_pow_n];
    {
      for j in 0 .. padded_pow_of_2 {
        for i in 0 .. COMMITMENT_BITS {
          r[0].0[(j * COMMITMENT_BITS) + i] += z[2 + j] * twos[i];
        }
      }
    }
    let t1 = (l[0].clone().inner_product(&r[1])) + (r[0].clone().inner_product(&l[1]));
    let t2 = l[1].clone().inner_product(&r[1]);

    let tau_1 = Scalar::random(&mut *rng);
    let T1 = {
      let mut T1_terms = [(t1, *MONERO_H), (tau_1, ED25519_BASEPOINT_POINT)];
      for term in &mut T1_terms {
        term.0 *= INV_EIGHT();
      }
      let T1 = multiexp(&T1_terms);
      T1_terms.zeroize();
      T1
    };
    let tau_2 = Scalar::random(&mut *rng);
    let T2 = {
      let mut T2_terms = [(t2, *MONERO_H), (tau_2, ED25519_BASEPOINT_POINT)];
      for term in &mut T2_terms {
        term.0 *= INV_EIGHT();
      }
      let T2 = multiexp(&T2_terms);
      T2_terms.zeroize();
      T2
    };

    transcript = Self::transcript_T12(transcript, T1, T2);
    let x = transcript;

    let [l0, l1] = l;
    let l = l0 + &(l1 * x);
    let [r0, r1] = r;
    let r = r0 + &(r1 * x);
    let t_hat = l.clone().inner_product(&r);
    let mut tau_x = ((tau_2 * x) + tau_1) * x;
    {
      for (i, commitment) in witness.commitments.iter().enumerate() {
        tau_x += z[2 + i] * commitment.mask;
      }
    }
    let mu = alpha + (rho * x);

    let y_inv_pow_n = ScalarVector::powers(y.invert(), l.len());

    transcript = Self::transcript_tau_x_mu_t_hat(transcript, tau_x, mu, t_hat);
    let x_ip = transcript;

    let ip = IpStatement::new_without_P_transcript(y_inv_pow_n, x_ip)
      .prove(transcript, IpWitness::new(l, r).unwrap())
      .unwrap();

    let res = AggregateRangeProof { A, S, T1, T2, tau_x, mu, t_hat, ip };
    #[cfg(debug_assertions)]
    {
      let mut verifier = BulletproofsBatchVerifier::default();
      debug_assert!(self.verify(rng, &mut verifier, res.clone()));
      debug_assert!(verifier.verify());
    }
    Some(res)
  }

  #[must_use]
  pub(crate) fn verify(
    self,
    rng: &mut (impl RngCore + CryptoRng),
    verifier: &mut BulletproofsBatchVerifier,
    mut proof: AggregateRangeProof,
  ) -> bool {
    let mut padded_pow_of_2 = 1;
    while padded_pow_of_2 < self.commitments.len() {
      padded_pow_of_2 <<= 1;
    }
    let ip_rows = padded_pow_of_2 * COMMITMENT_BITS;

    while verifier.0.g_bold.len() < ip_rows {
      verifier.0.g_bold.push(Scalar::ZERO);
      verifier.0.h_bold.push(Scalar::ZERO);
    }

    let (mut transcript, mut commitments) = self.initial_transcript();
    for commitment in &mut commitments {
      *commitment = commitment.mul_by_cofactor();
    }

    let (y, z) = Self::transcript_A_S(transcript, proof.A, proof.S);
    transcript = z;
    let z = ScalarVector::powers(z, 3 + padded_pow_of_2);
    transcript = Self::transcript_T12(transcript, proof.T1, proof.T2);
    let x = transcript;
    transcript = Self::transcript_tau_x_mu_t_hat(transcript, proof.tau_x, proof.mu, proof.t_hat);
    let x_ip = transcript;

    proof.A = proof.A.mul_by_cofactor();
    proof.S = proof.S.mul_by_cofactor();
    proof.T1 = proof.T1.mul_by_cofactor();
    proof.T2 = proof.T2.mul_by_cofactor();

    let y_pow_n = ScalarVector::powers(y, ip_rows);
    let y_inv_pow_n = ScalarVector::powers(y.invert(), ip_rows);

    let twos = ScalarVector::powers(Scalar::from(2u8), COMMITMENT_BITS);

    // 65
    {
      let weight = Scalar::random(&mut *rng);
      verifier.0.h += weight * proof.t_hat;
      verifier.0.g += weight * proof.tau_x;

      // Now that we've accumulated the lhs, negate the weight and accumulate the rhs
      // These will now sum to 0 if equal
      let weight = -weight;

      verifier.0.h += weight * (z[1] - (z[2])) * y_pow_n.sum();

      for (i, commitment) in commitments.iter().enumerate() {
        verifier.0.other.push((weight * z[2 + i], *commitment));
      }

      for i in 0 .. padded_pow_of_2 {
        verifier.0.h -= weight * z[3 + i] * twos.clone().sum();
      }
      verifier.0.other.push((weight * x, proof.T1));
      verifier.0.other.push((weight * (x * x), proof.T2));
    }

    let ip_weight = Scalar::random(&mut *rng);

    // 66
    verifier.0.other.push((ip_weight, proof.A));
    verifier.0.other.push((ip_weight * x, proof.S));
    // We can replace these with a g_sum, h_sum scalar in the batch verifier
    // It'd trade `2 * ip_rows` scalar additions (per proof) for one scalar addition and an
    // additional term in the MSM
    let ip_z = ip_weight * z[1];
    for i in 0 .. ip_rows {
      verifier.0.h_bold[i] += ip_z;
    }
    let neg_ip_z = -ip_z;
    for i in 0 .. ip_rows {
      verifier.0.g_bold[i] += neg_ip_z;
    }
    {
      for j in 0 .. padded_pow_of_2 {
        for i in 0 .. COMMITMENT_BITS {
          let full_i = (j * COMMITMENT_BITS) + i;
          verifier.0.h_bold[full_i] += ip_weight * y_inv_pow_n[full_i] * z[2 + j] * twos[i];
        }
      }
    }
    verifier.0.h += ip_weight * x_ip * proof.t_hat;

    // 67, 68
    verifier.0.g += ip_weight * -proof.mu;
    let res = IpStatement::new_without_P_transcript(y_inv_pow_n, x_ip)
      .verify(verifier, ip_rows, transcript, ip_weight, proof.ip);
    res.is_ok()
  }
}