zebra_chain/sapling/
commitment.rs

1//! Note and value commitments.
2
3use std::{fmt, io};
4
5use bitvec::prelude::*;
6use hex::{FromHex, FromHexError, 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
28/// Generates a random scalar from the scalar field 𝔽_{r_𝕁}.
29///
30/// The prime order subgroup 𝕁^(r) is the order-r_𝕁 subgroup of 𝕁 that consists
31/// of the points whose order divides r. This function is useful when generating
32/// the uniform distribution on 𝔽_{r_𝕁} needed for Sapling commitment schemes'
33/// trapdoor generators.
34///
35/// <https://zips.z.cash/protocol/protocol.pdf#jubjub>
36pub 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    // Fr::from_bytes_wide() reduces the input modulo r via Fr::from_u512()
45    Ok(jubjub::Fr::from_bytes_wide(&bytes))
46}
47
48/// The randomness used in the Pedersen Hash for note commitment.
49#[derive(Copy, Clone, Debug, PartialEq, Eq)]
50pub struct CommitmentRandomness(jubjub::Fr);
51
52/// Note commitments for the output notes.
53#[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    /// Generate a new _NoteCommitment_ and the randomness used to create it.
93    ///
94    /// We return the randomness because it is needed to construct a _Note_,
95    /// before it is encrypted as part of an _Output Description_. This is a
96    /// higher level function that calls `NoteCommit^Sapling_rcm` internally.
97    ///
98    /// NoteCommit^Sapling_rcm (g*_d , pk*_d , v) :=
99    ///   WindowedPedersenCommit_rcm([1; 6] || I2LEBSP_64(v) || g*_d || pk*_d)
100    ///
101    /// <https://zips.z.cash/protocol/protocol.pdf#concretewindowedcommit>
102    #[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        // s as in the argument name for WindowedPedersenCommit_r(s)
113        let mut s: BitVec<u8, Lsb0> = BitVec::new();
114
115        // Prefix
116        s.append(&mut bitvec![1; 6]);
117
118        // Jubjub repr_J canonical byte encoding
119        // https://zips.z.cash/protocol/protocol.pdf#jubjub
120        //
121        // The `TryFrom<Diversifier>` impls for the `jubjub::*Point`s handles
122        // calling `DiversifyHash` implicitly.
123
124        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    /// Hash Extractor for Jubjub (?)
144    ///
145    /// <https://zips.z.cash/protocol/protocol.pdf#concreteextractorjubjub>
146    pub fn extract_u(&self) -> jubjub::Fq {
147        self.0.get_u()
148    }
149}
150
151/// A Homomorphic Pedersen commitment to the value of a note.
152///
153/// This can be used as an intermediate value in some computations. For the
154/// type actually stored in Spend and Output descriptions, see
155/// [`NotSmallOrderValueCommitment`].
156///
157/// <https://zips.z.cash/protocol/protocol.pdf#concretehomomorphiccommit>
158#[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    /// Convert a Jubjub point into a ValueCommitment.
196    fn from(extended_point: jubjub::ExtendedPoint) -> Self {
197        Self(jubjub::AffinePoint::from(extended_point))
198    }
199}
200
201/// LEBS2OSP256(repr_J(cv))
202///
203/// <https://zips.z.cash/protocol/protocol.pdf#spendencoding>
204/// <https://zips.z.cash/protocol/protocol.pdf#jubjub>
205impl 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
245/// LEBS2OSP256(repr_J(cv))
246///
247/// <https://zips.z.cash/protocol/protocol.pdf#spendencoding>
248/// <https://zips.z.cash/protocol/protocol.pdf#jubjub>
249impl 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    /// Generate a new _ValueCommitment_.
266    ///
267    /// <https://zips.z.cash/protocol/protocol.pdf#concretehomomorphiccommit>
268    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    /// Generate a new _ValueCommitment_ from an existing _rcv_ on a _value_.
278    ///
279    /// <https://zips.z.cash/protocol/protocol.pdf#concretehomomorphiccommit>
280    #[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/// A Homomorphic Pedersen commitment to the value of a note, used in Spend and
293/// Output descriptions.
294///
295/// Elements that are of small order are not allowed. This is a separate
296/// consensus rule and not intrinsic of value commitments; which is why this
297/// type exists.
298///
299/// This is denoted by `cv` in the specification.
300///
301/// <https://zips.z.cash/protocol/protocol.pdf#spenddesc>
302/// <https://zips.z.cash/protocol/protocol.pdf#outputdesc>
303#[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    /// Return the hash bytes in big-endian byte-order suitable for printing out byte by byte.
309    ///
310    /// Zebra displays commitment value in big-endian byte-order,
311    /// following the convention set by zcashd.
312    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    /// Convert a ValueCommitment into a NotSmallOrderValueCommitment.
322    ///
323    /// Returns an error if the point is of small order.
324    ///
325    /// # Consensus
326    ///
327    /// > cv and rk [MUST NOT be of small order][1], i.e. \[h_J\]cv MUST NOT be 𝒪_J
328    /// > and \[h_J\]rk MUST NOT be 𝒪_J.
329    ///
330    /// > cv and epk [MUST NOT be of small order][2], i.e. \[h_J\]cv MUST NOT be 𝒪_J
331    /// > and \[ℎ_J\]epk MUST NOT be 𝒪_J.
332    ///
333    /// [1]: https://zips.z.cash/protocol/protocol.pdf#spenddesc
334    /// [2]: https://zips.z.cash/protocol/protocol.pdf#outputdesc
335    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    /// Convert a Jubjub point into a NotSmallOrderValueCommitment.
348    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
390impl FromHex for NotSmallOrderValueCommitment {
391    type Error = FromHexError;
392
393    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
394        // Parse hex string to 32 bytes
395        let mut bytes = <[u8; 32]>::from_hex(hex)?;
396        // Convert from big-endian (display) to little-endian (internal)
397        bytes.reverse();
398
399        Self::zcash_deserialize(io::Cursor::new(&bytes))
400            .map_err(|_| FromHexError::InvalidStringLength)
401    }
402}
403
404#[cfg(test)]
405mod tests {
406
407    use std::ops::Neg;
408
409    use super::*;
410
411    #[test]
412    fn pedersen_hash_to_point_test_vectors() {
413        let _init_guard = zebra_test::init();
414
415        const D: [u8; 8] = *b"Zcash_PH";
416
417        for test_vector in test_vectors::TEST_VECTORS.iter() {
418            let result = jubjub::AffinePoint::from(pedersen_hash_to_point(
419                D,
420                &test_vector.input_bits.clone(),
421            ));
422
423            assert_eq!(result, test_vector.output_point);
424        }
425    }
426
427    #[test]
428    fn add() {
429        let _init_guard = zebra_test::init();
430
431        let identity = ValueCommitment(jubjub::AffinePoint::identity());
432
433        let g = ValueCommitment(jubjub::AffinePoint::from_raw_unchecked(
434            jubjub::Fq::from_raw([
435                0xe4b3_d35d_f1a7_adfe,
436                0xcaf5_5d1b_29bf_81af,
437                0x8b0f_03dd_d60a_8187,
438                0x62ed_cbb8_bf37_87c8,
439            ]),
440            jubjub::Fq::from_raw([
441                0x0000_0000_0000_000b,
442                0x0000_0000_0000_0000,
443                0x0000_0000_0000_0000,
444                0x0000_0000_0000_0000,
445            ]),
446        ));
447
448        assert_eq!(identity + g, g);
449    }
450
451    #[test]
452    fn add_assign() {
453        let _init_guard = zebra_test::init();
454
455        let mut identity = ValueCommitment(jubjub::AffinePoint::identity());
456
457        let g = ValueCommitment(jubjub::AffinePoint::from_raw_unchecked(
458            jubjub::Fq::from_raw([
459                0xe4b3_d35d_f1a7_adfe,
460                0xcaf5_5d1b_29bf_81af,
461                0x8b0f_03dd_d60a_8187,
462                0x62ed_cbb8_bf37_87c8,
463            ]),
464            jubjub::Fq::from_raw([
465                0x0000_0000_0000_000b,
466                0x0000_0000_0000_0000,
467                0x0000_0000_0000_0000,
468                0x0000_0000_0000_0000,
469            ]),
470        ));
471
472        identity += g;
473        let new_g = identity;
474
475        assert_eq!(new_g, g);
476    }
477
478    #[test]
479    fn sub() {
480        let _init_guard = zebra_test::init();
481
482        let g_point = jubjub::AffinePoint::from_raw_unchecked(
483            jubjub::Fq::from_raw([
484                0xe4b3_d35d_f1a7_adfe,
485                0xcaf5_5d1b_29bf_81af,
486                0x8b0f_03dd_d60a_8187,
487                0x62ed_cbb8_bf37_87c8,
488            ]),
489            jubjub::Fq::from_raw([
490                0x0000_0000_0000_000b,
491                0x0000_0000_0000_0000,
492                0x0000_0000_0000_0000,
493                0x0000_0000_0000_0000,
494            ]),
495        );
496
497        let identity = ValueCommitment(jubjub::AffinePoint::identity());
498
499        let g = ValueCommitment(g_point);
500
501        assert_eq!(identity - g, ValueCommitment(g_point.neg()));
502    }
503
504    #[test]
505    fn sub_assign() {
506        let _init_guard = zebra_test::init();
507
508        let g_point = jubjub::AffinePoint::from_raw_unchecked(
509            jubjub::Fq::from_raw([
510                0xe4b3_d35d_f1a7_adfe,
511                0xcaf5_5d1b_29bf_81af,
512                0x8b0f_03dd_d60a_8187,
513                0x62ed_cbb8_bf37_87c8,
514            ]),
515            jubjub::Fq::from_raw([
516                0x0000_0000_0000_000b,
517                0x0000_0000_0000_0000,
518                0x0000_0000_0000_0000,
519                0x0000_0000_0000_0000,
520            ]),
521        );
522
523        let mut identity = ValueCommitment(jubjub::AffinePoint::identity());
524
525        let g = ValueCommitment(g_point);
526
527        identity -= g;
528        let new_g = identity;
529
530        assert_eq!(new_g, ValueCommitment(g_point.neg()));
531    }
532
533    #[test]
534    fn sum() {
535        let _init_guard = zebra_test::init();
536
537        let g_point = jubjub::AffinePoint::from_raw_unchecked(
538            jubjub::Fq::from_raw([
539                0xe4b3_d35d_f1a7_adfe,
540                0xcaf5_5d1b_29bf_81af,
541                0x8b0f_03dd_d60a_8187,
542                0x62ed_cbb8_bf37_87c8,
543            ]),
544            jubjub::Fq::from_raw([
545                0x0000_0000_0000_000b,
546                0x0000_0000_0000_0000,
547                0x0000_0000_0000_0000,
548                0x0000_0000_0000_0000,
549            ]),
550        );
551
552        let g = ValueCommitment(g_point);
553        let other_g = ValueCommitment(g_point);
554
555        let sum: ValueCommitment = vec![g, other_g].into_iter().sum();
556
557        let doubled_g = ValueCommitment(g_point.to_extended().double().into());
558
559        assert_eq!(sum, doubled_g);
560    }
561
562    #[test]
563    fn value_commitment_hex_roundtrip() {
564        use hex::{FromHex, ToHex};
565
566        let _init_guard = zebra_test::init();
567
568        let g_point = jubjub::AffinePoint::from_raw_unchecked(
569            jubjub::Fq::from_raw([
570                0xe4b3_d35d_f1a7_adfe,
571                0xcaf5_5d1b_29bf_81af,
572                0x8b0f_03dd_d60a_8187,
573                0x62ed_cbb8_bf37_87c8,
574            ]),
575            jubjub::Fq::from_raw([
576                0x0000_0000_0000_000b,
577                0x0000_0000_0000_0000,
578                0x0000_0000_0000_0000,
579                0x0000_0000_0000_0000,
580            ]),
581        );
582
583        let value_commitment = ValueCommitment(g_point);
584        let original = NotSmallOrderValueCommitment::try_from(value_commitment)
585            .expect("constructed point must not be small order");
586
587        let hex_str = (&original).encode_hex::<String>();
588
589        let decoded = NotSmallOrderValueCommitment::from_hex(&hex_str)
590            .expect("hex string should decode successfully");
591
592        assert_eq!(original, decoded);
593    }
594}