1use std::fmt;
4
5pub use zcash_primitives::transaction::TxVersion;
6
7use zcash_primitives::transaction::{self as zp_tx};
8use zcash_protocol::value::ZatBalance;
9
10mod auth_digest;
11pub(crate) mod compat;
12mod hash;
13mod joinsplit;
14mod lock_time;
15mod memo;
16mod serialize;
17mod sighash;
18mod unmined;
19
20#[cfg(any(test, feature = "proptest-impl"))]
21#[allow(clippy::unwrap_in_result)]
22pub mod arbitrary;
23#[cfg(any(test, feature = "proptest-impl"))]
24mod test_signing;
25#[cfg(test)]
26mod test_signing_tests;
27#[cfg(test)]
28mod tests;
29
30pub use crate::sapling::FieldNotPresent;
31pub use auth_digest::AuthDigest;
32pub use compat::{sprout_joinsplit_key_proof_and_ciphertexts, SPROUT_CIPHERTEXT_SIZE};
33pub use hash::{Hash, WtxId};
34pub use joinsplit::JoinSplitData;
35pub use lock_time::LockTime;
36pub use memo::Memo;
37pub use serialize::{
38 SerializedTransaction, MIN_TRANSPARENT_TX_SIZE, MIN_TRANSPARENT_TX_V4_SIZE,
39 MIN_TRANSPARENT_TX_V5_SIZE,
40};
41pub use sighash::{HashType, SigHash, SigHasher};
42#[cfg(any(test, feature = "proptest-impl"))]
43pub use test_signing::TransparentSigningKey;
44pub use unmined::{
45 zip317, UnminedTx, UnminedTxId, VerifiedUnminedTx, MEMPOOL_TRANSACTION_COST_THRESHOLD,
46};
47
48use crate::{
49 amount::{Amount, NegativeAllowed, NonNegative},
50 block,
51 parameters::NetworkUpgrade,
52 transparent,
53 value_balance::ValueBalance,
54 Error,
55};
56
57#[derive(Debug)]
59pub struct Transaction(pub(crate) zp_tx::Transaction);
60
61impl std::ops::Deref for Transaction {
62 type Target = zp_tx::TransactionData<zp_tx::Authorized>;
63
64 fn deref(&self) -> &Self::Target {
65 &self.0
66 }
67}
68
69impl Transaction {
70 pub(crate) fn inner(&self) -> &zp_tx::Transaction {
72 &self.0
73 }
74
75 pub fn tx_version(&self) -> TxVersion {
77 self.0.version()
78 }
79
80 #[allow(unreachable_patterns)]
82 pub fn version(&self) -> u32 {
83 match self.0.version() {
84 TxVersion::Sprout(v) => v,
85 TxVersion::V3 => 3,
86 TxVersion::V4 => 4,
87 TxVersion::V5 => 5,
88 TxVersion::V6 => 6,
89 _ => panic!("unsupported transaction version"),
90 }
91 }
92
93 pub fn is_overwintered(&self) -> bool {
95 !matches!(self.0.version(), TxVersion::Sprout(_))
96 }
97
98 #[allow(unreachable_patterns)]
100 pub fn network_upgrade(&self) -> Option<NetworkUpgrade> {
101 match self.tx_version() {
102 TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => None,
103 _ => compat::branch_id_to_network_upgrade(self.0.consensus_branch_id()),
105 }
106 }
107
108 pub fn sighash(
112 &self,
113 network_upgrade: NetworkUpgrade,
114 hash_type: sighash::HashType,
115 all_previous_outputs: std::sync::Arc<Vec<transparent::Output>>,
116 input_index_script_code: Option<(usize, Vec<u8>)>,
117 ) -> Result<sighash::SigHash, Error> {
118 let hasher = sighash::SigHasher::new(self, network_upgrade, all_previous_outputs)?;
119 Ok(hasher.sighash(hash_type, input_index_script_code))
120 }
121
122 pub fn sighasher(
126 &self,
127 network_upgrade: NetworkUpgrade,
128 all_previous_outputs: std::sync::Arc<Vec<transparent::Output>>,
129 ) -> Result<sighash::SigHasher, Error> {
130 sighash::SigHasher::new(self, network_upgrade, all_previous_outputs)
131 }
132
133 pub fn lock_time(&self) -> Option<LockTime> {
135 let lock_time = compat::u32_to_lock_time(self.0.lock_time());
136
137 if lock_time == LockTime::unlocked() {
138 return None;
139 }
140
141 let has_sequence_number_enabling_lock_time = self
142 .inputs()
143 .iter()
144 .map(transparent::Input::sequence)
145 .any(|seq| seq != u32::MAX);
146
147 if has_sequence_number_enabling_lock_time {
148 Some(lock_time)
149 } else {
150 None
151 }
152 }
153
154 pub fn raw_lock_time(&self) -> u32 {
156 self.0.lock_time()
157 }
158
159 pub fn lock_time_is_time(&self) -> bool {
161 matches!(self.lock_time(), Some(LockTime::Time(_)))
162 }
163
164 pub fn expiry_height(&self) -> Option<block::Height> {
173 match self.tx_version() {
174 TxVersion::Sprout(_) => None,
175 _ => match u32::from(self.0.expiry_height()) {
176 0 => None,
177 raw => Some(block::Height(raw)),
178 },
179 }
180 }
181
182 pub fn version_group_id(&self) -> Option<u32> {
184 match self.tx_version() {
185 TxVersion::Sprout(_) => None,
186 v => Some(v.version_group_id()),
187 }
188 }
189
190 pub fn inputs(&self) -> Vec<transparent::Input> {
192 let bundle = self.0.transparent_bundle();
193 match bundle {
194 Some(b) => b
195 .vin
196 .iter()
197 .map(|txin| {
198 compat::txin_to_input(txin)
199 .expect("librustzcash TxIn should be convertible to Zebra Input")
200 })
201 .collect(),
202 None => Vec::new(),
203 }
204 }
205
206 pub fn outputs(&self) -> Vec<transparent::Output> {
208 let bundle = self.0.transparent_bundle();
209 match bundle {
210 Some(b) => b.vout.iter().map(compat::txout_to_output).collect(),
211 None => Vec::new(),
212 }
213 }
214
215 pub fn has_transparent_inputs(&self) -> bool {
220 self.0
221 .transparent_bundle()
222 .is_some_and(|bundle| !bundle.vin.is_empty())
223 }
224
225 pub fn has_transparent_outputs(&self) -> bool {
230 self.0
231 .transparent_bundle()
232 .is_some_and(|bundle| !bundle.vout.is_empty())
233 }
234
235 pub fn has_transparent_inputs_or_outputs(&self) -> bool {
237 self.has_transparent_inputs() || self.has_transparent_outputs()
238 }
239
240 pub fn is_coinbase(&self) -> bool {
242 self.transparent_bundle().is_some_and(|b| b.is_coinbase())
243 }
244
245 pub fn is_valid_non_coinbase(&self) -> bool {
258 self.transparent_bundle().is_none_or(|bundle| {
259 bundle
260 .vin
261 .iter()
262 .all(|txin| *txin.prevout() != zcash_transparent::bundle::OutPoint::NULL)
263 })
264 }
265
266 pub fn spent_outpoints(&self) -> impl Iterator<Item = transparent::OutPoint> + '_ {
268 self.inputs()
269 .into_iter()
270 .filter_map(|input| input.outpoint())
271 }
272
273 pub fn hash(&self) -> Hash {
275 let txid_bytes: [u8; 32] = *self.0.txid().as_ref();
276 Hash(txid_bytes)
277 }
278
279 pub fn auth_digest(&self) -> Option<AuthDigest> {
283 match self.tx_version() {
284 TxVersion::Sprout(_) | TxVersion::V3 | TxVersion::V4 => None,
285 _ => {
286 let hash = self.0.auth_commitment();
287 let bytes: &[u8] = hash.as_ref();
288 let digest_bytes: [u8; 32] = bytes.try_into().ok()?;
289 Some(AuthDigest(digest_bytes))
290 }
291 }
292 }
293
294 pub fn unmined_id(&self) -> UnminedTxId {
296 match self.auth_digest() {
297 Some(auth_digest) => UnminedTxId::Witnessed(WtxId {
298 id: self.hash(),
299 auth_digest,
300 }),
301 None => UnminedTxId::Legacy(self.hash()),
302 }
303 }
304
305 pub fn joinsplit_count(&self) -> usize {
307 self.sprout_bundle().map_or(0, |b| b.joinsplits.len())
308 }
309
310 pub fn has_sprout_joinsplit_data(&self) -> bool {
312 self.0.sprout_bundle().is_some()
313 }
314
315 pub fn sprout_joinsplit_descriptions(
317 &self,
318 ) -> impl Iterator<Item = &zcash_primitives::transaction::components::sprout::JsDescription> + '_
319 {
320 self.sprout_bundle()
321 .into_iter()
322 .flat_map(|b| b.joinsplits.iter())
323 }
324
325 pub fn sprout_nullifiers(&self) -> impl Iterator<Item = crate::sprout::Nullifier> + '_ {
327 self.sprout_bundle()
328 .into_iter()
329 .flat_map(|b| b.joinsplits.iter())
330 .flat_map(|js| js.nullifiers().iter().copied())
331 .map(crate::sprout::Nullifier::from)
332 }
333
334 pub fn sprout_note_commitments(
336 &self,
337 ) -> impl Iterator<Item = crate::sprout::commitment::NoteCommitment> + '_ {
338 self.sprout_bundle()
339 .into_iter()
340 .flat_map(|b| b.joinsplits.iter())
341 .flat_map(|js| js.commitments().iter().copied())
342 .map(crate::sprout::commitment::NoteCommitment::from)
343 }
344
345 pub fn output_values_to_sprout(&self) -> Vec<i64> {
347 self.sprout_bundle()
348 .into_iter()
349 .flat_map(|b| b.joinsplits.iter())
350 .map(|js| js.vpub_old().into())
351 .collect()
352 }
353
354 pub fn input_values_from_sprout(&self) -> Vec<i64> {
356 self.sprout_bundle()
357 .into_iter()
358 .flat_map(|b| b.joinsplits.iter())
359 .map(|js| js.vpub_new().into())
360 .collect()
361 }
362
363 pub fn sprout_joinsplit_pub_key(
365 &self,
366 ) -> Option<crate::primitives::ed25519::VerificationKeyBytes> {
367 self.sprout_bundle()
368 .map(|b| crate::primitives::ed25519::VerificationKeyBytes::from(b.joinsplit_pubkey))
369 }
370
371 pub fn has_sapling_shielded_data(&self) -> bool {
373 self.0.sapling_bundle().is_some()
374 }
375
376 pub fn sapling_nullifiers(&self) -> impl Iterator<Item = crate::sapling::Nullifier> + '_ {
378 self.sapling_bundle()
379 .into_iter()
380 .flat_map(|b| b.shielded_spends().iter())
381 .map(|spend| crate::sapling::Nullifier::from(spend.nullifier().0))
382 }
383
384 pub fn sapling_spends(
389 &self,
390 ) -> impl Iterator<
391 Item = &sapling_crypto::bundle::SpendDescription<sapling_crypto::bundle::Authorized>,
392 > + '_ {
393 self.sapling_bundle()
394 .into_iter()
395 .flat_map(|b| b.shielded_spends().iter())
396 }
397
398 pub fn sapling_spends_count(&self) -> usize {
400 self.sapling_bundle()
401 .map_or(0, |b| b.shielded_spends().len())
402 }
403
404 pub fn sapling_outputs(
406 &self,
407 ) -> impl Iterator<
408 Item = &sapling_crypto::bundle::OutputDescription<sapling_crypto::bundle::GrothProofBytes>,
409 > + '_ {
410 self.sapling_bundle()
411 .into_iter()
412 .flat_map(|b| b.shielded_outputs().iter())
413 }
414
415 pub fn sapling_note_commitments(
417 &self,
418 ) -> impl Iterator<Item = sapling_crypto::note::ExtractedNoteCommitment> + '_ {
419 self.sapling_outputs().map(|output| *output.cmu())
420 }
421
422 pub fn sapling_anchors(&self) -> Vec<crate::sapling::tree::Root> {
424 let mut seen = Vec::new();
425 for spend in self.sapling_spends() {
426 let bytes = spend.anchor().to_bytes();
427 let root = crate::sapling::tree::Root::try_from(bytes)
428 .expect("sapling anchor from valid transaction should be a valid tree root");
429 if !seen.contains(&root) {
430 seen.push(root);
431 }
432 }
433 seen
434 }
435
436 pub fn sapling_value_balance(&self) -> ValueBalance<NegativeAllowed> {
438 let balance = self
439 .sapling_bundle()
440 .map(|b| *b.value_balance())
441 .unwrap_or(ZatBalance::zero());
442
443 let amount: Amount<NegativeAllowed> = Amount::try_from(i64::from(balance))
444 .expect("sapling value balance should be a valid Amount");
445
446 ValueBalance::from_sapling_amount(amount)
447 }
448
449 pub fn has_orchard_shielded_data(&self) -> bool {
451 self.0.orchard_bundle().is_some()
452 }
453
454 pub fn orchard_nullifiers(&self) -> impl Iterator<Item = crate::orchard::Nullifier> + '_ {
456 self.orchard_bundle()
457 .into_iter()
458 .flat_map(|b| b.actions().iter())
459 .map(|action| {
460 crate::orchard::Nullifier::try_from(action.nullifier().to_bytes())
461 .expect("orchard nullifier from valid transaction")
462 })
463 }
464
465 pub fn orchard_actions(
467 &self,
468 ) -> impl Iterator<
469 Item = &::orchard::Action<
470 <::orchard::bundle::Authorized as ::orchard::bundle::Authorization>::SpendAuth,
471 >,
472 > + '_ {
473 self.orchard_bundle()
474 .into_iter()
475 .flat_map(|b| b.actions().iter())
476 }
477
478 pub fn orchard_note_commitments(
480 &self,
481 ) -> impl Iterator<Item = ::orchard::note::ExtractedNoteCommitment> + '_ {
482 self.orchard_actions().map(|action| *action.cmx())
483 }
484
485 pub fn orchard_flags(&self) -> Option<::orchard::bundle::Flags> {
487 self.0.orchard_bundle().map(|b| *b.flags())
488 }
489
490 pub fn orchard_anchor(&self) -> Option<crate::orchard::tree::Root> {
492 self.0.orchard_bundle().and_then(|b| {
493 let bytes = b.anchor().to_bytes();
494 crate::orchard::tree::Root::try_from(bytes).ok()
495 })
496 }
497
498 pub fn orchard_value_balance(&self) -> ValueBalance<NegativeAllowed> {
500 let balance = self
501 .orchard_bundle()
502 .map(|b| *b.value_balance())
503 .unwrap_or(ZatBalance::zero());
504
505 let amount: Amount<NegativeAllowed> = Amount::try_from(i64::from(balance))
506 .expect("orchard value balance should be a valid Amount");
507
508 ValueBalance::from_orchard_amount(amount)
509 }
510
511 pub fn has_ironwood_shielded_data(&self) -> bool {
521 self.0.ironwood_bundle().is_some()
522 }
523
524 pub fn ironwood_nullifiers(&self) -> impl Iterator<Item = crate::ironwood::Nullifier> + '_ {
526 self.ironwood_actions().map(|action| {
527 let nullifier = crate::orchard::Nullifier::try_from(action.nullifier().to_bytes())
528 .expect("ironwood nullifier from valid transaction");
529 crate::ironwood::Nullifier::from(nullifier)
530 })
531 }
532
533 pub fn ironwood_actions(
535 &self,
536 ) -> impl Iterator<
537 Item = &::orchard::Action<
538 <::orchard::bundle::Authorized as ::orchard::bundle::Authorization>::SpendAuth,
539 >,
540 > + '_ {
541 self.0
542 .ironwood_bundle()
543 .into_iter()
544 .flat_map(|b| b.actions().iter())
545 }
546
547 pub fn ironwood_note_commitments(
549 &self,
550 ) -> impl Iterator<Item = ::orchard::note::ExtractedNoteCommitment> + '_ {
551 self.ironwood_actions().map(|action| *action.cmx())
552 }
553
554 pub fn ironwood_flags(&self) -> Option<::orchard::bundle::Flags> {
556 self.0.ironwood_bundle().map(|b| *b.flags())
557 }
558
559 pub fn ironwood_anchor(&self) -> Option<crate::orchard::tree::Root> {
561 self.0.ironwood_bundle().and_then(|b| {
562 let bytes = b.anchor().to_bytes();
563 crate::orchard::tree::Root::try_from(bytes).ok()
564 })
565 }
566
567 pub fn has_enough_ironwood_flags(&self) -> bool {
570 if !self.has_ironwood_shielded_data() {
571 return true;
572 }
573
574 self.ironwood_flags()
575 .is_some_and(|flags| flags.spends_enabled() || flags.outputs_enabled())
576 }
577
578 pub fn ironwood_value_balance(&self) -> ValueBalance<NegativeAllowed> {
586 let balance = self
587 .0
588 .ironwood_bundle()
589 .map(|b| *b.value_balance())
590 .unwrap_or(ZatBalance::zero());
591
592 let amount: Amount<NegativeAllowed> = Amount::try_from(i64::from(balance))
593 .expect("ironwood value balance should be a valid Amount");
594
595 ValueBalance::from_ironwood_amount(amount)
596 }
597
598 pub fn orchard_proof_size_is_canonical(&self) -> bool {
605 self.0.orchard_bundle().is_none_or(|bundle| {
606 bundle.authorization().proof().as_ref().len()
607 == crate::orchard::shielded_data::expected_proof_size(bundle.actions().len())
608 })
609 }
610
611 pub fn ironwood_proof_size_is_canonical(&self) -> bool {
617 self.0.ironwood_bundle().is_none_or(|bundle| {
618 bundle.authorization().proof().as_ref().len()
619 == crate::orchard::shielded_data::expected_proof_size(bundle.actions().len())
620 })
621 }
622
623 pub fn has_shielded_inputs(&self) -> bool {
625 self.has_sprout_joinsplit_data()
626 || self
627 .sapling_bundle()
628 .is_some_and(|b| !b.shielded_spends().is_empty())
629 || self
630 .orchard_bundle()
631 .is_some_and(|b| b.flags().spends_enabled() && !b.actions().is_empty())
632 || self
633 .0
634 .ironwood_bundle()
635 .is_some_and(|b| b.flags().spends_enabled() && !b.actions().is_empty())
636 }
637
638 pub fn has_shielded_outputs(&self) -> bool {
640 self.has_sprout_joinsplit_data()
641 || self
642 .sapling_bundle()
643 .is_some_and(|b| !b.shielded_outputs().is_empty())
644 || self
645 .orchard_bundle()
646 .is_some_and(|b| b.flags().outputs_enabled() && !b.actions().is_empty())
647 || self
648 .0
649 .ironwood_bundle()
650 .is_some_and(|b| b.flags().outputs_enabled() && !b.actions().is_empty())
651 }
652
653 pub fn has_shielded_data(&self) -> bool {
655 self.has_shielded_inputs() || self.has_shielded_outputs()
656 }
657
658 pub fn has_transparent_or_shielded_inputs(&self) -> bool {
660 self.has_transparent_inputs() || self.has_shielded_inputs()
661 }
662
663 pub fn has_transparent_or_shielded_outputs(&self) -> bool {
665 self.has_transparent_outputs() || self.has_shielded_outputs()
666 }
667
668 pub fn has_enough_orchard_flags(&self) -> bool {
670 match self.0.orchard_bundle() {
671 Some(bundle) => {
672 let flags = bundle.flags();
673 flags.spends_enabled() || flags.outputs_enabled()
674 }
675 None => true,
676 }
677 }
678
679 pub fn transparent_value_balance_from_outputs(
682 &self,
683 outputs: &std::collections::HashMap<transparent::OutPoint, transparent::Output>,
684 ) -> Result<ValueBalance<NegativeAllowed>, crate::value_balance::ValueBalanceError> {
685 self.transparent_value_balance_with(|input| input.value_from_outputs(outputs))
686 }
687
688 #[allow(clippy::unwrap_in_result)]
690 fn transparent_value_balance_with(
691 &self,
692 input_value: impl Fn(&transparent::Input) -> Amount<NonNegative>,
693 ) -> Result<ValueBalance<NegativeAllowed>, crate::value_balance::ValueBalanceError> {
694 use crate::amount::Error as AmountError;
695
696 let input_value = self
697 .inputs()
698 .iter()
699 .map(input_value)
700 .sum::<Result<Amount<NonNegative>, AmountError>>()
701 .map_err(crate::value_balance::ValueBalanceError::Transparent)?
702 .constrain()
703 .expect("conversion from NonNegative to NegativeAllowed is always valid");
704
705 let output_value = self
706 .outputs()
707 .iter()
708 .map(|o| o.value())
709 .sum::<Result<Amount<NonNegative>, AmountError>>()
710 .map_err(crate::value_balance::ValueBalanceError::Transparent)?
711 .constrain()
712 .expect("conversion from NonNegative to NegativeAllowed is always valid");
713
714 (input_value - output_value)
715 .map(ValueBalance::from_transparent_amount)
716 .map_err(crate::value_balance::ValueBalanceError::Transparent)
717 }
718
719 pub fn sprout_value_balance(
727 &self,
728 ) -> Result<ValueBalance<NegativeAllowed>, crate::value_balance::ValueBalanceError> {
729 let total = self
730 .sprout_joinsplit_descriptions()
731 .try_fold(Amount::<NegativeAllowed>::zero(), |total, js| {
732 let net = Amount::try_from(i64::from(js.vpub_new()) - i64::from(js.vpub_old()))?;
735 total + net
736 })
737 .map_err(crate::value_balance::ValueBalanceError::Sprout)?;
738
739 Ok(ValueBalance::from_sprout_amount(total))
740 }
741
742 pub fn value_balance<U: AsRef<transparent::Utxo>>(
748 &self,
749 utxos: &std::collections::HashMap<transparent::OutPoint, U>,
750 ) -> Result<ValueBalance<NegativeAllowed>, crate::value_balance::ValueBalanceError> {
751 let transparent = self.transparent_value_balance_with(|input| input.value(utxos))?;
752 let sprout = self.sprout_value_balance()?;
753 let sapling = self.sapling_value_balance();
754 let orchard = self.orchard_value_balance();
755 let ironwood = self.ironwood_value_balance();
756
757 transparent + sprout + sapling + orchard + ironwood
758 }
759
760 pub fn coinbase_spend_restriction(
763 &self,
764 network: &crate::parameters::Network,
765 spend_height: block::Height,
766 ) -> transparent::CoinbaseSpendRestriction {
767 if !self.has_transparent_outputs() || network.should_allow_unshielded_coinbase_spends() {
768 transparent::CoinbaseSpendRestriction::CheckCoinbaseMaturity { spend_height }
769 } else {
770 transparent::CoinbaseSpendRestriction::DisallowCoinbaseSpend
771 }
772 }
773}
774
775impl PartialEq for Transaction {
776 fn eq(&self, other: &Self) -> bool {
777 self.0.txid() == other.0.txid()
778 }
779}
780
781impl Eq for Transaction {}
782
783impl std::fmt::Display for Transaction {
784 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
785 let mut fmter = f.debug_struct("Transaction");
786
787 fmter.field("version", &self.version());
788
789 if let Some(network_upgrade) = self.network_upgrade() {
790 fmter.field("network_upgrade", &network_upgrade);
791 }
792
793 if let Some(lock_time) = self.lock_time() {
794 fmter.field("lock_time", &lock_time);
795 }
796
797 if let Some(expiry_height) = self.expiry_height() {
798 fmter.field("expiry_height", &expiry_height);
799 }
800
801 fmter.field("transparent_inputs", &self.inputs().len());
802 fmter.field("transparent_outputs", &self.outputs().len());
803 fmter.field("sprout_joinsplits", &self.joinsplit_count());
804 fmter.field("sapling_spends", &self.sapling_spends_count());
805 fmter.field("sapling_outputs", &self.sapling_outputs().count());
806 fmter.field("orchard_actions", &self.orchard_actions().count());
807 fmter.field("ironwood_actions", &self.ironwood_actions().count());
808
809 fmter.field("unmined_id", &self.unmined_id());
810
811 fmter.finish()
812 }
813}
814
815impl From<&Transaction> for Hash {
816 fn from(transaction: &Transaction) -> Self {
817 transaction.hash()
818 }
819}
820
821impl From<std::sync::Arc<Transaction>> for Hash {
822 fn from(transaction: std::sync::Arc<Transaction>) -> Self {
823 transaction.hash()
824 }
825}
826
827impl From<&Transaction> for UnminedTxId {
828 fn from(transaction: &Transaction) -> Self {
829 transaction.unmined_id()
830 }
831}
832
833impl From<std::sync::Arc<Transaction>> for UnminedTxId {
834 fn from(transaction: std::sync::Arc<Transaction>) -> Self {
835 transaction.unmined_id()
836 }
837}
838
839impl TryFrom<&Transaction> for AuthDigest {
840 type Error = &'static str;
841
842 fn try_from(transaction: &Transaction) -> Result<Self, Self::Error> {
846 transaction
847 .auth_digest()
848 .ok_or("pre-V5 transactions do not have an auth digest")
849 }
850}
851
852impl crate::serialization::ZcashSerialize for Transaction {
853 fn zcash_serialize<W: std::io::Write>(&self, writer: W) -> Result<(), std::io::Error> {
854 self.0.write(writer)
855 }
856}
857
858impl crate::serialization::ZcashDeserializeWithContext<zcash_protocol::consensus::BranchId>
859 for Transaction
860{
861 fn zcash_deserialize_with_context<R: std::io::Read>(
866 reader: R,
867 &branch_id: &zcash_protocol::consensus::BranchId,
868 ) -> Result<Self, crate::serialization::SerializationError> {
869 deserialize_and_check(reader, branch_id)
870 }
871}
872
873impl crate::serialization::ZcashDeserialize for Transaction {
874 fn zcash_deserialize<R: std::io::Read>(
893 reader: R,
894 ) -> Result<Self, crate::serialization::SerializationError> {
895 deserialize_and_check(reader, zcash_protocol::consensus::BranchId::Canopy)
896 }
897}
898
899fn deserialize_and_check<R: std::io::Read>(
903 reader: R,
904 branch_id: zcash_protocol::consensus::BranchId,
905) -> Result<Transaction, crate::serialization::SerializationError> {
906 use std::io::Read as _;
907
908 let mut limited = reader.take(crate::block::MAX_BLOCK_BYTES);
910
911 let mut header = [0u8; 4];
916 limited.read_exact(&mut header)?;
917 let is_v4 = {
918 let header = u32::from_le_bytes(header);
919 let overwintered = header & 0x8000_0000 != 0;
920 overwintered && (header & 0x7FFF_FFFF) == 4
921 };
922 let with_header = std::io::Read::chain(&header[..], limited);
923
924 let (inner, raw_bytes) = if is_v4 {
925 let mut recording = RecordingReader::new(with_header);
926 let inner = zp_tx::Transaction::read(&mut recording, branch_id)?;
927 (inner, recording.into_recorded())
928 } else {
929 (
930 zp_tx::Transaction::read(with_header, branch_id)?,
931 Vec::new(),
932 )
933 };
934
935 if inner.version() == TxVersion::V6
957 && compat::branch_id_to_network_upgrade(inner.consensus_branch_id())
958 .is_none_or(|network_upgrade| network_upgrade < NetworkUpgrade::Nu6_3)
959 {
960 return Err(crate::serialization::SerializationError::Parse(
961 "v6 transaction must have a NU6.3 or later consensus branch ID",
962 ));
963 }
964
965 if let Some(bundle) = inner.transparent_bundle() {
970 for txin in &bundle.vin {
971 if *txin.prevout() == zcash_transparent::bundle::OutPoint::NULL {
972 let script_bytes = &txin.script_sig().0 .0;
973 if script_bytes.as_slice() != transparent::serialize::GENESIS_COINBASE_SCRIPT_SIG {
976 transparent::serialize::parse_coinbase_height(script_bytes)?;
977 }
978 }
979 }
980 }
981
982 if inner
993 .transparent_bundle()
994 .is_some_and(|bundle| bundle.is_coinbase())
995 && inner
996 .sapling_bundle()
997 .is_some_and(|bundle| !bundle.shielded_spends().is_empty())
998 {
999 return Err(crate::serialization::SerializationError::Parse(
1000 "coinbase transaction must not have Sapling spends",
1001 ));
1002 }
1003
1004 if inner.version() == TxVersion::V4 && inner.sapling_bundle().is_none() {
1015 if let Some(value_balance) = v4_empty_sapling_value_balance(&raw_bytes, &inner) {
1016 if value_balance != 0 {
1017 return Err(crate::serialization::SerializationError::BadTransactionBalance);
1018 }
1019 }
1020 }
1021
1022 Ok(Transaction(inner))
1023}
1024
1025fn v4_empty_sapling_value_balance(raw_bytes: &[u8], inner: &zp_tx::Transaction) -> Option<i64> {
1045 const V4_JOINSPLIT_SIZE: usize = (2 * 8) + (9 * 32) + 192 + (2 * 601);
1048
1049 const JOINSPLIT_AUTH_SIZE: usize = 32 + 64;
1051
1052 let joinsplit_count = inner
1053 .sprout_bundle()
1054 .map_or(0, |bundle| bundle.joinsplits.len());
1055
1056 let count_size: usize = match joinsplit_count {
1058 0..=252 => 1,
1059 253..=0xFFFF => 3,
1060 0x1_0000..=0xFFFF_FFFF => 5,
1061 _ => 9,
1062 };
1063
1064 let mut sprout_size =
1065 count_size.checked_add(joinsplit_count.checked_mul(V4_JOINSPLIT_SIZE)?)?;
1066 if joinsplit_count > 0 {
1067 sprout_size = sprout_size.checked_add(JOINSPLIT_AUTH_SIZE)?;
1068 }
1069
1070 let counts_start = raw_bytes.len().checked_sub(sprout_size)?.checked_sub(2)?;
1072 let value_balance_start = counts_start.checked_sub(8)?;
1073
1074 if raw_bytes.get(counts_start..counts_start + 2)? != [0x00, 0x00] {
1076 return None;
1077 }
1078
1079 let field: [u8; 8] = raw_bytes
1080 .get(value_balance_start..counts_start)?
1081 .try_into()
1082 .ok()?;
1083
1084 Some(i64::from_le_bytes(field))
1085}
1086
1087struct RecordingReader<R> {
1089 inner: R,
1090 recorded: Vec<u8>,
1091}
1092
1093impl<R: std::io::Read> RecordingReader<R> {
1094 fn new(inner: R) -> Self {
1095 Self {
1096 inner,
1097 recorded: Vec::new(),
1098 }
1099 }
1100
1101 fn into_recorded(self) -> Vec<u8> {
1102 self.recorded
1103 }
1104}
1105
1106impl<R: std::io::Read> std::io::Read for RecordingReader<R> {
1107 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1108 let n = self.inner.read(buf)?;
1109 self.recorded.extend_from_slice(&buf[..n]);
1110 Ok(n)
1111 }
1112}
1113
1114impl Clone for Transaction {
1115 fn clone(&self) -> Self {
1116 Transaction(self.0.clone())
1117 }
1118}
1119
1120#[cfg(any(test, feature = "proptest-impl"))]
1124impl serde::Serialize for Transaction {
1125 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1126 use serde::ser::SerializeStructVariant;
1127
1128 let version = self.version();
1129 let (variant_name, field_count) = match version {
1132 1 => ("V1", 3),
1133 2 => ("V2", 4),
1134 3 => ("V3", 5),
1135 4 => ("V4", 6),
1136 5 => ("V5", 7),
1137 _ => ("V6", 8),
1138 };
1139
1140 let mut sv = serializer.serialize_struct_variant(
1141 "Transaction",
1142 version.saturating_sub(1),
1143 variant_name,
1144 field_count,
1145 )?;
1146
1147 if version >= 5 {
1149 let nu = self
1150 .network_upgrade()
1151 .unwrap_or(crate::parameters::NetworkUpgrade::Nu5);
1152 sv.serialize_field("network_upgrade", &nu)?;
1153 }
1154
1155 sv.serialize_field("lock_time", &compat::u32_to_lock_time(self.0.lock_time()))?;
1156
1157 if version >= 3 {
1159 let eh =
1160 compat::block_height_to_height(self.0.expiry_height()).unwrap_or(block::Height(0));
1161 sv.serialize_field("expiry_height", &eh)?;
1162 }
1163
1164 sv.serialize_field("inputs", &self.inputs())?;
1165 sv.serialize_field("outputs", &self.outputs())?;
1166
1167 if (2..=4).contains(&version) {
1168 let has_joinsplit = self.has_sprout_joinsplit_data();
1169 sv.serialize_field::<Option<()>>(
1170 "joinsplit_data",
1171 if has_joinsplit { &Some(()) } else { &None },
1172 )?;
1173 }
1174
1175 if version >= 4 {
1176 let has_sapling = self.has_sapling_shielded_data();
1177 sv.serialize_field::<Option<()>>(
1178 "sapling_shielded_data",
1179 if has_sapling { &Some(()) } else { &None },
1180 )?;
1181 }
1182
1183 if version >= 5 {
1184 let has_orchard = self.has_orchard_shielded_data();
1185 sv.serialize_field::<Option<()>>(
1186 "orchard_shielded_data",
1187 if has_orchard { &Some(()) } else { &None },
1188 )?;
1189 }
1190
1191 if version >= 6 {
1192 let has_ironwood = self.has_ironwood_shielded_data();
1193 sv.serialize_field::<Option<()>>(
1194 "ironwood_shielded_data",
1195 if has_ironwood { &Some(()) } else { &None },
1196 )?;
1197 }
1198
1199 sv.end()
1200 }
1201}
1202
1203#[cfg(any(test, feature = "proptest-impl"))]
1204impl Transaction {
1205 pub fn test_v1(
1207 inputs: Vec<transparent::Input>,
1208 outputs: Vec<transparent::Output>,
1209 lock_time: LockTime,
1210 ) -> Self {
1211 Self::build_transparent(
1212 zcash_primitives::transaction::TxVersion::Sprout(1),
1213 zcash_protocol::consensus::BranchId::Sprout,
1214 compat::lock_time_to_u32(&lock_time),
1215 zcash_protocol::consensus::BlockHeight::from_u32(0),
1216 inputs,
1217 outputs,
1218 )
1219 }
1220
1221 pub fn test_v2(
1223 inputs: Vec<transparent::Input>,
1224 outputs: Vec<transparent::Output>,
1225 lock_time: LockTime,
1226 ) -> Self {
1227 Self::build_transparent(
1228 zcash_primitives::transaction::TxVersion::Sprout(2),
1229 zcash_protocol::consensus::BranchId::Sprout,
1230 compat::lock_time_to_u32(&lock_time),
1231 zcash_protocol::consensus::BlockHeight::from_u32(0),
1232 inputs,
1233 outputs,
1234 )
1235 }
1236
1237 pub fn test_v3(
1239 inputs: Vec<transparent::Input>,
1240 outputs: Vec<transparent::Output>,
1241 lock_time: LockTime,
1242 expiry_height: block::Height,
1243 ) -> Self {
1244 Self::build_transparent(
1245 zcash_primitives::transaction::TxVersion::V3,
1246 zcash_protocol::consensus::BranchId::Overwinter,
1247 compat::lock_time_to_u32(&lock_time),
1248 compat::height_to_block_height(expiry_height),
1249 inputs,
1250 outputs,
1251 )
1252 }
1253
1254 pub fn test_v4(
1256 inputs: Vec<transparent::Input>,
1257 outputs: Vec<transparent::Output>,
1258 lock_time: LockTime,
1259 expiry_height: block::Height,
1260 ) -> Self {
1261 Self::build_transparent(
1262 zcash_primitives::transaction::TxVersion::V4,
1263 zcash_protocol::consensus::BranchId::Canopy,
1264 compat::lock_time_to_u32(&lock_time),
1265 compat::height_to_block_height(expiry_height),
1266 inputs,
1267 outputs,
1268 )
1269 }
1270
1271 pub fn test_v5(
1273 network_upgrade: crate::parameters::NetworkUpgrade,
1274 inputs: Vec<transparent::Input>,
1275 outputs: Vec<transparent::Output>,
1276 lock_time: LockTime,
1277 expiry_height: block::Height,
1278 ) -> Self {
1279 let branch_id = network_upgrade
1280 .branch_id()
1281 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
1282 .expect("the test transaction upgrade has a supported consensus branch ID");
1283 Self::build_transparent(
1284 zcash_primitives::transaction::TxVersion::V5,
1285 branch_id,
1286 compat::lock_time_to_u32(&lock_time),
1287 compat::height_to_block_height(expiry_height),
1288 inputs,
1289 outputs,
1290 )
1291 }
1292
1293 pub fn test_v6(
1295 network_upgrade: crate::parameters::NetworkUpgrade,
1296 inputs: Vec<transparent::Input>,
1297 outputs: Vec<transparent::Output>,
1298 lock_time: LockTime,
1299 expiry_height: block::Height,
1300 ) -> Self {
1301 let branch_id = network_upgrade
1302 .branch_id()
1303 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
1304 .expect("the test transaction upgrade has a supported consensus branch ID");
1305 Self::build_transparent(
1306 zcash_primitives::transaction::TxVersion::V6,
1307 branch_id,
1308 compat::lock_time_to_u32(&lock_time),
1309 compat::height_to_block_height(expiry_height),
1310 inputs,
1311 outputs,
1312 )
1313 }
1314
1315 fn build_transparent(
1316 version: zcash_primitives::transaction::TxVersion,
1317 branch_id: zcash_protocol::consensus::BranchId,
1318 lock_time: u32,
1319 expiry_height: zcash_protocol::consensus::BlockHeight,
1320 inputs: Vec<transparent::Input>,
1321 outputs: Vec<transparent::Output>,
1322 ) -> Self {
1323 let vin: Vec<_> = inputs.iter().map(compat::input_to_txin).collect();
1324 let vout: Vec<_> = outputs.iter().map(compat::output_to_txout).collect();
1325 let transparent_bundle = if vin.is_empty() && vout.is_empty() {
1326 None
1327 } else {
1328 Some(zcash_transparent::bundle::Bundle {
1329 vin,
1330 vout,
1331 authorization: zcash_transparent::bundle::Authorized,
1332 })
1333 };
1334 let tx_data = zp_tx::TransactionData::from_parts(
1335 version,
1336 branch_id,
1337 lock_time,
1338 expiry_height,
1339 transparent_bundle,
1340 None,
1341 None,
1342 None,
1343 );
1344 Transaction(tx_data.freeze().expect("built from valid components"))
1345 }
1346
1347 #[cfg(any(test, feature = "proptest-impl"))]
1352 pub fn test_v5_with_orchard(
1353 network_upgrade: crate::parameters::NetworkUpgrade,
1354 inputs: Vec<transparent::Input>,
1355 outputs: Vec<transparent::Output>,
1356 lock_time: LockTime,
1357 expiry_height: block::Height,
1358 orchard_bundle: Option<::orchard::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1359 ) -> Self {
1360 let branch_id = network_upgrade
1361 .branch_id()
1362 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
1363 .expect("the test transaction upgrade has a supported consensus branch ID");
1364
1365 let tx_data = zp_tx::TransactionData::from_parts(
1366 zp_tx::TxVersion::V5,
1367 branch_id,
1368 compat::lock_time_to_u32(&lock_time),
1369 compat::height_to_block_height(expiry_height),
1370 Self::transparent_bundle_from(inputs, outputs),
1371 None,
1372 None,
1373 orchard_bundle,
1374 );
1375
1376 Transaction(tx_data.freeze().expect("built from valid components"))
1377 }
1378
1379 #[cfg(any(test, feature = "proptest-impl"))]
1385 pub fn test_v6_with_bundles(
1386 network_upgrade: crate::parameters::NetworkUpgrade,
1387 inputs: Vec<transparent::Input>,
1388 outputs: Vec<transparent::Output>,
1389 lock_time: LockTime,
1390 expiry_height: block::Height,
1391 orchard_bundle: Option<::orchard::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1392 ironwood_bundle: Option<::orchard::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1393 ) -> Self {
1394 let branch_id = network_upgrade
1395 .branch_id()
1396 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
1397 .expect("the test transaction upgrade has a supported consensus branch ID");
1398
1399 let tx_data = zp_tx::TransactionData::from_parts_v6(
1400 branch_id,
1401 compat::lock_time_to_u32(&lock_time),
1402 compat::height_to_block_height(expiry_height),
1403 Self::transparent_bundle_from(inputs, outputs),
1404 None,
1405 orchard_bundle,
1406 ironwood_bundle,
1407 );
1408
1409 Transaction(tx_data.freeze().expect("built from valid components"))
1410 }
1411
1412 #[cfg(any(test, feature = "proptest-impl"))]
1415 fn transparent_bundle_from(
1416 inputs: Vec<transparent::Input>,
1417 outputs: Vec<transparent::Output>,
1418 ) -> Option<zcash_transparent::bundle::Bundle<zcash_transparent::bundle::Authorized>> {
1419 let vin: Vec<_> = inputs.iter().map(compat::input_to_txin).collect();
1420 let vout: Vec<_> = outputs.iter().map(compat::output_to_txout).collect();
1421
1422 (!vin.is_empty() || !vout.is_empty()).then_some(zcash_transparent::bundle::Bundle {
1423 vin,
1424 vout,
1425 authorization: zcash_transparent::bundle::Authorized,
1426 })
1427 }
1428
1429 pub fn with_transparent_inputs(self, inputs: Vec<transparent::Input>) -> Self {
1436 let vin: Vec<_> = inputs
1437 .iter()
1438 .map(crate::transaction::compat::input_to_txin)
1439 .collect();
1440 let vout = self
1441 .0
1442 .transparent_bundle()
1443 .map(|b| b.vout.clone())
1444 .unwrap_or_default();
1445 let transparent_bundle =
1446 (!vin.is_empty() || !vout.is_empty()).then_some(zcash_transparent::bundle::Bundle {
1447 vin,
1448 vout,
1449 authorization: zcash_transparent::bundle::Authorized,
1450 });
1451 self.rebuild_with_transparent(transparent_bundle)
1452 }
1453
1454 pub fn with_transparent_outputs(self, outputs: Vec<transparent::Output>) -> Self {
1456 let vin = self
1457 .0
1458 .transparent_bundle()
1459 .map(|b| b.vin.clone())
1460 .unwrap_or_default();
1461 let vout: Vec<_> = outputs
1462 .iter()
1463 .map(crate::transaction::compat::output_to_txout)
1464 .collect();
1465 let transparent_bundle = if vin.is_empty() && vout.is_empty() {
1466 None
1467 } else {
1468 Some(zcash_transparent::bundle::Bundle {
1469 vin,
1470 vout,
1471 authorization: zcash_transparent::bundle::Authorized,
1472 })
1473 };
1474 self.rebuild_with_transparent(transparent_bundle)
1475 }
1476
1477 fn rebuild_with_transparent(
1478 self,
1479 transparent_bundle: Option<
1480 zcash_transparent::bundle::Bundle<zcash_transparent::bundle::Authorized>,
1481 >,
1482 ) -> Self {
1483 let data = &*self.0;
1484 let tx_data = compat::transaction_data_from_parts(
1485 data.version(),
1486 data.consensus_branch_id(),
1487 data.lock_time(),
1488 data.expiry_height(),
1489 transparent_bundle,
1490 data.sprout_bundle().cloned(),
1491 data.sapling_bundle().cloned(),
1492 data.orchard_bundle().cloned(),
1493 data.ironwood_bundle().cloned(),
1494 );
1495 Transaction(tx_data.freeze().expect("rebuilt from valid transaction"))
1496 }
1497
1498 pub fn set_expiry_height(&mut self, height: block::Height) {
1500 let data = self.0.clone().into_data();
1501 let new_data = compat::transaction_data_from_parts(
1502 data.version(),
1503 data.consensus_branch_id(),
1504 data.lock_time(),
1505 compat::height_to_block_height(height),
1506 data.transparent_bundle().cloned(),
1507 data.sprout_bundle().cloned(),
1508 data.sapling_bundle().cloned(),
1509 data.orchard_bundle().cloned(),
1510 data.ironwood_bundle().cloned(),
1511 );
1512 self.0 = new_data.freeze().expect("rebuilt from valid transaction");
1513 }
1514
1515 pub fn set_network_upgrade(&mut self, nu: NetworkUpgrade) {
1517 let branch_id = nu
1518 .branch_id()
1519 .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
1520 .expect("network upgrade must have a valid branch ID");
1521 let data = self.0.clone().into_data();
1522 let new_data = compat::transaction_data_from_parts(
1523 data.version(),
1524 branch_id,
1525 data.lock_time(),
1526 data.expiry_height(),
1527 data.transparent_bundle().cloned(),
1528 data.sprout_bundle().cloned(),
1529 data.sapling_bundle().cloned(),
1530 data.orchard_bundle().cloned(),
1531 data.ironwood_bundle().cloned(),
1532 );
1533 self.0 = new_data.freeze().expect("rebuilt from valid transaction");
1534 }
1535
1536 pub fn set_outputs(&mut self, outputs: Vec<transparent::Output>) {
1538 *self = self.clone().with_transparent_outputs(outputs);
1539 }
1540
1541 #[cfg(any(test, feature = "proptest-impl"))]
1547 pub fn with_orchard_bundle(
1548 self,
1549 bundle: Option<::orchard::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1550 ) -> Self {
1551 let data = &*self.0;
1552 let tx_data = compat::transaction_data_from_parts(
1553 data.version(),
1554 data.consensus_branch_id(),
1555 data.lock_time(),
1556 data.expiry_height(),
1557 data.transparent_bundle().cloned(),
1558 data.sprout_bundle().cloned(),
1559 data.sapling_bundle().cloned(),
1560 bundle,
1561 data.ironwood_bundle().cloned(),
1562 );
1563 Transaction(tx_data.freeze().expect("rebuilt from valid transaction"))
1564 }
1565
1566 pub fn test_v4_with_joinsplit_data(
1571 joinsplit_data: Option<&JoinSplitData<crate::primitives::Groth16Proof>>,
1572 ) -> Self {
1573 use crate::serialization::{ZcashDeserialize, ZcashSerialize};
1574
1575 let mut bytes: Vec<u8> = Vec::new();
1576 bytes.extend_from_slice(&0x8000_0004u32.to_le_bytes()); bytes.extend_from_slice(&0x892F_2085u32.to_le_bytes()); bytes.push(0x00); bytes.push(0x00); bytes.extend_from_slice(&500_000_000u32.to_le_bytes()); bytes.extend_from_slice(&0u32.to_le_bytes()); bytes.extend_from_slice(&0i64.to_le_bytes()); bytes.push(0x00); bytes.push(0x00); if let Some(jsd) = joinsplit_data {
1586 jsd.zcash_serialize(&mut bytes)
1587 .expect("joinsplit_data serialization should succeed");
1588 } else {
1589 bytes.push(0x00); }
1591 Transaction::zcash_deserialize(bytes.as_slice())
1592 .expect("manually constructed V4 transaction should deserialize")
1593 }
1594}