monero_clsag_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 core::ops::Deref;
8use std_shims::{
9  vec,
10  vec::Vec,
11  io::{self, Read, Write},
12};
13
14use rand_core::{RngCore, CryptoRng};
15
16use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
17use subtle::{ConstantTimeEq, ConditionallySelectable};
18
19use curve25519_dalek::{
20  constants::{ED25519_BASEPOINT_TABLE, ED25519_BASEPOINT_POINT},
21  scalar::Scalar,
22  traits::{IsIdentity, MultiscalarMul, VartimePrecomputedMultiscalarMul},
23  edwards::{EdwardsPoint, VartimeEdwardsPrecomputation},
24};
25
26use monero_io::*;
27use monero_generators::hash_to_point;
28use monero_primitives::{INV_EIGHT, G_PRECOMP, Commitment, Decoys, keccak256_to_scalar};
29
30#[cfg(feature = "multisig")]
31mod multisig;
32#[cfg(feature = "multisig")]
33pub use multisig::{ClsagMultisigMaskSender, ClsagAddendum, ClsagMultisig};
34
35#[cfg(all(feature = "std", test))]
36mod tests;
37
38/// Errors when working with CLSAGs.
39#[derive(Clone, Copy, PartialEq, Eq, Debug)]
40#[cfg_attr(feature = "std", derive(thiserror::Error))]
41pub enum ClsagError {
42  /// The ring was invalid (such as being too small or too large).
43  #[cfg_attr(feature = "std", error("invalid ring"))]
44  InvalidRing,
45  /// The discrete logarithm of the key, scaling G, wasn't equivalent to the signing ring member.
46  #[cfg_attr(feature = "std", error("invalid commitment"))]
47  InvalidKey,
48  /// The commitment opening provided did not match the ring member's.
49  #[cfg_attr(feature = "std", error("invalid commitment"))]
50  InvalidCommitment,
51  /// The key image was invalid (such as being identity or torsioned)
52  #[cfg_attr(feature = "std", error("invalid key image"))]
53  InvalidImage,
54  /// The `D` component was invalid.
55  #[cfg_attr(feature = "std", error("invalid D"))]
56  InvalidD,
57  /// The `s` vector was invalid.
58  #[cfg_attr(feature = "std", error("invalid s"))]
59  InvalidS,
60  /// The `c1` variable was invalid.
61  #[cfg_attr(feature = "std", error("invalid c1"))]
62  InvalidC1,
63}
64
65/// Context on the input being signed for.
66#[derive(Clone, PartialEq, Eq, Debug, Zeroize, ZeroizeOnDrop)]
67pub struct ClsagContext {
68  // The opening for the commitment of the signing ring member
69  commitment: Commitment,
70  // Selected ring members' positions, signer index, and ring
71  decoys: Decoys,
72}
73
74impl ClsagContext {
75  /// Create a new context, as necessary for signing.
76  pub fn new(decoys: Decoys, commitment: Commitment) -> Result<ClsagContext, ClsagError> {
77    if decoys.len() > u8::MAX.into() {
78      Err(ClsagError::InvalidRing)?;
79    }
80
81    // Validate the commitment matches
82    if decoys.signer_ring_members()[1] != commitment.calculate() {
83      Err(ClsagError::InvalidCommitment)?;
84    }
85
86    Ok(ClsagContext { commitment, decoys })
87  }
88}
89
90#[allow(clippy::large_enum_variant)]
91enum Mode {
92  Sign(usize, EdwardsPoint, EdwardsPoint),
93  Verify(Scalar),
94}
95
96// Core of the CLSAG algorithm, applicable to both sign and verify with minimal differences
97//
98// Said differences are covered via the above Mode
99fn core(
100  ring: &[[EdwardsPoint; 2]],
101  I: &EdwardsPoint,
102  pseudo_out: &EdwardsPoint,
103  msg: &[u8; 32],
104  D: &EdwardsPoint,
105  s: &[Scalar],
106  A_c1: &Mode,
107) -> ((EdwardsPoint, Scalar, Scalar), Scalar) {
108  let n = ring.len();
109
110  let images_precomp = match A_c1 {
111    Mode::Sign(..) => None,
112    Mode::Verify(..) => Some(VartimeEdwardsPrecomputation::new([I, D])),
113  };
114  let D_INV_EIGHT = D * INV_EIGHT();
115
116  // Generate the transcript
117  // Instead of generating multiple, a single transcript is created and then edited as needed
118  const PREFIX: &[u8] = b"CLSAG_";
119  #[rustfmt::skip]
120  const AGG_0: &[u8]  =       b"agg_0";
121  #[rustfmt::skip]
122  const ROUND: &[u8]  =       b"round";
123  const PREFIX_AGG_0_LEN: usize = PREFIX.len() + AGG_0.len();
124
125  let mut to_hash = Vec::with_capacity(((2 * n) + 5) * 32);
126  to_hash.extend(PREFIX);
127  to_hash.extend(AGG_0);
128  to_hash.extend([0; 32 - PREFIX_AGG_0_LEN]);
129
130  let mut P = Vec::with_capacity(n);
131  for member in ring {
132    P.push(member[0]);
133    to_hash.extend(member[0].compress().to_bytes());
134  }
135
136  let mut C = Vec::with_capacity(n);
137  for member in ring {
138    C.push(member[1] - pseudo_out);
139    to_hash.extend(member[1].compress().to_bytes());
140  }
141
142  to_hash.extend(I.compress().to_bytes());
143  to_hash.extend(D_INV_EIGHT.compress().to_bytes());
144  to_hash.extend(pseudo_out.compress().to_bytes());
145  // mu_P with agg_0
146  let mu_P = keccak256_to_scalar(&to_hash);
147  // mu_C with agg_1
148  to_hash[PREFIX_AGG_0_LEN - 1] = b'1';
149  let mu_C = keccak256_to_scalar(&to_hash);
150
151  // Truncate it for the round transcript, altering the DST as needed
152  to_hash.truncate(((2 * n) + 1) * 32);
153  for i in 0 .. ROUND.len() {
154    to_hash[PREFIX.len() + i] = ROUND[i];
155  }
156  // Unfortunately, it's I D pseudo_out instead of pseudo_out I D, meaning this needs to be
157  // truncated just to add it back
158  to_hash.extend(pseudo_out.compress().to_bytes());
159  to_hash.extend(msg);
160
161  // Configure the loop based on if we're signing or verifying
162  let start;
163  let end;
164  let mut c;
165  match A_c1 {
166    Mode::Sign(r, A, AH) => {
167      start = r + 1;
168      end = r + n;
169      to_hash.extend(A.compress().to_bytes());
170      to_hash.extend(AH.compress().to_bytes());
171      c = keccak256_to_scalar(&to_hash);
172    }
173
174    Mode::Verify(c1) => {
175      start = 0;
176      end = n;
177      c = *c1;
178    }
179  }
180
181  // Perform the core loop
182  let mut c1 = c;
183  for i in (start .. end).map(|i| i % n) {
184    let c_p = mu_P * c;
185    let c_c = mu_C * c;
186
187    // (s_i * G) + (c_p * P_i) + (c_c * C_i)
188    let L = match A_c1 {
189      Mode::Sign(..) => {
190        EdwardsPoint::multiscalar_mul([s[i], c_p, c_c], [ED25519_BASEPOINT_POINT, P[i], C[i]])
191      }
192      Mode::Verify(..) => {
193        G_PRECOMP().vartime_mixed_multiscalar_mul([s[i]], [c_p, c_c], [P[i], C[i]])
194      }
195    };
196
197    let PH = hash_to_point(P[i].compress().0);
198
199    // (c_p * I) + (c_c * D) + (s_i * PH)
200    let R = match A_c1 {
201      Mode::Sign(..) => EdwardsPoint::multiscalar_mul([c_p, c_c, s[i]], [I, D, &PH]),
202      Mode::Verify(..) => {
203        images_precomp.as_ref().unwrap().vartime_mixed_multiscalar_mul([c_p, c_c], [s[i]], [PH])
204      }
205    };
206
207    to_hash.truncate(((2 * n) + 3) * 32);
208    to_hash.extend(L.compress().to_bytes());
209    to_hash.extend(R.compress().to_bytes());
210    c = keccak256_to_scalar(&to_hash);
211
212    // This will only execute once and shouldn't need to be constant time. Making it constant time
213    // removes the risk of branch prediction creating timing differences depending on ring index
214    // however
215    c1.conditional_assign(&c, i.ct_eq(&(n - 1)));
216  }
217
218  // This first tuple is needed to continue signing, the latter is the c to be tested/worked with
219  ((D_INV_EIGHT, c * mu_P, c * mu_C), c1)
220}
221
222/// The CLSAG signature, as used in Monero.
223#[derive(Clone, PartialEq, Eq, Debug)]
224pub struct Clsag {
225  /// The difference of the commitment randomnesses, scaling the key image generator.
226  pub D: EdwardsPoint,
227  /// The responses for each ring member.
228  pub s: Vec<Scalar>,
229  /// The first challenge in the ring.
230  pub c1: Scalar,
231}
232
233struct ClsagSignCore {
234  incomplete_clsag: Clsag,
235  pseudo_out: EdwardsPoint,
236  key_challenge: Scalar,
237  challenged_mask: Scalar,
238}
239
240impl Clsag {
241  // Sign core is the extension of core as needed for signing, yet is shared between single signer
242  // and multisig, hence why it's still core
243  fn sign_core<R: RngCore + CryptoRng>(
244    rng: &mut R,
245    I: &EdwardsPoint,
246    input: &ClsagContext,
247    mask: Scalar,
248    msg: &[u8; 32],
249    A: EdwardsPoint,
250    AH: EdwardsPoint,
251  ) -> ClsagSignCore {
252    let r: usize = input.decoys.signer_index().into();
253
254    let pseudo_out = Commitment::new(mask, input.commitment.amount).calculate();
255    let mask_delta = input.commitment.mask - mask;
256
257    let H = hash_to_point(input.decoys.ring()[r][0].compress().0);
258    let D = H * mask_delta;
259    let mut s = Vec::with_capacity(input.decoys.ring().len());
260    for _ in 0 .. input.decoys.ring().len() {
261      s.push(Scalar::random(rng));
262    }
263    let ((D, c_p, c_c), c1) =
264      core(input.decoys.ring(), I, &pseudo_out, msg, &D, &s, &Mode::Sign(r, A, AH));
265
266    ClsagSignCore {
267      incomplete_clsag: Clsag { D, s, c1 },
268      pseudo_out,
269      key_challenge: c_p,
270      challenged_mask: c_c * mask_delta,
271    }
272  }
273
274  /// Sign CLSAG signatures for the provided inputs.
275  ///
276  /// Monero ensures the rerandomized input commitments have the same value as the outputs by
277  /// checking `sum(rerandomized_input_commitments) - sum(output_commitments) == 0`. This requires
278  /// not only the amounts balance, yet also
279  /// `sum(input_commitment_masks) - sum(output_commitment_masks)`.
280  ///
281  /// Monero solves this by following the wallet protocol to determine each output commitment's
282  /// randomness, then using random masks for all but the last input. The last input is
283  /// rerandomized to the necessary mask for the equation to balance.
284  ///
285  /// Due to Monero having this behavior, it only makes sense to sign CLSAGs as a list, hence this
286  /// API being the way it is.
287  ///
288  /// `inputs` is of the form (discrete logarithm of the key, context).
289  ///
290  /// `sum_outputs` is for the sum of the output commitments' masks.
291  pub fn sign<R: RngCore + CryptoRng>(
292    rng: &mut R,
293    mut inputs: Vec<(Zeroizing<Scalar>, ClsagContext)>,
294    sum_outputs: Scalar,
295    msg: [u8; 32],
296  ) -> Result<Vec<(Clsag, EdwardsPoint)>, ClsagError> {
297    // Create the key images
298    let mut key_image_generators = vec![];
299    let mut key_images = vec![];
300    for input in &inputs {
301      let key = input.1.decoys.signer_ring_members()[0];
302
303      // Check the key is consistent
304      if (ED25519_BASEPOINT_TABLE * input.0.deref()) != key {
305        Err(ClsagError::InvalidKey)?;
306      }
307
308      let key_image_generator = hash_to_point(key.compress().0);
309      key_image_generators.push(key_image_generator);
310      key_images.push(key_image_generator * input.0.deref());
311    }
312
313    let mut res = Vec::with_capacity(inputs.len());
314    let mut sum_pseudo_outs = Scalar::ZERO;
315    for i in 0 .. inputs.len() {
316      let mask;
317      // If this is the last input, set the mask as described above
318      if i == (inputs.len() - 1) {
319        mask = sum_outputs - sum_pseudo_outs;
320      } else {
321        mask = Scalar::random(rng);
322        sum_pseudo_outs += mask;
323      }
324
325      let mut nonce = Zeroizing::new(Scalar::random(rng));
326      let ClsagSignCore { mut incomplete_clsag, pseudo_out, key_challenge, challenged_mask } =
327        Clsag::sign_core(
328          rng,
329          &key_images[i],
330          &inputs[i].1,
331          mask,
332          &msg,
333          nonce.deref() * ED25519_BASEPOINT_TABLE,
334          nonce.deref() * key_image_generators[i],
335        );
336      // Effectively r - c x, except c x is (c_p x) + (c_c z), where z is the delta between the
337      // ring member's commitment and our pseudo-out commitment (which will only have a known
338      // discrete log over G if the amounts cancel out)
339      incomplete_clsag.s[usize::from(inputs[i].1.decoys.signer_index())] =
340        nonce.deref() - ((key_challenge * inputs[i].0.deref()) + challenged_mask);
341      let clsag = incomplete_clsag;
342
343      // Zeroize private keys and nonces.
344      inputs[i].0.zeroize();
345      nonce.zeroize();
346
347      debug_assert!(clsag
348        .verify(inputs[i].1.decoys.ring(), &key_images[i], &pseudo_out, &msg)
349        .is_ok());
350
351      res.push((clsag, pseudo_out));
352    }
353
354    Ok(res)
355  }
356
357  /// Verify a CLSAG signature for the provided context.
358  pub fn verify(
359    &self,
360    ring: &[[EdwardsPoint; 2]],
361    I: &EdwardsPoint,
362    pseudo_out: &EdwardsPoint,
363    msg: &[u8; 32],
364  ) -> Result<(), ClsagError> {
365    // Preliminary checks
366    // s, c1, and points must also be encoded canonically, which is checked at time of decode
367    if ring.is_empty() {
368      Err(ClsagError::InvalidRing)?;
369    }
370    if ring.len() != self.s.len() {
371      Err(ClsagError::InvalidS)?;
372    }
373    if I.is_identity() || (!I.is_torsion_free()) {
374      Err(ClsagError::InvalidImage)?;
375    }
376
377    let D = self.D.mul_by_cofactor();
378    if D.is_identity() {
379      Err(ClsagError::InvalidD)?;
380    }
381
382    let (_, c1) = core(ring, I, pseudo_out, msg, &D, &self.s, &Mode::Verify(self.c1));
383    if c1 != self.c1 {
384      Err(ClsagError::InvalidC1)?;
385    }
386    Ok(())
387  }
388
389  /// Write a CLSAG.
390  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
391    write_raw_vec(write_scalar, &self.s, w)?;
392    w.write_all(&self.c1.to_bytes())?;
393    write_point(&self.D, w)
394  }
395
396  /// Read a CLSAG.
397  pub fn read<R: Read>(decoys: usize, r: &mut R) -> io::Result<Clsag> {
398    Ok(Clsag { s: read_raw_vec(read_scalar, decoys, r)?, c1: read_scalar(r)?, D: read_point(r)? })
399  }
400}