1use std::{fmt, io};
4
5use bitvec::prelude::*;
6use hex::ToHex;
7use jubjub::ExtendedPoint;
8use lazy_static::lazy_static;
9use rand_core::{CryptoRng, RngCore};
10
11use crate::{
12 amount::{Amount, NonNegative},
13 error::{NoteCommitmentError, RandError},
14 serialization::{
15 serde_helpers, ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize,
16 },
17};
18
19use super::keys::{find_group_hash, Diversifier, TransmissionKey};
20
21pub mod pedersen_hashes;
22
23#[cfg(test)]
24mod test_vectors;
25
26use pedersen_hashes::*;
27
28pub fn generate_trapdoor<T>(csprng: &mut T) -> Result<jubjub::Fr, RandError>
37where
38 T: RngCore + CryptoRng,
39{
40 let mut bytes = [0u8; 64];
41 csprng
42 .try_fill_bytes(&mut bytes)
43 .map_err(|_| RandError::FillBytes)?;
44 Ok(jubjub::Fr::from_bytes_wide(&bytes))
46}
47
48#[derive(Copy, Clone, Debug, PartialEq, Eq)]
50pub struct CommitmentRandomness(jubjub::Fr);
51
52#[derive(Clone, Copy, Deserialize, PartialEq, Eq, Serialize)]
54pub struct NoteCommitment(#[serde(with = "serde_helpers::AffinePoint")] pub jubjub::AffinePoint);
55
56impl fmt::Debug for NoteCommitment {
57 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58 f.debug_struct("NoteCommitment")
59 .field("u", &hex::encode(self.0.get_u().to_bytes()))
60 .field("v", &hex::encode(self.0.get_v().to_bytes()))
61 .finish()
62 }
63}
64
65impl From<jubjub::ExtendedPoint> for NoteCommitment {
66 fn from(extended_point: jubjub::ExtendedPoint) -> Self {
67 Self(jubjub::AffinePoint::from(extended_point))
68 }
69}
70
71impl From<NoteCommitment> for [u8; 32] {
72 fn from(cm: NoteCommitment) -> [u8; 32] {
73 cm.0.to_bytes()
74 }
75}
76
77impl TryFrom<[u8; 32]> for NoteCommitment {
78 type Error = &'static str;
79
80 fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
81 let possible_point = jubjub::AffinePoint::from_bytes(bytes);
82
83 if possible_point.is_some().into() {
84 Ok(Self(possible_point.unwrap()))
85 } else {
86 Err("Invalid jubjub::AffinePoint value")
87 }
88 }
89}
90
91impl NoteCommitment {
92 #[allow(non_snake_case)]
103 pub fn new<T>(
104 csprng: &mut T,
105 diversifier: Diversifier,
106 transmission_key: TransmissionKey,
107 value: Amount<NonNegative>,
108 ) -> Result<(CommitmentRandomness, Self), NoteCommitmentError>
109 where
110 T: RngCore + CryptoRng,
111 {
112 let mut s: BitVec<u8, Lsb0> = BitVec::new();
114
115 s.append(&mut bitvec![1; 6]);
117
118 let g_d_bytes = jubjub::AffinePoint::try_from(diversifier)
125 .map_err(|_| NoteCommitmentError::InvalidDiversifier)?
126 .to_bytes();
127
128 let pk_d_bytes = <[u8; 32]>::from(transmission_key);
129 let v_bytes = value.to_bytes();
130
131 s.extend(g_d_bytes);
132 s.extend(pk_d_bytes);
133 s.extend(v_bytes);
134
135 let rcm = CommitmentRandomness(generate_trapdoor(csprng)?);
136
137 Ok((
138 rcm,
139 NoteCommitment::from(windowed_pedersen_commitment(rcm.0, &s)),
140 ))
141 }
142
143 pub fn extract_u(&self) -> jubjub::Fq {
147 self.0.get_u()
148 }
149}
150
151#[derive(Clone, Copy, Deserialize, PartialEq, Eq, Serialize)]
159#[cfg_attr(any(test, feature = "proptest-impl"), derive(Default))]
160pub struct ValueCommitment(#[serde(with = "serde_helpers::AffinePoint")] jubjub::AffinePoint);
161
162impl<'a> std::ops::Add<&'a ValueCommitment> for ValueCommitment {
163 type Output = Self;
164
165 fn add(self, rhs: &'a ValueCommitment) -> Self::Output {
166 self + *rhs
167 }
168}
169
170impl std::ops::Add<ValueCommitment> for ValueCommitment {
171 type Output = Self;
172
173 fn add(self, rhs: ValueCommitment) -> Self::Output {
174 let value = self.0.to_extended() + rhs.0.to_extended();
175 ValueCommitment(value.into())
176 }
177}
178
179impl std::ops::AddAssign<ValueCommitment> for ValueCommitment {
180 fn add_assign(&mut self, rhs: ValueCommitment) {
181 *self = *self + rhs
182 }
183}
184
185impl fmt::Debug for ValueCommitment {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 f.debug_struct("ValueCommitment")
188 .field("u", &hex::encode(self.0.get_u().to_bytes()))
189 .field("v", &hex::encode(self.0.get_v().to_bytes()))
190 .finish()
191 }
192}
193
194impl From<jubjub::ExtendedPoint> for ValueCommitment {
195 fn from(extended_point: jubjub::ExtendedPoint) -> Self {
197 Self(jubjub::AffinePoint::from(extended_point))
198 }
199}
200
201impl From<ValueCommitment> for [u8; 32] {
206 fn from(cm: ValueCommitment) -> [u8; 32] {
207 cm.0.to_bytes()
208 }
209}
210
211impl<'a> std::ops::Sub<&'a ValueCommitment> for ValueCommitment {
212 type Output = Self;
213
214 fn sub(self, rhs: &'a ValueCommitment) -> Self::Output {
215 self - *rhs
216 }
217}
218
219impl std::ops::Sub<ValueCommitment> for ValueCommitment {
220 type Output = Self;
221
222 fn sub(self, rhs: ValueCommitment) -> Self::Output {
223 ValueCommitment((self.0.to_extended() - rhs.0.to_extended()).into())
224 }
225}
226
227impl std::ops::SubAssign<ValueCommitment> for ValueCommitment {
228 fn sub_assign(&mut self, rhs: ValueCommitment) {
229 *self = *self - rhs;
230 }
231}
232
233impl std::iter::Sum for ValueCommitment {
234 fn sum<I>(iter: I) -> Self
235 where
236 I: Iterator<Item = Self>,
237 {
238 iter.fold(
239 ValueCommitment(jubjub::AffinePoint::identity()),
240 std::ops::Add::add,
241 )
242 }
243}
244
245impl TryFrom<[u8; 32]> for ValueCommitment {
250 type Error = &'static str;
251
252 fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
253 let possible_point = jubjub::AffinePoint::from_bytes(bytes);
254
255 if possible_point.is_some().into() {
256 let point = possible_point.unwrap();
257 Ok(ExtendedPoint::from(point).into())
258 } else {
259 Err("Invalid jubjub::AffinePoint value")
260 }
261 }
262}
263
264impl ValueCommitment {
265 pub fn randomized<T>(csprng: &mut T, value: Amount) -> Result<Self, RandError>
269 where
270 T: RngCore + CryptoRng,
271 {
272 let rcv = generate_trapdoor(csprng)?;
273
274 Ok(Self::new(rcv, value))
275 }
276
277 #[allow(non_snake_case)]
281 pub fn new(rcv: jubjub::Fr, value: Amount) -> Self {
282 let v = jubjub::Fr::from(value);
283 Self::from(*V * v + *R * rcv)
284 }
285}
286
287lazy_static! {
288 static ref V: ExtendedPoint = find_group_hash(*b"Zcash_cv", b"v");
289 static ref R: ExtendedPoint = find_group_hash(*b"Zcash_cv", b"r");
290}
291
292#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq, Serialize)]
304#[cfg_attr(any(test, feature = "proptest-impl"), derive(Default))]
305pub struct NotSmallOrderValueCommitment(ValueCommitment);
306
307impl NotSmallOrderValueCommitment {
308 pub fn bytes_in_display_order(&self) -> [u8; 32] {
313 let mut reversed_bytes = self.0 .0.to_bytes();
314 reversed_bytes.reverse();
315 reversed_bytes
316 }
317}
318impl TryFrom<ValueCommitment> for NotSmallOrderValueCommitment {
319 type Error = &'static str;
320
321 fn try_from(value_commitment: ValueCommitment) -> Result<Self, Self::Error> {
336 if value_commitment.0.is_small_order().into() {
337 Err("jubjub::AffinePoint value for Sapling ValueCommitment is of small order")
338 } else {
339 Ok(Self(value_commitment))
340 }
341 }
342}
343
344impl TryFrom<jubjub::ExtendedPoint> for NotSmallOrderValueCommitment {
345 type Error = &'static str;
346
347 fn try_from(extended_point: jubjub::ExtendedPoint) -> Result<Self, Self::Error> {
349 ValueCommitment::from(extended_point).try_into()
350 }
351}
352
353impl From<NotSmallOrderValueCommitment> for ValueCommitment {
354 fn from(cv: NotSmallOrderValueCommitment) -> Self {
355 cv.0
356 }
357}
358
359impl From<NotSmallOrderValueCommitment> for jubjub::AffinePoint {
360 fn from(cv: NotSmallOrderValueCommitment) -> Self {
361 cv.0 .0
362 }
363}
364
365impl ZcashSerialize for NotSmallOrderValueCommitment {
366 fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
367 writer.write_all(&<[u8; 32]>::from(self.0)[..])?;
368 Ok(())
369 }
370}
371
372impl ZcashDeserialize for NotSmallOrderValueCommitment {
373 fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
374 let vc = ValueCommitment::try_from(reader.read_32_bytes()?)
375 .map_err(SerializationError::Parse)?;
376 vc.try_into().map_err(SerializationError::Parse)
377 }
378}
379
380impl ToHex for &NotSmallOrderValueCommitment {
381 fn encode_hex<T: FromIterator<char>>(&self) -> T {
382 self.bytes_in_display_order().encode_hex()
383 }
384
385 fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
386 self.bytes_in_display_order().encode_hex_upper()
387 }
388}
389
390#[cfg(test)]
391mod tests {
392
393 use std::ops::Neg;
394
395 use super::*;
396
397 #[test]
398 fn pedersen_hash_to_point_test_vectors() {
399 let _init_guard = zebra_test::init();
400
401 const D: [u8; 8] = *b"Zcash_PH";
402
403 for test_vector in test_vectors::TEST_VECTORS.iter() {
404 let result = jubjub::AffinePoint::from(pedersen_hash_to_point(
405 D,
406 &test_vector.input_bits.clone(),
407 ));
408
409 assert_eq!(result, test_vector.output_point);
410 }
411 }
412
413 #[test]
414 fn add() {
415 let _init_guard = zebra_test::init();
416
417 let identity = ValueCommitment(jubjub::AffinePoint::identity());
418
419 let g = ValueCommitment(jubjub::AffinePoint::from_raw_unchecked(
420 jubjub::Fq::from_raw([
421 0xe4b3_d35d_f1a7_adfe,
422 0xcaf5_5d1b_29bf_81af,
423 0x8b0f_03dd_d60a_8187,
424 0x62ed_cbb8_bf37_87c8,
425 ]),
426 jubjub::Fq::from_raw([
427 0x0000_0000_0000_000b,
428 0x0000_0000_0000_0000,
429 0x0000_0000_0000_0000,
430 0x0000_0000_0000_0000,
431 ]),
432 ));
433
434 assert_eq!(identity + g, g);
435 }
436
437 #[test]
438 fn add_assign() {
439 let _init_guard = zebra_test::init();
440
441 let mut identity = ValueCommitment(jubjub::AffinePoint::identity());
442
443 let g = ValueCommitment(jubjub::AffinePoint::from_raw_unchecked(
444 jubjub::Fq::from_raw([
445 0xe4b3_d35d_f1a7_adfe,
446 0xcaf5_5d1b_29bf_81af,
447 0x8b0f_03dd_d60a_8187,
448 0x62ed_cbb8_bf37_87c8,
449 ]),
450 jubjub::Fq::from_raw([
451 0x0000_0000_0000_000b,
452 0x0000_0000_0000_0000,
453 0x0000_0000_0000_0000,
454 0x0000_0000_0000_0000,
455 ]),
456 ));
457
458 identity += g;
459 let new_g = identity;
460
461 assert_eq!(new_g, g);
462 }
463
464 #[test]
465 fn sub() {
466 let _init_guard = zebra_test::init();
467
468 let g_point = jubjub::AffinePoint::from_raw_unchecked(
469 jubjub::Fq::from_raw([
470 0xe4b3_d35d_f1a7_adfe,
471 0xcaf5_5d1b_29bf_81af,
472 0x8b0f_03dd_d60a_8187,
473 0x62ed_cbb8_bf37_87c8,
474 ]),
475 jubjub::Fq::from_raw([
476 0x0000_0000_0000_000b,
477 0x0000_0000_0000_0000,
478 0x0000_0000_0000_0000,
479 0x0000_0000_0000_0000,
480 ]),
481 );
482
483 let identity = ValueCommitment(jubjub::AffinePoint::identity());
484
485 let g = ValueCommitment(g_point);
486
487 assert_eq!(identity - g, ValueCommitment(g_point.neg()));
488 }
489
490 #[test]
491 fn sub_assign() {
492 let _init_guard = zebra_test::init();
493
494 let g_point = jubjub::AffinePoint::from_raw_unchecked(
495 jubjub::Fq::from_raw([
496 0xe4b3_d35d_f1a7_adfe,
497 0xcaf5_5d1b_29bf_81af,
498 0x8b0f_03dd_d60a_8187,
499 0x62ed_cbb8_bf37_87c8,
500 ]),
501 jubjub::Fq::from_raw([
502 0x0000_0000_0000_000b,
503 0x0000_0000_0000_0000,
504 0x0000_0000_0000_0000,
505 0x0000_0000_0000_0000,
506 ]),
507 );
508
509 let mut identity = ValueCommitment(jubjub::AffinePoint::identity());
510
511 let g = ValueCommitment(g_point);
512
513 identity -= g;
514 let new_g = identity;
515
516 assert_eq!(new_g, ValueCommitment(g_point.neg()));
517 }
518
519 #[test]
520 fn sum() {
521 let _init_guard = zebra_test::init();
522
523 let g_point = jubjub::AffinePoint::from_raw_unchecked(
524 jubjub::Fq::from_raw([
525 0xe4b3_d35d_f1a7_adfe,
526 0xcaf5_5d1b_29bf_81af,
527 0x8b0f_03dd_d60a_8187,
528 0x62ed_cbb8_bf37_87c8,
529 ]),
530 jubjub::Fq::from_raw([
531 0x0000_0000_0000_000b,
532 0x0000_0000_0000_0000,
533 0x0000_0000_0000_0000,
534 0x0000_0000_0000_0000,
535 ]),
536 );
537
538 let g = ValueCommitment(g_point);
539 let other_g = ValueCommitment(g_point);
540
541 let sum: ValueCommitment = vec![g, other_g].into_iter().sum();
542
543 let doubled_g = ValueCommitment(g_point.to_extended().double().into());
544
545 assert_eq!(sum, doubled_g);
546 }
547}