pczt 0.8.0

Tools for working with partially-created Zcash transactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! The Partially Created Zcash Transaction (PCZT) format.
//!
//! This format enables splitting up the logical steps of creating a Zcash transaction
//! across distinct entities. The entity roles roughly match those specified in
//! [BIP 174: Partially Signed Bitcoin Transaction Format] and [BIP 370: PSBT Version 2],
//! with additional Zcash-specific roles.
//!
//! [BIP 174: Partially Signed Bitcoin Transaction Format]: https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki
//! [BIP 370: PSBT Version 2]: https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki
//!
#![cfg_attr(feature = "std", doc = "## Feature flags")]
#![cfg_attr(feature = "std", doc = document_features::document_features!())]
//!

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, doc(auto_cfg))]
// Catch documentation errors caused by code changes.
#![deny(rustdoc::broken_intra_doc_links)]

#[macro_use]
extern crate alloc;

use alloc::vec::Vec;

use getset::Getters;

#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
use zcash_protocol::constants::{V6_TX_VERSION, V6_VERSION_GROUP_ID};
#[cfg(all(
    any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"),
    zcash_unstable = "nu7",
    feature = "zip-233",
))]
use zcash_protocol::value::Zatoshis;
#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
use {
    common::{Global, determine_lock_time},
    zcash_primitives::transaction::{Authorization, TransactionData, TxVersion},
    zcash_protocol::{
        consensus::{BranchId, OrchardProtocolRevision},
        constants::{V5_TX_VERSION, V5_VERSION_GROUP_ID},
    },
};

#[cfg(any(feature = "io-finalizer", feature = "signer"))]
use zcash_primitives::transaction::sighash_v6::v6_signature_hash;
#[cfg(any(feature = "io-finalizer", feature = "signer"))]
use {
    blake2b_simd::Hash as Blake2bHash,
    zcash_primitives::transaction::{
        TxDigests, sighash::SignableInput, sighash_v5::v5_signature_hash,
    },
};

pub mod roles;

pub mod common;
pub mod orchard;
pub mod sapling;
pub mod transparent;

pub(crate) const MAGIC_BYTES: &[u8; 4] = b"PCZT";
pub(crate) const PCZT_VERSION_1: u32 = 1;
pub(crate) const PCZT_VERSION_2: u32 = 2;

const VERSIONED_HEADER_LEN: usize = 8;

pub(crate) enum HeaderParseError {
    InvalidMagic,
    TooShort,
}

pub(crate) fn parse_header<'a>(
    bytes: &'a [u8],
    magic: &[u8; 4],
) -> Result<(u32, &'a [u8]), HeaderParseError> {
    if bytes.len() < VERSIONED_HEADER_LEN {
        return Err(HeaderParseError::TooShort);
    }
    if &bytes[..4] != magic {
        return Err(HeaderParseError::InvalidMagic);
    }

    let version = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
    Ok((version, &bytes[VERSIONED_HEADER_LEN..]))
}

pub(crate) fn serialize_header(magic: &[u8; 4], version: u32) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(VERSIONED_HEADER_LEN);
    bytes.extend_from_slice(magic);
    bytes.extend_from_slice(&version.to_le_bytes());
    bytes
}

/// Parses a PCZT from its encoding.
pub fn parse(bytes: &[u8]) -> Result<Pczt, ParseError> {
    Pczt::parse(bytes)
}

/// A partially-created Zcash transaction.
#[derive(Clone, Debug, Getters)]
pub struct Pczt {
    /// Global fields that are relevant to the transaction as a whole.
    #[getset(get = "pub")]
    pub(crate) global: common::Global,

    //
    // Protocol-specific fields.
    //
    // Unlike the `TransactionData` type in `zcash_primitives`, these are not optional.
    // This is because a PCZT does not always contain a semantically-valid transaction,
    // and there may be phases where we need to store protocol-specific metadata before
    // it has been determined whether there are protocol-specific inputs or outputs.
    //
    #[getset(get = "pub")]
    pub(crate) transparent: transparent::Bundle,
    #[getset(get = "pub")]
    pub(crate) sapling: sapling::Bundle,
    #[getset(get = "pub")]
    pub(crate) orchard: orchard::Bundle,
    #[getset(get = "pub")]
    pub(crate) ironwood: orchard::Bundle,
}

/// Types and operations for the v1 Pczt encoding.
pub mod v1 {
    use alloc::vec::Vec;
    use serde::{Deserialize, Serialize};

    use crate::{common, orchard, sapling, transparent};

    /// The in-memory type used for derived serialization of the v1 Pczt encoding.
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct Pczt {
        global: common::Global,
        transparent: transparent::Bundle,
        sapling: sapling::v1::Bundle,
        orchard: orchard::v1::Bundle,
    }

    impl Pczt {
        pub fn serialize(&self) -> Vec<u8> {
            let bytes = crate::serialize_header(crate::MAGIC_BYTES, crate::PCZT_VERSION_1);
            postcard::to_extend(&self, bytes).expect("can serialize into memory")
        }
    }

    /// Encodes the in-memory [`super::Pczt`] into the v1 serialization type [`Pczt`].
    impl TryFrom<super::Pczt> for Pczt {
        type Error = super::EncodingError;

        fn try_from(pczt: super::Pczt) -> Result<Self, Self::Error> {
            // The v1 format predates the v6 transaction format; a parser of the v1
            // encoding could parse a v6 PCZT but never extract a transaction from it.
            if pczt.global.tx_version == zcash_protocol::constants::V6_TX_VERSION {
                return Err(super::EncodingError::UnsupportedTxVersion);
            }

            // The v1 format cannot represent an Ironwood bundle in any state other
            // than the canonical empty one; a parser of the v1 encoding will
            // reconstruct exactly that value.
            if pczt.ironwood != orchard::EMPTY_IRONWOOD {
                return Err(super::EncodingError::UnsupportedTxVersion);
            }

            Ok(Self {
                global: pczt.global,
                transparent: pczt.transparent,
                sapling: sapling::v1::Bundle::try_from(pczt.sapling)?,
                orchard: orchard::v1::Bundle::try_from(pczt.orchard)?,
            })
        }
    }

    impl From<Pczt> for super::Pczt {
        fn from(pczt: Pczt) -> Self {
            Self {
                global: pczt.global,
                transparent: pczt.transparent,
                sapling: pczt.sapling.into(),
                orchard: pczt.orchard.into(),
                ironwood: orchard::EMPTY_IRONWOOD,
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use zcash_protocol::consensus::BranchId;

        use crate::roles::creator::Creator;

        #[test]
        fn v1_refuses_v6_pczts_and_non_canonical_ironwood_bundles() {
            // A v6 tx cannot be encoded as a v1 PCZT, even when its Ironwood bundle is
            // canonically empty.
            let pczt = Creator::new(
                BranchId::Nu6_3.into(),
                10_000_000,
                133,
                Some([0; 32]),
                Some([0; 32]),
            )
            .unwrap()
            .build()
            .unwrap();
            assert!(matches!(
                super::Pczt::try_from(pczt),
                Err(crate::EncodingError::UnsupportedTxVersion)
            ));

            // A v5 tx carrying non-canonical Ironwood bundle data cannot be encoded
            // as a v1 PCZT, because the data would be dropped.
            let mut pczt = Creator::new(
                BranchId::Nu6.into(),
                10_000_000,
                133,
                Some([0; 32]),
                Some([0; 32]),
            )
            .unwrap()
            .build()
            .unwrap();
            pczt.ironwood.bsk = Some([1; 32]);
            assert!(matches!(
                super::Pczt::try_from(pczt),
                Err(crate::EncodingError::UnsupportedTxVersion)
            ));
        }
    }
}

/// Types and operations for the v2 Pczt encoding.
pub mod v2 {
    use alloc::vec::Vec;
    use serde::{Deserialize, Serialize};

    use crate::{common, orchard, sapling, transparent};

    /// The in-memory type used for derived serialization of the v2 Pczt encoding.
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct Pczt {
        global: common::Global,
        // This value is set to `None` if the transparent bundle is empty,
        // meaning inputs and outputs are empty.
        transparent: Option<transparent::Bundle>,
        // This value is set to `None` if the Sapling bundle is empty,
        // meaning every field has its empty/default value.
        sapling: Option<sapling::Bundle>,
        // This value is set to `None` if the Orchard bundle is empty,
        // meaning actions, value sum, anchor, zkproof, and bsk are all
        // empty. Flags and note version are not checked, as values can be
        // defaulted there.
        orchard: Option<orchard::v2::Bundle>,
        ironwood: Option<orchard::v2::Bundle>,
    }

    impl Pczt {
        pub fn serialize(&self) -> Vec<u8> {
            let bytes = crate::serialize_header(crate::MAGIC_BYTES, crate::PCZT_VERSION_2);
            postcard::to_extend(&self, bytes).expect("can serialize into memory")
        }
    }

    /// Encodes the in-memory [`super::Pczt`] into the v2 serialization type [`Pczt`],
    /// omitting empty Transparent, Sapling, and Orchard bundles.
    impl TryFrom<super::Pczt> for Pczt {
        type Error = super::EncodingError;

        fn try_from(pczt: super::Pczt) -> Result<Self, Self::Error> {
            Ok(Self {
                global: pczt.global,
                transparent: (pczt.transparent != transparent::EMPTY_BUNDLE)
                    .then_some(pczt.transparent),
                sapling: sapling::v2::encode(pczt.sapling),
                orchard: orchard::v2::encode(pczt.orchard, &orchard::EMPTY_ORCHARD)?,
                ironwood: orchard::v2::encode(pczt.ironwood, &orchard::EMPTY_IRONWOOD)?,
            })
        }
    }

    impl Pczt {
        pub(super) fn into_logical(self) -> Result<super::Pczt, super::ParseError> {
            Ok(super::Pczt {
                global: self.global,
                transparent: self.transparent.unwrap_or(transparent::EMPTY_BUNDLE),
                sapling: self.sapling.unwrap_or(sapling::EMPTY_BUNDLE),
                orchard: self
                    .orchard
                    .map(orchard::v2::Bundle::into_logical)
                    .transpose()?
                    .unwrap_or(orchard::EMPTY_ORCHARD),
                ironwood: self
                    .ironwood
                    .map(orchard::v2::Bundle::into_logical)
                    .transpose()?
                    .unwrap_or(orchard::EMPTY_IRONWOOD),
            })
        }
    }

    #[cfg(test)]
    mod tests {
        use zcash_protocol::consensus::BranchId;

        use super::Pczt;
        use crate::{orchard::NoteVersion, roles::creator::Creator};

        #[test]
        fn empty_bundles_encode_as_none_and_decode_as_empty() {
            // Absent anchors: the shielded bundles carry no anchor and no
            // spends/actions, so they are fully empty and omitted.
            let pczt = Creator::new(BranchId::Nu6_3.into(), 10_000_000, 133, None, None)
                .unwrap()
                .build()
                .unwrap();

            let encoded = Pczt::try_from(pczt).unwrap();

            assert!(encoded.transparent.is_none());
            assert!(encoded.sapling.is_none());
            assert!(encoded.orchard.is_none());
            assert!(encoded.ironwood.is_none());

            let decoded = crate::parse(&encoded.serialize()).unwrap();

            assert!(decoded.transparent.inputs.is_empty());
            assert!(decoded.transparent.outputs.is_empty());
            assert!(decoded.sapling.spends.is_empty());
            assert!(decoded.sapling.outputs.is_empty());
            assert!(decoded.sapling.anchor.is_none());
            assert!(decoded.orchard.actions.is_empty());
            assert_eq!(decoded.orchard.note_version, NoteVersion::V2);
            {
                assert!(decoded.ironwood.actions.is_empty());
                assert_eq!(decoded.ironwood.note_version, NoteVersion::V3);
            }
        }

        #[test]
        fn anchored_bundles_are_preserved() {
            // A Sapling/Orchard bundle with a non-empty anchor differs from its
            // empty form, so it must not be omitted even with no spends/actions,
            // and the anchor must survive the v2 round-trip.
            let pczt = Creator::new(
                BranchId::Nu6.into(),
                10_000_000,
                133,
                Some([1; 32]),
                Some([2; 32]),
            )
            .unwrap()
            .build()
            .unwrap();

            let encoded = Pczt::try_from(pczt).unwrap();

            assert!(encoded.transparent.is_none());
            assert!(encoded.sapling.is_some());
            assert!(encoded.orchard.is_some());

            let decoded = crate::parse(&encoded.serialize()).unwrap();

            assert_eq!(decoded.sapling.anchor, Some([1; 32]));
            assert_eq!(decoded.orchard.anchor, Some([2; 32]));
        }

        #[test]
        fn non_canonical_orchard_flags_and_note_version_prevent_omission() {
            let mut pczt = Creator::new(
                BranchId::Nu6.into(),
                10_000_000,
                133,
                Some([0; 32]),
                Some([0; 32]),
            )
            .unwrap()
            .build()
            .unwrap();
            pczt.orchard.flags = 0;
            pczt.orchard.note_version = NoteVersion::V3;

            // A bundle whose flags or note version differ from the canonical empty
            // bundle is not omitted, so that those fields round-trip losslessly.
            let encoded = Pczt::try_from(pczt.clone()).unwrap();
            assert!(encoded.orchard.is_some());

            let decoded = encoded.into_logical().unwrap();
            assert_eq!(decoded.orchard, pczt.orchard);
            assert_eq!(decoded.orchard.flags, 0);
            assert_eq!(decoded.orchard.note_version, NoteVersion::V3);
        }
    }
}

/// Errors that can occur while serializing a PCZT.
#[derive(Debug)]
#[non_exhaustive]
pub enum EncodingError {
    /// The requested transaction version cannot be represented in this PCZT
    /// encoding.
    UnsupportedTxVersion,
    /// The v1 PCZT encoding does not support this Orchard note plaintext version.
    UnsupportedOrchardNoteVersion,
    /// The PCZT contains data that can only be represented in v2.
    RequiresV2,
}

impl Pczt {
    /// Parses a PCZT from its encoding.
    pub fn parse(bytes: &[u8]) -> Result<Self, ParseError> {
        let (version, body) = parse_header(bytes, MAGIC_BYTES).map_err(|e| match e {
            HeaderParseError::InvalidMagic => ParseError::NotPczt,
            HeaderParseError::TooShort => ParseError::TooShort,
        })?;
        match version {
            PCZT_VERSION_1 => postcard::from_bytes::<v1::Pczt>(body)
                .map(Pczt::from)
                .map_err(ParseError::Invalid),
            PCZT_VERSION_2 => postcard::from_bytes::<v2::Pczt>(body)
                .map_err(ParseError::Invalid)
                .and_then(v2::Pczt::into_logical),
            _ => Err(ParseError::UnknownVersion(version)),
        }
    }

    /// Serializes this PCZT as the latest PCZT version.
    ///
    /// To serialize a specific PCZT version, e.g. v1, use [`v1::Pczt::serialize`].
    pub fn serialize(self) -> Result<Vec<u8>, EncodingError> {
        Ok(v2::Pczt::try_from(self)?.serialize())
    }

    /// Resolves derived or compact field representations carried by this PCZT.
    ///
    /// For improved efficiency, callers that will pass the same PCZT through
    /// multiple roles should call this once up front. Parsing also resolves fields
    /// defensively.
    #[cfg(feature = "orchard")]
    pub fn resolve_fields(&mut self) -> Result<(), ::orchard::pczt::ParseError> {
        self.orchard.resolve_fields()?;
        self.ironwood.resolve_fields()
    }

    /// Parses this PCZT's bundles and constructs a `TransactionData` using caller-provided
    /// bundle extraction closures.
    ///
    /// This handles bundle parsing, version validation, consensus branch ID parsing,
    /// lock time computation, and final assembly, delegating bundle extraction to the
    /// caller via closures that receive references to the parsed bundles.
    #[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
    pub(crate) fn extract_tx_data<A, E>(
        self,
        anchor_requirement: common::AnchorRequirement,
        extract_transparent: impl FnOnce(
            &::transparent::pczt::Bundle,
        ) -> Result<
            Option<::transparent::bundle::Bundle<A::TransparentAuth>>,
            E,
        >,
        extract_sapling: impl FnOnce(
            &::sapling::pczt::Bundle,
        ) -> Result<
            Option<::sapling::Bundle<A::SaplingAuth, zcash_protocol::value::ZatBalance>>,
            E,
        >,
        extract_orchard: impl FnOnce(
            &::orchard::pczt::Bundle,
        ) -> Result<
            Option<::orchard::Bundle<A::OrchardAuth, zcash_protocol::value::ZatBalance>>,
            E,
        >,
        extract_ironwood: impl FnOnce(
            &::orchard::pczt::Bundle,
        ) -> Result<
            Option<::orchard::Bundle<A::OrchardAuth, zcash_protocol::value::ZatBalance>>,
            E,
        >,
    ) -> Result<ParsedPczt<A>, E>
    where
        A: Authorization,
        E: From<ExtractError>,
    {
        let Pczt {
            global,
            transparent,
            sapling,
            orchard,
            ironwood,
        } = self;

        let consensus_branch_id = BranchId::try_from(global.consensus_branch_id)
            .map_err(|_| ExtractError::UnknownConsensusBranchId)?;
        let orchard_protocol_revision = consensus_branch_id
            .orchard_protocol_revision()
            // The v5 and v6 transaction formats do not exist prior to NU5, so no
            // transaction could be extracted under such a branch in any case.
            .ok_or(ExtractError::UnsupportedConsensusBranchId)?;

        let version = match (global.tx_version, global.version_group_id) {
            (V5_TX_VERSION, V5_VERSION_GROUP_ID) => Ok(TxVersion::V5),
            (V6_TX_VERSION, V6_VERSION_GROUP_ID) => Ok(TxVersion::V6),
            (version, version_group_id) => Err(ExtractError::UnsupportedTxVersion {
                version,
                version_group_id,
            }),
        }?;

        match version {
            // Only the v6 transaction format carries an Ironwood bundle.
            TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
                if ironwood != crate::orchard::EMPTY_IRONWOOD {
                    return Err(ExtractError::IronwoodNotSupported.into());
                }
            }
            // The v6 transaction format does not exist prior to NU6.3 (the first
            // upgrade under which the Orchard protocol is at revision V3).
            TxVersion::V6 => {
                if orchard_protocol_revision < OrchardProtocolRevision::V3 {
                    return Err(ExtractError::UnsupportedConsensusBranchId.into());
                }
            }
        }

        let transparent = transparent
            .into_parsed()
            .map_err(ExtractError::TransparentParse)?;
        let sapling = sapling
            .into_parsed(anchor_requirement)
            .map_err(ExtractError::SaplingParse)?;
        let orchard_bundle_version = crate::orchard::bundle_version_for_revision(
            orchard_protocol_revision,
            ::orchard::ValuePool::Orchard,
        )
        .expect("the Orchard pool is supported under every protocol revision");
        let orchard = orchard
            .into_parsed_with_version(orchard_bundle_version, anchor_requirement)
            .map_err(ExtractError::OrchardParse)?;
        let ironwood = ironwood
            .into_ironwood_parsed(anchor_requirement)
            .map_err(ExtractError::IronwoodParse)?;

        let lock_time = determine_lock_time(&global, transparent.inputs())
            .ok_or(ExtractError::IncompatibleLockTimes)?;

        let transparent_bundle = extract_transparent(&transparent)?;
        let sapling_bundle = extract_sapling(&sapling.bundle)?;
        let orchard_bundle = extract_orchard(&orchard.bundle)?;
        let ironwood_bundle = extract_ironwood(&ironwood.bundle)?;

        let tx_data = match version {
            TxVersion::V6 => TransactionData::from_parts_v6(
                consensus_branch_id,
                lock_time,
                global.expiry_height.into(),
                #[cfg(all(zcash_unstable = "nu7", feature = "zip-233"))]
                Zatoshis::ZERO,
                transparent_bundle,
                sapling_bundle,
                orchard_bundle,
                ironwood_bundle,
            ),
            _ => TransactionData::from_parts(
                version,
                consensus_branch_id,
                lock_time,
                global.expiry_height.into(),
                #[cfg(all(zcash_unstable = "nu7", feature = "zip-233"))]
                Zatoshis::ZERO,
                transparent_bundle,
                None,
                sapling_bundle,
                orchard_bundle,
            ),
        };

        Ok(ParsedPczt {
            global,
            transparent,
            sapling,
            orchard,
            ironwood,
            tx_data,
        })
    }

    /// Gets the effects of this transaction.
    #[cfg(any(feature = "io-finalizer", feature = "signer"))]
    pub fn into_effects(self) -> Result<TransactionData<EffectsOnly>, ExtractError> {
        let anchor_requirement =
            common::AnchorRequirement::for_pre_authorization(self.global.tx_version);

        self.extract_tx_data(
            anchor_requirement,
            |t| {
                t.extract_effects()
                    .map_err(ExtractError::TransparentExtract)
            },
            |s| s.extract_effects().map_err(ExtractError::SaplingExtract),
            |o| o.extract_effects().map_err(ExtractError::OrchardExtract),
            |i| i.extract_effects().map_err(ExtractError::IronwoodExtract),
        )
        .map(|parsed| parsed.tx_data)
    }
}

/// The result of parsing a PCZT and constructing its `TransactionData`.
#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
#[cfg_attr(
    not(any(feature = "io-finalizer", feature = "signer")),
    allow(dead_code)
)]
pub(crate) struct ParsedPczt<A: Authorization> {
    pub(crate) global: Global,
    pub(crate) transparent: ::transparent::pczt::Bundle,
    pub(crate) sapling: crate::sapling::Parsed,
    pub(crate) orchard: crate::orchard::Parsed,
    pub(crate) ironwood: crate::orchard::Parsed,
    pub(crate) tx_data: TransactionData<A>,
}

#[cfg(any(feature = "io-finalizer", feature = "signer"))]
pub struct EffectsOnly;

#[cfg(any(feature = "io-finalizer", feature = "signer"))]
impl Authorization for EffectsOnly {
    type TransparentAuth = ::transparent::bundle::EffectsOnly;
    type SaplingAuth = ::sapling::bundle::EffectsOnly;
    type OrchardAuth = ::orchard::bundle::EffectsOnly;
}

/// Helper to produce the correct sighash for a PCZT.
#[cfg(any(feature = "io-finalizer", feature = "signer"))]
pub(crate) fn sighash(
    tx_data: &TransactionData<EffectsOnly>,
    signable_input: &SignableInput,
    txid_parts: &TxDigests<Blake2bHash>,
) -> [u8; 32] {
    match tx_data.version() {
        TxVersion::V5 => v5_signature_hash(tx_data, signable_input, txid_parts),
        TxVersion::V6 => v6_signature_hash(tx_data, signable_input, txid_parts),
        _ => unreachable!("PCZT only supports v5 and v6 transaction data"),
    }
    .as_ref()
    .try_into()
    .expect("correct length")
}

/// Errors that can occur while parsing PCZT bundles and extracting transaction data.
#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
#[derive(Debug)]
#[non_exhaustive]
pub enum ExtractError {
    /// The PCZT's transparent inputs have incompatible lock time requirements.
    IncompatibleLockTimes,
    /// An error occurred extracting the Ironwood protocol bundle from the Ironwood PCZT bundle.
    IronwoodExtract(::orchard::pczt::TxExtractorError),
    /// The PCZT carries Ironwood bundle data, but its transaction version does not
    /// support an Ironwood bundle.
    IronwoodNotSupported,
    /// An error occurred parsing the Ironwood PCZT bundle from the PCZT data.
    IronwoodParse(crate::orchard::ParseError),
    /// An error occurred extracting the Orchard protocol bundle from the Orchard PCZT bundle.
    OrchardExtract(::orchard::pczt::TxExtractorError),
    /// An error occurred parsing the Orchard PCZT bundle from the PCZT data.
    OrchardParse(crate::orchard::ParseError),
    /// An error occurred extracting the Sapling protocol bundle from the Sapling PCZT bundle.
    SaplingExtract(::sapling::pczt::TxExtractorError),
    /// An error occurred parsing the Sapling PCZT bundle from the PCZT data.
    SaplingParse(crate::sapling::ParseError),
    /// An error occurred extracting the transparent protocol bundle from the
    /// transparent PCZT bundle.
    TransparentExtract(::transparent::pczt::TxExtractorError),
    /// An error occurred parsing the transparent PCZT bundle from the PCZT data.
    TransparentParse(::transparent::pczt::ParseError),
    /// The consensus branch ID requested by the PCZT does not correspond to a
    /// known network upgrade.
    UnknownConsensusBranchId,
    /// The network upgrade for the PCZT's consensus branch ID predates the v5
    /// transaction format, so no transaction can be extracted from it.
    UnsupportedConsensusBranchId,
    /// The PCZT specifies an unsupported transaction version.
    UnsupportedTxVersion { version: u32, version_group_id: u32 },
}

/// Errors that can occur while parsing a PCZT.
#[derive(Debug)]
pub enum ParseError {
    /// The bytes do not contain a PCZT.
    NotPczt,
    /// The PCZT encoding was invalid.
    Invalid(postcard::Error),
    /// The PCZT encoding omitted a field that is required by the logical PCZT
    /// type.
    MissingRequiredField(&'static str),
    /// The bytes are too short to contain a PCZT.
    TooShort,
    /// The PCZT has an unknown version.
    UnknownVersion(u32),
}

#[cfg(all(test, any(feature = "io-finalizer", feature = "signer")))]
mod extraction_tests {
    use zcash_protocol::consensus::BranchId;

    use crate::{ExtractError, roles::creator::Creator};

    #[test]
    fn v5_pczt_with_ironwood_data_does_not_extract() {
        let mut pczt = Creator::new(
            BranchId::Nu6.into(),
            10_000_000,
            133,
            Some([0; 32]),
            Some([0; 32]),
        )
        .unwrap()
        .build()
        .unwrap();
        pczt.ironwood.bsk = Some([1; 32]);
        assert!(matches!(
            pczt.into_effects(),
            Err(ExtractError::IronwoodNotSupported)
        ));
    }

    #[test]
    fn v6_pczt_with_pre_nu6_3_branch_does_not_extract() {
        let mut pczt = Creator::new(
            BranchId::Nu6_3.into(),
            10_000_000,
            133,
            Some([0; 32]),
            Some([0; 32]),
        )
        .unwrap()
        .build()
        .unwrap();
        pczt.global.consensus_branch_id = BranchId::Nu6_2.into();
        assert!(matches!(
            pczt.into_effects(),
            Err(ExtractError::UnsupportedConsensusBranchId)
        ));
    }
}