1#![cfg_attr(feature = "std", doc = "## Feature flags")]
12#![cfg_attr(feature = "std", doc = document_features::document_features!())]
13#![no_std]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17#![cfg_attr(docsrs, doc(auto_cfg))]
18#![deny(rustdoc::broken_intra_doc_links)]
20
21#[macro_use]
22extern crate alloc;
23#[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
92pub fn parse(bytes: &[u8]) -> Result<Pczt, ParseError> {
94 Pczt::parse(bytes)
95}
96
97#[derive(Clone, Debug, Getters)]
99pub struct Pczt {
100 #[getset(get = "pub")]
102 pub(crate) global: common::Global,
103
104 #[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
122pub mod v1 {
124 use alloc::vec::Vec;
125 use serde::{Deserialize, Serialize};
126
127 use crate::{common, orchard, sapling, transparent};
128
129 #[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 impl TryFrom<super::Pczt> for Pczt {
147 type Error = super::EncodingError;
148
149 fn try_from(pczt: super::Pczt) -> Result<Self, Self::Error> {
150 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 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 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 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
234pub mod v2 {
236 use alloc::vec::Vec;
237 use serde::{Deserialize, Serialize};
238
239 use crate::{common, orchard, sapling, transparent};
240
241 #[derive(Clone, Debug, Serialize, Deserialize)]
243 pub struct Pczt {
244 global: common::Global,
245 transparent: Option<transparent::Bundle>,
248 sapling: Option<sapling::Bundle>,
251 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 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 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 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 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#[derive(Debug)]
399#[non_exhaustive]
400pub enum EncodingError {
401 UnsupportedTxVersion,
404 UnsupportedOrchardNoteVersion,
406 RequiresV2,
408}
409
410#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412pub enum EncodingVersion {
413 V1,
415 V2,
417}
418
419impl Pczt {
420 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 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 pub fn serialize(self) -> Result<Vec<u8>, EncodingError> {
463 self.serialize_with_version().map(|(_, bytes)| bytes)
464 }
465
466 pub fn serialize_with_version(self) -> Result<(EncodingVersion, Vec<u8>), EncodingError> {
477 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 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 #[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 #[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 .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 TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 | TxVersion::V5 => {
578 if ironwood != crate::orchard::EMPTY_IRONWOOD {
579 return Err(ExtractError::IronwoodNotSupported.into());
580 }
581 }
582 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 #[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#[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#[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#[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#[cfg(any(feature = "io-finalizer", feature = "signer", feature = "tx-extractor"))]
735#[derive(Debug)]
736#[non_exhaustive]
737pub enum ExtractError {
738 IncompatibleLockTimes,
740 IronwoodExtract(::orchard::pczt::TxExtractorError),
742 IronwoodNotSupported,
745 IronwoodParse(crate::orchard::ParseError),
747 OrchardExtract(::orchard::pczt::TxExtractorError),
749 OrchardParse(crate::orchard::ParseError),
751 SaplingExtract(::sapling::pczt::TxExtractorError),
753 SaplingParse(crate::sapling::ParseError),
755 TransparentExtract(::transparent::pczt::TxExtractorError),
758 TransparentParse(::transparent::pczt::ParseError),
760 UnknownConsensusBranchId,
763 UnsupportedConsensusBranchId,
766 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#[derive(Debug)]
823pub enum ParseError {
824 NotPczt,
826 Invalid(postcard::Error),
828 MissingRequiredField(&'static str),
831 TooShort,
833 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 const EXPIRY_HEIGHT: u32 = 1;
868 const COIN_TYPE: u32 = 133;
870 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 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 assert!(crate::Pczt::parse(&bytes).is_ok());
984
985 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 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 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 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 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 assert_eq!(version, expected);
1053 assert_eq!(encoding_version(&bytes), expected_header);
1054
1055 assert_eq!(pczt.serialize().unwrap(), bytes);
1057 }
1058 }
1059}