Skip to main content

zcash_primitives/transaction/components/
sapling.rs

1use alloc::vec::Vec;
2use core::mem::size_of;
3use corez::io::{self, Read, Write};
4use ff::PrimeField;
5
6use ::sapling::{
7    Nullifier,
8    bundle::{
9        Authorization, Authorized, Bundle, GrothProofBytes, OutputDescription, OutputDescriptionV5,
10        SpendDescription, SpendDescriptionV5,
11    },
12    note::ExtractedNoteCommitment,
13    note_encryption::{ENC_CIPHERTEXT_SIZE, Zip212Enforcement},
14    value::ValueCommitment,
15};
16use redjubjub::SpendAuth;
17use zcash_encoding::{Array, CompactSize, Vector};
18use zcash_note_encryption::{EphemeralKeyBytes, OUT_CIPHERTEXT_SIZE};
19use zcash_protocol::{
20    consensus::{BlockHeight, NetworkUpgrade, Parameters, ZIP212_GRACE_PERIOD},
21    value::ZatBalance,
22};
23
24use super::GROTH_PROOF_SIZE;
25use crate::transaction::Transaction;
26
27/// The size in bytes of a Sapling spend description in its v4 (pre-NU5) serialized form, as
28/// written by the internal `write_spend_v4` encoder.
29///
30/// This is the full per-spend cost on the wire in a version 4 transaction: the value
31/// commitment, the anchor, the nullifier, the randomized spending key, the Groth16 proof,
32/// and the spend authorization signature. Version 5 transactions move the proofs and
33/// authorization signatures to bundle-level fields (the v5 spend encoder writes only
34/// `cv` + `nullifier` + `rk`), so this v4 size is the conservative upper bound: dividing a
35/// per-spend byte budget by this constant yields a lower bound on the number of spends
36/// that fit within it.
37pub const SPEND_DESCRIPTION_SIZE: usize = VALUE_COMMITMENT_BYTE_SIZE
38    + ANCHOR_BYTE_SIZE
39    + NULLIFIER_BYTE_SIZE
40    + RK_BYTE_SIZE
41    + GROTH_PROOF_SIZE
42    + SPEND_AUTH_SIG_BYTE_SIZE;
43
44/// The size in bytes of a Sapling output description in its v4 (pre-NU5) serialized form, as
45/// written by the internal `write_output_v4` encoder.
46///
47/// This is the full per-output cost on the wire in a version 4 transaction: the value
48/// commitment, the extracted note commitment, the ephemeral key, the encrypted note
49/// ciphertext, the encrypted outgoing ciphertext, and the Groth16 proof. Version 5
50/// transactions move the proofs to a bundle-level field (the v5 output encoder omits the
51/// `zkproof`), so this v4 size is the conservative upper bound: dividing a per-output byte
52/// budget by this constant yields a lower bound on the number of outputs that fit within it.
53pub const OUTPUT_DESCRIPTION_SIZE: usize = VALUE_COMMITMENT_BYTE_SIZE
54    + CMU_BYTE_SIZE
55    + EPHEMERAL_KEY_BYTE_SIZE
56    + ENC_CIPHERTEXT_SIZE
57    + OUT_CIPHERTEXT_SIZE
58    + GROTH_PROOF_SIZE;
59
60/// The size in bytes of the encoding of a Sapling value commitment (a Jubjub group element).
61const VALUE_COMMITMENT_BYTE_SIZE: usize = 32;
62/// The size in bytes of the encoding of a Sapling nullifier.
63const NULLIFIER_BYTE_SIZE: usize = 32;
64/// The size in bytes of the encoding of a Sapling spend authorization key (a RedJubjub
65/// verification key).
66const RK_BYTE_SIZE: usize = 32;
67/// The size in bytes of the encoding of a Sapling spend authorization signature.
68const SPEND_AUTH_SIG_BYTE_SIZE: usize = 64;
69/// The size in bytes of the encoding of a Sapling anchor (a Jubjub base field element).
70const ANCHOR_BYTE_SIZE: usize = 32;
71/// The size in bytes of the encoding of a Sapling extracted note commitment.
72const CMU_BYTE_SIZE: usize = 32;
73/// The size in bytes of the encoding of a Sapling ephemeral key.
74const EPHEMERAL_KEY_BYTE_SIZE: usize = size_of::<EphemeralKeyBytes>();
75
76/// The per-bundle overhead of a Sapling bundle, excluding the per-spend and per-output
77/// data: CompactSize prefixes for the spends and outputs arrays (at most 9 + 9) +
78/// value_balance (8) + anchor (32) + binding_sig (64).
79pub const BUNDLE_OVERHEAD: usize = 9 + 9 + 8 + 32 + 64;
80
81/// Returns the enforcement policy for ZIP 212 at the given height.
82pub fn zip212_enforcement(params: &impl Parameters, height: BlockHeight) -> Zip212Enforcement {
83    if params.is_nu_active(NetworkUpgrade::Canopy, height) {
84        let grace_period_end_height =
85            params.activation_height(NetworkUpgrade::Canopy).unwrap() + ZIP212_GRACE_PERIOD;
86
87        if height < grace_period_end_height {
88            Zip212Enforcement::GracePeriod
89        } else {
90            Zip212Enforcement::On
91        }
92    } else {
93        Zip212Enforcement::Off
94    }
95}
96
97/// A map from one bundle authorization to another.
98///
99/// For use with [`TransactionData::map_authorization`].
100///
101/// [`TransactionData::map_authorization`]: crate::transaction::TransactionData::map_authorization
102pub trait MapAuth<A: Authorization, B: Authorization> {
103    fn map_spend_proof(&mut self, p: A::SpendProof) -> B::SpendProof;
104    fn map_output_proof(&mut self, p: A::OutputProof) -> B::OutputProof;
105    fn map_auth_sig(&mut self, s: A::AuthSig) -> B::AuthSig;
106    fn map_authorization(&mut self, a: A) -> B;
107}
108
109/// The identity map.
110///
111/// This can be used with [`TransactionData::map_authorization`] when you want to map the
112/// authorization of a subset of a transaction's bundles.
113///
114/// [`TransactionData::map_authorization`]: crate::transaction::TransactionData::map_authorization
115impl MapAuth<Authorized, Authorized> for () {
116    fn map_spend_proof(
117        &mut self,
118        p: <Authorized as Authorization>::SpendProof,
119    ) -> <Authorized as Authorization>::SpendProof {
120        p
121    }
122
123    fn map_output_proof(
124        &mut self,
125        p: <Authorized as Authorization>::OutputProof,
126    ) -> <Authorized as Authorization>::OutputProof {
127        p
128    }
129
130    fn map_auth_sig(
131        &mut self,
132        s: <Authorized as Authorization>::AuthSig,
133    ) -> <Authorized as Authorization>::AuthSig {
134        s
135    }
136
137    fn map_authorization(&mut self, a: Authorized) -> Authorized {
138        a
139    }
140}
141
142/// Consensus rules (§4.4) & (§4.5):
143/// - Canonical encoding is enforced here.
144/// - "Not small order" is enforced here.
145fn read_value_commitment<R: Read>(mut reader: R) -> io::Result<ValueCommitment> {
146    let mut bytes = [0u8; 32];
147    reader.read_exact(&mut bytes)?;
148    let cv = ValueCommitment::from_bytes_not_small_order(&bytes);
149
150    if cv.is_none().into() {
151        Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid cv"))
152    } else {
153        Ok(cv.unwrap())
154    }
155}
156
157/// Consensus rules (§7.3) & (§7.4):
158/// - Canonical encoding is enforced here
159fn read_cmu<R: Read>(mut reader: R) -> io::Result<ExtractedNoteCommitment> {
160    let mut f = [0u8; 32];
161    reader.read_exact(&mut f)?;
162    Option::from(ExtractedNoteCommitment::from_bytes(&f))
163        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "cmu not in field"))
164}
165
166/// Consensus rules (§7.3) & (§7.4):
167/// - Canonical encoding is enforced here
168pub fn read_base<R: Read>(mut reader: R, _field: &str) -> io::Result<jubjub::Base> {
169    let mut f = [0u8; 32];
170    reader.read_exact(&mut f)?;
171    Option::from(jubjub::Base::from_repr(f)).ok_or_else(|| {
172        io::Error::new(
173            io::ErrorKind::InvalidInput,
174            "base value not a valid field element",
175        )
176    })
177}
178
179/// Consensus rules (§4.4) & (§4.5):
180/// - Canonical encoding is enforced by the API of SaplingVerificationContext::check_spend()
181///   and SaplingVerificationContext::check_output() due to the need to parse this into a
182///   groth16::Proof.
183/// - Proof validity is enforced in SaplingVerificationContext::check_spend()
184///   and SaplingVerificationContext::check_output()
185pub fn read_zkproof<R: Read>(mut reader: R) -> io::Result<GrothProofBytes> {
186    let mut zkproof = [0u8; GROTH_PROOF_SIZE];
187    reader.read_exact(&mut zkproof)?;
188    Ok(zkproof)
189}
190
191fn read_nullifier<R: Read>(mut reader: R) -> io::Result<Nullifier> {
192    let mut nullifier = Nullifier([0u8; 32]);
193    reader.read_exact(&mut nullifier.0)?;
194    Ok(nullifier)
195}
196
197/// Consensus rules (§4.4):
198/// - Canonical encoding is enforced here.
199/// - "Not small order" is enforced in SaplingVerificationContext::check_spend()
200fn read_rk<R: Read>(mut reader: R) -> io::Result<redjubjub::VerificationKey<SpendAuth>> {
201    let mut bytes = [0; 32];
202    reader.read_exact(&mut bytes)?;
203    redjubjub::VerificationKey::try_from(bytes)
204        .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "verification key is invalid"))
205}
206
207/// Consensus rules (§4.4):
208/// - Canonical encoding is enforced here.
209/// - Signature validity is enforced in SaplingVerificationContext::check_spend()
210fn read_spend_auth_sig<R: Read>(mut reader: R) -> io::Result<redjubjub::Signature<SpendAuth>> {
211    let mut sig = [0; 64];
212    reader.read_exact(&mut sig)?;
213    Ok(redjubjub::Signature::from(sig))
214}
215
216#[cfg(feature = "temporary-zcashd")]
217pub fn temporary_zcashd_read_spend_v4<R: Read>(
218    reader: R,
219) -> io::Result<SpendDescription<Authorized>> {
220    read_spend_v4(reader)
221}
222
223fn read_spend_v4<R: Read>(mut reader: R) -> io::Result<SpendDescription<Authorized>> {
224    // Consensus rules (§4.4) & (§4.5):
225    // - Canonical encoding is enforced here.
226    // - "Not small order" is enforced in SaplingVerificationContext::(check_spend()/check_output())
227    //   (located in zcash_proofs::sapling::verifier).
228    let cv = read_value_commitment(&mut reader)?;
229    // Consensus rules (§7.3) & (§7.4):
230    // - Canonical encoding is enforced here
231    let anchor = read_base(&mut reader, "anchor")?;
232    let nullifier = read_nullifier(&mut reader)?;
233    let rk = read_rk(&mut reader)?;
234    let zkproof = read_zkproof(&mut reader)?;
235    let spend_auth_sig = read_spend_auth_sig(&mut reader)?;
236
237    Ok(SpendDescription::from_parts(
238        cv,
239        anchor,
240        nullifier,
241        rk,
242        zkproof,
243        spend_auth_sig,
244    ))
245}
246
247fn write_spend_v4<W: Write>(mut writer: W, spend: &SpendDescription<Authorized>) -> io::Result<()> {
248    writer.write_all(&spend.cv().to_bytes())?;
249    writer.write_all(spend.anchor().to_repr().as_ref())?;
250    writer.write_all(&spend.nullifier().0)?;
251    writer.write_all(&<[u8; 32]>::from(*spend.rk()))?;
252    writer.write_all(spend.zkproof())?;
253    writer.write_all(&<[u8; 64]>::from(*spend.spend_auth_sig()))
254}
255
256fn write_spend_v5_without_witness_data<W: Write>(
257    mut writer: W,
258    spend: &SpendDescription<Authorized>,
259) -> io::Result<()> {
260    writer.write_all(&spend.cv().to_bytes())?;
261    writer.write_all(&spend.nullifier().0)?;
262    writer.write_all(&<[u8; 32]>::from(*spend.rk()))
263}
264
265fn read_spend_v5<R: Read>(mut reader: &mut R) -> io::Result<SpendDescriptionV5> {
266    let cv = read_value_commitment(&mut reader)?;
267    let nullifier = read_nullifier(&mut reader)?;
268    let rk = read_rk(&mut reader)?;
269
270    Ok(SpendDescriptionV5::from_parts(cv, nullifier, rk))
271}
272
273#[cfg(feature = "temporary-zcashd")]
274pub fn temporary_zcashd_read_output_v4<R: Read>(
275    mut reader: R,
276) -> io::Result<OutputDescription<GrothProofBytes>> {
277    read_output_v4(&mut reader)
278}
279
280fn read_output_v4<R: Read>(mut reader: &mut R) -> io::Result<OutputDescription<GrothProofBytes>> {
281    // Consensus rules (§4.5):
282    // - Canonical encoding is enforced here.
283    // - "Not small order" is enforced in SaplingVerificationContext::check_output()
284    //   (located in zcash_proofs::sapling::verifier).
285    let cv = read_value_commitment(&mut reader)?;
286
287    // Consensus rule (§7.4): Canonical encoding is enforced here
288    let cmu = read_cmu(&mut reader)?;
289
290    // Consensus rules (§4.5):
291    // - Canonical encoding is enforced in librustzcash_sapling_check_output by zcashd
292    // - "Not small order" is enforced in SaplingVerificationContext::check_output()
293    let mut ephemeral_key = EphemeralKeyBytes([0u8; 32]);
294    reader.read_exact(&mut ephemeral_key.0)?;
295
296    let mut enc_ciphertext = [0u8; ENC_CIPHERTEXT_SIZE];
297    let mut out_ciphertext = [0u8; OUT_CIPHERTEXT_SIZE];
298    reader.read_exact(&mut enc_ciphertext)?;
299    reader.read_exact(&mut out_ciphertext)?;
300
301    let zkproof = read_zkproof(&mut reader)?;
302
303    Ok(OutputDescription::from_parts(
304        cv,
305        cmu,
306        ephemeral_key,
307        enc_ciphertext,
308        out_ciphertext,
309        zkproof,
310    ))
311}
312
313#[cfg(feature = "temporary-zcashd")]
314pub fn temporary_zcashd_write_output_v4<W: Write>(
315    writer: W,
316    output: &OutputDescription<GrothProofBytes>,
317) -> io::Result<()> {
318    write_output_v4(writer, output)
319}
320
321pub(crate) fn write_output_v4<W: Write>(
322    mut writer: W,
323    output: &OutputDescription<GrothProofBytes>,
324) -> io::Result<()> {
325    writer.write_all(&output.cv().to_bytes())?;
326    writer.write_all(output.cmu().to_bytes().as_ref())?;
327    writer.write_all(output.ephemeral_key().as_ref())?;
328    writer.write_all(output.enc_ciphertext())?;
329    writer.write_all(output.out_ciphertext())?;
330    writer.write_all(output.zkproof())
331}
332
333fn write_output_v5_without_proof<W: Write>(
334    mut writer: W,
335    output: &OutputDescription<GrothProofBytes>,
336) -> io::Result<()> {
337    writer.write_all(&output.cv().to_bytes())?;
338    writer.write_all(output.cmu().to_bytes().as_ref())?;
339    writer.write_all(output.ephemeral_key().as_ref())?;
340    writer.write_all(output.enc_ciphertext())?;
341    writer.write_all(output.out_ciphertext())
342}
343
344fn read_output_v5<R: Read>(mut reader: &mut R) -> io::Result<OutputDescriptionV5> {
345    let cv = read_value_commitment(&mut reader)?;
346    let cmu = read_cmu(&mut reader)?;
347
348    // Consensus rules (§4.5):
349    // - Canonical encoding is enforced in librustzcash_sapling_check_output by zcashd
350    // - "Not small order" is enforced in SaplingVerificationContext::check_output()
351    let mut ephemeral_key = EphemeralKeyBytes([0u8; 32]);
352    reader.read_exact(&mut ephemeral_key.0)?;
353
354    let mut enc_ciphertext = [0u8; ENC_CIPHERTEXT_SIZE];
355    let mut out_ciphertext = [0u8; OUT_CIPHERTEXT_SIZE];
356    reader.read_exact(&mut enc_ciphertext)?;
357    reader.read_exact(&mut out_ciphertext)?;
358
359    Ok(OutputDescriptionV5::from_parts(
360        cv,
361        cmu,
362        ephemeral_key,
363        enc_ciphertext,
364        out_ciphertext,
365    ))
366}
367
368/// Reads the Sapling components of a v4 transaction.
369#[cfg(feature = "temporary-zcashd")]
370#[allow(clippy::type_complexity)]
371pub fn temporary_zcashd_read_v4_components<R: Read>(
372    reader: R,
373    tx_has_sapling: bool,
374) -> io::Result<(
375    ZatBalance,
376    Vec<SpendDescription<Authorized>>,
377    Vec<OutputDescription<GrothProofBytes>>,
378)> {
379    read_v4_components(reader, tx_has_sapling)
380}
381
382/// Reads the Sapling components of a v4 transaction.
383#[allow(clippy::type_complexity)]
384pub(crate) fn read_v4_components<R: Read>(
385    mut reader: R,
386    tx_has_sapling: bool,
387) -> io::Result<(
388    ZatBalance,
389    Vec<SpendDescription<Authorized>>,
390    Vec<OutputDescription<GrothProofBytes>>,
391)> {
392    if tx_has_sapling {
393        let vb = Transaction::read_amount(&mut reader)?;
394        #[allow(clippy::redundant_closure)]
395        let ss: Vec<SpendDescription<Authorized>> =
396            Vector::read(&mut reader, |r| read_spend_v4(r))?;
397        #[allow(clippy::redundant_closure)]
398        let so: Vec<OutputDescription<GrothProofBytes>> =
399            Vector::read(&mut reader, |r| read_output_v4(r))?;
400        Ok((vb, ss, so))
401    } else {
402        Ok((ZatBalance::zero(), vec![], vec![]))
403    }
404}
405
406/// Writes the Sapling components of a v4 transaction.
407#[cfg(feature = "temporary-zcashd")]
408pub fn temporary_zcashd_write_v4_components<W: Write>(
409    writer: W,
410    bundle: Option<&Bundle<Authorized, ZatBalance>>,
411    tx_has_sapling: bool,
412) -> io::Result<()> {
413    write_v4_components(writer, bundle, tx_has_sapling)
414}
415
416/// Writes the Sapling components of a v4 transaction.
417pub(crate) fn write_v4_components<W: Write>(
418    mut writer: W,
419    bundle: Option<&Bundle<Authorized, ZatBalance>>,
420    tx_has_sapling: bool,
421) -> io::Result<()> {
422    if tx_has_sapling {
423        writer.write_all(
424            &bundle
425                .map_or(ZatBalance::zero(), |b| *b.value_balance())
426                .to_i64_le_bytes(),
427        )?;
428        Vector::write(
429            &mut writer,
430            bundle.map_or(&[], |b| b.shielded_spends()),
431            |w, e| write_spend_v4(w, e),
432        )?;
433        Vector::write(
434            &mut writer,
435            bundle.map_or(&[], |b| b.shielded_outputs()),
436            |w, e| write_output_v4(w, e),
437        )?;
438    } else if bundle.is_some() {
439        return Err(io::Error::new(
440            io::ErrorKind::InvalidInput,
441            "Sapling components may not be present if Sapling is not active.",
442        ));
443    }
444
445    Ok(())
446}
447
448/// Reads a [`Bundle`] from a v5 transaction format.
449#[allow(clippy::redundant_closure)]
450pub(crate) fn read_v5_bundle<R: Read>(
451    mut reader: R,
452) -> io::Result<Option<Bundle<Authorized, ZatBalance>>> {
453    let sd_v5s = Vector::read(&mut reader, read_spend_v5)?;
454    let od_v5s = Vector::read(&mut reader, read_output_v5)?;
455    let n_spends = sd_v5s.len();
456    let n_outputs = od_v5s.len();
457    let value_balance = if n_spends > 0 || n_outputs > 0 {
458        Transaction::read_amount(&mut reader)?
459    } else {
460        ZatBalance::zero()
461    };
462
463    let anchor = if n_spends > 0 {
464        Some(read_base(&mut reader, "anchor")?)
465    } else {
466        None
467    };
468
469    let v_spend_proofs = Array::read(&mut reader, n_spends, |r| read_zkproof(r))?;
470    let v_spend_auth_sigs = Array::read(&mut reader, n_spends, |r| read_spend_auth_sig(r))?;
471    let v_output_proofs = Array::read(&mut reader, n_outputs, |r| read_zkproof(r))?;
472
473    let binding_sig = if n_spends > 0 || n_outputs > 0 {
474        let mut sig = [0; 64];
475        reader.read_exact(&mut sig)?;
476        Some(redjubjub::Signature::from(sig))
477    } else {
478        None
479    };
480
481    let shielded_spends = sd_v5s
482        .into_iter()
483        .zip(v_spend_proofs.into_iter().zip(v_spend_auth_sigs))
484        .map(|(sd_5, (zkproof, spend_auth_sig))| {
485            // the following `unwrap` is safe because we know n_spends > 0.
486            sd_5.into_spend_description(anchor.unwrap(), zkproof, spend_auth_sig)
487        })
488        .collect();
489
490    let shielded_outputs = od_v5s
491        .into_iter()
492        .zip(v_output_proofs)
493        .map(|(od_5, zkproof)| od_5.into_output_description(zkproof))
494        .collect();
495
496    Ok(binding_sig.and_then(|binding_sig| {
497        Bundle::from_parts(
498            shielded_spends,
499            shielded_outputs,
500            value_balance,
501            Authorized { binding_sig },
502        )
503    }))
504}
505
506/// Writes a [`Bundle`] in the v5 transaction format.
507pub(crate) fn write_v5_bundle<W: Write>(
508    mut writer: W,
509    sapling_bundle: Option<&Bundle<Authorized, ZatBalance>>,
510) -> io::Result<()> {
511    if let Some(bundle) = sapling_bundle {
512        Vector::write(&mut writer, bundle.shielded_spends(), |w, e| {
513            write_spend_v5_without_witness_data(w, e)
514        })?;
515
516        Vector::write(&mut writer, bundle.shielded_outputs(), |w, e| {
517            write_output_v5_without_proof(w, e)
518        })?;
519
520        if !(bundle.shielded_spends().is_empty() && bundle.shielded_outputs().is_empty()) {
521            writer.write_all(&bundle.value_balance().to_i64_le_bytes())?;
522        }
523        if !bundle.shielded_spends().is_empty() {
524            writer.write_all(bundle.shielded_spends()[0].anchor().to_repr().as_ref())?;
525        }
526
527        Array::write(
528            &mut writer,
529            bundle.shielded_spends().iter().map(|s| &s.zkproof()[..]),
530            |w, e| w.write_all(e),
531        )?;
532        Array::write(
533            &mut writer,
534            bundle.shielded_spends().iter().map(|s| s.spend_auth_sig()),
535            |w, e| w.write_all(&<[u8; 64]>::from(**e)),
536        )?;
537
538        Array::write(
539            &mut writer,
540            bundle.shielded_outputs().iter().map(|s| &s.zkproof()[..]),
541            |w, e| w.write_all(e),
542        )?;
543
544        if !(bundle.shielded_spends().is_empty() && bundle.shielded_outputs().is_empty()) {
545            writer.write_all(&<[u8; 64]>::from(bundle.authorization().binding_sig))?;
546        }
547    } else {
548        CompactSize::write(&mut writer, 0)?;
549        CompactSize::write(&mut writer, 0)?;
550    }
551
552    Ok(())
553}
554
555#[cfg(any(test, feature = "test-dependencies"))]
556pub mod testing {
557    use proptest::prelude::*;
558
559    use crate::transaction::TxVersion;
560    use ::sapling::bundle::{Authorized, Bundle, testing as t_sap};
561    use zcash_protocol::value::{ZatBalance, testing::arb_zat_balance};
562
563    prop_compose! {
564        pub fn arb_bundle()(
565            value_balance in arb_zat_balance()
566        )(
567            bundle in t_sap::arb_bundle(value_balance)
568        ) -> Option<Bundle<Authorized, ZatBalance>> {
569            bundle
570        }
571    }
572
573    pub fn arb_bundle_for_version(
574        v: TxVersion,
575    ) -> impl Strategy<Value = Option<Bundle<Authorized, ZatBalance>>> {
576        if v.has_sapling() {
577            Strategy::boxed(arb_bundle())
578        } else {
579            Strategy::boxed(Just(None))
580        }
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use alloc::vec::Vec;
587
588    use corez::io::{self, Write};
589    use proptest::prelude::*;
590
591    use super::{
592        ANCHOR_BYTE_SIZE, CMU_BYTE_SIZE, EPHEMERAL_KEY_BYTE_SIZE, GROTH_PROOF_SIZE,
593        NULLIFIER_BYTE_SIZE, OUTPUT_DESCRIPTION_SIZE, RK_BYTE_SIZE, SPEND_AUTH_SIG_BYTE_SIZE,
594        SPEND_DESCRIPTION_SIZE, VALUE_COMMITMENT_BYTE_SIZE, testing::arb_bundle, write_output_v4,
595        write_spend_v4,
596    };
597    use ff::PrimeField;
598
599    // Returns the number of bytes `write` emits.
600    fn encoded_len(write: impl FnOnce(&mut Vec<u8>) -> io::Result<()>) -> usize {
601        let mut buf = Vec::new();
602        write(&mut buf).expect("writing to a Vec cannot fail");
603        buf.len()
604    }
605
606    proptest! {
607        /// `SPEND_DESCRIPTION_SIZE` is what callers divide a per-spend byte budget by to bound a
608        /// spend count, so it must equal what the v4 encoder actually writes, not merely what the
609        /// constant's own arithmetic says. Measure a real spend description rather than restating
610        /// the composition, so that a change to any element's encoding fails here.
611        ///
612        /// This is also what keeps the per-element sizes honest while `sapling` exposes none of
613        /// them itself: each is checked against the encoding of the field it describes. The v4
614        /// form is used (rather than v5) because it carries every per-spend byte inline, making it
615        /// the conservative upper bound for size budgeting.
616        #[test]
617        fn spend_description_size_matches_the_encoding(
618            bundle in arb_bundle().prop_filter("bundle has spends", |b| {
619                b.as_ref().is_some_and(|b| !b.shielded_spends().is_empty())
620            }),
621        ) {
622            let bundle = bundle.unwrap();
623            let spend = &bundle.shielded_spends()[0];
624            prop_assert_eq!(
625                encoded_len(|w| write_spend_v4(w, spend)),
626                SPEND_DESCRIPTION_SIZE
627            );
628
629            // Each element, against the constant that names it.
630            prop_assert_eq!(
631                encoded_len(|w| w.write_all(&spend.cv().to_bytes())),
632                VALUE_COMMITMENT_BYTE_SIZE
633            );
634            prop_assert_eq!(
635                encoded_len(|w| w.write_all(spend.anchor().to_repr().as_ref())),
636                ANCHOR_BYTE_SIZE
637            );
638            prop_assert_eq!(
639                encoded_len(|w| w.write_all(&spend.nullifier().0)),
640                NULLIFIER_BYTE_SIZE
641            );
642            prop_assert_eq!(
643                encoded_len(|w| w.write_all(&<[u8; 32]>::from(*spend.rk()))),
644                RK_BYTE_SIZE
645            );
646            prop_assert_eq!(
647                encoded_len(|w| w.write_all(spend.zkproof())),
648                GROTH_PROOF_SIZE
649            );
650            prop_assert_eq!(
651                encoded_len(|w| w.write_all(&<[u8; 64]>::from(*spend.spend_auth_sig()))),
652                SPEND_AUTH_SIG_BYTE_SIZE
653            );
654        }
655
656        /// `OUTPUT_DESCRIPTION_SIZE` is what callers divide a per-output byte budget by to bound an
657        /// output count, so it must equal what the v4 encoder actually writes. See
658        /// `spend_description_size_matches_the_encoding` for the rationale.
659        #[test]
660        fn output_description_size_matches_the_encoding(
661            bundle in arb_bundle().prop_filter("bundle has outputs", |b| {
662                b.as_ref().is_some_and(|b| !b.shielded_outputs().is_empty())
663            }),
664        ) {
665            let bundle = bundle.unwrap();
666            let output = &bundle.shielded_outputs()[0];
667            prop_assert_eq!(
668                encoded_len(|w| write_output_v4(w, output)),
669                OUTPUT_DESCRIPTION_SIZE
670            );
671
672            // Each element, against the constant that names it.
673            prop_assert_eq!(
674                encoded_len(|w| w.write_all(&output.cv().to_bytes())),
675                VALUE_COMMITMENT_BYTE_SIZE
676            );
677            prop_assert_eq!(
678                encoded_len(|w| w.write_all(output.cmu().to_bytes().as_ref())),
679                CMU_BYTE_SIZE
680            );
681            prop_assert_eq!(
682                encoded_len(|w| w.write_all(output.ephemeral_key().as_ref())),
683                EPHEMERAL_KEY_BYTE_SIZE
684            );
685            prop_assert_eq!(
686                encoded_len(|w| w.write_all(output.zkproof())),
687                GROTH_PROOF_SIZE
688            );
689        }
690    }
691}