Skip to main content

orchard/
note.rs

1//! Data structures used for note construction.
2use core::fmt;
3use memuse::DynamicUsage;
4
5use blake2b_simd::Params as Blake2bParams;
6use ff::PrimeField;
7use group::GroupEncoding;
8use pasta_curves::pallas;
9use rand::Rng;
10use subtle::CtOption;
11
12use crate::note_encryption::NoteCiphertextBytes;
13use crate::{
14    keys::{EphemeralSecretKey, FullViewingKey, Scope, SpendingKey},
15    spec::{to_base, to_scalar, NonIdentityPallasPoint, NonZeroPallasScalar, PrfExpand},
16    value::NoteValue,
17    Address,
18};
19
20const PRF_EXPAND_PERSONALIZATION: &[u8; 16] = b"Zcash_ExpandSeed";
21const ZIP2005_ORCHARD_QR_RCM_DOMAIN_SEPARATOR: u8 = 0x0B;
22
23#[cfg(not(feature = "unstable-voting-circuits"))]
24pub(crate) mod commitment;
25#[cfg(feature = "unstable-voting-circuits")]
26pub mod commitment;
27#[cfg(any(feature = "unstable-voting-circuits", feature = "unsafe-zns"))]
28pub use self::commitment::NoteCommitTrapdoor;
29#[cfg(feature = "unsafe-zns")]
30pub use self::commitment::Psi;
31pub use self::commitment::{ExtractedNoteCommitment, NoteCommitment};
32
33/// Note plaintext version.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum NoteVersion {
36    /// The [ZIP 212] Orchard note plaintext format, identified by lead byte
37    /// `0x02`.
38    ///
39    /// [ZIP 212]: https://zips.z.cash/zip-0212
40    V2,
41    /// The quantum-recoverable Ironwood note plaintext version defined in
42    /// [ZIP 2005].
43    ///
44    /// [ZIP 2005]: https://zips.z.cash/zip-2005
45    V3,
46}
47
48impl NoteVersion {
49    /// Returns the note plaintext lead byte signaling this version.
50    pub(crate) const fn lead_byte(self) -> u8 {
51        match self {
52            Self::V2 => 0x02,
53            Self::V3 => 0x03,
54        }
55    }
56
57    /// Parses a note plaintext lead byte into the corresponding version,
58    /// returning `None` if the byte is not a recognized version.
59    pub(crate) fn from_lead_byte(b: u8) -> Option<Self> {
60        match b {
61            0x02 => Some(Self::V2),
62            0x03 => Some(Self::V3),
63            _ => None,
64        }
65    }
66}
67
68#[cfg(not(feature = "unstable-voting-circuits"))]
69pub(crate) mod nullifier;
70#[cfg(feature = "unstable-voting-circuits")]
71pub mod nullifier;
72pub use self::nullifier::Nullifier;
73
74/// The randomness used to construct a note.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
76pub struct Rho(pallas::Base);
77
78// We know that `pallas::Base` doesn't allocate internally.
79memuse::impl_no_dynamic_usage!(Rho);
80
81impl Rho {
82    /// Deserialize the rho value from a byte array.
83    ///
84    /// This should only be used in cases where the components of a `Note` are being serialized and
85    /// stored individually. Use [`Action::rho`] or [`CompactAction::rho`] to obtain the [`Rho`]
86    /// value otherwise.
87    ///
88    /// [`Action::rho`]: crate::action::Action::rho
89    /// [`CompactAction::rho`]: crate::note_encryption::CompactAction::rho
90    pub fn from_bytes(bytes: &[u8; 32]) -> CtOption<Self> {
91        pallas::Base::from_repr(*bytes).map(Rho)
92    }
93
94    /// Serialize the rho value to its canonical byte representation.
95    pub fn to_bytes(self) -> [u8; 32] {
96        self.0.to_repr()
97    }
98
99    /// Constructs the [`Rho`] value to be used to construct a new note from the revealed nullifier
100    /// of the note being spent in the [`Action`] under construction.
101    ///
102    /// [`Action`]: crate::action::Action
103    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
104    pub(crate) fn from_nf_old(nf: Nullifier) -> Self {
105        Rho(nf.inner())
106    }
107
108    /// Consumes `self` and returns the inner field element.
109    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
110    pub(crate) fn into_inner(self) -> pallas::Base {
111        self.0
112    }
113}
114
115/// The ZIP 212 seed randomness for a note.
116#[derive(Copy, Clone, Debug)]
117pub struct RandomSeed([u8; 32]);
118
119impl RandomSeed {
120    pub(crate) fn random(rng: &mut impl Rng, rho: &Rho) -> Self {
121        loop {
122            let mut bytes = [0; 32];
123            rng.fill_bytes(&mut bytes);
124            let rseed = RandomSeed::from_bytes(bytes, rho);
125            if rseed.is_some().into() {
126                break rseed.unwrap();
127            }
128        }
129    }
130
131    /// Reads a note's random seed from bytes, given the note's rho value.
132    ///
133    /// Returns `None` if the rho value is not for the same note as the seed.
134    pub fn from_bytes(rseed: [u8; 32], rho: &Rho) -> CtOption<Self> {
135        let rseed = RandomSeed(rseed);
136        let esk = rseed.esk_inner(rho);
137        CtOption::new(rseed, esk.is_some())
138    }
139
140    /// Returns the byte array corresponding to this seed.
141    pub fn as_bytes(&self) -> &[u8; 32] {
142        &self.0
143    }
144
145    /// Defined in [Zcash Protocol Spec § 4.7.3: Sending Notes (Orchard)][orchardsend].
146    ///
147    /// [orchardsend]: https://zips.z.cash/protocol/nu5.pdf#orchardsend
148    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
149    pub(crate) fn psi(&self, rho: &Rho) -> pallas::Base {
150        to_base(&PrfExpand::PSI.with(&self.0, &rho.to_bytes()))
151    }
152
153    /// Defined in [Zcash Protocol Spec § 4.7.3: Sending Notes (Orchard)][orchardsend].
154    ///
155    /// [orchardsend]: https://zips.z.cash/protocol/nu5.pdf#orchardsend
156    fn esk_inner(&self, rho: &Rho) -> CtOption<NonZeroPallasScalar> {
157        NonZeroPallasScalar::from_scalar(to_scalar(
158            &PrfExpand::ORCHARD_ESK.with(&self.0, &rho.to_bytes()),
159        ))
160    }
161
162    /// Defined in [Zcash Protocol Spec § 4.7.3: Sending Notes (Orchard)][orchardsend].
163    ///
164    /// [orchardsend]: https://zips.z.cash/protocol/nu5.pdf#orchardsend
165    fn esk(&self, rho: &Rho) -> NonZeroPallasScalar {
166        // We can't construct a RandomSeed for which this unwrap fails.
167        self.esk_inner(rho).unwrap()
168    }
169
170    /// The rcm derivation for V2 (ZIP 212) notes.
171    ///
172    /// Defined in [Zcash Protocol Spec § 4.7.3: Sending Notes (Orchard)][orchardsend].
173    ///
174    /// [orchardsend]: https://zips.z.cash/protocol/nu5.pdf#orchardsend
175    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
176    pub(crate) fn rcm_v2(&self, rho: &Rho) -> commitment::NoteCommitTrapdoor {
177        commitment::NoteCommitTrapdoor(to_scalar(
178            &PrfExpand::ORCHARD_RCM.with(&self.0, &rho.to_bytes()),
179        ))
180    }
181
182    /// Quantum-recoverable rcm derivation per [ZIP 2005].
183    ///
184    /// Binds rcm to all note fields for post-quantum commitment binding. This
185    /// implements $\mathsf{H}^{\mathsf{rcm},\mathsf{Orchard}}\_{\mathsf{rseed}}$:
186    ///
187    /// $$
188    /// \mathsf{pre}\_{\mathsf{rcm}} =
189    /// [ \mathtt{0x0B} ]
190    /// \mathbin\Vert \mathsf{g}^\star\_{\mathsf{d}}
191    /// \mathbin\Vert \mathsf{pk}^\star\_{\mathsf{d}}
192    /// \mathbin\Vert \mathsf{I2LEOSP}\_{64}(\mathsf{v})
193    /// \mathbin\Vert \rho
194    /// \mathbin\Vert \mathsf{I2LEOSP}\_{256}(\psi)
195    /// $$
196    ///
197    /// $$
198    /// \mathsf{rcm} =
199    /// \mathsf{ToScalar}^{\mathsf{Orchard}}
200    /// \left(\mathsf{PRF}^{\mathsf{expand}}\_{\mathsf{rseed}}
201    /// (\mathsf{pre}\_{\mathsf{rcm}})\right)
202    /// $$
203    ///
204    /// [ZIP 2005]: https://zips.z.cash/zip-2005
205    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
206    pub(crate) fn rcm_v3(
207        &self,
208        rho: &Rho,
209        g_d: &NonIdentityPallasPoint,
210        pk_d: &NonIdentityPallasPoint,
211        value: u64,
212        psi: &pallas::Base,
213    ) -> commitment::NoteCommitTrapdoor {
214        let mut h = Blake2bParams::new()
215            .hash_length(64)
216            .personal(PRF_EXPAND_PERSONALIZATION)
217            .to_state();
218        // rseed: raw bytes (32 bytes)
219        h.update(&self.0);
220        // domain separator: [0x0B] (1 byte, literal)
221        h.update(&[ZIP2005_ORCHARD_QR_RCM_DOMAIN_SEPARATOR]);
222        // g_d: LEBS2OSP_256(repr_P(g_d)) — compressed Pallas point (32 bytes)
223        h.update(&g_d.to_bytes());
224        // pk_d: LEBS2OSP_256(repr_P(pk_d)) — compressed Pallas point (32 bytes)
225        h.update(&pk_d.to_bytes());
226        // v: I2LEOSP_64(v) — unsigned 64-bit little-endian (8 bytes)
227        h.update(&value.to_le_bytes());
228        // rho: LEBS2OSP_256(repr_P(rho)) — Pallas base field canonical repr (32 bytes)
229        h.update(&rho.0.to_repr());
230        // psi: LEBS2OSP_256(repr_P(psi)) — Pallas base field canonical repr (32 bytes)
231        h.update(&psi.to_repr());
232
233        commitment::NoteCommitTrapdoor(to_scalar(h.finalize().as_array()))
234    }
235}
236
237/// A discrete amount of funds received by an address.
238#[derive(Debug, Copy, Clone)]
239pub struct Note {
240    /// The recipient of the funds.
241    recipient: Address,
242    /// The value of this note.
243    value: NoteValue,
244    /// A unique creation ID for this note.
245    ///
246    /// This is produced from the nullifier of the note that will be spent in the [`Action`] that
247    /// creates this note.
248    ///
249    /// [`Action`]: crate::action::Action
250    rho: Rho,
251    /// The seed randomness for various note components.
252    rseed: RandomSeed,
253    /// The note plaintext version, determining rcm derivation strategy.
254    version: NoteVersion,
255}
256
257impl PartialEq for Note {
258    fn eq(&self, other: &Self) -> bool {
259        // Notes are canonically defined by their commitments.
260        ExtractedNoteCommitment::from(self.commitment())
261            .eq(&ExtractedNoteCommitment::from(other.commitment()))
262    }
263}
264
265impl Eq for Note {}
266
267impl Note {
268    /// Creates a `Note` from its component parts.
269    ///
270    /// Returns `None` if a valid [`NoteCommitment`] cannot be derived from the note.
271    ///
272    /// # Caveats
273    ///
274    /// This low-level constructor enforces that the provided arguments produce an
275    /// internally valid `Note`. However, it allows notes to be constructed in a way that
276    /// violates required security checks for note decryption, as specified in
277    /// [Section 4.19] of the Zcash Protocol Specification. Users of this constructor
278    /// should only call it with note components that have been fully validated by
279    /// decrypting a received note according to [Section 4.19].
280    ///
281    /// [Section 4.19]: https://zips.z.cash/protocol/protocol.pdf#saplingandorchardinband
282    pub fn from_parts(
283        recipient: Address,
284        value: NoteValue,
285        rho: Rho,
286        rseed: RandomSeed,
287        version: NoteVersion,
288    ) -> CtOption<Self> {
289        let note = Note {
290            recipient,
291            value,
292            rho,
293            rseed,
294            version,
295        };
296        CtOption::new(note, note.commitment_inner().is_some())
297    }
298
299    /// Generates a new note.
300    ///
301    /// Defined in [Zcash Protocol Spec § 4.7.3: Sending Notes (Orchard)][orchardsend].
302    ///
303    /// [orchardsend]: https://zips.z.cash/protocol/nu5.pdf#orchardsend
304    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
305    pub(crate) fn new(
306        recipient: Address,
307        value: NoteValue,
308        rho: Rho,
309        version: NoteVersion,
310        mut rng: impl Rng,
311    ) -> Self {
312        loop {
313            let note = Note::from_parts(
314                recipient,
315                value,
316                rho,
317                RandomSeed::random(&mut rng, &rho),
318                version,
319            );
320            if note.is_some().into() {
321                break note.unwrap();
322            }
323        }
324    }
325
326    /// Generates a dummy spent note.
327    ///
328    /// Defined in [Zcash Protocol Spec § 4.8.3: Dummy Notes (Orchard)][orcharddummynotes].
329    ///
330    /// [orcharddummynotes]: https://zips.z.cash/protocol/nu5.pdf#orcharddummynotes
331    #[cfg_attr(feature = "unstable-voting-circuits", visibility::make(pub))]
332    pub(crate) fn dummy(
333        rng: &mut impl Rng,
334        rho: Option<Rho>,
335        note_version: NoteVersion,
336    ) -> (SpendingKey, FullViewingKey, Self) {
337        let sk = SpendingKey::random(rng);
338        let fvk: FullViewingKey = (&sk).into();
339        let recipient = fvk.address_at(0u32, Scope::External);
340
341        let note = Note::new(
342            recipient,
343            NoteValue::ZERO,
344            rho.unwrap_or_else(|| Rho::from_nf_old(Nullifier::dummy(rng))),
345            note_version,
346            rng,
347        );
348
349        (sk, fvk, note)
350    }
351
352    /// Returns the recipient of this note.
353    pub fn recipient(&self) -> Address {
354        self.recipient
355    }
356
357    /// Returns the value of this note.
358    pub fn value(&self) -> NoteValue {
359        self.value
360    }
361
362    /// Returns the rseed value of this note.
363    pub fn rseed(&self) -> &RandomSeed {
364        &self.rseed
365    }
366
367    /// Derives the ephemeral secret key for this note.
368    pub(crate) fn esk(&self) -> EphemeralSecretKey {
369        EphemeralSecretKey(self.rseed.esk(&self.rho))
370    }
371
372    /// Returns rho of this note.
373    pub fn rho(&self) -> Rho {
374        self.rho
375    }
376
377    /// Returns the version of this note.
378    pub fn version(&self) -> NoteVersion {
379        self.version
380    }
381
382    /// Derives the ψ value for this note.
383    pub(crate) fn psi(&self) -> pallas::Base {
384        self.rseed.psi(&self.rho())
385    }
386
387    /// Derives the note commitment trapdoor for this note.
388    pub(crate) fn rcm(&self) -> commitment::NoteCommitTrapdoor {
389        let rho = self.rho();
390
391        match self.version {
392            NoteVersion::V2 => self.rseed.rcm_v2(&rho),
393            NoteVersion::V3 => {
394                let g_d = self.recipient.g_d();
395                let pk_d = self.recipient.pk_d().inner();
396                let psi = self.rseed.psi(&rho);
397
398                self.rseed
399                    .rcm_v3(&rho, &g_d, &pk_d, self.value.inner(), &psi)
400            }
401        }
402    }
403
404    /// Derives the commitment to this note.
405    ///
406    /// Defined in [Zcash Protocol Spec § 3.2: Notes][notes].
407    ///
408    /// [notes]: https://zips.z.cash/protocol/nu5.pdf#notes
409    pub fn commitment(&self) -> NoteCommitment {
410        // `Note` will always have a note commitment by construction.
411        self.commitment_inner().unwrap()
412    }
413
414    /// Derives the commitment to this note.
415    ///
416    /// This is the internal fallible API, used to check at construction time that the
417    /// note has a commitment. Once you have a [`Note`] object, use `note.commitment()`
418    /// instead.
419    ///
420    /// Defined in [Zcash Protocol Spec § 3.2: Notes][notes].
421    ///
422    /// [notes]: https://zips.z.cash/protocol/nu5.pdf#notes
423    fn commitment_inner(&self) -> CtOption<NoteCommitment> {
424        let g_d = self.recipient.g_d();
425        let g_d_bytes = g_d.to_bytes();
426        let pk_d = self.recipient.pk_d().inner();
427        let pk_d_bytes = pk_d.to_bytes();
428        let psi = self.psi();
429
430        NoteCommitment::derive(
431            g_d_bytes,
432            pk_d_bytes,
433            self.value,
434            self.rho.0,
435            psi,
436            self.rcm(),
437        )
438    }
439
440    /// Derives the nullifier for this note.
441    pub fn nullifier(&self, fvk: &FullViewingKey) -> Nullifier {
442        Nullifier::derive(fvk.nk(), self.rho.0, self.psi(), self.commitment())
443    }
444
445    /// Derives this note's commitment from the supplied `(rcm, ψ)` opening
446    /// instead of the note's `rseed`-derived values — the single derivation
447    /// site shared by the ZNS builder and scan paths.
448    ///
449    /// The returned `CtOption` is absent if the commitment is the identity point.
450    pub(crate) fn zns_commitment(
451        &self,
452        rcm: commitment::NoteCommitTrapdoor,
453        psi: commitment::Psi,
454    ) -> CtOption<commitment::NoteCommitment> {
455        let g_d = self.recipient.g_d();
456        let g_d_bytes = g_d.to_bytes();
457        let pk_d = self.recipient.pk_d().inner();
458        let pk_d_bytes = pk_d.to_bytes();
459
460        commitment::NoteCommitment::derive(
461            g_d_bytes,
462            pk_d_bytes,
463            self.value,
464            self.rho.0,
465            psi.inner(),
466            rcm,
467        )
468    }
469
470    /// Derives the extracted note commitment (`cmx`) for this note from
471    /// caller-supplied `(rcm, ψ)` instead of the values derived from the
472    /// note's `rseed`.
473    ///
474    /// A ZcashName Name Note publishes in its action the `cmx` derived from
475    /// ZcashName commitment parameters rather than from `rseed`. Trial
476    /// decryption via
477    /// [`ZnsIronwoodDomain`](crate::note_encryption::ZnsIronwoodDomain)
478    /// returns the decrypted note; the caller derives `(rcm, ψ)` from the
479    /// transition σ carried in its memo (whitepaper §3.3) and feeds them to
480    /// this method. The note authenticates exactly when the `cmx` recomputed
481    /// by this method equals the action's `cmx`.
482    ///
483    /// Returns `None` if the commitment is the identity point; scanners
484    /// should reject the note rather than panic.
485    #[cfg(feature = "unsafe-zns")]
486    pub fn zns_cmx(
487        &self,
488        rcm: commitment::NoteCommitTrapdoor,
489        psi: commitment::Psi,
490    ) -> Option<ExtractedNoteCommitment> {
491        let cm = Option::<commitment::NoteCommitment>::from(self.zns_commitment(rcm, psi))?;
492        Some(ExtractedNoteCommitment::from(cm))
493    }
494
495    /// Derives the nullifier for this note from caller-supplied `(rcm, ψ)`
496    /// and the commitment they produce, instead of the values derived from
497    /// the note's `rseed`.
498    ///
499    /// A Name Note's on-chain nullifier is derived from its ZcashName
500    /// commitment parameters, so [`nullifier`](Self::nullifier) does not
501    /// match the nullifier revealed when the note is spent. Wallets must
502    /// store this method's result to detect their own Name Notes being
503    /// spent.
504    ///
505    /// Returns `None` if the commitment is the identity point.
506    #[cfg(feature = "unsafe-zns")]
507    pub fn zns_nullifier(
508        &self,
509        fvk: &FullViewingKey,
510        rcm: commitment::NoteCommitTrapdoor,
511        psi: commitment::Psi,
512    ) -> Option<Nullifier> {
513        let cm = Option::<commitment::NoteCommitment>::from(self.zns_commitment(rcm, psi))?;
514        Some(Nullifier::derive(fvk.nk(), self.rho.0, psi.inner(), cm))
515    }
516}
517
518/// An encrypted note.
519#[derive(Clone)]
520pub struct TransmittedNoteCiphertext {
521    /// The serialization of the ephemeral public key
522    pub epk_bytes: [u8; 32],
523    /// The encrypted note ciphertext
524    pub enc_ciphertext: NoteCiphertextBytes,
525    /// An encrypted value that allows the holder of the outgoing cipher
526    /// key for the note to recover the note plaintext.
527    pub out_ciphertext: [u8; 80],
528}
529
530impl fmt::Debug for TransmittedNoteCiphertext {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        f.debug_struct("TransmittedNoteCiphertext")
533            .field("epk_bytes", &self.epk_bytes)
534            .field("enc_ciphertext", &hex::encode(self.enc_ciphertext.0))
535            .field("out_ciphertext", &hex::encode(self.out_ciphertext))
536            .finish()
537    }
538}
539
540/// Generators for property testing.
541#[cfg(any(test, feature = "test-dependencies"))]
542#[cfg_attr(docsrs, doc(cfg(feature = "test-dependencies")))]
543pub mod testing {
544    use proptest::prelude::*;
545
546    use crate::{
547        address::testing::arb_address, note::nullifier::testing::arb_nullifier, value::NoteValue,
548    };
549
550    #[cfg(feature = "unsafe-zns")]
551    pub use super::commitment::testing::{arb_note_commit_trapdoor, arb_psi};
552
553    use super::{Note, NoteVersion, RandomSeed, Rho};
554
555    prop_compose! {
556        /// Generate an arbitrary random seed
557        pub(crate) fn arb_rseed()(elems in prop::array::uniform32(prop::num::u8::ANY)) -> RandomSeed {
558            RandomSeed(elems)
559        }
560    }
561
562    prop_compose! {
563        /// Generate an arbitrary note with the given plaintext version.
564        pub fn arb_note(value: NoteValue, version: NoteVersion)(
565            recipient in arb_address(),
566            rho in arb_nullifier().prop_map(Rho::from_nf_old),
567            rseed in arb_rseed(),
568        ) -> Note {
569            Note {
570                recipient,
571                value,
572                rho,
573                rseed,
574                version,
575            }
576        }
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583    use crate::{
584        keys::{FullViewingKey, Scope, SpendingKey},
585        test_vectors::keys::TestVector,
586    };
587    use ff::PrimeField;
588    use group::GroupEncoding;
589
590    struct QrRcmDerivation {
591        rcm_old_repr: [u8; 32],
592        rcm_new_repr: [u8; 32],
593        cmx_old_bytes: [u8; 32],
594        cmx_qr_bytes: [u8; 32],
595    }
596
597    fn qr_rcm_from_key_test_vector(tv: &TestVector) -> QrRcmDerivation {
598        let sk = SpendingKey::from_bytes(tv.sk).unwrap();
599        let fvk = FullViewingKey::from(&sk);
600        let addr = fvk.address_at(0u32, Scope::External);
601        let rho = Rho::from_bytes(&tv.note_rho).unwrap();
602        let rseed = RandomSeed::from_bytes(tv.note_rseed, &rho).unwrap();
603
604        let g_d = addr.g_d();
605        let pk_d = addr.pk_d().inner();
606        let g_d_bytes = g_d.to_bytes();
607        let pk_d_bytes = pk_d.to_bytes();
608
609        let rcm_old = rseed.rcm_v2(&rho);
610        let psi = rseed.psi(&rho);
611        let rcm_new = rseed.rcm_v3(&rho, &g_d, &pk_d, tv.note_v, &psi);
612
613        let rcm_old_repr = rcm_old.0.to_repr();
614        let rcm_new_repr = rcm_new.0.to_repr();
615        let rho_inner = rho.into_inner();
616        let value = NoteValue::from_raw(tv.note_v);
617
618        let cmx_old =
619            NoteCommitment::derive(g_d_bytes, pk_d_bytes, value, rho_inner, psi, rcm_old).unwrap();
620        let cmx_old_bytes = ExtractedNoteCommitment::from(cmx_old).to_bytes();
621
622        let cmx_qr =
623            NoteCommitment::derive(g_d_bytes, pk_d_bytes, value, rho_inner, psi, rcm_new).unwrap();
624        let cmx_qr_bytes = ExtractedNoteCommitment::from(cmx_qr).to_bytes();
625
626        QrRcmDerivation {
627            rcm_old_repr,
628            rcm_new_repr,
629            cmx_old_bytes,
630            cmx_qr_bytes,
631        }
632    }
633
634    #[test]
635    fn qr_rcm_differs_from_old_rcm() {
636        let tv = &crate::test_vectors::keys::test_vectors()[0];
637        let derived = qr_rcm_from_key_test_vector(tv);
638
639        assert_ne!(derived.rcm_old_repr, derived.rcm_new_repr);
640        assert_eq!(
641            derived.cmx_old_bytes, tv.note_cmx,
642            "old cmx must match known test vector"
643        );
644        assert_ne!(derived.cmx_old_bytes, derived.cmx_qr_bytes);
645    }
646
647    #[test]
648    fn qr_rcm_verify_stored_vectors() {
649        for (i, key_tv) in crate::test_vectors::keys::test_vectors().iter().enumerate() {
650            let derived = qr_rcm_from_key_test_vector(key_tv);
651
652            assert_eq!(
653                derived.rcm_new_repr, key_tv.note_qr_rcm,
654                "vector {i}: rcm_qr mismatch"
655            );
656            assert_eq!(
657                derived.cmx_old_bytes, key_tv.note_cmx,
658                "vector {i}: cmx_old mismatch"
659            );
660            assert_eq!(
661                derived.cmx_qr_bytes, key_tv.note_qr_cmx,
662                "vector {i}: cmx_qr mismatch"
663            );
664        }
665    }
666}