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
6use std_shims::{io, vec::Vec};
7#[cfg(feature = "std")]
8use std_shims::sync::LazyLock;
9
10use zeroize::{Zeroize, ZeroizeOnDrop};
11
12use sha3::{Digest, Keccak256};
13use curve25519_dalek::{
14 constants::ED25519_BASEPOINT_POINT,
15 traits::VartimePrecomputedMultiscalarMul,
16 scalar::Scalar,
17 edwards::{EdwardsPoint, VartimeEdwardsPrecomputation},
18};
19
20use monero_io::*;
21use monero_generators::H;
22
23mod unreduced_scalar;
24pub use unreduced_scalar::UnreducedScalar;
25
26#[cfg(test)]
27mod tests;
28
29#[cfg(feature = "std")]
31static INV_EIGHT_CELL: LazyLock<Scalar> = LazyLock::new(|| Scalar::from(8u8).invert());
32#[cfg(feature = "std")]
34#[allow(non_snake_case)]
35pub fn INV_EIGHT() -> Scalar {
36 *INV_EIGHT_CELL
37}
38#[cfg(not(feature = "std"))]
41#[allow(non_snake_case)]
42pub fn INV_EIGHT() -> Scalar {
43 Scalar::from(8u8).invert()
44}
45
46#[cfg(feature = "std")]
47static G_PRECOMP_CELL: LazyLock<VartimeEdwardsPrecomputation> =
48 LazyLock::new(|| VartimeEdwardsPrecomputation::new([ED25519_BASEPOINT_POINT]));
49#[cfg(feature = "std")]
51#[allow(non_snake_case)]
52pub fn G_PRECOMP() -> &'static VartimeEdwardsPrecomputation {
53 &G_PRECOMP_CELL
54}
55#[cfg(not(feature = "std"))]
57#[allow(non_snake_case)]
58pub fn G_PRECOMP() -> VartimeEdwardsPrecomputation {
59 VartimeEdwardsPrecomputation::new([ED25519_BASEPOINT_POINT])
60}
61
62pub fn keccak256(data: impl AsRef<[u8]>) -> [u8; 32] {
64 Keccak256::digest(data.as_ref()).into()
65}
66
67pub fn keccak256_to_scalar(data: impl AsRef<[u8]>) -> Scalar {
71 let scalar = Scalar::from_bytes_mod_order(keccak256(data.as_ref()));
72 assert!(scalar != Scalar::ZERO, "ZERO HASH: {:?}", data.as_ref());
77 scalar
78}
79
80#[allow(non_snake_case)]
82#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
83pub struct Commitment {
84 pub mask: Scalar,
86 pub amount: u64,
88}
89
90impl core::fmt::Debug for Commitment {
91 fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
92 fmt.debug_struct("Commitment").field("amount", &self.amount).finish_non_exhaustive()
93 }
94}
95
96impl Commitment {
97 pub fn zero() -> Commitment {
99 Commitment { mask: Scalar::ONE, amount: 0 }
100 }
101
102 pub fn new(mask: Scalar, amount: u64) -> Commitment {
104 Commitment { mask, amount }
105 }
106
107 pub fn calculate(&self) -> EdwardsPoint {
109 EdwardsPoint::vartime_double_scalar_mul_basepoint(&Scalar::from(self.amount), &H, &self.mask)
110 }
111
112 pub fn write<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
117 w.write_all(&self.mask.to_bytes())?;
118 w.write_all(&self.amount.to_le_bytes())
119 }
120
121 pub fn serialize(&self) -> Vec<u8> {
126 let mut res = Vec::with_capacity(32 + 8);
127 self.write(&mut res).unwrap();
128 res
129 }
130
131 pub fn read<R: io::Read>(r: &mut R) -> io::Result<Commitment> {
136 Ok(Commitment::new(read_scalar(r)?, read_u64(r)?))
137 }
138}
139
140#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
142pub struct Decoys {
143 offsets: Vec<u64>,
144 signer_index: u8,
145 ring: Vec<[EdwardsPoint; 2]>,
146}
147
148impl core::fmt::Debug for Decoys {
149 fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
150 fmt
151 .debug_struct("Decoys")
152 .field("offsets", &self.offsets)
153 .field("ring", &self.ring)
154 .finish_non_exhaustive()
155 }
156}
157
158#[allow(clippy::len_without_is_empty)]
159impl Decoys {
160 pub fn new(offsets: Vec<u64>, signer_index: u8, ring: Vec<[EdwardsPoint; 2]>) -> Option<Self> {
165 if (offsets.len() != ring.len()) || (usize::from(signer_index) >= ring.len()) {
166 None?;
167 }
168 Some(Decoys { offsets, signer_index, ring })
169 }
170
171 pub fn len(&self) -> usize {
173 self.offsets.len()
174 }
175
176 pub fn offsets(&self) -> &[u64] {
181 &self.offsets
182 }
183
184 pub fn positions(&self) -> Vec<u64> {
186 let mut res = Vec::with_capacity(self.len());
187 res.push(self.offsets[0]);
188 for m in 1 .. self.len() {
189 res.push(res[m - 1] + self.offsets[m]);
190 }
191 res
192 }
193
194 pub fn signer_index(&self) -> u8 {
196 self.signer_index
197 }
198
199 pub fn ring(&self) -> &[[EdwardsPoint; 2]] {
201 &self.ring
202 }
203
204 pub fn signer_ring_members(&self) -> [EdwardsPoint; 2] {
206 self.ring[usize::from(self.signer_index)]
207 }
208
209 pub fn write(&self, w: &mut impl io::Write) -> io::Result<()> {
214 write_vec(write_varint, &self.offsets, w)?;
215 w.write_all(&[self.signer_index])?;
216 write_vec(
217 |pair, w| {
218 write_point(&pair[0], w)?;
219 write_point(&pair[1], w)
220 },
221 &self.ring,
222 w,
223 )
224 }
225
226 pub fn serialize(&self) -> Vec<u8> {
231 let mut res =
232 Vec::with_capacity((1 + (2 * self.offsets.len())) + 1 + 1 + (self.ring.len() * 64));
233 self.write(&mut res).unwrap();
234 res
235 }
236
237 pub fn read(r: &mut impl io::Read) -> io::Result<Decoys> {
242 Decoys::new(
243 read_vec(read_varint, r)?,
244 read_byte(r)?,
245 read_vec(|r| Ok([read_point(r)?, read_point(r)?]), r)?,
246 )
247 .ok_or_else(|| io::Error::other("invalid Decoys"))
248 }
249}