monero_mlsag/
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 zeroize::Zeroize;
14
15use curve25519_dalek::{traits::IsIdentity, Scalar, EdwardsPoint};
16
17use monero_io::*;
18use monero_generators::{H, biased_hash_to_point};
19use monero_primitives::keccak256_to_scalar;
20
21/// Errors when working with MLSAGs.
22#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
23pub enum MlsagError {
24  /// Invalid ring (such as too small or too large).
25  #[error("invalid ring")]
26  InvalidRing,
27  /// Invalid amount of key images.
28  #[error("invalid amount of key images")]
29  InvalidAmountOfKeyImages,
30  /// Invalid ss matrix.
31  #[error("invalid ss")]
32  InvalidSs,
33  /// Invalid key image.
34  #[error("invalid key image")]
35  InvalidKeyImage,
36  /// Invalid ci vector.
37  #[error("invalid ci")]
38  InvalidCi,
39}
40
41/// A vector of rings, forming a matrix, to verify the MLSAG with.
42#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
43pub struct RingMatrix {
44  matrix: Vec<Vec<EdwardsPoint>>,
45}
46
47impl RingMatrix {
48  /// Construct a ring matrix from an already formatted series of points.
49  fn new(matrix: Vec<Vec<EdwardsPoint>>) -> Result<Self, MlsagError> {
50    // Monero requires that there is more than one ring member for MLSAG signatures:
51    // https://github.com/monero-project/monero/blob/ac02af92867590ca80b2779a7bbeafa99ff94dcb/
52    // src/ringct/rctSigs.cpp#L462
53    if matrix.len() < 2 {
54      Err(MlsagError::InvalidRing)?;
55    }
56    for member in &matrix {
57      if member.is_empty() || (member.len() != matrix[0].len()) {
58        Err(MlsagError::InvalidRing)?;
59      }
60    }
61
62    Ok(RingMatrix { matrix })
63  }
64
65  /// Construct a ring matrix for an individual output.
66  pub fn individual(
67    ring: &[[CompressedPoint; 2]],
68    pseudo_out: CompressedPoint,
69  ) -> Result<Self, MlsagError> {
70    let mut matrix = Vec::with_capacity(ring.len());
71    for ring_member in ring {
72      let decomp = |p: CompressedPoint| p.decompress().ok_or(MlsagError::InvalidRing);
73
74      matrix.push(vec![decomp(ring_member[0])?, decomp(ring_member[1])? - decomp(pseudo_out)?]);
75    }
76    RingMatrix::new(matrix)
77  }
78
79  /// Iterate over the members of the matrix.
80  fn iter(&self) -> impl Iterator<Item = &[EdwardsPoint]> {
81    self.matrix.iter().map(AsRef::as_ref)
82  }
83
84  /// Get the amount of members in the ring.
85  pub fn members(&self) -> usize {
86    self.matrix.len()
87  }
88
89  /// Get the length of a ring member.
90  ///
91  /// A ring member is a vector of points for which the signer knows all of the discrete logarithms
92  /// of.
93  pub fn member_len(&self) -> usize {
94    // this is safe to do as the constructors don't allow empty rings
95    self.matrix[0].len()
96  }
97}
98
99/// The MLSAG linkable ring signature, as used in Monero.
100#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
101pub struct Mlsag {
102  ss: Vec<Vec<Scalar>>,
103  cc: Scalar,
104}
105
106impl Mlsag {
107  /// Write a MLSAG.
108  pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
109    for ss in &self.ss {
110      write_raw_vec(write_scalar, ss, w)?;
111    }
112    write_scalar(&self.cc, w)
113  }
114
115  /// Read a MLSAG.
116  pub fn read<R: Read>(mixins: usize, ss_2_elements: usize, r: &mut R) -> io::Result<Mlsag> {
117    Ok(Mlsag {
118      ss: (0 .. mixins)
119        .map(|_| read_raw_vec(read_scalar, ss_2_elements, r))
120        .collect::<Result<_, _>>()?,
121      cc: read_scalar(r)?,
122    })
123  }
124
125  /// Verify a MLSAG.
126  ///
127  /// WARNING: This follows the Fiat-Shamir transcript format used by the Monero protocol, which
128  /// makes assumptions on what has already been transcripted and bound to within `msg`. Do not use
129  /// this if you don't know what you're doing.
130  pub fn verify(
131    &self,
132    msg: &[u8; 32],
133    ring: &RingMatrix,
134    key_images: &[CompressedPoint],
135  ) -> Result<(), MlsagError> {
136    // Mlsag allows for layers to not need linkability, hence they don't need key images
137    // Monero requires that there is always only 1 non-linkable layer - the amount commitments.
138    if ring.member_len() != (key_images.len() + 1) {
139      Err(MlsagError::InvalidAmountOfKeyImages)?;
140    }
141
142    let mut buf = Vec::with_capacity(6 * 32);
143    buf.extend_from_slice(msg);
144
145    let mut ci = self.cc;
146
147    // This is an iterator over the key images as options with an added entry of `None` at the
148    // end for the non-linkable layer
149    let key_images_iter = key_images.iter().map(Some).chain(core::iter::once(None));
150
151    if ring.matrix.len() != self.ss.len() {
152      Err(MlsagError::InvalidSs)?;
153    }
154
155    for (ring_member, ss) in ring.iter().zip(&self.ss) {
156      if ring_member.len() != ss.len() {
157        Err(MlsagError::InvalidSs)?;
158      }
159
160      for ((ring_member_entry, s), ki) in ring_member.iter().zip(ss).zip(key_images_iter.clone()) {
161        #[allow(non_snake_case)]
162        let L = EdwardsPoint::vartime_double_scalar_mul_basepoint(&ci, ring_member_entry, s);
163
164        let compressed_ring_member_entry = ring_member_entry.compress();
165        buf.extend_from_slice(compressed_ring_member_entry.as_bytes());
166        buf.extend_from_slice(L.compress().as_bytes());
167
168        // Not all dimensions need to be linkable, e.g. commitments, and only linkable layers need
169        // to have key images.
170        if let Some(ki) = ki {
171          let Some(ki) = ki.decompress() else {
172            return Err(MlsagError::InvalidKeyImage);
173          };
174
175          if ki.is_identity() || (!ki.is_torsion_free()) {
176            Err(MlsagError::InvalidKeyImage)?;
177          }
178
179          #[allow(non_snake_case)]
180          let R = (s * biased_hash_to_point(compressed_ring_member_entry.to_bytes())) + (ci * ki);
181          buf.extend_from_slice(R.compress().as_bytes());
182        }
183      }
184
185      ci = keccak256_to_scalar(&buf);
186      // keep the msg in the buffer.
187      buf.drain(msg.len() ..);
188    }
189
190    if ci != self.cc {
191      Err(MlsagError::InvalidCi)?
192    }
193    Ok(())
194  }
195}
196
197/// Builder for a RingMatrix when using an aggregate signature.
198///
199/// This handles the formatting as necessary.
200#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
201pub struct AggregateRingMatrixBuilder {
202  key_ring: Vec<Vec<EdwardsPoint>>,
203  amounts_ring: Vec<EdwardsPoint>,
204  sum_out: EdwardsPoint,
205}
206
207impl AggregateRingMatrixBuilder {
208  /// Create a new AggregateRingMatrixBuilder.
209  ///
210  /// This takes in the transaction's outputs' commitments and fee used.
211  pub fn new(commitments: &[CompressedPoint], fee: u64) -> Result<Self, MlsagError> {
212    Ok(AggregateRingMatrixBuilder {
213      key_ring: vec![],
214      amounts_ring: vec![],
215      sum_out: commitments
216        .iter()
217        .map(CompressedPoint::decompress)
218        .sum::<Option<EdwardsPoint>>()
219        .ok_or(MlsagError::InvalidRing)? +
220        (*H * Scalar::from(fee)),
221    })
222  }
223
224  /// Push a ring of [output key, commitment] to the matrix.
225  pub fn push_ring(&mut self, ring: &[[CompressedPoint; 2]]) -> Result<(), MlsagError> {
226    if self.key_ring.is_empty() {
227      self.key_ring = vec![vec![]; ring.len()];
228      // Now that we know the length of the ring, fill the `amounts_ring`.
229      self.amounts_ring = vec![-self.sum_out; ring.len()];
230    }
231
232    if (self.amounts_ring.len() != ring.len()) || ring.is_empty() {
233      // All the rings in an aggregate matrix must be the same length.
234      return Err(MlsagError::InvalidRing);
235    }
236
237    for (i, ring_member) in ring.iter().enumerate() {
238      self.key_ring[i].push(ring_member[0].decompress().ok_or(MlsagError::InvalidRing)?);
239      self.amounts_ring[i] += ring_member[1].decompress().ok_or(MlsagError::InvalidRing)?;
240    }
241
242    Ok(())
243  }
244
245  /// Build and return the [`RingMatrix`].
246  pub fn build(mut self) -> Result<RingMatrix, MlsagError> {
247    for (i, amount_commitment) in self.amounts_ring.drain(..).enumerate() {
248      self.key_ring[i].push(amount_commitment);
249    }
250    RingMatrix::new(self.key_ring)
251  }
252}