monero_bulletproofs_mirror/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![doc = include_str!("../README.md")]
3#![deny(missing_docs)]
4#![cfg_attr(not(feature = "std"), no_std)]
5#![allow(non_snake_case)]
6
7use std_shims::{
8  vec,
9  vec::Vec,
10  io::{self, Read, Write},
11};
12
13use rand_core::{RngCore, CryptoRng};
14use zeroize::Zeroizing;
15
16use curve25519_dalek::edwards::EdwardsPoint;
17
18use monero_io::*;
19pub use monero_generators::MAX_COMMITMENTS;
20use monero_primitives::Commitment;
21
22pub(crate) mod scalar_vector;
23pub(crate) mod point_vector;
24
25pub(crate) mod core;
26use crate::core::LOG_COMMITMENT_BITS;
27
28pub(crate) mod batch_verifier;
29use batch_verifier::{BulletproofsBatchVerifier, BulletproofsPlusBatchVerifier};
30pub use batch_verifier::BatchVerifier;
31
32pub(crate) mod original;
33use crate::original::{
34  IpProof, AggregateRangeStatement as OriginalStatement, AggregateRangeWitness as OriginalWitness,
35  AggregateRangeProof as OriginalProof,
36};
37
38pub(crate) mod plus;
39use crate::plus::{
40  WipProof, AggregateRangeStatement as PlusStatement, AggregateRangeWitness as PlusWitness,
41  AggregateRangeProof as PlusProof,
42};
43
44#[cfg(test)]
45mod tests;
46
47/// An error from proving/verifying Bulletproofs(+).
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49#[cfg_attr(feature = "std", derive(thiserror::Error))]
50pub enum BulletproofError {
51  /// Proving/verifying a Bulletproof(+) range proof with no commitments.
52  #[cfg_attr(feature = "std", error("no commitments to prove the range for"))]
53  NoCommitments,
54  /// Proving/verifying a Bulletproof(+) range proof with more commitments than supported.
55  #[cfg_attr(feature = "std", error("too many commitments to prove the range for"))]
56  TooManyCommitments,
57}
58
59/// A Bulletproof(+).
60///
61/// This encapsulates either a Bulletproof or a Bulletproof+.
62#[allow(clippy::large_enum_variant)]
63#[derive(Clone, PartialEq, Eq, Debug)]
64pub enum Bulletproof {
65  /// A Bulletproof.
66  Original(OriginalProof),
67  /// A Bulletproof+.
68  Plus(PlusProof),
69}
70
71impl Bulletproof {
72  fn bp_fields(plus: bool) -> usize {
73    if plus {
74      6
75    } else {
76      9
77    }
78  }
79
80  /// Calculate the weight penalty for the Bulletproof(+).
81  ///
82  /// Bulletproofs(+) are logarithmically sized yet linearly timed. Evaluating by their size alone
83  /// accordingly doesn't properly represent the burden of the proof. Monero 'claws back' some of
84  /// the weight lost by using a proof smaller than it is fast to compensate for this.
85  // https://github.com/monero-project/monero/blob/94e67bf96bbc010241f29ada6abc89f49a81759c/
86  //   src/cryptonote_basic/cryptonote_format_utils.cpp#L106-L124
87  pub fn calculate_bp_clawback(plus: bool, n_outputs: usize) -> (usize, usize) {
88    #[allow(non_snake_case)]
89    let mut LR_len = 0;
90    let mut n_padded_outputs = 1;
91    while n_padded_outputs < n_outputs {
92      LR_len += 1;
93      n_padded_outputs = 1 << LR_len;
94    }
95    LR_len += LOG_COMMITMENT_BITS;
96
97    let mut bp_clawback = 0;
98    if n_padded_outputs > 2 {
99      let fields = Bulletproof::bp_fields(plus);
100      let base = ((fields + (2 * (LOG_COMMITMENT_BITS + 1))) * 32) / 2;
101      let size = (fields + (2 * LR_len)) * 32;
102      bp_clawback = ((base * n_padded_outputs) - size) * 4 / 5;
103    }
104
105    (bp_clawback, LR_len)
106  }
107
108  /// Prove the list of commitments are within [0 .. 2^64) with an aggregate Bulletproof.
109  pub fn prove<R: RngCore + CryptoRng>(
110    rng: &mut R,
111    outputs: Vec<Commitment>,
112  ) -> Result<Bulletproof, BulletproofError> {
113    if outputs.is_empty() {
114      Err(BulletproofError::NoCommitments)?;
115    }
116    if outputs.len() > MAX_COMMITMENTS {
117      Err(BulletproofError::TooManyCommitments)?;
118    }
119    let commitments = outputs.iter().map(Commitment::calculate).collect::<Vec<_>>();
120    Ok(Bulletproof::Original(
121      OriginalStatement::new(&commitments)
122        .unwrap()
123        .prove(rng, OriginalWitness::new(outputs).unwrap())
124        .unwrap(),
125    ))
126  }
127
128  /// Prove the list of commitments are within [0 .. 2^64) with an aggregate Bulletproof+.
129  pub fn prove_plus<R: RngCore + CryptoRng>(
130    rng: &mut R,
131    outputs: Vec<Commitment>,
132  ) -> Result<Bulletproof, BulletproofError> {
133    if outputs.is_empty() {
134      Err(BulletproofError::NoCommitments)?;
135    }
136    if outputs.len() > MAX_COMMITMENTS {
137      Err(BulletproofError::TooManyCommitments)?;
138    }
139    let commitments = outputs.iter().map(Commitment::calculate).collect::<Vec<_>>();
140    Ok(Bulletproof::Plus(
141      PlusStatement::new(&commitments)
142        .unwrap()
143        .prove(rng, &Zeroizing::new(PlusWitness::new(outputs).unwrap()))
144        .unwrap(),
145    ))
146  }
147
148  /// Verify the given Bulletproof(+).
149  #[must_use]
150  pub fn verify<R: RngCore + CryptoRng>(&self, rng: &mut R, commitments: &[EdwardsPoint]) -> bool {
151    match self {
152      Bulletproof::Original(bp) => {
153        let mut verifier = BulletproofsBatchVerifier::default();
154        let Some(statement) = OriginalStatement::new(commitments) else {
155          return false;
156        };
157        if !statement.verify(rng, &mut verifier, bp.clone()) {
158          return false;
159        }
160        verifier.verify()
161      }
162      Bulletproof::Plus(bp) => {
163        let mut verifier = BulletproofsPlusBatchVerifier::default();
164        let Some(statement) = PlusStatement::new(commitments) else {
165          return false;
166        };
167        if !statement.verify(rng, &mut verifier, bp.clone()) {
168          return false;
169        }
170        verifier.verify()
171      }
172    }
173  }
174
175  /// Accumulate the verification for the given Bulletproof(+) into the specified BatchVerifier.
176  ///
177  /// Returns false if the Bulletproof(+) isn't sane, leaving the BatchVerifier in an undefined
178  /// state.
179  ///
180  /// Returns true if the Bulletproof(+) is sane, regardless of its validity.
181  ///
182  /// The BatchVerifier must have its verification function executed to actually verify this proof.
183  #[must_use]
184  pub fn batch_verify<R: RngCore + CryptoRng>(
185    &self,
186    rng: &mut R,
187    verifier: &mut BatchVerifier,
188    commitments: &[EdwardsPoint],
189  ) -> bool {
190    match self {
191      Bulletproof::Original(bp) => {
192        let Some(statement) = OriginalStatement::new(commitments) else {
193          return false;
194        };
195        statement.verify(rng, &mut verifier.original, bp.clone())
196      }
197      Bulletproof::Plus(bp) => {
198        let Some(statement) = PlusStatement::new(commitments) else {
199          return false;
200        };
201        statement.verify(rng, &mut verifier.plus, bp.clone())
202      }
203    }
204  }
205
206  fn write_core<W: Write, F: Fn(&[EdwardsPoint], &mut W) -> io::Result<()>>(
207    &self,
208    w: &mut W,
209    specific_write_vec: F,
210  ) -> io::Result<()> {
211    match self {
212      Bulletproof::Original(bp) => {
213        write_point(&bp.A, w)?;
214        write_point(&bp.S, w)?;
215        write_point(&bp.T1, w)?;
216        write_point(&bp.T2, w)?;
217        write_scalar(&bp.tau_x, w)?;
218        write_scalar(&bp.mu, w)?;
219        specific_write_vec(&bp.ip.L, w)?;
220        specific_write_vec(&bp.ip.R, w)?;
221        write_scalar(&bp.ip.a, w)?;
222        write_scalar(&bp.ip.b, w)?;
223        write_scalar(&bp.t_hat, w)
224      }
225
226      Bulletproof::Plus(bp) => {
227        write_point(&bp.A, w)?;
228        write_point(&bp.wip.A, w)?;
229        write_point(&bp.wip.B, w)?;
230        write_scalar(&bp.wip.r_answer, w)?;
231        write_scalar(&bp.wip.s_answer, w)?;
232        write_scalar(&bp.wip.delta_answer, w)?;
233        specific_write_vec(&bp.wip.L, w)?;
234        specific_write_vec(&bp.wip.R, w)
235      }
236    }
237  }
238
239  /// Write a Bulletproof(+) for the message signed by a transaction's signature.
240  ///
241  /// This has a distinct encoding from the standard encoding.
242  pub fn signature_write<W: Write>(&self, w: &mut W) -> io::Result<()> {
243    self.write_core(w, |points, w| write_raw_vec(write_point, points, w))
244  }
245
246  /// Write a Bulletproof(+).
247  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
248    self.write_core(w, |points, w| write_vec(write_point, points, w))
249  }
250
251  /// Serialize a Bulletproof(+) to a `Vec<u8>`.
252  pub fn serialize(&self) -> Vec<u8> {
253    let mut serialized = vec![];
254    self.write(&mut serialized).unwrap();
255    serialized
256  }
257
258  /// Read a Bulletproof.
259  pub fn read<R: Read>(r: &mut R) -> io::Result<Bulletproof> {
260    Ok(Bulletproof::Original(OriginalProof {
261      A: read_point(r)?,
262      S: read_point(r)?,
263      T1: read_point(r)?,
264      T2: read_point(r)?,
265      tau_x: read_scalar(r)?,
266      mu: read_scalar(r)?,
267      ip: IpProof {
268        L: read_vec(read_point, r)?,
269        R: read_vec(read_point, r)?,
270        a: read_scalar(r)?,
271        b: read_scalar(r)?,
272      },
273      t_hat: read_scalar(r)?,
274    }))
275  }
276
277  /// Read a Bulletproof+.
278  pub fn read_plus<R: Read>(r: &mut R) -> io::Result<Bulletproof> {
279    Ok(Bulletproof::Plus(PlusProof {
280      A: read_point(r)?,
281      wip: WipProof {
282        A: read_point(r)?,
283        B: read_point(r)?,
284        r_answer: read_scalar(r)?,
285        s_answer: read_scalar(r)?,
286        delta_answer: read_scalar(r)?,
287        L: read_vec(read_point, r)?.into_iter().collect(),
288        R: read_vec(read_point, r)?.into_iter().collect(),
289      },
290    }))
291  }
292}