Skip to main content

zcash_primitives/transaction/components/
orchard.rs

1//! Functions for parsing & serialization of Orchard transaction components.
2use alloc::vec::Vec;
3use core::convert::TryFrom;
4use corez::io::{self, Read, Write};
5
6use nonempty::NonEmpty;
7
8use core::mem::size_of;
9use orchard::{
10    Action, Anchor, ValuePool,
11    bundle::{Authorization, Authorized, BundleVersion, Flags},
12    note::{ExtractedNoteCommitment, Nullifier, TransmittedNoteCiphertext},
13    note_encryption::{ENC_CIPHERTEXT_SIZE, NoteBytesData},
14    primitives::redpallas::{self, SigType, Signature, SpendAuth, VerificationKey},
15    value::ValueCommitment,
16};
17use zcash_encoding::{Array, CompactSize, Vector};
18use zcash_note_encryption::{EphemeralKeyBytes, OUT_CIPHERTEXT_SIZE};
19use zcash_protocol::{
20    consensus::{BranchId, OrchardProtocolRevision},
21    value::ZatBalance,
22};
23
24use crate::transaction::Transaction;
25
26pub const FLAG_SPENDS_ENABLED: u8 = 0b0000_0001;
27pub const FLAG_OUTPUTS_ENABLED: u8 = 0b0000_0010;
28pub const FLAGS_EXPECTED_UNSET: u8 = !(FLAG_SPENDS_ENABLED | FLAG_OUTPUTS_ENABLED);
29
30// The encoded size of each element of an Orchard action. Each is a Pallas group element or base
31// field element, both of which encode to 32 bytes; note that this is a property of the *encoding*,
32// and unrelated to the in-memory representation, which differs between these types.
33//
34// These belong upstream in `orchard`, beside the types themselves: it defines each of these
35// elements but exposes no constant for the width of any of their encodings, so they are restated
36// here. Prefer upstream constants over these if `orchard` ever gains them. The
37// `action_size_matches_the_encoding` proptest holds each one to what the encoder actually writes.
38
39/// The size in bytes of the encoding of an Orchard value commitment (a Pallas group element).
40const VALUE_COMMITMENT_BYTE_SIZE: usize = 32;
41/// The size in bytes of the encoding of an Orchard nullifier (a Pallas base field element).
42const NULLIFIER_BYTE_SIZE: usize = 32;
43/// The size in bytes of the encoding of a randomized spend validating key (a Pallas group element).
44const VERIFICATION_KEY_BYTE_SIZE: usize = 32;
45/// The size in bytes of the encoding of an extracted note commitment (a Pallas base field element).
46const NOTE_COMMITMENT_BYTE_SIZE: usize = 32;
47/// The size in bytes of the encoding of an ephemeral key (a Pallas group element).
48///
49/// Unlike the others, this one the note encryption layer does give a name to.
50const EPHEMERAL_KEY_BYTE_SIZE: usize = size_of::<EphemeralKeyBytes>();
51
52/// The size in bytes of an Orchard action description, as written by
53/// [`write_action_without_auth`].
54///
55/// This does not include the action's spend authorization signature or its share of the bundle's
56/// proof, both of which are encoded separately from the action descriptions (see
57/// [`write_v5_bundle`]). Dividing a size budget by this constant therefore yields an upper bound
58/// on the number of actions that fit within it.
59pub const ACTION_SIZE: usize = VALUE_COMMITMENT_BYTE_SIZE
60    + NULLIFIER_BYTE_SIZE
61    + VERIFICATION_KEY_BYTE_SIZE
62    + NOTE_COMMITMENT_BYTE_SIZE
63    + EPHEMERAL_KEY_BYTE_SIZE
64    + ENC_CIPHERTEXT_SIZE
65    + OUT_CIPHERTEXT_SIZE;
66
67/// The size in bytes of an Orchard/Ironwood spend authorization signature, as encoded
68/// separately from the action description in the bundle's `vSpendAuthSigs` array.
69pub const SPEND_AUTH_SIG_SIZE: usize = 64;
70
71/// The per-bundle overhead of an Orchard/Ironwood bundle, excluding the proof and the
72/// per-action data: flags (1) + value_balance (8) + anchor (32) + binding_sig (64) +
73/// a CompactSize prefix for the actions vector (at most 9 bytes, budgeted as 10). The
74/// proof is a fixed base plus a per-action share computed via
75/// `orchard::Proof::expected_proof_size`, so it is added at the call site rather than
76/// included here.
77pub const BUNDLE_OVERHEAD: usize = 1 + 8 + 32 + 64 + 10;
78
79pub trait MapAuth<A: Authorization, B: Authorization> {
80    fn map_spend_auth(&self, s: A::SpendAuth) -> B::SpendAuth;
81    fn map_authorization(&self, a: A) -> B;
82}
83
84/// The identity map.
85///
86/// This can be used with [`TransactionData::map_authorization`] when you want to map the
87/// authorization of a subset of the transaction's bundles.
88///
89/// [`TransactionData::map_authorization`]: crate::transaction::TransactionData::map_authorization
90impl MapAuth<Authorized, Authorized> for () {
91    fn map_spend_auth(
92        &self,
93        s: <Authorized as Authorization>::SpendAuth,
94    ) -> <Authorized as Authorization>::SpendAuth {
95        s
96    }
97
98    fn map_authorization(&self, a: Authorized) -> Authorized {
99        a
100    }
101}
102
103fn read_bundle<R: Read>(
104    mut reader: R,
105    bundle_version: Option<BundleVersion>,
106) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
107    #[allow(clippy::redundant_closure)]
108    let actions_without_auth = Vector::read(&mut reader, |r| read_action_without_auth(r))?;
109    if actions_without_auth.is_empty() {
110        Ok(None)
111    } else {
112        let bundle_version = bundle_version.ok_or_else(|| {
113            io::Error::new(
114                io::ErrorKind::InvalidData,
115                "Orchard-protocol bundles may not be present in this transaction version \
116                 under the transaction's consensus branch ID",
117            )
118        })?;
119        let flags = read_flags(&mut reader, bundle_version)?;
120        let value_balance = Transaction::read_amount(&mut reader)?;
121        let anchor = read_anchor(&mut reader)?;
122        let proof_bytes = Vector::read_bytes(&mut reader)?;
123        let actions = NonEmpty::from_vec(
124            actions_without_auth
125                .into_iter()
126                .map(|act| act.try_map(|_| read_signature::<_, redpallas::SpendAuth>(&mut reader)))
127                .collect::<Result<Vec<_>, _>>()?,
128        )
129        .expect("A nonzero number of actions was read from the transaction data.");
130        let binding_signature = read_signature::<_, redpallas::Binding>(&mut reader)?;
131
132        let authorization = orchard::bundle::Authorized::from_parts(
133            orchard::Proof::new(proof_bytes),
134            binding_signature,
135        );
136
137        // `try_from_parts` rejects a proof whose length is not the canonical size for the number
138        // of actions, preventing a proof padded with arbitrary data (GHSA-2x4w-pxqw-58v9). Proof
139        // size is enforced for every version except the historical pre-NU6.2 Orchard pool
140        // ([`BundleVersion::orchard_insecure_v1`]); see the `bundle_version` chosen by the caller.
141        orchard::Bundle::try_from_parts(
142            actions,
143            flags,
144            value_balance,
145            anchor,
146            authorization,
147            bundle_version,
148        )
149        .map(Some)
150        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
151    }
152}
153
154/// Returns the [`BundleVersion`] in effect for the given Orchard-protocol value pool
155/// under the given consensus branch, or `None` if the pool is not supported under that
156/// branch (the Orchard pool prior to NU5; the Ironwood pool prior to NU6.3).
157///
158/// The protocol revision is determined by
159/// [`BranchId::orchard_protocol_revision`]. The `BundleVersion` fixes a bundle's
160/// flag-byte grammar, cross-address semantics, and circuit generation:
161///   * Orchard pool, NU5 through NU6.1: historical insecure circuit, cross-address
162///     enabled, proof size not enforced;
163///   * Orchard pool, NU6.2: fixed circuit, cross-address enabled;
164///   * Orchard pool, NU6.3 onward: post-NU6.3 circuit, cross-address disabled
165///     (consensus-mandated);
166///   * Ironwood pool, NU6.3 onward: post-NU6.3 circuit, cross-address enabled.
167pub fn bundle_version_for_branch(
168    consensus_branch_id: BranchId,
169    pool: ValuePool,
170) -> Option<BundleVersion> {
171    let revision = consensus_branch_id.orchard_protocol_revision()?;
172    match pool {
173        ValuePool::Orchard => Some(match revision {
174            OrchardProtocolRevision::InsecureV1 => BundleVersion::orchard_insecure_v1(),
175            OrchardProtocolRevision::V2 => BundleVersion::orchard_v2(),
176            OrchardProtocolRevision::V3 => BundleVersion::orchard_v3(),
177        }),
178        ValuePool::Ironwood => match revision {
179            OrchardProtocolRevision::InsecureV1 | OrchardProtocolRevision::V2 => None,
180            OrchardProtocolRevision::V3 => Some(BundleVersion::ironwood_v3()),
181        },
182    }
183}
184
185/// Reads an [`orchard::Bundle`] from a v5 transaction format.
186///
187/// The v5 Orchard wire serialization is identical in every epoch (flag bit 2 is
188/// reserved), but the returned bundle's [`BundleVersion`] — which fixes its
189/// cross-address semantics and circuit generation — follows the consensus epoch
190/// identified by `consensus_branch_id` (see [`bundle_version_for_branch`]). A
191/// non-empty Orchard bundle under a consensus branch that predates NU5 is
192/// rejected as invalid data.
193pub fn read_v5_bundle<R: Read>(
194    reader: R,
195    consensus_branch_id: BranchId,
196) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
197    read_bundle(
198        reader,
199        bundle_version_for_branch(consensus_branch_id, ValuePool::Orchard),
200    )
201}
202
203/// Rejects bundle versions that are not valid for the v6 transaction format, which has exactly
204/// two Orchard-bundle slots: the Orchard slot ([`BundleVersion::orchard_v3`]) and the Ironwood
205/// slot ([`BundleVersion::ironwood_v3`]). A pre-NU6.3 version would (de)serialize the flag byte
206/// with the wrong cross-address (bit 2) semantics.
207fn check_v6_bundle_version(bundle_version: BundleVersion) -> io::Result<()> {
208    if bundle_version == BundleVersion::orchard_v3()
209        || bundle_version == BundleVersion::ironwood_v3()
210    {
211        Ok(())
212    } else {
213        Err(io::Error::new(
214            io::ErrorKind::InvalidInput,
215            "v6 Orchard bundles require orchard_v3 or ironwood_v3",
216        ))
217    }
218}
219
220/// Reads an [`orchard::Bundle`] from a v6 transaction format. `pool` selects the bundle
221/// slot to read: the Orchard slot ([`ValuePool::Orchard`]) or the Ironwood slot
222/// ([`ValuePool::Ironwood`], whose flag-byte encoding permits the cross-address bit,
223/// unlike the Orchard v6 pool). The slot's [`BundleVersion`] is derived from
224/// `consensus_branch_id` (see [`bundle_version_for_branch`]); a non-empty bundle in a
225/// slot whose value pool is not supported under the transaction's consensus branch is
226/// rejected as invalid data.
227pub fn read_v6_bundle<R: Read>(
228    reader: R,
229    consensus_branch_id: BranchId,
230    pool: ValuePool,
231) -> io::Result<Option<orchard::Bundle<Authorized, ZatBalance>>> {
232    read_bundle(reader, bundle_version_for_branch(consensus_branch_id, pool))
233}
234
235pub fn read_value_commitment<R: Read>(mut reader: R) -> io::Result<ValueCommitment> {
236    let mut bytes = [0u8; 32];
237    reader.read_exact(&mut bytes)?;
238    let cv = ValueCommitment::from_bytes(&bytes);
239
240    if cv.is_none().into() {
241        Err(io::Error::new(
242            io::ErrorKind::InvalidInput,
243            "invalid Pallas point for value commitment",
244        ))
245    } else {
246        Ok(cv.unwrap())
247    }
248}
249
250pub fn read_nullifier<R: Read>(mut reader: R) -> io::Result<Nullifier> {
251    let mut bytes = [0u8; 32];
252    reader.read_exact(&mut bytes)?;
253    let nullifier_ctopt = Nullifier::from_bytes(&bytes);
254    if nullifier_ctopt.is_none().into() {
255        Err(io::Error::new(
256            io::ErrorKind::InvalidInput,
257            "invalid Pallas point for nullifier",
258        ))
259    } else {
260        Ok(nullifier_ctopt.unwrap())
261    }
262}
263
264pub fn read_verification_key<R: Read>(mut reader: R) -> io::Result<VerificationKey<SpendAuth>> {
265    let mut bytes = [0u8; 32];
266    reader.read_exact(&mut bytes)?;
267    VerificationKey::try_from(bytes)
268        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid verification key"))
269}
270
271pub fn read_cmx<R: Read>(mut reader: R) -> io::Result<ExtractedNoteCommitment> {
272    let mut bytes = [0u8; 32];
273    reader.read_exact(&mut bytes)?;
274    let cmx = ExtractedNoteCommitment::from_bytes(&bytes);
275    Option::from(cmx).ok_or_else(|| {
276        io::Error::new(
277            io::ErrorKind::InvalidInput,
278            "invalid Pallas base for field cmx",
279        )
280    })
281}
282
283pub fn read_note_ciphertext<R: Read>(mut reader: R) -> io::Result<TransmittedNoteCiphertext> {
284    let mut tnc = TransmittedNoteCiphertext {
285        epk_bytes: [0u8; 32],
286        enc_ciphertext: NoteBytesData([0u8; ENC_CIPHERTEXT_SIZE]),
287        out_ciphertext: [0u8; OUT_CIPHERTEXT_SIZE],
288    };
289
290    reader.read_exact(&mut tnc.epk_bytes)?;
291    reader.read_exact(&mut tnc.enc_ciphertext.0)?;
292    reader.read_exact(&mut tnc.out_ciphertext)?;
293
294    Ok(tnc)
295}
296
297pub fn read_action_without_auth<R: Read>(mut reader: R) -> io::Result<Action<()>> {
298    let cv_net = read_value_commitment(&mut reader)?;
299    let nf_old = read_nullifier(&mut reader)?;
300    let rk = read_verification_key(&mut reader)?;
301    let cmx = read_cmx(&mut reader)?;
302    let encrypted_note = read_note_ciphertext(&mut reader)?;
303
304    Action::from_parts(nf_old, rk, cmx, encrypted_note, cv_net, ())
305        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
306}
307
308pub fn read_flags<R: Read>(mut reader: R, bundle_version: BundleVersion) -> io::Result<Flags> {
309    let mut byte = [0u8; 1];
310    reader.read_exact(&mut byte)?;
311    Flags::from_byte(byte[0], bundle_version)
312        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid Orchard flags"))
313}
314
315pub fn read_anchor<R: Read>(mut reader: R) -> io::Result<Anchor> {
316    let mut bytes = [0u8; 32];
317    reader.read_exact(&mut bytes)?;
318    Option::from(Anchor::from_bytes(bytes))
319        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid Orchard anchor"))
320}
321
322pub fn read_signature<R: Read, T: SigType>(mut reader: R) -> io::Result<Signature<T>> {
323    let mut bytes = [0u8; 64];
324    reader.read_exact(&mut bytes)?;
325    Ok(Signature::from(bytes))
326}
327
328fn write_bundle<W: Write>(
329    bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
330    mut writer: W,
331) -> io::Result<()> {
332    if let Some(bundle) = &bundle {
333        Vector::write_nonempty(&mut writer, bundle.actions(), |w, a| {
334            write_action_without_auth(w, a)
335        })?;
336
337        // The flag byte is encoded under the bundle's own `BundleVersion`, which is infallible:
338        // a `Bundle` is only ever constructed with flags representable under its version.
339        writer.write_all(&[bundle.flag_byte()])?;
340        writer.write_all(&bundle.value_balance().to_i64_le_bytes())?;
341        writer.write_all(&bundle.anchor().to_bytes())?;
342        Vector::write_bytes(&mut writer, bundle.authorization().proof().as_ref())?;
343        Array::write(
344            &mut writer,
345            bundle.actions().iter().map(|a| a.authorization()),
346            |w, auth| w.write_all(&<[u8; 64]>::from(*auth)),
347        )?;
348        writer.write_all(&<[u8; 64]>::from(
349            bundle.authorization().binding_signature(),
350        ))?;
351    } else {
352        CompactSize::write(&mut writer, 0)?;
353    }
354
355    Ok(())
356}
357
358/// Writes an [`orchard::Bundle`] in the v5 transaction format.
359///
360/// The Orchard flag byte is encoded under the bundle's own [`BundleVersion`]; an Orchard bundle
361/// never sets the cross-address bit, so its byte is always valid for the v5 format.
362pub fn write_v5_bundle<W: Write>(
363    bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
364    writer: W,
365) -> io::Result<()> {
366    write_bundle(bundle, writer)
367}
368
369/// Writes an [`orchard::Bundle`] in the v6 transaction format. The bundle's own
370/// [`BundleVersion`] selects the pool (and hence the flag-byte grammar): the Orchard slot uses
371/// [`BundleVersion::orchard_v3`], the Ironwood slot [`BundleVersion::ironwood_v3`].
372pub fn write_v6_bundle<W: Write>(
373    bundle: Option<&orchard::Bundle<Authorized, ZatBalance>>,
374    writer: W,
375) -> io::Result<()> {
376    if let Some(bundle) = bundle {
377        check_v6_bundle_version(bundle.bundle_version())?;
378    }
379    write_bundle(bundle, writer)
380}
381
382pub fn write_value_commitment<W: Write>(mut writer: W, cv: &ValueCommitment) -> io::Result<()> {
383    writer.write_all(&cv.to_bytes())
384}
385
386pub fn write_nullifier<W: Write>(mut writer: W, nf: &Nullifier) -> io::Result<()> {
387    writer.write_all(&nf.to_bytes())
388}
389
390pub fn write_verification_key<W: Write>(
391    mut writer: W,
392    rk: &redpallas::VerificationKey<SpendAuth>,
393) -> io::Result<()> {
394    writer.write_all(&<[u8; 32]>::from(rk))
395}
396
397pub fn write_cmx<W: Write>(mut writer: W, cmx: &ExtractedNoteCommitment) -> io::Result<()> {
398    writer.write_all(&cmx.to_bytes())
399}
400
401pub fn write_note_ciphertext<W: Write>(
402    mut writer: W,
403    nc: &TransmittedNoteCiphertext,
404) -> io::Result<()> {
405    writer.write_all(&nc.epk_bytes)?;
406    writer.write_all(&nc.enc_ciphertext.0)?;
407    writer.write_all(&nc.out_ciphertext)
408}
409
410pub fn write_action_without_auth<W: Write>(
411    mut writer: W,
412    act: &Action<<Authorized as Authorization>::SpendAuth>,
413) -> io::Result<()> {
414    write_value_commitment(&mut writer, act.cv_net())?;
415    write_nullifier(&mut writer, act.nullifier())?;
416    write_verification_key(&mut writer, act.rk())?;
417    write_cmx(&mut writer, act.cmx())?;
418    write_note_ciphertext(&mut writer, act.encrypted_note())?;
419    Ok(())
420}
421
422#[cfg(any(test, feature = "test-dependencies"))]
423pub mod testing {
424    use proptest::prelude::*;
425
426    use orchard::bundle::{
427        Authorized, Bundle, BundleVersion, Flags,
428        testing::{self as t_orch},
429    };
430    use zcash_protocol::value::{ZatBalance, testing::arb_zat_balance};
431
432    use crate::transaction::TxVersion;
433
434    prop_compose! {
435        pub fn arb_bundle(n_actions: usize)(
436            orchard_value_balance in arb_zat_balance(),
437            bundle in t_orch::arb_bundle(n_actions)
438        ) -> Bundle<Authorized, ZatBalance> {
439            // overwrite the value balance, as we can't guarantee that the
440            // value doesn't exceed the MAX_MONEY bounds.
441            bundle.try_map_value_balance::<_, (), _>(|_| Ok(orchard_value_balance)).unwrap()
442        }
443    }
444
445    pub fn arb_bundle_for_version(
446        v: TxVersion,
447    ) -> impl Strategy<Value = Option<Bundle<Authorized, ZatBalance>>> {
448        if v.has_orchard() {
449            // The Orchard slot uses `orchard_v3()` in a v6 transaction (cross-address forbidden)
450            // and `orchard_v2()` in a v5 transaction; the Ironwood slot is generated separately by
451            // `arb_ironwood_bundle_for_version`.
452            let bundle_version = orchard_bundle_version(v);
453            (1usize..100)
454                .prop_flat_map(move |n| {
455                    prop::option::of(
456                        arb_bundle(n).prop_map(move |b| rebuild_with_version(b, bundle_version)),
457                    )
458                })
459                .boxed()
460        } else {
461            Just(None).boxed()
462        }
463    }
464
465    /// Generates Ironwood bundles for the v6 transaction format. Unlike the Orchard v6 pool, the
466    /// Ironwood pool ([`BundleVersion::ironwood_v3`]) permits cross-address transfers, so this
467    /// exercises the Ironwood serialization path the Orchard generator cannot.
468    pub fn arb_ironwood_bundle_for_version(
469        v: TxVersion,
470    ) -> impl Strategy<Value = Option<Bundle<Authorized, ZatBalance>>> {
471        if v.has_ironwood() {
472            (1usize..100)
473                .prop_flat_map(|n| {
474                    prop::option::of(
475                        arb_bundle(n)
476                            .prop_map(|b| rebuild_with_version(b, BundleVersion::ironwood_v3())),
477                    )
478                })
479                .boxed()
480        } else {
481            Just(None).boxed()
482        }
483    }
484
485    /// The Orchard-slot [`BundleVersion`] for a transaction version: `orchard_v3()` in v6 (where
486    /// the Orchard pool forbids cross-address transfers), `orchard_v2()` otherwise.
487    fn orchard_bundle_version(v: TxVersion) -> BundleVersion {
488        if match v {
489            TxVersion::V6 => true,
490            #[cfg(zcash_unstable = "nutachyon")]
491            TxVersion::V7 => true,
492            _ => false,
493        } {
494            return BundleVersion::orchard_v3();
495        }
496        let _ = v;
497        BundleVersion::orchard_v2()
498    }
499
500    /// Rebuilds an arbitrary bundle under `bundle_version`, choosing a cross-address flag value
501    /// that the version can represent while preserving the generated spend/output flags.
502    ///
503    /// Cross-address is only encodable in bit 2 for the Ironwood pool, so bit 2 is set there (to
504    /// exercise that serialization path) and left clear otherwise: pre-NU6.3 Orchard has
505    /// cross-address implicitly enabled, and post-NU6.3 Orchard forbids it.
506    pub(crate) fn rebuild_with_version(
507        bundle: Bundle<Authorized, ZatBalance>,
508        bundle_version: BundleVersion,
509    ) -> Bundle<Authorized, ZatBalance> {
510        let mut byte = u8::from(bundle.flags().spends_enabled())
511            | (u8::from(bundle.flags().outputs_enabled()) << 1);
512        if bundle_version == BundleVersion::ironwood_v3() {
513            byte |= 0b100;
514        }
515        let flags = Flags::from_byte(byte, bundle_version)
516            .expect("constructed flag byte is representable under the target version");
517        ::orchard::Bundle::try_from_parts(
518            bundle.actions().clone(),
519            flags,
520            *bundle.value_balance(),
521            *bundle.anchor(),
522            bundle.authorization().clone(),
523            bundle_version,
524        )
525        .expect("flags are representable under the target version")
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use alloc::vec::Vec;
532
533    use orchard::{bundle::testing::arb_action, note::NoteVersion, value::NoteValue};
534    use proptest::prelude::*;
535
536    use super::{
537        ACTION_SIZE, ENC_CIPHERTEXT_SIZE, EPHEMERAL_KEY_BYTE_SIZE, NOTE_COMMITMENT_BYTE_SIZE,
538        NULLIFIER_BYTE_SIZE, OUT_CIPHERTEXT_SIZE, VALUE_COMMITMENT_BYTE_SIZE,
539        VERIFICATION_KEY_BYTE_SIZE, io, write_action_without_auth, write_cmx,
540        write_note_ciphertext, write_nullifier, write_value_commitment, write_verification_key,
541    };
542
543    // Returns the number of bytes `write` emits.
544    fn encoded_len(write: impl FnOnce(&mut Vec<u8>) -> io::Result<()>) -> usize {
545        let mut buf = Vec::new();
546        write(&mut buf).expect("writing to a Vec cannot fail");
547        buf.len()
548    }
549
550    proptest! {
551        /// `ACTION_SIZE` is what callers divide a size budget by to bound an action count, and so
552        /// feeds fee estimation: it must equal what the encoder actually writes, not merely what
553        /// the constant's own arithmetic says. Measure a real action rather than restating the
554        /// composition, so that a change to any element's encoding fails here.
555        ///
556        /// This is also what keeps the per-element sizes honest while `orchard` exposes none of
557        /// them itself: each is checked against the encoding of the field it describes.
558        #[test]
559        fn action_size_matches_the_encoding(
560            action in arb_action(
561                NoteVersion::V2,
562                NoteValue::from_raw(1),
563                NoteValue::from_raw(1),
564            ),
565        ) {
566            prop_assert_eq!(
567                encoded_len(|w| write_action_without_auth(w, &action)),
568                ACTION_SIZE
569            );
570
571            // Each element, against the constant that names it.
572            prop_assert_eq!(
573                encoded_len(|w| write_value_commitment(w, action.cv_net())),
574                VALUE_COMMITMENT_BYTE_SIZE
575            );
576            prop_assert_eq!(
577                encoded_len(|w| write_nullifier(w, action.nullifier())),
578                NULLIFIER_BYTE_SIZE
579            );
580            prop_assert_eq!(
581                encoded_len(|w| write_verification_key(w, action.rk())),
582                VERIFICATION_KEY_BYTE_SIZE
583            );
584            prop_assert_eq!(
585                encoded_len(|w| write_cmx(w, action.cmx())),
586                NOTE_COMMITMENT_BYTE_SIZE
587            );
588
589            // The note ciphertext carries the remaining three: the ephemeral key, followed by the
590            // note and outgoing ciphertexts.
591            prop_assert_eq!(
592                encoded_len(|w| write_note_ciphertext(w, action.encrypted_note())),
593                EPHEMERAL_KEY_BYTE_SIZE + ENC_CIPHERTEXT_SIZE + OUT_CIPHERTEXT_SIZE
594            );
595        }
596    }
597}