Skip to main content

zebra_chain/
transaction.rs

1//! Transactions and transaction-related structures.
2
3use 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/// A Zcash transaction, wrapping `zcash_primitives::transaction::Transaction`.
58#[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    /// Access the inner `zcash_primitives::transaction::Transaction`.
71    pub(crate) fn inner(&self) -> &zp_tx::Transaction {
72        &self.0
73    }
74
75    /// Returns the transaction version.
76    pub fn tx_version(&self) -> TxVersion {
77        self.0.version()
78    }
79
80    /// Returns the numeric version of this transaction.
81    #[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    /// Returns `true` if this is an overwinter or later transaction.
94    pub fn is_overwintered(&self) -> bool {
95        !matches!(self.0.version(), TxVersion::Sprout(_))
96    }
97
98    /// Get the network upgrade for this transaction, if any (V5+).
99    #[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            // V5+ transactions embed the consensus branch ID
104            _ => compat::branch_id_to_network_upgrade(self.0.consensus_branch_id()),
105        }
106    }
107
108    /// Compute the sighash for this transaction.
109    ///
110    /// Returns an error if `network_upgrade` doesn't match the transaction's consensus branch ID.
111    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    /// Returns a [`SigHasher`] for this transaction.
123    ///
124    /// Returns an error if `network_upgrade` doesn't match the transaction's consensus branch ID.
125    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    /// Get this transaction's lock time.
134    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    /// Get the raw lock time value as a `u32`.
155    pub fn raw_lock_time(&self) -> u32 {
156        self.0.lock_time()
157    }
158
159    /// Returns `true` if `lock_time` is a [`LockTime::Time`] and is not disabled by sequence numbers.
160    pub fn lock_time_is_time(&self) -> bool {
161        matches!(self.lock_time(), Some(LockTime::Time(_)))
162    }
163
164    /// Get the expiry height for this transaction, if any (V3+).
165    ///
166    /// Returns `None` if the transaction is Sprout, or if `nExpiryHeight == 0`
167    /// (which means "no expiry" per the Zcash protocol spec).
168    ///
169    /// Returns the raw wire value, which can exceed [`block::Height::MAX`]: the ZIP-203
170    /// maximum of 499,999,999 is a verifier rule, not a limit of this accessor, so an
171    /// out-of-range value must reach the verifier to be rejected.
172    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    /// Get the version group ID for this transaction, if any.
183    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    /// Get the transparent inputs, converted to Zebra types.
191    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    /// Get the transparent outputs, converted to Zebra types.
207    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    /// Returns `true` if this transaction has transparent inputs.
216    ///
217    /// Reads the bundle's input count directly: `inputs()` rebuilds and converts the whole
218    /// input vector, which is wasteful when only the count is needed.
219    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    /// Returns `true` if this transaction has transparent outputs.
226    ///
227    /// Reads the bundle's output count directly: `outputs()` rebuilds and converts the whole
228    /// output vector, which is wasteful when only the count is needed.
229    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    /// Returns `true` if this transaction has transparent inputs or outputs.
236    pub fn has_transparent_inputs_or_outputs(&self) -> bool {
237        self.has_transparent_inputs() || self.has_transparent_outputs()
238    }
239
240    /// Returns `true` if this is a coinbase transaction.
241    pub fn is_coinbase(&self) -> bool {
242        self.transparent_bundle().is_some_and(|b| b.is_coinbase())
243    }
244
245    /// Returns `true` if this transaction has valid inputs for a non-coinbase
246    /// transaction, that is, none of its transparent inputs has a null prevout.
247    ///
248    /// # Consensus
249    ///
250    /// > A transparent input in a non-coinbase transaction MUST NOT have a null prevout.
251    ///
252    /// <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
253    ///
254    /// Note that a transaction can return `false` from both [`Transaction::is_coinbase`] and
255    /// this method, for example a transaction with a null-prevout input alongside other
256    /// inputs. Such transactions are rejected by the verifier.
257    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    /// Returns the outpoints spent by this transaction's transparent inputs.
267    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    /// Compute the hash (txid) of this transaction.
274    pub fn hash(&self) -> Hash {
275        let txid_bytes: [u8; 32] = *self.0.txid().as_ref();
276        Hash(txid_bytes)
277    }
278
279    /// Compute the authorizing data commitment for this transaction.
280    ///
281    /// Returns `None` for pre-V5 transactions (which don't have auth digests).
282    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    /// Compute the unmined transaction ID for this transaction.
295    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    /// Returns the number of JoinSplit descriptions in this transaction.
306    pub fn joinsplit_count(&self) -> usize {
307        self.sprout_bundle().map_or(0, |b| b.joinsplits.len())
308    }
309
310    /// Returns `true` if this transaction has Sprout JoinSplit data.
311    pub fn has_sprout_joinsplit_data(&self) -> bool {
312        self.0.sprout_bundle().is_some()
313    }
314
315    /// Iterate over the Sprout JoinSplit descriptions (librustzcash type).
316    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    /// Access the Sprout nullifiers in this transaction.
326    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    /// Access the Sprout note commitments in this transaction.
335    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    /// Returns vpub_old values (amounts entering the Sprout pool).
346    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    /// Returns vpub_new values (amounts leaving the Sprout pool).
355    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    /// Access the JoinSplit public validating key, if any.
364    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    /// Returns `true` if this transaction has Sapling shielded data.
372    pub fn has_sapling_shielded_data(&self) -> bool {
373        self.0.sapling_bundle().is_some()
374    }
375
376    /// Access the Sapling nullifiers in this transaction.
377    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    /// Access the Sapling spend descriptions (librustzcash type).
385    ///
386    /// The spend description type uses `GrothProofBytes` for proofs and
387    /// `redjubjub::Signature<SpendAuth>` for auth sigs.
388    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    /// Returns the number of Sapling spends.
399    pub fn sapling_spends_count(&self) -> usize {
400        self.sapling_bundle()
401            .map_or(0, |b| b.shielded_spends().len())
402    }
403
404    /// Access the Sapling output descriptions (librustzcash type).
405    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    /// Access the Sapling note commitments in this transaction.
416    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    /// Iterate over deduplicated Sapling anchors as zebra tree roots.
423    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    /// Get the Sapling value balance.
437    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    /// Returns `true` if this transaction has Orchard shielded data.
450    pub fn has_orchard_shielded_data(&self) -> bool {
451        self.0.orchard_bundle().is_some()
452    }
453
454    /// Access the Orchard nullifiers in this transaction.
455    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    /// Access the Orchard actions (librustzcash type).
466    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    /// Access Orchard note commitments.
479    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    /// Access the Orchard flags, if any.
486    pub fn orchard_flags(&self) -> Option<::orchard::bundle::Flags> {
487        self.0.orchard_bundle().map(|b| *b.flags())
488    }
489
490    /// Access the Orchard anchor as a zebra tree root, if any.
491    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    /// Get the Orchard value balance.
499    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    // Ironwood (NU6.3 onward).
512    //
513    // Ironwood reuses the Orchard action and proof system, so `zcash_primitives` models it with
514    // the same `orchard::Bundle` type, kept in a separate `ironwood_bundle` field. These
515    // accessors mirror the Orchard ones above, but convert into Zebra's type-distinct
516    // `crate::ironwood` newtypes so the two pools' nullifiers and note commitments can never be
517    // interchanged.
518
519    /// Returns `true` if this transaction has an Ironwood bundle.
520    pub fn has_ironwood_shielded_data(&self) -> bool {
521        self.0.ironwood_bundle().is_some()
522    }
523
524    /// Access the Ironwood nullifiers in this transaction.
525    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    /// Access the Ironwood actions (librustzcash type).
534    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    /// Access Ironwood note commitments.
548    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    /// Access the Ironwood flags, if any.
555    pub fn ironwood_flags(&self) -> Option<::orchard::bundle::Flags> {
556        self.0.ironwood_bundle().map(|b| *b.flags())
557    }
558
559    /// Access the Ironwood anchor as a zebra tree root, if any.
560    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    /// Returns `true` unless this transaction has an Ironwood bundle that enables neither
568    /// spends nor outputs.
569    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    /// Get the Ironwood value balance.
579    ///
580    /// Positive values are added to this transaction's value pool, and removed from the Ironwood
581    /// chain value pool. Negative values are removed from this transaction, and added to the
582    /// Ironwood pool. This is zero for transactions without an Ironwood bundle.
583    ///
584    /// <https://zebra.zfnd.org/dev/rfcs/0012-value-pools.html#definitions>
585    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    /// Returns `true` if the Orchard bundle's Halo2 proof has the canonical size for its
599    /// action count, or if there is no Orchard bundle.
600    ///
601    /// A proof that is present but not canonically sized can be padded with arbitrary trailing
602    /// data without affecting its validity (GHSA-jfw5-j458-pfv6). Bundles are deserialized
603    /// leniently, so this is checked by the verifier rather than during parsing.
604    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    /// Returns `true` if the Ironwood bundle's Halo2 proof has the canonical size for its
612    /// action count, or if there is no Ironwood bundle.
613    ///
614    /// See [`Self::orchard_proof_size_is_canonical`]; Ironwood reuses the Orchard circuit, so it
615    /// has the same expected proof size.
616    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    /// Returns `true` if this transaction has shielded inputs.
624    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    /// Returns `true` if this transaction has shielded outputs.
639    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    /// Does this transaction have shielded inputs or outputs?
654    pub fn has_shielded_data(&self) -> bool {
655        self.has_shielded_inputs() || self.has_shielded_outputs()
656    }
657
658    /// Returns `true` if this transaction has transparent or shielded inputs.
659    pub fn has_transparent_or_shielded_inputs(&self) -> bool {
660        self.has_transparent_inputs() || self.has_shielded_inputs()
661    }
662
663    /// Returns `true` if this transaction has transparent or shielded outputs.
664    pub fn has_transparent_or_shielded_outputs(&self) -> bool {
665        self.has_transparent_outputs() || self.has_shielded_outputs()
666    }
667
668    /// Returns `true` if the Orchard flags are consistent.
669    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    /// Return the transparent value balance,
680    /// the change in the transaction value pool due to transparent inputs and outputs.
681    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    /// Computes the transparent balance using borrowed input values.
689    #[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    /// Return the sprout value balance.
720    ///
721    /// Errors when the aggregate JoinSplit value balance (or any prefix of it, matching the
722    /// pre-refactor fold) leaves the valid monetary range. Aggregated here because
723    /// `zcash_primitives` collapses that case to `None`, conflating it with "no Sprout
724    /// bundle". The net-sum bound matches zcashd from Canopy onward, where `vpub_old` is
725    /// always zero; pre-Canopy heights are checkpointed.
726    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                // Not `js.net_value()`: its `expect` trusts upstream parse bounds. The
733                // subtraction can't overflow `i64`, each `vpub` is at most `MAX_MONEY`.
734                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    /// Get the overall value balance using plain or ordered UTXOs, without copying outputs.
743    ///
744    /// # Panics
745    ///
746    /// Panics if `utxos` omits a transparent input's UTXO.
747    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    /// Returns the [`transparent::CoinbaseSpendRestriction`] for this transaction,
761    /// assuming it is mined at `spend_height`.
762    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    /// Computes the authorizing data commitment for a transaction.
843    ///
844    /// Returns an error if passed a pre-V5 transaction (which has no auth digest).
845    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    /// Deserialize a transaction with a known consensus branch ID.
862    ///
863    /// Runs the same parse-time consensus checks as
864    /// [`Transaction::zcash_deserialize`](crate::serialization::ZcashDeserialize::zcash_deserialize).
865    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    /// Deserialize a transaction without network context.
875    ///
876    /// # Branch ID handling
877    ///
878    /// - **V5+ transactions**: the consensus branch ID is read from the wire. Correct.
879    /// - **V1-V4 transactions**: the branch ID is NOT on the wire, so a default
880    ///   (`BranchId::Canopy`) is stored.  This does not affect parsing or txid
881    ///   computation, but the stored `consensus_branch_id` field will be wrong for
882    ///   transactions mined before Canopy.  Use
883    ///   `ZcashDeserializeWithContext<BranchId>` when the correct branch ID is known.
884    ///
885    /// # Callers
886    ///
887    /// Prefer `ZcashDeserializeWithContext<BranchId>` when the correct branch ID is
888    /// known.  This context-free impl exists for:
889    /// - Block deserialization (branch ID is corrected afterward)
890    /// - Network message parsing and RPC (transactions are re-validated with the
891    ///   correct branch ID before sighash computation)
892    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
899/// Parses a transaction and runs the parse-time consensus checks that `zcash_primitives`
900/// does not enforce. Both deserialization impls go through this function, so a transaction
901/// cannot reach a [`Transaction`] value without passing the checks.
902fn 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    // Limit to MAX_BLOCK_BYTES: a transaction larger than a block is always invalid.
909    let mut limited = reader.take(crate::block::MAX_BLOCK_BYTES);
910
911    // Only V4 transactions need their bytes recorded, for the `valueBalanceSapling` check
912    // below. Reading the 4-byte header up front and putting it back lets every other
913    // version parse without copying the transaction a second time, which matters during
914    // the initial block download.
915    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    // # Consensus
936    //
937    // > [NU5 onward] If effectiveVersion ≥ 5, the nConsensusBranchId field MUST match the
938    // > consensus branch ID used for SIGHASH transaction hashes, as specified in [ZIP-244].
939    //
940    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
941    //
942    // > CONSENSUS_BRANCH_ID is the 4-byte little-endian encoding of the consensus branch ID
943    // > for the epoch of the block containing the transaction.
944    //
945    // <https://zips.z.cash/zip-0244#txid-digest>
946    //
947    // ZIP 229 introduces V6 at NU6.3, replacing the pre-NU6.3 version restriction with:
948    //
949    // > [NU6.3 onward] The transaction version number MUST be 4 or 5 or 6.
950    //
951    // <https://zips.z.cash/zip-0229#consensus-rules>
952    //
953    // Together, these rules exclude pre-NU6.3 branch IDs from V6 transactions.
954    // Older branch IDs select Orchard bundle versions that the V6 writer rejects.
955    // Reject them here so every successfully parsed transaction can be serialized.
956    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    // Validate coinbase inputs: the script length must be in bounds and the height
966    // encoding must parse correctly. zcash_primitives accepts raw bytes without
967    // validating either, so we validate explicitly here to preserve Zebra's
968    // parse-time checks.
969    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                // The genesis coinbase predates BIP-34: its 77-byte script has no height
974                // prefix, so skip the height parse, matching `compat::txin_to_input`.
975                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    // # Consensus
983    //
984    // > A coinbase transaction MUST NOT have any Spend descriptions.
985    //
986    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
987    //
988    // `zcash_primitives` does not enforce this while parsing, so it is checked here to keep
989    // Zebra's parse-time rejection (GHSA-rgwx-8r98-p34c). Upstream decodes spend descriptions
990    // one at a time rather than pre-allocating from the claimed count, so a rejected
991    // transaction cannot force an outsized allocation before reaching this check.
992    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    // # Consensus
1005    //
1006    // > [Sapling onward] If effectiveVersion < 5 and nSpendsSapling + nOutputsSapling > 0,
1007    // > then valueBalanceSapling MUST be 0.
1008    //
1009    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
1010    //
1011    // `zcash_primitives` reads `valueBalanceSapling` but discards it when there are no
1012    // Sapling spends or outputs, so the value is not recoverable from the parsed
1013    // transaction and has to be read back out of the bytes that were consumed.
1014    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
1025/// Reads the `valueBalanceSapling` field of a V4 transaction that has no Sapling spends or
1026/// outputs, from the bytes that were consumed while parsing it.
1027///
1028/// Returns `None` if the bytes do not have the expected shape, in which case the caller should
1029/// not treat the transaction as having a bad balance — a malformed encoding would already have
1030/// failed to parse.
1031///
1032/// # Layout
1033///
1034/// The caller has established that the Sapling bundle is empty, which on the wire means
1035/// `nSpendsSapling` and `nOutputsSapling` are both the single byte `0x00`, and that no
1036/// `bindingSigSapling` follows. So the tail of a V4 transaction is:
1037///
1038/// ```text
1039/// .. | valueBalanceSapling (8) | 0x00 | 0x00 | nJoinSplit | vJoinSplit.. | [pubkey | sig]
1040/// ```
1041///
1042/// Locating the field from the end of the transaction avoids re-parsing the variable-length
1043/// transparent inputs and outputs that precede it.
1044fn v4_empty_sapling_value_balance(raw_bytes: &[u8], inner: &zp_tx::Transaction) -> Option<i64> {
1045    /// The serialized size of one V4 JoinSplit description, which always carries a Groth16
1046    /// proof: two 8-byte values, nine 32-byte fields, the proof, and two note ciphertexts.
1047    const V4_JOINSPLIT_SIZE: usize = (2 * 8) + (9 * 32) + 192 + (2 * 601);
1048
1049    /// `joinSplitPubKey` and `joinSplitSig`, present only when there is at least one JoinSplit.
1050    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    // The CompactSize encoding of the JoinSplit count.
1057    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    // Step back over the Sprout section and the two zero Sapling counts.
1071    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    // Confirm the offsets landed where expected before trusting the field.
1075    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
1087/// An `io::Read` wrapper that records every byte consumed, for post-parse validation.
1088struct 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// Human-readable Serialize for tests and snapshots.
1121// Produces structured output matching the old Transaction enum format
1122// so that RON snapshot tests remain human-readable.
1123#[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        // The field counts match the variants of the `Transaction` enum this output mirrors,
1130        // so V6 must be named and counted separately from V5: it has its own Ironwood bundle.
1131        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        // V5+ has network_upgrade as the first field (unwrap since V5 always has one)
1148        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        // V3+ has expiry_height (use Height(0) when nExpiryHeight == 0, matching old format)
1158        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    /// Build a V1 transaction from transparent components. Used in tests.
1206    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    /// Build a V2 transaction from transparent components. Used in tests.
1222    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    /// Build a V3 (Overwinter) transaction from transparent components. Used in tests.
1238    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    /// Build a V4 (Sapling) transaction from transparent components. Used in tests.
1255    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    /// Build a V5 (NU5) transaction from transparent components. Used in tests.
1272    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    /// Build a transparent-only V6 transaction, for tests.
1294    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    /// Build a V5 transaction with an Orchard bundle, for tests.
1348    ///
1349    /// The bundle must have been constructed for [`orchard::bundle::BundleVersion::orchard_v2`]
1350    /// or [`orchard::bundle::BundleVersion::orchard_v3`], matching `network_upgrade`.
1351    #[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    /// Build a V6 transaction with Orchard and Ironwood bundles, for tests.
1380    ///
1381    /// `orchard_bundle` must have been constructed for
1382    /// [`orchard::bundle::BundleVersion::orchard_v3`] and `ironwood_bundle` for
1383    /// [`orchard::bundle::BundleVersion::ironwood_v3`]; the two slots are not interchangeable.
1384    #[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    /// Converts Zebra transparent inputs and outputs into a librustzcash bundle,
1413    /// returning `None` if both are empty.
1414    #[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    /// Rebuild this transaction with new transparent inputs.
1430    ///
1431    /// Drops the transparent bundle if it ends up with no inputs and no outputs, because
1432    /// librustzcash hashes an empty bundle differently from an absent one, and the
1433    /// serialized transaction always parses as absent. This keeps the v5 and v6 txid
1434    /// matching the one parsed from the serialized transaction.
1435    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    /// Rebuild this transaction with new transparent outputs.
1455    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    /// Rebuild this transaction with a different expiry height (recomputes txid).
1499    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    /// Rebuild this transaction with a different network upgrade / branch ID (recomputes txid).
1516    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    /// Replace all transparent outputs (recomputes txid).
1537    pub fn set_outputs(&mut self, outputs: Vec<transparent::Output>) {
1538        *self = self.clone().with_transparent_outputs(outputs);
1539    }
1540
1541    /// Rebuild this transaction with a replaced Orchard bundle (recomputes txid).
1542    ///
1543    /// Test helper for synthesizing transactions with malformed orchard data
1544    /// (e.g. duplicated actions) that would otherwise be unreachable through
1545    /// normal construction paths.
1546    #[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    /// Build a V4 transaction with optional JoinSplit data via byte-level serialization.
1567    ///
1568    /// Transparent inputs/outputs and sapling shielded data are empty.
1569    /// Used by tests that need V4 transactions with sprout data.
1570    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()); // V4 overwintered
1577        bytes.extend_from_slice(&0x892F_2085u32.to_le_bytes()); // Sapling versionGroupId
1578        bytes.push(0x00); // nTransparentInputs
1579        bytes.push(0x00); // nTransparentOutputs
1580        bytes.extend_from_slice(&500_000_000u32.to_le_bytes()); // nLockTime
1581        bytes.extend_from_slice(&0u32.to_le_bytes()); // nExpiryHeight
1582        bytes.extend_from_slice(&0i64.to_le_bytes()); // valueBalanceSapling
1583        bytes.push(0x00); // nSpendsSapling
1584        bytes.push(0x00); // nOutputsSapling
1585        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); // nJoinSplits
1590        }
1591        Transaction::zcash_deserialize(bytes.as_slice())
1592            .expect("manually constructed V4 transaction should deserialize")
1593    }
1594}