Skip to main content

pczt/
lib.rs

1//! The Partially Created Zcash Transaction (PCZT) format.
2//!
3//! This format enables splitting up the logical steps of creating a Zcash transaction
4//! across distinct entities. The entity roles roughly match those specified in
5//! [BIP 174: Partially Signed Bitcoin Transaction Format] and [BIP 370: PSBT Version 2],
6//! with additional Zcash-specific roles.
7//!
8//! [BIP 174: Partially Signed Bitcoin Transaction Format]: https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki
9//! [BIP 370: PSBT Version 2]: https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki
10//!
11#![cfg_attr(feature = "std", doc = "## Feature flags")]
12#![cfg_attr(feature = "std", doc = document_features::document_features!())]
13//!
14
15#![no_std]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17#![cfg_attr(docsrs, doc(auto_cfg))]
18// Catch documentation errors caused by code changes.
19#![deny(rustdoc::broken_intra_doc_links)]
20
21#[macro_use]
22extern crate alloc;
23// The crate itself needs only `alloc`; the unit tests lean on `proptest`, which is a `std` crate.
24#[cfg(test)]
25extern crate std;
26
27use alloc::vec::Vec;
28
29use getset::Getters;
30
31use zcash_protocol::PoolType;
32#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
33use zcash_protocol::constants::{V6_TX_VERSION, V6_VERSION_GROUP_ID};
34#[cfg(all(
35    any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"),
36    zcash_unstable = "nutachyon"
37))]
38use zcash_protocol::constants::{V7_TX_VERSION, V7_VERSION_GROUP_ID};
39#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
40use {
41    common::{Global, determine_lock_time},
42    zcash_primitives::transaction::{Authorization, TransactionData, TxVersion},
43    zcash_protocol::{
44        consensus::{BranchId, OrchardProtocolRevision},
45        constants::{V5_TX_VERSION, V5_VERSION_GROUP_ID},
46    },
47};
48
49#[cfg(any(feature = "io-finalizer", feature = "signer"))]
50use zcash_primitives::transaction::sighash::{PrecomputedSighashData, SignableInput};
51
52pub mod roles;
53
54pub mod common;
55pub mod orchard;
56pub mod sapling;
57pub mod transparent;
58
59pub(crate) const MAGIC_BYTES: &[u8; 4] = b"PCZT";
60pub(crate) const PCZT_VERSION_1: u32 = 1;
61pub(crate) const PCZT_VERSION_2: u32 = 2;
62
63const VERSIONED_HEADER_LEN: usize = 8;
64
65pub(crate) enum HeaderParseError {
66    InvalidMagic,
67    TooShort,
68}
69
70pub(crate) fn parse_header<'a>(
71    bytes: &'a [u8],
72    magic: &[u8; 4],
73) -> Result<(u32, &'a [u8]), HeaderParseError> {
74    if bytes.len() < VERSIONED_HEADER_LEN {
75        return Err(HeaderParseError::TooShort);
76    }
77    if &bytes[..4] != magic {
78        return Err(HeaderParseError::InvalidMagic);
79    }
80
81    let version = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
82    Ok((version, &bytes[VERSIONED_HEADER_LEN..]))
83}
84
85pub(crate) fn serialize_header(magic: &[u8; 4], version: u32) -> Vec<u8> {
86    let mut bytes = Vec::with_capacity(VERSIONED_HEADER_LEN);
87    bytes.extend_from_slice(magic);
88    bytes.extend_from_slice(&version.to_le_bytes());
89    bytes
90}
91
92/// Parses a PCZT from its encoding.
93pub fn parse(bytes: &[u8]) -> Result<Pczt, ParseError> {
94    Pczt::parse(bytes)
95}
96
97/// A partially-created Zcash transaction.
98#[derive(Clone, Debug, Getters)]
99pub struct Pczt {
100    /// Global fields that are relevant to the transaction as a whole.
101    #[getset(get = "pub")]
102    pub(crate) global: common::Global,
103
104    //
105    // Protocol-specific fields.
106    //
107    // Unlike the `TransactionData` type in `zcash_primitives`, these are not optional.
108    // This is because a PCZT does not always contain a semantically-valid transaction,
109    // and there may be phases where we need to store protocol-specific metadata before
110    // it has been determined whether there are protocol-specific inputs or outputs.
111    //
112    #[getset(get = "pub")]
113    pub(crate) transparent: transparent::Bundle,
114    #[getset(get = "pub")]
115    pub(crate) sapling: sapling::Bundle,
116    #[getset(get = "pub")]
117    pub(crate) orchard: orchard::Bundle,
118    #[getset(get = "pub")]
119    pub(crate) ironwood: orchard::Bundle,
120}
121
122/// Types and operations for the v1 Pczt encoding.
123pub mod v1 {
124    use alloc::vec::Vec;
125    use serde::{Deserialize, Serialize};
126
127    use crate::{common, orchard, sapling, transparent};
128
129    /// The in-memory type used for derived serialization of the v1 Pczt encoding.
130    #[derive(Clone, Debug, Serialize, Deserialize)]
131    pub struct Pczt {
132        global: common::Global,
133        transparent: transparent::Bundle,
134        sapling: sapling::v1::Bundle,
135        orchard: orchard::v1::Bundle,
136    }
137
138    impl Pczt {
139        pub fn serialize(&self) -> Vec<u8> {
140            let bytes = crate::serialize_header(crate::MAGIC_BYTES, crate::PCZT_VERSION_1);
141            postcard::to_extend(&self, bytes).expect("can serialize into memory")
142        }
143    }
144
145    /// Encodes the in-memory [`super::Pczt`] into the v1 serialization type [`Pczt`].
146    impl TryFrom<super::Pczt> for Pczt {
147        type Error = super::EncodingError;
148
149        fn try_from(pczt: super::Pczt) -> Result<Self, Self::Error> {
150            // The v1 encoding cannot represent V6 or V7 transactions.
151            if match pczt.global.tx_version {
152                zcash_protocol::constants::V6_TX_VERSION => true,
153                #[cfg(zcash_unstable = "nutachyon")]
154                zcash_protocol::constants::V7_TX_VERSION => true,
155                _ => false,
156            } {
157                return Err(super::EncodingError::UnsupportedTxVersion);
158            }
159
160            // The v1 format cannot represent an Ironwood bundle in any state other
161            // than the canonical empty one; a parser of the v1 encoding will
162            // reconstruct exactly that value.
163            if pczt.ironwood != orchard::EMPTY_IRONWOOD {
164                return Err(super::EncodingError::UnsupportedTxVersion);
165            }
166
167            Ok(Self {
168                global: pczt.global,
169                transparent: pczt.transparent,
170                sapling: sapling::v1::Bundle::try_from(pczt.sapling)?,
171                orchard: orchard::v1::Bundle::try_from(pczt.orchard)?,
172            })
173        }
174    }
175
176    impl From<Pczt> for super::Pczt {
177        fn from(pczt: Pczt) -> Self {
178            Self {
179                global: pczt.global,
180                transparent: pczt.transparent,
181                sapling: pczt.sapling.into(),
182                orchard: pczt.orchard.into(),
183                ironwood: orchard::EMPTY_IRONWOOD,
184            }
185        }
186    }
187
188    #[cfg(test)]
189    mod tests {
190        use zcash_protocol::consensus::BranchId;
191
192        use crate::roles::creator::Creator;
193
194        #[test]
195        fn v1_refuses_v6_pczts_and_non_canonical_ironwood_bundles() {
196            // A v6 tx cannot be encoded as a v1 PCZT, even when its Ironwood bundle is
197            // canonically empty.
198            let pczt = Creator::new(
199                BranchId::Nu6_3.into(),
200                10_000_000,
201                133,
202                Some([0; 32]),
203                Some([0; 32]),
204            )
205            .unwrap()
206            .build()
207            .unwrap();
208            assert!(matches!(
209                super::Pczt::try_from(pczt),
210                Err(crate::EncodingError::UnsupportedTxVersion)
211            ));
212
213            // A v5 tx carrying non-canonical Ironwood bundle data cannot be encoded
214            // as a v1 PCZT, because the data would be dropped.
215            let mut pczt = Creator::new(
216                BranchId::Nu6.into(),
217                10_000_000,
218                133,
219                Some([0; 32]),
220                Some([0; 32]),
221            )
222            .unwrap()
223            .build()
224            .unwrap();
225            pczt.ironwood.bsk = Some(crate::common::SecretKeyBytes::new([1; 32]));
226            assert!(matches!(
227                super::Pczt::try_from(pczt),
228                Err(crate::EncodingError::UnsupportedTxVersion)
229            ));
230        }
231    }
232}
233
234/// Types and operations for the v2 Pczt encoding.
235pub mod v2 {
236    use alloc::vec::Vec;
237    use serde::{Deserialize, Serialize};
238
239    use crate::{common, orchard, sapling, transparent};
240
241    /// The in-memory type used for derived serialization of the v2 Pczt encoding.
242    #[derive(Clone, Debug, Serialize, Deserialize)]
243    pub struct Pczt {
244        global: common::Global,
245        // This value is set to `None` if the transparent bundle is empty,
246        // meaning inputs and outputs are empty.
247        transparent: Option<transparent::Bundle>,
248        // This value is set to `None` if the Sapling bundle is empty,
249        // meaning every field has its empty/default value.
250        sapling: Option<sapling::Bundle>,
251        // This value is set to `None` if the Orchard bundle is empty,
252        // meaning actions, value sum, anchor, zkproof, and bsk are all
253        // empty. Flags and note version are not checked, as values can be
254        // defaulted there.
255        orchard: Option<orchard::v2::Bundle>,
256        ironwood: Option<orchard::v2::Bundle>,
257    }
258
259    impl Pczt {
260        pub fn serialize(&self) -> Vec<u8> {
261            let bytes = crate::serialize_header(crate::MAGIC_BYTES, crate::PCZT_VERSION_2);
262            postcard::to_extend(&self, bytes).expect("can serialize into memory")
263        }
264    }
265
266    /// Encodes the in-memory [`super::Pczt`] into the v2 serialization type [`Pczt`],
267    /// omitting empty Transparent, Sapling, and Orchard bundles.
268    impl TryFrom<super::Pczt> for Pczt {
269        type Error = super::EncodingError;
270
271        fn try_from(pczt: super::Pczt) -> Result<Self, Self::Error> {
272            Ok(Self {
273                global: pczt.global,
274                transparent: (pczt.transparent != transparent::EMPTY_BUNDLE)
275                    .then_some(pczt.transparent),
276                sapling: sapling::v2::encode(pczt.sapling),
277                orchard: orchard::v2::encode(pczt.orchard, &orchard::EMPTY_ORCHARD)?,
278                ironwood: orchard::v2::encode(pczt.ironwood, &orchard::EMPTY_IRONWOOD)?,
279            })
280        }
281    }
282
283    impl Pczt {
284        pub(super) fn into_logical(self) -> Result<super::Pczt, super::ParseError> {
285            Ok(super::Pczt {
286                global: self.global,
287                transparent: self.transparent.unwrap_or(transparent::EMPTY_BUNDLE),
288                sapling: self.sapling.unwrap_or(sapling::EMPTY_BUNDLE),
289                orchard: self
290                    .orchard
291                    .map(orchard::v2::Bundle::into_logical)
292                    .transpose()?
293                    .unwrap_or(orchard::EMPTY_ORCHARD),
294                ironwood: self
295                    .ironwood
296                    .map(orchard::v2::Bundle::into_logical)
297                    .transpose()?
298                    .unwrap_or(orchard::EMPTY_IRONWOOD),
299            })
300        }
301    }
302
303    #[cfg(test)]
304    mod tests {
305        use zcash_protocol::consensus::BranchId;
306
307        use super::Pczt;
308        use crate::{orchard::NoteVersion, roles::creator::Creator};
309
310        #[test]
311        fn empty_bundles_encode_as_none_and_decode_as_empty() {
312            // Absent anchors: the shielded bundles carry no anchor and no
313            // spends/actions, so they are fully empty and omitted.
314            let pczt = Creator::new(BranchId::Nu6_3.into(), 10_000_000, 133, None, None)
315                .unwrap()
316                .build()
317                .unwrap();
318
319            let encoded = Pczt::try_from(pczt).unwrap();
320
321            assert!(encoded.transparent.is_none());
322            assert!(encoded.sapling.is_none());
323            assert!(encoded.orchard.is_none());
324            assert!(encoded.ironwood.is_none());
325
326            let decoded = crate::parse(&encoded.serialize()).unwrap();
327
328            assert!(decoded.transparent.inputs.is_empty());
329            assert!(decoded.transparent.outputs.is_empty());
330            assert!(decoded.sapling.spends.is_empty());
331            assert!(decoded.sapling.outputs.is_empty());
332            assert!(decoded.sapling.anchor.is_none());
333            assert!(decoded.orchard.actions.is_empty());
334            assert_eq!(decoded.orchard.note_version, NoteVersion::V2);
335            {
336                assert!(decoded.ironwood.actions.is_empty());
337                assert_eq!(decoded.ironwood.note_version, NoteVersion::V3);
338            }
339        }
340
341        #[test]
342        fn anchored_bundles_are_preserved() {
343            // A Sapling/Orchard bundle with a non-empty anchor differs from its
344            // empty form, so it must not be omitted even with no spends/actions,
345            // and the anchor must survive the v2 round-trip.
346            let pczt = Creator::new(
347                BranchId::Nu6.into(),
348                10_000_000,
349                133,
350                Some([1; 32]),
351                Some([2; 32]),
352            )
353            .unwrap()
354            .build()
355            .unwrap();
356
357            let encoded = Pczt::try_from(pczt).unwrap();
358
359            assert!(encoded.transparent.is_none());
360            assert!(encoded.sapling.is_some());
361            assert!(encoded.orchard.is_some());
362
363            let decoded = crate::parse(&encoded.serialize()).unwrap();
364
365            assert_eq!(decoded.sapling.anchor, Some([1; 32]));
366            assert_eq!(decoded.orchard.anchor, Some([2; 32]));
367        }
368
369        #[test]
370        fn non_canonical_orchard_flags_and_note_version_prevent_omission() {
371            let mut pczt = Creator::new(
372                BranchId::Nu6.into(),
373                10_000_000,
374                133,
375                Some([0; 32]),
376                Some([0; 32]),
377            )
378            .unwrap()
379            .build()
380            .unwrap();
381            pczt.orchard.flags = 0;
382            pczt.orchard.note_version = NoteVersion::V3;
383
384            // A bundle whose flags or note version differ from the canonical empty
385            // bundle is not omitted, so that those fields round-trip losslessly.
386            let encoded = Pczt::try_from(pczt.clone()).unwrap();
387            assert!(encoded.orchard.is_some());
388
389            let decoded = encoded.into_logical().unwrap();
390            assert_eq!(decoded.orchard, pczt.orchard);
391            assert_eq!(decoded.orchard.flags, 0);
392            assert_eq!(decoded.orchard.note_version, NoteVersion::V3);
393        }
394    }
395}
396
397/// Errors that can occur while serializing a PCZT.
398#[derive(Debug)]
399#[non_exhaustive]
400pub enum EncodingError {
401    /// The requested transaction version cannot be represented in this PCZT
402    /// encoding.
403    UnsupportedTxVersion,
404    /// The v1 PCZT encoding does not support this Orchard note plaintext version.
405    UnsupportedOrchardNoteVersion,
406    /// The PCZT contains data that can only be represented in v2.
407    RequiresV2,
408}
409
410/// A version of the PCZT serialization format.
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412pub enum EncodingVersion {
413    /// The version 1 encoding, produced by [`v1::Pczt::serialize`].
414    V1,
415    /// The version 2 encoding, produced by [`v2::Pczt::serialize`].
416    V2,
417}
418
419impl Pczt {
420    /// Whether this PCZT carries any inputs or outputs in the given pool.
421    ///
422    /// Every bundle is always present as a value, so its existence says nothing; this asks whether
423    /// it holds anything.
424    pub fn has_data_in_pool(&self, pool: PoolType) -> bool {
425        match pool {
426            PoolType::TRANSPARENT => {
427                !self.transparent.inputs().is_empty() || !self.transparent.outputs().is_empty()
428            }
429            PoolType::SAPLING => {
430                !self.sapling.spends().is_empty() || !self.sapling.outputs().is_empty()
431            }
432            PoolType::ORCHARD => !self.orchard.actions().is_empty(),
433            PoolType::IRONWOOD => !self.ironwood.actions().is_empty(),
434        }
435    }
436
437    /// Parses a PCZT from its encoding.
438    pub fn parse(bytes: &[u8]) -> Result<Self, ParseError> {
439        let (version, body) = parse_header(bytes, MAGIC_BYTES).map_err(|e| match e {
440            HeaderParseError::InvalidMagic => ParseError::NotPczt,
441            HeaderParseError::TooShort => ParseError::TooShort,
442        })?;
443        match version {
444            PCZT_VERSION_1 => postcard::from_bytes::<v1::Pczt>(body)
445                .map(Pczt::from)
446                .map_err(ParseError::Invalid),
447            PCZT_VERSION_2 => postcard::from_bytes::<v2::Pczt>(body)
448                .map_err(ParseError::Invalid)
449                .and_then(v2::Pczt::into_logical),
450            _ => Err(ParseError::UnknownVersion(version)),
451        }
452    }
453
454    /// Serializes this PCZT in the minimal encoding version capable of
455    /// representing its content: the v1 encoding whenever the PCZT is
456    /// representable in it (maximizing compatibility with receivers that
457    /// predate the v2 encoding), and the v2 encoding otherwise.
458    ///
459    /// To force a specific PCZT version, use [`v1::Pczt`] or [`v2::Pczt`]
460    /// directly. To learn the encoding version that was used, use
461    /// [`Pczt::serialize_with_version`].
462    pub fn serialize(self) -> Result<Vec<u8>, EncodingError> {
463        self.serialize_with_version().map(|(_, bytes)| bytes)
464    }
465
466    /// Serializes this PCZT, reporting the encoding version it was serialized
467    /// in alongside the encoded bytes.
468    ///
469    /// The encoding version is selected as documented for [`Pczt::serialize`],
470    /// which returns the same bytes.
471    ///
472    /// # Errors
473    ///
474    /// Returns an [`EncodingError`] if this PCZT's content cannot be
475    /// represented in any encoding version.
476    pub fn serialize_with_version(self) -> Result<(EncodingVersion, Vec<u8>), EncodingError> {
477        // Fast pre-checks for the conditions that most commonly rule out the
478        // v1 encoding, avoiding the speculative clone below.
479        let requires_v2 = match self.global.tx_version {
480            zcash_protocol::constants::V6_TX_VERSION => true,
481            #[cfg(zcash_unstable = "nutachyon")]
482            zcash_protocol::constants::V7_TX_VERSION => true,
483            _ => false,
484        };
485        if !requires_v2 && self.ironwood == orchard::EMPTY_IRONWOOD {
486            // The full v1-representability conditions live in the bundle
487            // conversions; attempting the conversion is the single source of
488            // truth for them.
489            if let Ok(v1) = v1::Pczt::try_from(self.clone()) {
490                return Ok((EncodingVersion::V1, v1.serialize()));
491            }
492        }
493        Ok((EncodingVersion::V2, v2::Pczt::try_from(self)?.serialize()))
494    }
495
496    /// Resolves derived or compact field representations carried by this PCZT.
497    ///
498    /// For improved efficiency, callers that will pass the same PCZT through
499    /// multiple roles should call this once up front. Parsing also resolves fields
500    /// defensively.
501    #[cfg(feature = "orchard")]
502    pub fn resolve_fields(&mut self) -> Result<(), ::orchard::pczt::ParseError> {
503        self.orchard.resolve_fields()?;
504        self.ironwood.resolve_fields()
505    }
506
507    /// Parses this PCZT's bundles and constructs a `TransactionData` using caller-provided
508    /// bundle extraction closures.
509    ///
510    /// This handles bundle parsing, version validation, consensus branch ID parsing,
511    /// lock time computation, and final assembly, delegating bundle extraction to the
512    /// caller via closures that receive references to the parsed bundles.
513    #[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
514    pub(crate) fn extract_tx_data<A, E>(
515        self,
516        anchor_requirement: common::AnchorRequirement,
517        extract_transparent: impl FnOnce(
518            &::transparent::pczt::Bundle<zcash_protocol::value::Zatoshis>,
519        ) -> Result<
520            Option<
521                ::transparent::bundle::Bundle<A::TransparentAuth, zcash_protocol::value::Zatoshis>,
522            >,
523            E,
524        >,
525        extract_sapling: impl FnOnce(
526            &::sapling::pczt::Bundle,
527        ) -> Result<
528            Option<::sapling::Bundle<A::SaplingAuth, zcash_protocol::value::ZatBalance>>,
529            E,
530        >,
531        extract_orchard: impl FnOnce(
532            &::orchard::pczt::Bundle,
533        ) -> Result<
534            Option<::orchard::Bundle<A::OrchardAuth, zcash_protocol::value::ZatBalance>>,
535            E,
536        >,
537        extract_ironwood: impl FnOnce(
538            &::orchard::pczt::Bundle,
539        ) -> Result<
540            Option<::orchard::Bundle<A::OrchardAuth, zcash_protocol::value::ZatBalance>>,
541            E,
542        >,
543    ) -> Result<ParsedPczt<A>, E>
544    where
545        A: Authorization,
546        E: From<ExtractError>,
547    {
548        let Pczt {
549            global,
550            transparent,
551            sapling,
552            orchard,
553            ironwood,
554        } = self;
555
556        let consensus_branch_id = BranchId::try_from(global.consensus_branch_id)
557            .map_err(|_| ExtractError::UnknownConsensusBranchId)?;
558        let orchard_protocol_revision = consensus_branch_id
559            .orchard_protocol_revision()
560            // The supported transaction formats do not exist prior to NU5, so no
561            // transaction could be extracted under such a branch in any case.
562            .ok_or(ExtractError::UnsupportedConsensusBranchId)?;
563
564        let version = match (global.tx_version, global.version_group_id) {
565            (V5_TX_VERSION, V5_VERSION_GROUP_ID) => Ok(TxVersion::V5),
566            (V6_TX_VERSION, V6_VERSION_GROUP_ID) => Ok(TxVersion::V6),
567            #[cfg(zcash_unstable = "nutachyon")]
568            (V7_TX_VERSION, V7_VERSION_GROUP_ID) => Ok(TxVersion::V7),
569            (version, version_group_id) => Err(ExtractError::UnsupportedTxVersion {
570                version,
571                version_group_id,
572            }),
573        }?;
574
575        match version {
576            // Only V6 and later transaction formats carry an Ironwood bundle.
577            TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
578                if ironwood != crate::orchard::EMPTY_IRONWOOD {
579                    return Err(ExtractError::IronwoodNotSupported.into());
580                }
581            }
582            // V6 and later transaction formats do not exist prior to NU6.3 (the first
583            // upgrade under which the Orchard protocol is at revision V3).
584            TxVersion::V6 => {
585                if orchard_protocol_revision < OrchardProtocolRevision::V3 {
586                    return Err(ExtractError::UnsupportedConsensusBranchId.into());
587                }
588            }
589            #[cfg(zcash_unstable = "nutachyon")]
590            TxVersion::V7 => {
591                if orchard_protocol_revision < OrchardProtocolRevision::V3 {
592                    return Err(ExtractError::UnsupportedConsensusBranchId.into());
593                }
594            }
595        }
596
597        let transparent = transparent
598            .into_parsed()
599            .map_err(ExtractError::TransparentParse)?;
600        let sapling = sapling
601            .into_parsed(anchor_requirement)
602            .map_err(ExtractError::SaplingParse)?;
603        let orchard_bundle_version = crate::orchard::bundle_version_for_revision(
604            orchard_protocol_revision,
605            ::orchard::ValuePool::Orchard,
606        )
607        .expect("the Orchard pool is supported under every protocol revision");
608        let orchard = orchard
609            .into_parsed_with_version(orchard_bundle_version, anchor_requirement)
610            .map_err(ExtractError::OrchardParse)?;
611        let ironwood = ironwood
612            .into_ironwood_parsed(anchor_requirement)
613            .map_err(ExtractError::IronwoodParse)?;
614
615        let lock_time = determine_lock_time(&global, transparent.inputs())
616            .ok_or(ExtractError::IncompatibleLockTimes)?;
617
618        let transparent_bundle = extract_transparent(&transparent)?;
619        let sapling_bundle = extract_sapling(&sapling.bundle)?;
620        let orchard_bundle = extract_orchard(&orchard.bundle)?;
621        let ironwood_bundle = extract_ironwood(&ironwood.bundle)?;
622
623        let tx_data = match version {
624            TxVersion::V6 => TransactionData::from_parts_v6(
625                consensus_branch_id,
626                lock_time,
627                global.expiry_height.into(),
628                transparent_bundle,
629                sapling_bundle,
630                orchard_bundle,
631                ironwood_bundle,
632            ),
633            #[cfg(zcash_unstable = "nutachyon")]
634            TxVersion::V7 => TransactionData::from_parts_v7(
635                consensus_branch_id,
636                lock_time,
637                global.expiry_height.into(),
638                transparent_bundle,
639                sapling_bundle,
640                orchard_bundle,
641                ironwood_bundle,
642            ),
643            _ => TransactionData::from_parts(
644                version,
645                consensus_branch_id,
646                lock_time,
647                global.expiry_height.into(),
648                transparent_bundle,
649                None,
650                sapling_bundle,
651                orchard_bundle,
652            ),
653        };
654
655        Ok(ParsedPczt {
656            global,
657            transparent,
658            sapling,
659            orchard,
660            ironwood,
661            tx_data,
662        })
663    }
664
665    /// Gets the effects of this transaction.
666    #[cfg(any(feature = "io-finalizer", feature = "signer"))]
667    pub fn into_effects(self) -> Result<TransactionData<EffectsOnly>, ExtractError> {
668        let anchor_requirement =
669            common::AnchorRequirement::for_pre_authorization(self.global.tx_version);
670
671        self.extract_tx_data(
672            anchor_requirement,
673            |t| {
674                t.extract_effects()
675                    .map_err(ExtractError::TransparentExtract)
676            },
677            |s| s.extract_effects().map_err(ExtractError::SaplingExtract),
678            |o| o.extract_effects().map_err(ExtractError::OrchardExtract),
679            |i| i.extract_effects().map_err(ExtractError::IronwoodExtract),
680        )
681        .map(|parsed| parsed.tx_data)
682    }
683}
684
685/// The result of parsing a PCZT and constructing its `TransactionData`.
686#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
687#[cfg_attr(
688    not(any(feature = "io-finalizer", feature = "signer")),
689    allow(dead_code)
690)]
691pub(crate) struct ParsedPczt<A: Authorization> {
692    pub(crate) global: Global,
693    pub(crate) transparent: ::transparent::pczt::Bundle<zcash_protocol::value::Zatoshis>,
694    pub(crate) sapling: crate::sapling::Parsed,
695    pub(crate) orchard: crate::orchard::Parsed,
696    pub(crate) ironwood: crate::orchard::Parsed,
697    pub(crate) tx_data: TransactionData<A>,
698}
699
700#[cfg(any(feature = "io-finalizer", feature = "signer"))]
701pub struct EffectsOnly;
702
703#[cfg(any(feature = "io-finalizer", feature = "signer"))]
704impl Authorization for EffectsOnly {
705    type TransparentAuth = ::transparent::bundle::EffectsOnly<zcash_protocol::value::Zatoshis>;
706    type SaplingAuth = ::sapling::bundle::EffectsOnly;
707    type OrchardAuth = ::orchard::bundle::EffectsOnly;
708}
709
710/// Computes the digests that the signature hashes of `tx_data` commit to.
711///
712/// `global` must be the global data of the PCZT that `tx_data` was extracted from.
713#[cfg(any(feature = "io-finalizer", feature = "signer"))]
714pub(crate) fn precompute_sighash_data(
715    global: &Global,
716    tx_data: TransactionData<EffectsOnly>,
717) -> Result<PrecomputedSighashData<EffectsOnly>, ExtractError> {
718    PrecomputedSighashData::new_zip244(tx_data).map_err(|_| ExtractError::UnsupportedTxVersion {
719        version: global.tx_version,
720        version_group_id: global.version_group_id,
721    })
722}
723
724/// Computes the signature hash of an input to the transaction extracted from a PCZT.
725#[cfg(any(feature = "io-finalizer", feature = "signer"))]
726pub(crate) fn sighash(
727    sighash_data: &PrecomputedSighashData<EffectsOnly>,
728    signable_input: &SignableInput,
729) -> [u8; 32] {
730    *sighash_data.signature_hash(signable_input).as_ref()
731}
732
733/// Errors that can occur while parsing PCZT bundles and extracting transaction data.
734#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
735#[derive(Debug)]
736#[non_exhaustive]
737pub enum ExtractError {
738    /// The PCZT's transparent inputs have incompatible lock time requirements.
739    IncompatibleLockTimes,
740    /// An error occurred extracting the Ironwood protocol bundle from the Ironwood PCZT bundle.
741    IronwoodExtract(::orchard::pczt::TxExtractorError),
742    /// The PCZT carries Ironwood bundle data, but its transaction version does not
743    /// support an Ironwood bundle.
744    IronwoodNotSupported,
745    /// An error occurred parsing the Ironwood PCZT bundle from the PCZT data.
746    IronwoodParse(crate::orchard::ParseError),
747    /// An error occurred extracting the Orchard protocol bundle from the Orchard PCZT bundle.
748    OrchardExtract(::orchard::pczt::TxExtractorError),
749    /// An error occurred parsing the Orchard PCZT bundle from the PCZT data.
750    OrchardParse(crate::orchard::ParseError),
751    /// An error occurred extracting the Sapling protocol bundle from the Sapling PCZT bundle.
752    SaplingExtract(::sapling::pczt::TxExtractorError),
753    /// An error occurred parsing the Sapling PCZT bundle from the PCZT data.
754    SaplingParse(crate::sapling::ParseError),
755    /// An error occurred extracting the transparent protocol bundle from the
756    /// transparent PCZT bundle.
757    TransparentExtract(::transparent::pczt::TxExtractorError),
758    /// An error occurred parsing the transparent PCZT bundle from the PCZT data.
759    TransparentParse(::transparent::pczt::ParseError),
760    /// The consensus branch ID requested by the PCZT does not correspond to a
761    /// known network upgrade.
762    UnknownConsensusBranchId,
763    /// The network upgrade for the PCZT's consensus branch ID predates the v5
764    /// transaction format, so no transaction can be extracted from it.
765    UnsupportedConsensusBranchId,
766    /// The PCZT specifies an unsupported transaction version.
767    UnsupportedTxVersion { version: u32, version_group_id: u32 },
768}
769
770#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
771impl core::fmt::Display for ExtractError {
772    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
773        match self {
774            ExtractError::IncompatibleLockTimes => {
775                write!(f, "the transparent inputs have incompatible lock times")
776            }
777            ExtractError::IronwoodExtract(e) => {
778                write!(f, "could not extract the Ironwood bundle: {e}")
779            }
780            ExtractError::IronwoodNotSupported => write!(
781                f,
782                "the PCZT carries Ironwood bundle data, but its transaction version has no \
783                 Ironwood bundle"
784            ),
785            ExtractError::IronwoodParse(e) => {
786                write!(f, "could not parse the Ironwood bundle: {e:?}")
787            }
788            ExtractError::OrchardExtract(e) => {
789                write!(f, "could not extract the Orchard bundle: {e}")
790            }
791            ExtractError::OrchardParse(e) => write!(f, "could not parse the Orchard bundle: {e:?}"),
792            ExtractError::SaplingExtract(e) => {
793                write!(f, "could not extract the Sapling bundle: {e}")
794            }
795            ExtractError::SaplingParse(e) => write!(f, "could not parse the Sapling bundle: {e:?}"),
796            ExtractError::TransparentExtract(e) => {
797                write!(f, "could not extract the transparent bundle: {e:?}")
798            }
799            ExtractError::TransparentParse(e) => {
800                write!(f, "could not parse the transparent bundle: {e:?}")
801            }
802            ExtractError::UnknownConsensusBranchId => write!(f, "unknown consensus branch ID"),
803            ExtractError::UnsupportedConsensusBranchId => write!(
804                f,
805                "the consensus branch ID predates the v5 transaction format"
806            ),
807            ExtractError::UnsupportedTxVersion {
808                version,
809                version_group_id,
810            } => write!(
811                f,
812                "unsupported transaction version {version} (version group ID {version_group_id})"
813            ),
814        }
815    }
816}
817
818#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
819impl core::error::Error for ExtractError {}
820
821/// Errors that can occur while parsing a PCZT.
822#[derive(Debug)]
823pub enum ParseError {
824    /// The bytes do not contain a PCZT.
825    NotPczt,
826    /// The PCZT encoding was invalid.
827    Invalid(postcard::Error),
828    /// The PCZT encoding omitted a field that is required by the logical PCZT
829    /// type.
830    MissingRequiredField(&'static str),
831    /// The bytes are too short to contain a PCZT.
832    TooShort,
833    /// The PCZT has an unknown version.
834    UnknownVersion(u32),
835}
836
837impl core::fmt::Display for ParseError {
838    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
839        match self {
840            ParseError::NotPczt => write!(f, "the bytes do not contain a PCZT"),
841            ParseError::Invalid(e) => write!(f, "invalid PCZT encoding: {e}"),
842            ParseError::MissingRequiredField(field) => {
843                write!(f, "the PCZT encoding omitted the required field {field}")
844            }
845            ParseError::TooShort => write!(f, "the bytes are too short to contain a PCZT"),
846            ParseError::UnknownVersion(v) => write!(f, "unknown PCZT version {v}"),
847        }
848    }
849}
850
851impl core::error::Error for ParseError {}
852
853#[cfg(all(test, any(feature = "io-finalizer", feature = "signer")))]
854mod extraction_tests {
855    use zcash_primitives::transaction::{
856        TxVersion,
857        sighash::{PrecomputedSighashData, SignableInput},
858        txid::{TxIdDigester, to_txid},
859    };
860    use zcash_protocol::consensus::BranchId;
861
862    use crate::{ExtractError, roles::creator::Creator};
863
864    #[test]
865    fn nu7_pczt_preserves_canonical_v6_digests() {
866        /// Match the independent empty NU7 v6 fixture in the transaction codec tests.
867        const EXPIRY_HEIGHT: u32 = 1;
868        /// Mainnet's registered coin type; no keys or addresses are present in this fixture.
869        const COIN_TYPE: u32 = 133;
870        /// Independently calculated with Python hashlib.blake2b using ZIP 244/229 domains.
871        const EXPECTED_DIGEST: &str =
872            "78296c68a370c2e1f058d997c81c7b011c4562c52fc5ca2994ad59cd179fbe9e";
873        let pczt = Creator::new(BranchId::Nu7.into(), EXPIRY_HEIGHT, COIN_TYPE, None, None)
874            .unwrap()
875            .build()
876            .unwrap();
877        let data = pczt.into_effects().unwrap();
878        assert_eq!(data.version(), TxVersion::V6);
879        let digests = data.digest(TxIdDigester);
880        let expected = hex::decode(EXPECTED_DIGEST).unwrap();
881        assert_eq!(
882            to_txid(data.version(), data.consensus_branch_id(), &digests)
883                .expect("Creator::new returns a compatible version")
884                .as_ref()
885                .as_slice(),
886            expected
887        );
888        assert_eq!(
889            PrecomputedSighashData::new_zip244(data)
890                .unwrap()
891                .signature_hash(&SignableInput::Shielded)
892                .as_ref()
893                .as_slice(),
894            expected
895        );
896    }
897
898    #[test]
899    fn v5_pczt_with_ironwood_data_does_not_extract() {
900        let mut pczt = Creator::new(
901            BranchId::Nu6.into(),
902            10_000_000,
903            133,
904            Some([0; 32]),
905            Some([0; 32]),
906        )
907        .unwrap()
908        .build()
909        .unwrap();
910        pczt.ironwood.bsk = Some(crate::common::SecretKeyBytes::new([1; 32]));
911        assert!(matches!(
912            pczt.into_effects(),
913            Err(ExtractError::IronwoodNotSupported)
914        ));
915    }
916
917    #[test]
918    fn v6_pczt_with_pre_nu6_3_branch_does_not_extract() {
919        let mut pczt = Creator::new(
920            BranchId::Nu6_3.into(),
921            10_000_000,
922            133,
923            Some([0; 32]),
924            Some([0; 32]),
925        )
926        .unwrap()
927        .build()
928        .unwrap();
929        pczt.global.consensus_branch_id = BranchId::Nu6_2.into();
930        assert!(matches!(
931            pczt.into_effects(),
932            Err(ExtractError::UnsupportedConsensusBranchId)
933        ));
934    }
935
936    #[test]
937    #[cfg(zcash_unstable = "nutachyon")]
938    fn nu_tachyon_pczt_extracts_as_v7() {
939        let pczt = Creator::new(
940            BranchId::NuTachyon.into(),
941            10_000_000,
942            133,
943            Some([0; 32]),
944            Some([0; 32]),
945        )
946        .unwrap()
947        .build()
948        .unwrap();
949
950        let tx_data = pczt.into_effects().unwrap();
951        assert_eq!(tx_data.version(), TxVersion::V7);
952        assert_eq!(tx_data.consensus_branch_id(), BranchId::NuTachyon);
953    }
954}
955
956#[cfg(test)]
957mod serialize_tests {
958    use zcash_protocol::consensus::BranchId;
959
960    use crate::{EncodingVersion, roles::creator::Creator};
961
962    fn encoding_version(bytes: &[u8]) -> u32 {
963        assert_eq!(&bytes[..4], crate::MAGIC_BYTES);
964        u32::from_le_bytes(bytes[4..8].try_into().unwrap())
965    }
966
967    #[test]
968    fn serialize_emits_minimal_encoding() {
969        // A v1-representable (v5, canonical-empty Ironwood) PCZT serializes as v1.
970        let pczt = Creator::new(
971            BranchId::Nu6.into(),
972            10_000_000,
973            133,
974            Some([0; 32]),
975            Some([0; 32]),
976        )
977        .unwrap()
978        .build()
979        .unwrap();
980        let bytes = pczt.clone().serialize().unwrap();
981        assert_eq!(encoding_version(&bytes), crate::PCZT_VERSION_1);
982        // The minimal encoding still round-trips through the ordinary parser.
983        assert!(crate::Pczt::parse(&bytes).is_ok());
984
985        // Non-canonical Ironwood data forces the v2 encoding.
986        let mut with_ironwood = pczt.clone();
987        with_ironwood.ironwood.bsk = Some(crate::common::SecretKeyBytes::new([1; 32]));
988        assert_eq!(
989            encoding_version(&with_ironwood.serialize().unwrap()),
990            crate::PCZT_VERSION_2,
991        );
992
993        // An Orchard note-plaintext version the v1 encoding cannot carry
994        // forces the v2 encoding.
995        let mut with_note_v3 = pczt;
996        with_note_v3.orchard.note_version = crate::orchard::NoteVersion::V3;
997        assert_eq!(
998            encoding_version(&with_note_v3.serialize().unwrap()),
999            crate::PCZT_VERSION_2,
1000        );
1001
1002        // A v6 transaction forces the v2 encoding.
1003        let v6 = Creator::new(
1004            BranchId::Nu6_3.into(),
1005            10_000_000,
1006            133,
1007            Some([0; 32]),
1008            Some([0; 32]),
1009        )
1010        .unwrap()
1011        .build()
1012        .unwrap();
1013        assert_eq!(
1014            encoding_version(&v6.serialize().unwrap()),
1015            crate::PCZT_VERSION_2,
1016        );
1017    }
1018
1019    #[test]
1020    fn serialize_with_version_reports_the_encoding_used() {
1021        // A v1-representable (v5, canonical-empty Ironwood) PCZT.
1022        let v5 = Creator::new(
1023            BranchId::Nu6.into(),
1024            10_000_000,
1025            133,
1026            Some([0; 32]),
1027            Some([0; 32]),
1028        )
1029        .unwrap()
1030        .build()
1031        .unwrap();
1032
1033        // A v6 transaction, which the v1 encoding cannot represent.
1034        let v6 = Creator::new(
1035            BranchId::Nu6_3.into(),
1036            10_000_000,
1037            133,
1038            Some([0; 32]),
1039            Some([0; 32]),
1040        )
1041        .unwrap()
1042        .build()
1043        .unwrap();
1044
1045        for (pczt, expected, expected_header) in [
1046            (v5, EncodingVersion::V1, crate::PCZT_VERSION_1),
1047            (v6, EncodingVersion::V2, crate::PCZT_VERSION_2),
1048        ] {
1049            let (version, bytes) = pczt.clone().serialize_with_version().unwrap();
1050
1051            // The reported version is the one the encoding's header carries.
1052            assert_eq!(version, expected);
1053            assert_eq!(encoding_version(&bytes), expected_header);
1054
1055            // `serialize` produces exactly these bytes.
1056            assert_eq!(pczt.serialize().unwrap(), bytes);
1057        }
1058    }
1059}