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#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
23pub enum MlsagError {
24 #[error("invalid ring")]
26 InvalidRing,
27 #[error("invalid amount of key images")]
29 InvalidAmountOfKeyImages,
30 #[error("invalid ss")]
32 InvalidSs,
33 #[error("invalid key image")]
35 InvalidKeyImage,
36 #[error("invalid ci")]
38 InvalidCi,
39}
40
41#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
43pub struct RingMatrix {
44 matrix: Vec<Vec<EdwardsPoint>>,
45}
46
47impl RingMatrix {
48 fn new(matrix: Vec<Vec<EdwardsPoint>>) -> Result<Self, MlsagError> {
50 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 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 fn iter(&self) -> impl Iterator<Item = &[EdwardsPoint]> {
81 self.matrix.iter().map(AsRef::as_ref)
82 }
83
84 pub fn members(&self) -> usize {
86 self.matrix.len()
87 }
88
89 pub fn member_len(&self) -> usize {
94 self.matrix[0].len()
96 }
97}
98
99#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
101pub struct Mlsag {
102 ss: Vec<Vec<Scalar>>,
103 cc: Scalar,
104}
105
106impl Mlsag {
107 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 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 pub fn verify(
131 &self,
132 msg: &[u8; 32],
133 ring: &RingMatrix,
134 key_images: &[CompressedPoint],
135 ) -> Result<(), MlsagError> {
136 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 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 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 buf.drain(msg.len() ..);
188 }
189
190 if ci != self.cc {
191 Err(MlsagError::InvalidCi)?
192 }
193 Ok(())
194 }
195}
196
197#[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 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 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 self.amounts_ring = vec![-self.sum_out; ring.len()];
230 }
231
232 if (self.amounts_ring.len() != ring.len()) || ring.is_empty() {
233 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 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}