Skip to main content

zcash_primitives/transaction/
tests.rs

1use proptest::prelude::*;
2
3#[cfg(test)]
4use {
5    crate::transaction::{
6        Authorization, Authorized, Transaction, TransactionData, TransactionDigest, TxVersion,
7        Zip244Digests,
8        coinbase::is_coinbase,
9        sighash::{PrecomputedSighashData, SignableInput},
10        sighash_v4::{v4_signature_hash, zip143_digests},
11        sighash_v5::v5_signature_hash,
12        sighash_v6::v6_signature_hash,
13        testing::arb_tx,
14        transparent,
15        txid::{BlockTxCommitmentDigester, TxIdDigester, hash_sapling_spends},
16    },
17    ::transparent::{
18        address::Script,
19        bundle::TxIn,
20        sighash::{SighashType, TransparentAuthorizingContext},
21    },
22    alloc::vec::Vec,
23    blake2b_simd::{Hash as Blake2bHash, Params},
24    core::{cell::Cell, ops::Deref},
25    ff::PrimeField,
26    zcash_protocol::{
27        consensus::BranchId,
28        value::{ZatBalance, Zatoshis},
29    },
30    zcash_script::script,
31};
32
33#[cfg(all(test, zcash_unstable = "nutachyon"))]
34use zcash_protocol::constants::{V7_TX_VERSION, V7_VERSION_GROUP_ID};
35
36#[cfg(any(test, feature = "test-dependencies"))]
37pub mod data;
38
39/// An empty NU7 v6 codec fixture, not a spendable transaction. The header follows ZIP 229;
40/// the six zero counts encode transparent inputs/outputs, Sapling spends/outputs,
41/// Orchard actions, and Ironwood actions. Expected hashes were independently calculated
42/// with Python hashlib.blake2b (32-byte output), using the ZIP 244/229 digest tree:
43/// header || empty transparent || empty Sapling || empty v6 Orchard || empty Ironwood.
44/// With no transparent bundle, the shielded signature digest equals this transaction digest.
45/// Keep these expectations identical in builds with and without the ZIP 233 opt-in.
46#[test]
47fn nu7_v6_encoding_and_digests_are_feature_independent() {
48    const ENCODED: &str = "0600008098b684d8d90a19770000000001000000000000000000";
49    const HEADER_DIGEST: &str = "199b8446da5a9247711a94527997d7e87c31dfe5e8efb4b34d020a2aee8ee1c5";
50    const TX_DIGEST: &str = "78296c68a370c2e1f058d997c81c7b011c4562c52fc5ca2994ad59cd179fbe9e";
51    /// The smallest nonzero expiry height, used only to distinguish header fields.
52    const EXPIRY_HEIGHT: u32 = 1;
53    /// A suffix owned by an enclosing stream, which transaction parsing must not consume.
54    const TRAILER: &[u8] = b"next-record";
55
56    let encoded = hex::decode(ENCODED).unwrap();
57    let expected_digest = hex::decode(TX_DIGEST).unwrap();
58    let data = TransactionData::<TestUnauthorized>::from_parts_v6(
59        BranchId::Nu7,
60        0,
61        EXPIRY_HEIGHT.into(),
62        None,
63        None,
64        None,
65        None,
66    );
67    let digests = data.digest(TxIdDigester);
68    assert_eq!(
69        digests.header_digest.as_bytes(),
70        hex::decode(HEADER_DIGEST).unwrap()
71    );
72    assert_eq!(
73        v6_signature_hash(&data, &SignableInput::Shielded, &digests, None).as_bytes(),
74        expected_digest,
75    );
76
77    let tx = TransactionData::from_parts_v6(
78        BranchId::Nu7,
79        0,
80        EXPIRY_HEIGHT.into(),
81        None,
82        None,
83        None,
84        None,
85    )
86    .freeze()
87    .unwrap();
88    assert_eq!(tx_bytes(&tx), encoded);
89    assert_eq!(tx.txid().as_ref().as_slice(), expected_digest);
90
91    let mut stream = encoded.clone();
92    stream.extend_from_slice(TRAILER);
93    let mut reader = stream.as_slice();
94    let parsed = Transaction::read(&mut reader, BranchId::Nu7).unwrap();
95    assert_eq!(reader, TRAILER);
96    assert_eq!(parsed.txid(), tx.txid());
97    assert_eq!(tx_bytes(&parsed), encoded);
98    for end in 0..encoded.len() {
99        assert!(Transaction::read(&encoded[..end], BranchId::Nu7).is_err());
100    }
101
102    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
103    {
104        let explicit_zero = TransactionData::from_parts_v6_with_zip233(
105            BranchId::Nu7,
106            0,
107            EXPIRY_HEIGHT.into(),
108            Zatoshis::ZERO,
109            None,
110            None,
111            None,
112            None,
113        )
114        .freeze()
115        .unwrap();
116        assert_eq!(tx_bytes(&explicit_zero), encoded);
117        assert_eq!(explicit_zero.txid(), tx.txid());
118        assert!(!TxVersion::V6.has_zip233(BranchId::Nu7));
119    }
120}
121
122#[test]
123fn nu7_v5_encoding_and_digests_are_feature_independent() {
124    // Empty codec fixture calculated independently with Python hashlib.blake2b,
125    // using the ZIP 244 header and empty transparent, Sapling, and Orchard digests.
126    const ENCODED: &str = "050000800a27a726d90a197700000000010000000000000000";
127    const DIGEST: &str = "328d975581fbf002206ef6f0b69fe57fb47f40ec31c59ac62c3565d4e259e128";
128    /// The smallest nonzero expiry height, matching the v6 fixture.
129    const EXPIRY_HEIGHT: u32 = 1;
130    let data = TransactionData::<TestUnauthorized>::from_parts(
131        TxVersion::V5,
132        BranchId::Nu7,
133        0,
134        EXPIRY_HEIGHT.into(),
135        None,
136        None,
137        None,
138        None,
139    );
140    let expected = hex::decode(DIGEST).unwrap();
141    assert_eq!(v5_shielded_sighash(&data).as_bytes(), expected);
142    let tx = TransactionData::from_parts(
143        TxVersion::V5,
144        BranchId::Nu7,
145        0,
146        EXPIRY_HEIGHT.into(),
147        None,
148        None,
149        None,
150        None,
151    )
152    .freeze()
153    .unwrap();
154    let encoded = hex::decode(ENCODED).unwrap();
155    assert_eq!(tx_bytes(&tx), encoded);
156    assert_eq!(tx.txid().as_ref().as_slice(), expected);
157    let mut reader = encoded.as_slice();
158    assert_eq!(
159        Transaction::read(&mut reader, BranchId::Nu7)
160            .unwrap()
161            .txid(),
162        tx.txid()
163    );
164    assert!(reader.is_empty());
165    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
166    {
167        let zero = TransactionData::from_parts_with_zip233(
168            TxVersion::V5,
169            BranchId::Nu7,
170            0,
171            EXPIRY_HEIGHT.into(),
172            Zatoshis::ZERO,
173            None,
174            None,
175            None,
176            None,
177        )
178        .freeze()
179        .unwrap();
180        assert_eq!(tx_bytes(&zero), encoded);
181        assert_eq!(zero.txid(), tx.txid());
182    }
183}
184
185#[test]
186#[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
187fn freeze_rejects_nonzero_zip233_in_v5_and_v6() {
188    /// The smallest unsupported nonzero amount exercises the rejection boundary.
189    const NONZERO_AMOUNT: Zatoshis = Zatoshis::const_from_u64(1);
190    for branch in [BranchId::Nu6_3, BranchId::Nu7] {
191        for version in [TxVersion::V5, TxVersion::V6] {
192            for amount in [
193                NONZERO_AMOUNT,
194                Zatoshis::const_from_u64(zcash_protocol::value::MAX_MONEY),
195            ] {
196                let data =
197                    TransactionData::<crate::transaction::Authorized>::from_parts_with_zip233(
198                        version,
199                        branch,
200                        0,
201                        0u32.into(),
202                        amount,
203                        None,
204                        None,
205                        None,
206                        None,
207                    );
208                assert_eq!(
209                    data.freeze().unwrap_err().kind(),
210                    corez::io::ErrorKind::InvalidInput
211                );
212            }
213        }
214    }
215}
216#[test]
217fn tx_read_write() {
218    let data = &self::data::tx_read_write::TX_READ_WRITE;
219    let tx = Transaction::read(&data[..], BranchId::Canopy).unwrap();
220    assert_eq!(
221        format!("{}", tx.txid()),
222        "64f0bd7fe30ce23753358fe3a2dc835b8fba9c0274c4e2c54a6f73114cb55639"
223    );
224
225    let mut encoded = Vec::with_capacity(data.len());
226    tx.write(&mut encoded).unwrap();
227    assert_eq!(&data[..], &encoded[..]);
228}
229
230#[test]
231#[cfg(target_pointer_width = "64")]
232fn transaction_size_excludes_absent_shielded_bundles() {
233    /// Upper bound on the in-memory size of a [`Transaction`] on 64-bit targets. Shielded
234    /// bundles are boxed, so an absent bundle costs one pointer; storing any of them
235    /// inline would exceed this bound.
236    const MAX_TRANSACTION_SIZE: usize = 192;
237
238    assert!(core::mem::size_of::<Transaction>() <= MAX_TRANSACTION_SIZE);
239}
240
241#[test]
242fn suggested_version_for_v5_branches_is_not_v6() {
243    assert_eq!(
244        TxVersion::suggested_for_branch(BranchId::Nu5),
245        TxVersion::V5
246    );
247    assert_eq!(
248        TxVersion::suggested_for_branch(BranchId::Nu6),
249        TxVersion::V5
250    );
251    assert_eq!(
252        TxVersion::suggested_for_branch(BranchId::Nu6_1),
253        TxVersion::V5
254    );
255}
256
257#[test]
258#[cfg(zcash_unstable = "nutachyon")]
259fn v7_is_enabled_by_nu_tachyon_and_roundtrips() {
260    assert_eq!(
261        TxVersion::suggested_for_branch(BranchId::NuTachyon),
262        TxVersion::V7
263    );
264    assert!(TxVersion::V7.valid_in_branch(BranchId::NuTachyon));
265    assert!(!TxVersion::V7.valid_in_branch(BranchId::Nu6_3));
266
267    let tx =
268        TransactionData::from_parts_v7(BranchId::NuTachyon, 0, 0u32.into(), None, None, None, None)
269            .freeze()
270            .unwrap();
271
272    let mut encoded = Vec::new();
273    tx.write(&mut encoded).unwrap();
274    assert_eq!(&encoded[..4], &(V7_TX_VERSION | (1 << 31)).to_le_bytes());
275    assert_eq!(&encoded[4..8], &V7_VERSION_GROUP_ID.to_le_bytes());
276    assert_eq!(
277        &encoded[8..12],
278        &u32::from(BranchId::NuTachyon).to_le_bytes()
279    );
280
281    let decoded = Transaction::read(&encoded[..], BranchId::Sprout).unwrap();
282    assert_eq!(decoded.version(), TxVersion::V7);
283    assert_eq!(decoded.consensus_branch_id(), BranchId::NuTachyon);
284    let mut reencoded = Vec::new();
285    decoded.write(&mut reencoded).unwrap();
286    assert_eq!(reencoded, encoded);
287}
288
289#[test]
290fn v4_transactions_remain_valid_in_nu6_3() {
291    assert!(TxVersion::V4.valid_in_branch(BranchId::Nu6_3));
292}
293
294#[test]
295fn v5_auth_commitment_in_nu6_3_does_not_include_ironwood_digest() {
296    fn empty_hash(personal: &[u8; 16]) -> Blake2bHash {
297        Params::new().hash_length(32).personal(personal).hash(&[])
298    }
299
300    let mut personal = [0; 16];
301    personal[..12].copy_from_slice(b"ZTxAuthHash_");
302    personal[12..].copy_from_slice(&u32::from(BranchId::Nu6_3).to_le_bytes());
303
304    let mut expected = Params::new().hash_length(32).personal(&personal).to_state();
305    expected.update(empty_hash(b"ZTxAuthTransHash").as_bytes());
306    expected.update(empty_hash(b"ZTxAuthSapliHash").as_bytes());
307    expected.update(empty_hash(b"ZTxAuthOrchaHash").as_bytes());
308
309    let tx = TransactionData::from_parts(
310        TxVersion::V5,
311        BranchId::Nu6_3,
312        0,
313        0u32.into(),
314        None,
315        None,
316        None,
317        None,
318    )
319    .freeze()
320    .unwrap();
321
322    assert_eq!(tx.auth_commitment(), expected.finalize());
323}
324
325#[test]
326fn v6_empty_auth_commitment_uses_v6_shielded_personalizations() {
327    fn empty_hash(personal: &[u8; 16]) -> Blake2bHash {
328        Params::new().hash_length(32).personal(personal).hash(&[])
329    }
330
331    let mut personal = [0; 16];
332    personal[..12].copy_from_slice(b"ZTxAuthHash_");
333    personal[12..].copy_from_slice(&u32::from(BranchId::Nu6_3).to_le_bytes());
334
335    let mut expected = Params::new().hash_length(32).personal(&personal).to_state();
336    expected.update(empty_hash(b"ZTxAuthTransHash").as_bytes());
337    expected.update(empty_hash(b"ZTxAuthSapliH_v6").as_bytes());
338    expected.update(empty_hash(b"ZTxAuthOrchaH_v6").as_bytes());
339    expected.update(empty_hash(b"ZTxAuthIrnwdH_v6").as_bytes());
340
341    let tx =
342        TransactionData::from_parts_v6(BranchId::Nu6_3, 0, 0u32.into(), None, None, None, None)
343            .freeze()
344            .unwrap();
345
346    assert_eq!(tx.auth_commitment(), expected.finalize());
347}
348
349#[test]
350fn v6_empty_orchard_txid_uses_v6_orchard_personalization() {
351    fn empty_hash(personal: &[u8; 16]) -> Blake2bHash {
352        Params::new().hash_length(32).personal(personal).hash(&[])
353    }
354
355    let tx_data =
356        TransactionData::from_parts_v6(BranchId::Nu6_3, 0, 0u32.into(), None, None, None, None);
357    let txid_parts = tx_data.digest(TxIdDigester);
358    let tx = tx_data.freeze().unwrap();
359
360    assert!(txid_parts.orchard_digest.is_none());
361    assert!(txid_parts.ironwood_digest.is_none());
362
363    let mut personal = [0; 16];
364    personal[..12].copy_from_slice(b"ZcashTxHash_");
365    personal[12..].copy_from_slice(&u32::from(BranchId::Nu6_3).to_le_bytes());
366
367    let mut expected = Params::new().hash_length(32).personal(&personal).to_state();
368    expected.update(txid_parts.header_digest.as_bytes());
369    expected.update(empty_hash(b"ZTxIdTranspaHash").as_bytes());
370    expected.update(empty_hash(b"ZTxIdSaplingHash").as_bytes());
371    expected.update(empty_hash(b"ZTxIdOrchardH_v6").as_bytes());
372    expected.update(empty_hash(b"ZTxIdIronwd_H_v6").as_bytes());
373
374    let expected = expected.finalize();
375    assert_eq!(&tx.txid().as_ref()[..], expected.as_bytes());
376}
377
378#[test]
379fn v6_branch_reconstruction_preserves_ironwood_bundle() {
380    use proptest::test_runner::TestRunner;
381
382    let mut runner = TestRunner::default();
383    let ironwood_bundle = test_ironwood_bundle(&mut runner);
384    let tx = TransactionData::from_parts_v6(
385        BranchId::Nu6_3,
386        0,
387        1u32.into(),
388        None,
389        None,
390        None,
391        Some(ironwood_bundle),
392    )
393    .freeze()
394    .unwrap();
395
396    let original_txid = tx.txid();
397    let mut tx_bytes = vec![];
398    tx.write(&mut tx_bytes).unwrap();
399
400    let tx_data = Transaction::read(&tx_bytes[..], BranchId::Sprout)
401        .unwrap()
402        .into_data();
403
404    let legacy_rebuilt = TransactionData::from_parts(
405        tx_data.version(),
406        tx_data.consensus_branch_id(),
407        tx_data.lock_time(),
408        tx_data.expiry_height(),
409        tx_data.transparent_bundle().cloned(),
410        tx_data.sprout_bundle().cloned(),
411        tx_data.sapling_bundle().cloned(),
412        tx_data.orchard_bundle().cloned(),
413    )
414    .freeze()
415    .unwrap();
416    assert!(legacy_rebuilt.ironwood_bundle().is_none());
417    assert_ne!(legacy_rebuilt.txid(), original_txid);
418
419    let rebuilt = TransactionData::from_parts_v6(
420        tx_data.consensus_branch_id(),
421        tx_data.lock_time(),
422        tx_data.expiry_height(),
423        tx_data.transparent_bundle().cloned(),
424        tx_data.sapling_bundle().cloned(),
425        tx_data.orchard_bundle().cloned(),
426        tx_data.ironwood_bundle().cloned(),
427    )
428    .freeze()
429    .unwrap();
430
431    assert!(rebuilt.ironwood_bundle().is_some());
432    assert_eq!(rebuilt.txid(), original_txid);
433}
434
435#[cfg(test)]
436fn test_anchor(byte: u8) -> orchard::Anchor {
437    let mut bytes = [0u8; 32];
438    bytes[0] = byte;
439    orchard::Anchor::from_bytes(bytes).unwrap()
440}
441
442#[cfg(test)]
443fn test_orchard_bundle(
444    runner: &mut proptest::test_runner::TestRunner,
445) -> orchard::Bundle<orchard::bundle::Authorized, ZatBalance> {
446    use proptest::strategy::ValueTree;
447
448    let bundle = crate::transaction::components::orchard::testing::arb_bundle(1)
449        .new_tree(runner)
450        .unwrap()
451        .current();
452    crate::transaction::components::orchard::testing::rebuild_with_version(
453        bundle,
454        orchard::bundle::BundleVersion::orchard_v3(),
455    )
456}
457
458#[cfg(test)]
459fn test_ironwood_bundle(
460    runner: &mut proptest::test_runner::TestRunner,
461) -> orchard::Bundle<orchard::bundle::Authorized, ZatBalance> {
462    use proptest::strategy::ValueTree;
463
464    let bundle = crate::transaction::components::orchard::testing::arb_bundle(1)
465        .new_tree(runner)
466        .unwrap()
467        .current();
468    crate::transaction::components::orchard::testing::rebuild_with_version(
469        bundle,
470        orchard::bundle::BundleVersion::ironwood_v3(),
471    )
472}
473
474#[cfg(test)]
475fn bundle_with_anchor(
476    bundle: &orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
477    anchor: orchard::Anchor,
478) -> orchard::Bundle<orchard::bundle::Authorized, ZatBalance> {
479    orchard::Bundle::try_from_parts(
480        bundle.actions().clone(),
481        *bundle.flags(),
482        *bundle.value_balance(),
483        anchor,
484        bundle.authorization().clone(),
485        bundle.bundle_version(),
486    )
487    .unwrap()
488}
489
490#[cfg(test)]
491fn test_sapling_anchor(byte: u8) -> bls12_381::Scalar {
492    bls12_381::Scalar::from(u64::from(byte))
493}
494
495#[cfg(test)]
496fn test_sapling_bundle(
497    runner: &mut proptest::test_runner::TestRunner,
498) -> sapling::Bundle<sapling::bundle::Authorized, ZatBalance> {
499    use proptest::strategy::ValueTree;
500
501    let bundle_strategy =
502        crate::transaction::components::sapling::testing::arb_bundle_for_version(TxVersion::V6);
503
504    for _ in 0..100 {
505        if let Some(bundle) = bundle_strategy.new_tree(runner).unwrap().current()
506            && !bundle.shielded_spends().is_empty()
507        {
508            return bundle;
509        }
510    }
511
512    panic!("Sapling bundle strategy should generate a bundle with spends");
513}
514
515#[cfg(test)]
516fn test_sapling_output_only_bundle(
517    runner: &mut proptest::test_runner::TestRunner,
518) -> sapling::Bundle<sapling::bundle::Authorized, ZatBalance> {
519    use proptest::strategy::ValueTree;
520
521    let bundle_strategy =
522        crate::transaction::components::sapling::testing::arb_bundle_for_version(TxVersion::V6);
523
524    for _ in 0..1000 {
525        if let Some(bundle) = bundle_strategy.new_tree(runner).unwrap().current()
526            && bundle.shielded_spends().is_empty()
527            && !bundle.shielded_outputs().is_empty()
528        {
529            return bundle;
530        }
531    }
532
533    panic!("Sapling bundle strategy should generate an output-only bundle");
534}
535
536#[cfg(test)]
537fn sapling_bundle_with_anchor(
538    bundle: &sapling::Bundle<sapling::bundle::Authorized, ZatBalance>,
539    anchor: bls12_381::Scalar,
540) -> sapling::Bundle<sapling::bundle::Authorized, ZatBalance> {
541    let spends = bundle
542        .shielded_spends()
543        .iter()
544        .map(|spend| {
545            sapling::bundle::SpendDescription::from_parts(
546                spend.cv().clone(),
547                anchor,
548                *spend.nullifier(),
549                *spend.rk(),
550                *spend.zkproof(),
551                *spend.spend_auth_sig(),
552            )
553        })
554        .collect();
555
556    sapling::Bundle::from_parts(
557        spends,
558        bundle.shielded_outputs().to_vec(),
559        *bundle.value_balance(),
560        *bundle.authorization(),
561    )
562    .expect("test bundle has Sapling spends")
563}
564
565#[cfg(test)]
566fn tx_bytes(tx: &Transaction) -> Vec<u8> {
567    let mut encoded = Vec::new();
568    tx.write(&mut encoded).unwrap();
569    encoded
570}
571
572#[cfg(test)]
573fn v5_tx_with_orchard_bundle(
574    orchard_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
575) -> Transaction {
576    TransactionData::<crate::transaction::Authorized>::from_parts(
577        TxVersion::V5,
578        BranchId::Nu5,
579        0,
580        1u32.into(),
581        None,
582        None,
583        None,
584        Some(orchard_bundle),
585    )
586    .freeze()
587    .unwrap()
588}
589
590#[cfg(test)]
591fn v5_tx_data_with_orchard_bundle(
592    orchard_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
593) -> TransactionData<TestUnauthorized> {
594    TransactionData::from_parts(
595        TxVersion::V5,
596        BranchId::Nu5,
597        0,
598        1u32.into(),
599        None,
600        None,
601        None,
602        Some(orchard_bundle),
603    )
604}
605
606#[cfg(test)]
607fn v5_tx_with_sapling_bundle(
608    sapling_bundle: sapling::Bundle<sapling::bundle::Authorized, ZatBalance>,
609) -> Transaction {
610    TransactionData::<crate::transaction::Authorized>::from_parts(
611        TxVersion::V5,
612        BranchId::Nu5,
613        0,
614        1u32.into(),
615        None,
616        None,
617        Some(sapling_bundle),
618        None,
619    )
620    .freeze()
621    .unwrap()
622}
623
624#[cfg(test)]
625fn v5_tx_data_with_sapling_bundle(
626    sapling_bundle: sapling::Bundle<sapling::bundle::Authorized, ZatBalance>,
627) -> TransactionData<TestUnauthorized> {
628    TransactionData::from_parts(
629        TxVersion::V5,
630        BranchId::Nu5,
631        0,
632        1u32.into(),
633        None,
634        None,
635        Some(sapling_bundle),
636        None,
637    )
638}
639
640/// Clears the cross-address flag on an Orchard bundle (preserving spends/outputs)
641/// so it is representable in a v6 Orchard slot ([`orchard::bundle::BundleVersion::orchard_v3`],
642/// which forbids cross-address transfers; cross-address is Ironwood-only).
643#[cfg(test)]
644fn disable_cross_address(
645    bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
646) -> orchard::Bundle<orchard::bundle::Authorized, ZatBalance> {
647    let byte = u8::from(bundle.flags().spends_enabled())
648        | (u8::from(bundle.flags().outputs_enabled()) << 1);
649    let flags =
650        orchard::bundle::Flags::from_byte(byte, orchard::bundle::BundleVersion::orchard_v3())
651            .unwrap();
652    orchard::Bundle::try_from_parts(
653        bundle.actions().clone(),
654        flags,
655        *bundle.value_balance(),
656        *bundle.anchor(),
657        bundle.authorization().clone(),
658        orchard::bundle::BundleVersion::orchard_v3(),
659    )
660    .unwrap()
661}
662
663#[cfg(test)]
664fn v6_tx_with_orchard_bundle(
665    orchard_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
666) -> Transaction {
667    TransactionData::<crate::transaction::Authorized>::from_parts_v6(
668        BranchId::Nu6_3,
669        0,
670        1u32.into(),
671        None,
672        None,
673        Some(disable_cross_address(orchard_bundle)),
674        None,
675    )
676    .freeze()
677    .unwrap()
678}
679
680#[cfg(test)]
681fn v6_tx_with_sapling_bundle(
682    sapling_bundle: sapling::Bundle<sapling::bundle::Authorized, ZatBalance>,
683) -> Transaction {
684    TransactionData::<crate::transaction::Authorized>::from_parts_v6(
685        BranchId::Nu6_3,
686        0,
687        1u32.into(),
688        None,
689        Some(sapling_bundle),
690        None,
691        None,
692    )
693    .freeze()
694    .unwrap()
695}
696
697#[cfg(test)]
698fn v6_tx_data_with_sapling_bundle(
699    sapling_bundle: sapling::Bundle<sapling::bundle::Authorized, ZatBalance>,
700) -> TransactionData<TestUnauthorized> {
701    TransactionData::from_parts_v6(
702        BranchId::Nu6_3,
703        0,
704        1u32.into(),
705        None,
706        Some(sapling_bundle),
707        None,
708        None,
709    )
710}
711
712#[cfg(test)]
713fn v6_tx_data_with_orchard_bundle(
714    orchard_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
715) -> TransactionData<TestUnauthorized> {
716    TransactionData::from_parts_v6(
717        BranchId::Nu6_3,
718        0,
719        1u32.into(),
720        None,
721        None,
722        Some(disable_cross_address(orchard_bundle)),
723        None,
724    )
725}
726
727#[cfg(test)]
728fn v6_tx_with_ironwood_bundle(
729    ironwood_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
730) -> Transaction {
731    TransactionData::<crate::transaction::Authorized>::from_parts_v6(
732        BranchId::Nu6_3,
733        0,
734        1u32.into(),
735        None,
736        None,
737        None,
738        Some(ironwood_bundle),
739    )
740    .freeze()
741    .unwrap()
742}
743
744#[cfg(test)]
745fn v6_tx_data_with_ironwood_bundle(
746    ironwood_bundle: orchard::Bundle<orchard::bundle::Authorized, ZatBalance>,
747) -> TransactionData<TestUnauthorized> {
748    TransactionData::from_parts_v6(
749        BranchId::Nu6_3,
750        0,
751        1u32.into(),
752        None,
753        None,
754        None,
755        Some(ironwood_bundle),
756    )
757}
758
759#[cfg(test)]
760fn v5_shielded_sighash(tx_data: &TransactionData<TestUnauthorized>) -> Blake2bHash {
761    let txid_parts = tx_data.digest(TxIdDigester);
762    v5_signature_hash(tx_data, &SignableInput::Shielded, &txid_parts, None)
763}
764
765#[cfg(test)]
766fn v6_shielded_sighash(tx_data: &TransactionData<TestUnauthorized>) -> Blake2bHash {
767    let txid_parts = tx_data.digest(TxIdDigester);
768    v6_signature_hash(tx_data, &SignableInput::Shielded, &txid_parts, None)
769}
770
771#[test]
772fn v6_orchard_anchor_changes_auth_commitment_not_txid_or_sighash() {
773    let mut runner = proptest::test_runner::TestRunner::default();
774    let bundle = test_orchard_bundle(&mut runner);
775
776    let bundle_a = bundle_with_anchor(&bundle, test_anchor(1));
777    let bundle_b = bundle_with_anchor(&bundle, test_anchor(2));
778    let tx_data_a = v6_tx_data_with_orchard_bundle(bundle_a.clone());
779    let tx_data_b = v6_tx_data_with_orchard_bundle(bundle_b.clone());
780    let tx_a = v6_tx_with_orchard_bundle(bundle_a);
781    let tx_b = v6_tx_with_orchard_bundle(bundle_b);
782
783    assert_ne!(tx_bytes(&tx_a), tx_bytes(&tx_b));
784    assert_eq!(tx_a.txid(), tx_b.txid());
785    assert_eq!(
786        v6_shielded_sighash(&tx_data_a),
787        v6_shielded_sighash(&tx_data_b)
788    );
789    assert_ne!(tx_a.auth_commitment(), tx_b.auth_commitment());
790}
791
792#[test]
793fn v6_ironwood_anchor_changes_auth_commitment_not_txid_or_sighash() {
794    let mut runner = proptest::test_runner::TestRunner::default();
795    let bundle = test_ironwood_bundle(&mut runner);
796
797    let bundle_a = bundle_with_anchor(&bundle, test_anchor(1));
798    let bundle_b = bundle_with_anchor(&bundle, test_anchor(2));
799    let tx_data_a = v6_tx_data_with_ironwood_bundle(bundle_a.clone());
800    let tx_data_b = v6_tx_data_with_ironwood_bundle(bundle_b.clone());
801    let tx_a = v6_tx_with_ironwood_bundle(bundle_a);
802    let tx_b = v6_tx_with_ironwood_bundle(bundle_b);
803
804    assert_ne!(tx_bytes(&tx_a), tx_bytes(&tx_b));
805    assert_eq!(tx_a.txid(), tx_b.txid());
806    assert_eq!(
807        v6_shielded_sighash(&tx_data_a),
808        v6_shielded_sighash(&tx_data_b)
809    );
810    assert_ne!(tx_a.auth_commitment(), tx_b.auth_commitment());
811}
812
813#[test]
814fn v5_orchard_anchor_still_changes_txid_and_sighash() {
815    let mut runner = proptest::test_runner::TestRunner::default();
816    let bundle = test_orchard_bundle(&mut runner);
817
818    let bundle_a = bundle_with_anchor(&bundle, test_anchor(1));
819    let bundle_b = bundle_with_anchor(&bundle, test_anchor(2));
820    let tx_data_a = v5_tx_data_with_orchard_bundle(bundle_a.clone());
821    let tx_data_b = v5_tx_data_with_orchard_bundle(bundle_b.clone());
822    let tx_a = v5_tx_with_orchard_bundle(bundle_a);
823    let tx_b = v5_tx_with_orchard_bundle(bundle_b);
824
825    assert_ne!(tx_a.txid(), tx_b.txid());
826    assert_ne!(
827        v5_shielded_sighash(&tx_data_a),
828        v5_shielded_sighash(&tx_data_b)
829    );
830    assert_eq!(tx_a.auth_commitment(), tx_b.auth_commitment());
831}
832
833#[test]
834fn v6_sapling_anchor_changes_auth_commitment_not_txid_or_sighash() {
835    let mut runner = proptest::test_runner::TestRunner::default();
836    let bundle = test_sapling_bundle(&mut runner);
837
838    let bundle_a = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(1));
839    let bundle_b = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(2));
840    let tx_data_a = v6_tx_data_with_sapling_bundle(bundle_a.clone());
841    let tx_data_b = v6_tx_data_with_sapling_bundle(bundle_b.clone());
842    let tx_a = v6_tx_with_sapling_bundle(bundle_a);
843    let tx_b = v6_tx_with_sapling_bundle(bundle_b);
844
845    assert_ne!(tx_bytes(&tx_a), tx_bytes(&tx_b));
846    assert_eq!(tx_a.txid(), tx_b.txid());
847    assert_eq!(
848        v6_shielded_sighash(&tx_data_a),
849        v6_shielded_sighash(&tx_data_b)
850    );
851    assert_ne!(tx_a.auth_commitment(), tx_b.auth_commitment());
852}
853
854#[test]
855fn v5_sapling_anchor_still_changes_txid_and_sighash() {
856    let mut runner = proptest::test_runner::TestRunner::default();
857    let bundle = test_sapling_bundle(&mut runner);
858
859    let bundle_a = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(1));
860    let bundle_b = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(2));
861    let tx_data_a = v5_tx_data_with_sapling_bundle(bundle_a.clone());
862    let tx_data_b = v5_tx_data_with_sapling_bundle(bundle_b.clone());
863    let tx_a = v5_tx_with_sapling_bundle(bundle_a);
864    let tx_b = v5_tx_with_sapling_bundle(bundle_b);
865
866    assert_ne!(tx_a.txid(), tx_b.txid());
867    assert_ne!(
868        v5_shielded_sighash(&tx_data_a),
869        v5_shielded_sighash(&tx_data_b)
870    );
871    assert_eq!(tx_a.auth_commitment(), tx_b.auth_commitment());
872}
873
874#[test]
875fn v6_sapling_spends_digest_uses_v6_noncompact_domain_without_anchor() {
876    let mut runner = proptest::test_runner::TestRunner::default();
877    let bundle = test_sapling_bundle(&mut runner);
878
879    let mut h = Params::new()
880        .hash_length(32)
881        .personal(b"ZTxIdSSpendsHash")
882        .to_state();
883    let mut ch = Params::new()
884        .hash_length(32)
885        .personal(b"ZTxIdSSpendCHash")
886        .to_state();
887    let mut nh = Params::new()
888        .hash_length(32)
889        .personal(b"ZTxIdSSpendNH_v6")
890        .to_state();
891
892    for spend in bundle.shielded_spends() {
893        ch.update(spend.nullifier().as_ref());
894        nh.update(&spend.cv().to_bytes());
895        nh.update(&<[u8; 32]>::from(*spend.rk()));
896    }
897
898    h.update(ch.finalize().as_bytes());
899    h.update(nh.finalize().as_bytes());
900
901    assert_eq!(
902        hash_sapling_spends(TxVersion::V6, bundle.shielded_spends()),
903        h.finalize()
904    );
905
906    let bundle_a = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(1));
907    let bundle_b = sapling_bundle_with_anchor(&bundle, test_sapling_anchor(2));
908    assert_eq!(
909        hash_sapling_spends(TxVersion::V6, bundle_a.shielded_spends()),
910        hash_sapling_spends(TxVersion::V6, bundle_b.shielded_spends())
911    );
912}
913
914#[test]
915fn v6_sapling_auth_digest_uses_v6_domain_and_appends_anchor() {
916    let mut runner = proptest::test_runner::TestRunner::default();
917    let bundle = test_sapling_bundle(&mut runner);
918
919    let mut h = Params::new()
920        .hash_length(32)
921        .personal(b"ZTxAuthSapliH_v6")
922        .to_state();
923    for spend in bundle.shielded_spends() {
924        h.update(spend.zkproof());
925    }
926    for spend in bundle.shielded_spends() {
927        h.update(&<[u8; 64]>::from(*spend.spend_auth_sig()));
928    }
929    for output in bundle.shielded_outputs() {
930        h.update(output.zkproof());
931    }
932    h.update(&<[u8; 64]>::from(bundle.authorization().binding_sig));
933    h.update(bundle.shielded_spends()[0].anchor().to_repr().as_ref());
934
935    let actual = TransactionDigest::<crate::transaction::Authorized>::digest_sapling(
936        &BlockTxCommitmentDigester,
937        TxVersion::V6,
938        Some(&bundle),
939    );
940
941    assert_eq!(actual, h.finalize());
942}
943
944#[test]
945fn v6_sapling_output_only_auth_digest_uses_v6_domain_without_anchor() {
946    let mut runner = proptest::test_runner::TestRunner::default();
947    let bundle = test_sapling_output_only_bundle(&mut runner);
948
949    let mut h = Params::new()
950        .hash_length(32)
951        .personal(b"ZTxAuthSapliH_v6")
952        .to_state();
953    for output in bundle.shielded_outputs() {
954        h.update(output.zkproof());
955    }
956    h.update(&<[u8; 64]>::from(bundle.authorization().binding_sig));
957
958    let actual = TransactionDigest::<crate::transaction::Authorized>::digest_sapling(
959        &BlockTxCommitmentDigester,
960        TxVersion::V6,
961        Some(&bundle),
962    );
963
964    assert_eq!(actual, h.finalize());
965}
966
967#[test]
968fn v6_orchard_non_anchor_bundle_data_still_changes_txid_and_sighash() {
969    let mut runner = proptest::test_runner::TestRunner::default();
970    let anchor = test_anchor(1);
971
972    let bundle_a = bundle_with_anchor(&test_orchard_bundle(&mut runner), anchor);
973    let bundle_b = bundle_with_anchor(&test_orchard_bundle(&mut runner), anchor);
974    let tx_data_a = v6_tx_data_with_orchard_bundle(bundle_a.clone());
975    let tx_data_b = v6_tx_data_with_orchard_bundle(bundle_b.clone());
976    let tx_a = v6_tx_with_orchard_bundle(bundle_a);
977    let tx_b = v6_tx_with_orchard_bundle(bundle_b);
978
979    assert_ne!(tx_a.txid(), tx_b.txid());
980    assert_ne!(
981        v6_shielded_sighash(&tx_data_a),
982        v6_shielded_sighash(&tx_data_b)
983    );
984    assert_ne!(tx_a.auth_commitment(), tx_b.auth_commitment());
985}
986
987#[cfg(test)]
988fn check_roundtrip(tx: Transaction) -> Result<(), TestCaseError> {
989    let mut txn_bytes = vec![];
990    tx.write(&mut txn_bytes).unwrap();
991    let txo = Transaction::read(&txn_bytes[..], tx.consensus_branch_id).unwrap();
992
993    prop_assert_eq!(tx.version, txo.version);
994    prop_assert_eq!(tx.lock_time, txo.lock_time);
995    prop_assert_eq!(
996        tx.transparent_bundle.as_ref(),
997        txo.transparent_bundle.as_ref()
998    );
999    prop_assert_eq!(tx.sapling_value_balance(), txo.sapling_value_balance());
1000    prop_assert_eq!(
1001        tx.orchard_bundle.as_ref().map(|v| *v.value_balance()),
1002        txo.orchard_bundle.as_ref().map(|v| *v.value_balance())
1003    );
1004    prop_assert_eq!(
1005        tx.ironwood_bundle.as_ref().map(|v| *v.value_balance()),
1006        txo.ironwood_bundle.as_ref().map(|v| *v.value_balance())
1007    );
1008    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1009    if tx.version.has_zip233(tx.consensus_branch_id) {
1010        prop_assert_eq!(tx.zip233_amount, txo.zip233_amount);
1011    }
1012    Ok(())
1013}
1014
1015proptest! {
1016    #[test]
1017    #[cfg(all(feature = "expensive-tests", not(feature = "no-expensive-tests")))]
1018    fn tx_serialization_roundtrip_sprout(tx in arb_tx(BranchId::Sprout)) {
1019        check_roundtrip(tx)?;
1020    }
1021}
1022
1023proptest! {
1024    #[test]
1025    #[cfg(all(feature = "expensive-tests", not(feature = "no-expensive-tests")))]
1026    fn tx_serialization_roundtrip_overwinter(tx in arb_tx(BranchId::Overwinter)) {
1027        check_roundtrip(tx)?;
1028    }
1029}
1030
1031proptest! {
1032    #[test]
1033    #[cfg(all(feature = "expensive-tests", not(feature = "no-expensive-tests")))]
1034    fn tx_serialization_roundtrip_sapling(tx in arb_tx(BranchId::Sapling)) {
1035        check_roundtrip(tx)?;
1036    }
1037}
1038
1039proptest! {
1040    #[test]
1041    #[cfg(all(feature = "expensive-tests", not(feature = "no-expensive-tests")))]
1042    fn tx_serialization_roundtrip_blossom(tx in arb_tx(BranchId::Blossom)) {
1043        check_roundtrip(tx)?;
1044    }
1045}
1046
1047proptest! {
1048    #[test]
1049    #[cfg(all(feature = "expensive-tests", not(feature = "no-expensive-tests")))]
1050    fn tx_serialization_roundtrip_heartwood(tx in arb_tx(BranchId::Heartwood)) {
1051        check_roundtrip(tx)?;
1052    }
1053}
1054
1055proptest! {
1056    #![proptest_config(ProptestConfig::with_cases(10))]
1057    #[test]
1058    fn tx_serialization_roundtrip_canopy(tx in arb_tx(BranchId::Canopy)) {
1059        check_roundtrip(tx)?;
1060    }
1061}
1062
1063proptest! {
1064    #![proptest_config(ProptestConfig::with_cases(10))]
1065    #[test]
1066    fn tx_serialization_roundtrip_nu5(tx in arb_tx(BranchId::Nu5)) {
1067        check_roundtrip(tx)?;
1068    }
1069}
1070
1071proptest! {
1072    #![proptest_config(ProptestConfig::with_cases(10))]
1073    #[test]
1074    fn tx_serialization_roundtrip_nu6_3(tx in arb_tx(BranchId::Nu6_3)) {
1075        check_roundtrip(tx)?;
1076    }
1077}
1078
1079#[cfg(test)]
1080proptest! {
1081    #![proptest_config(ProptestConfig::with_cases(10))]
1082    #[test]
1083    fn tx_serialization_roundtrip_nu7(tx in arb_tx(BranchId::Nu7)) {
1084        check_roundtrip(tx)?;
1085    }
1086}
1087
1088#[cfg(zcash_unstable = "nutachyon")]
1089proptest! {
1090    #![proptest_config(ProptestConfig::with_cases(10))]
1091    #[test]
1092    fn tx_serialization_roundtrip_nu_tachyon(tx in arb_tx(BranchId::NuTachyon)) {
1093        check_roundtrip(tx)?;
1094    }
1095}
1096
1097#[test]
1098fn zip_0143() {
1099    for tv in self::data::zip_0143::make_test_vectors() {
1100        let tx = Transaction::read(&tv.tx[..], tv.consensus_branch_id).unwrap();
1101        let signable_input = match tv.transparent_input {
1102            Some(n) => SignableInput::Transparent(
1103                ::transparent::sighash::SignableInput::from_parts(
1104                    tx.transparent_bundle().unwrap(),
1105                    SighashType::parse(tv.hash_type as u8).unwrap(),
1106                    n as usize,
1107                    &tv.script_code,
1108                    &tv.script_code,
1109                    Zatoshis::from_nonnegative_i64(tv.amount).unwrap(),
1110                )
1111                .unwrap(),
1112            ),
1113            _ => SignableInput::Shielded,
1114        };
1115
1116        assert_eq!(
1117            v4_signature_hash(tx.deref(), &signable_input, &zip143_digests(tx.deref())).as_ref(),
1118            tv.sighash
1119        );
1120
1121        let precomputed =
1122            PrecomputedSighashData::new(with_test_transparent_auth(tx.into_data(), vec![], vec![]));
1123        assert_eq!(
1124            precomputed.signature_hash(&signable_input).as_ref(),
1125            &tv.sighash
1126        );
1127    }
1128}
1129
1130#[test]
1131fn zip_0243() {
1132    for tv in self::data::zip_0243::make_test_vectors() {
1133        let tx = Transaction::read(&tv.tx[..], tv.consensus_branch_id).unwrap();
1134        let signable_input = match tv.transparent_input {
1135            Some(n) => SignableInput::Transparent(
1136                ::transparent::sighash::SignableInput::from_parts(
1137                    tx.transparent_bundle().unwrap(),
1138                    SighashType::parse(tv.hash_type as u8).unwrap(),
1139                    n as usize,
1140                    &tv.script_code,
1141                    &tv.script_code,
1142                    Zatoshis::from_nonnegative_i64(tv.amount).unwrap(),
1143                )
1144                .unwrap(),
1145            ),
1146            _ => SignableInput::Shielded,
1147        };
1148
1149        assert_eq!(
1150            v4_signature_hash(tx.deref(), &signable_input, &zip143_digests(tx.deref())).as_ref(),
1151            tv.sighash
1152        );
1153
1154        let precomputed =
1155            PrecomputedSighashData::new(with_test_transparent_auth(tx.into_data(), vec![], vec![]));
1156        assert_eq!(
1157            precomputed.signature_hash(&signable_input).as_ref(),
1158            &tv.sighash
1159        );
1160    }
1161}
1162
1163#[cfg(test)]
1164#[derive(Debug)]
1165struct TestTransparentAuth {
1166    input_amounts: Vec<Zatoshis>,
1167    input_scriptpubkeys: Vec<Script>,
1168    /// The number of calls to `input_amounts` and `input_scriptpubkeys`.
1169    reads: Cell<usize>,
1170}
1171
1172#[cfg(test)]
1173impl TestTransparentAuth {
1174    fn new(input_amounts: Vec<Zatoshis>, input_scriptpubkeys: Vec<Script>) -> Self {
1175        TestTransparentAuth {
1176            input_amounts,
1177            input_scriptpubkeys,
1178            reads: Cell::new(0),
1179        }
1180    }
1181}
1182
1183/// Returns `txdata` with a transparent authorization that provides `input_amounts` and
1184/// `input_scriptpubkeys` to the signature hash.
1185#[cfg(test)]
1186fn with_test_transparent_auth(
1187    txdata: TransactionData<Authorized>,
1188    input_amounts: Vec<Zatoshis>,
1189    input_scriptpubkeys: Vec<Script>,
1190) -> TransactionData<TestUnauthorized> {
1191    txdata.map_bundles(
1192        |b| {
1193            b.map(|b| transparent::Bundle {
1194                vin: b
1195                    .vin
1196                    .iter()
1197                    .map(|vin| {
1198                        TxIn::from_parts(
1199                            vin.prevout().clone(),
1200                            vin.script_sig().clone(),
1201                            vin.sequence(),
1202                        )
1203                    })
1204                    .collect(),
1205                vout: b.vout,
1206                authorization: TestTransparentAuth::new(input_amounts, input_scriptpubkeys),
1207            })
1208        },
1209        |b| b,
1210        |b| b,
1211    )
1212}
1213
1214#[cfg(test)]
1215impl transparent::Authorization for TestTransparentAuth {
1216    type ScriptSig = Script;
1217}
1218
1219#[cfg(test)]
1220impl TransparentAuthorizingContext<Zatoshis> for TestTransparentAuth {
1221    fn input_amounts(&self) -> Vec<Zatoshis> {
1222        self.reads.set(self.reads.get() + 1);
1223        self.input_amounts.clone()
1224    }
1225
1226    fn input_scriptpubkeys(&self) -> Vec<Script> {
1227        self.reads.set(self.reads.get() + 1);
1228        self.input_scriptpubkeys.clone()
1229    }
1230}
1231
1232#[cfg(test)]
1233struct TestUnauthorized;
1234
1235#[cfg(test)]
1236impl Authorization for TestUnauthorized {
1237    type TransparentAuth = TestTransparentAuth;
1238    type SaplingAuth = sapling::bundle::Authorized;
1239    type OrchardAuth = orchard::bundle::Authorized;
1240}
1241
1242#[test]
1243fn zip_0244() {
1244    fn to_test_txdata(
1245        tv: &self::data::zip_0244::TestVector,
1246    ) -> (
1247        TransactionData<TestUnauthorized>,
1248        Zip244Digests<Blake2bHash>,
1249    ) {
1250        let tx = Transaction::read(&tv.tx[..], BranchId::Nu5).unwrap();
1251
1252        assert_eq!(tx.txid.as_ref(), &tv.txid);
1253        assert_eq!(tx.auth_commitment().as_ref(), &tv.auth_digest);
1254
1255        let txdata = tx.deref();
1256
1257        let input_amounts = tv
1258            .amounts
1259            .iter()
1260            .map(|amount| Zatoshis::from_nonnegative_i64(*amount).unwrap())
1261            .collect();
1262        let input_scriptpubkeys = tv
1263            .script_pubkeys
1264            .iter()
1265            .cloned()
1266            .map(script::Code)
1267            .map(Script)
1268            .collect();
1269
1270        let test_bundle = txdata
1271            .transparent_bundle
1272            .as_ref()
1273            .map(|b| transparent::Bundle {
1274                // we have to do this map/clone to make the types line up, since the
1275                // Authorization::ScriptSig type is bound to transparent::Authorized, and we need
1276                // it to be bound to TestTransparentAuth.
1277                vin: b
1278                    .vin
1279                    .iter()
1280                    .map(|vin| {
1281                        TxIn::from_parts(
1282                            vin.prevout().clone(),
1283                            vin.script_sig().clone(),
1284                            vin.sequence(),
1285                        )
1286                    })
1287                    .collect(),
1288                vout: b.vout.clone(),
1289                authorization: TestTransparentAuth::new(input_amounts, input_scriptpubkeys),
1290            });
1291
1292        #[cfg(not(all(feature = "zip-233", zcash_unstable = "zip233")))]
1293        let tdata = TransactionData::from_parts(
1294            txdata.version(),
1295            txdata.consensus_branch_id(),
1296            txdata.lock_time(),
1297            txdata.expiry_height(),
1298            test_bundle,
1299            txdata.sprout_bundle().cloned(),
1300            txdata.sapling_bundle().cloned(),
1301            txdata.orchard_bundle().cloned(),
1302        );
1303        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1304        let tdata = TransactionData::from_parts_with_zip233(
1305            txdata.version(),
1306            txdata.consensus_branch_id(),
1307            txdata.lock_time(),
1308            txdata.expiry_height(),
1309            txdata.zip233_amount,
1310            test_bundle,
1311            txdata.sprout_bundle().cloned(),
1312            txdata.sapling_bundle().cloned(),
1313            txdata.orchard_bundle().cloned(),
1314        );
1315        (tdata, txdata.digest(TxIdDigester))
1316    }
1317
1318    for tv in self::data::zip_0244::make_test_vectors() {
1319        let (txdata, txid_parts) = to_test_txdata(&tv);
1320        let precomputed = PrecomputedSighashData::new(txdata);
1321        let txdata = precomputed.tx();
1322
1323        // Computes the signature hash both from the precomputed digests and with the input
1324        // digests computed on demand, and checks that the results agree.
1325        let check_sighash = |signable_input: &SignableInput<'_>| {
1326            let sighash = v5_signature_hash(txdata, signable_input, &txid_parts, None);
1327            assert_eq!(
1328                precomputed.signature_hash(signable_input).as_ref(),
1329                sighash.as_bytes()
1330            );
1331            sighash
1332        };
1333
1334        if let Some(index) = tv.transparent_input {
1335            // nIn is a u32, but to actually use it we need a usize.
1336            let index = index as usize;
1337            let bundle = txdata.transparent_bundle().unwrap();
1338            let value = bundle.authorization.input_amounts[index];
1339            let script_pubkey = &bundle.authorization.input_scriptpubkeys[index];
1340            let signable_input = |hash_type| {
1341                SignableInput::Transparent(
1342                    ::transparent::sighash::SignableInput::from_parts(
1343                        bundle,
1344                        hash_type,
1345                        index,
1346                        script_pubkey,
1347                        script_pubkey,
1348                        value,
1349                    )
1350                    .unwrap(),
1351                )
1352            };
1353
1354            assert_eq!(
1355                check_sighash(&signable_input(SighashType::ALL)).as_ref(),
1356                &tv.sighash_all.unwrap()
1357            );
1358
1359            assert_eq!(
1360                check_sighash(&signable_input(SighashType::NONE)).as_ref(),
1361                &tv.sighash_none.unwrap()
1362            );
1363
1364            if index < bundle.vout.len() {
1365                assert_eq!(
1366                    check_sighash(&signable_input(SighashType::SINGLE)).as_ref(),
1367                    &tv.sighash_single.unwrap()
1368                );
1369            } else {
1370                assert_eq!(tv.sighash_single, None);
1371            }
1372
1373            assert_eq!(
1374                check_sighash(&signable_input(SighashType::ALL_ANYONECANPAY)).as_ref(),
1375                &tv.sighash_all_anyone.unwrap()
1376            );
1377
1378            assert_eq!(
1379                check_sighash(&signable_input(SighashType::NONE_ANYONECANPAY)).as_ref(),
1380                &tv.sighash_none_anyone.unwrap()
1381            );
1382
1383            if index < bundle.vout.len() {
1384                assert_eq!(
1385                    check_sighash(&signable_input(SighashType::SINGLE_ANYONECANPAY)).as_ref(),
1386                    &tv.sighash_single_anyone.unwrap()
1387                );
1388            } else {
1389                assert_eq!(tv.sighash_single_anyone, None);
1390            }
1391        };
1392
1393        assert_eq!(
1394            check_sighash(&SignableInput::Shielded).as_ref(),
1395            tv.sighash_shielded
1396        );
1397
1398        // Computing the signature hashes of every input under every hash type reads the
1399        // input amounts and `scriptPubKey`s only once.
1400        let precomputed = PrecomputedSighashData::new(to_test_txdata(&tv).0);
1401        if let Some(bundle) = precomputed
1402            .tx()
1403            .transparent_bundle()
1404            .filter(|b| !is_coinbase(precomputed.tx()) && !b.vin.is_empty())
1405        {
1406            for index in 0..bundle.vin.len() {
1407                for hash_type in [
1408                    SighashType::ALL,
1409                    SighashType::NONE,
1410                    SighashType::SINGLE,
1411                    SighashType::ALL_ANYONECANPAY,
1412                    SighashType::NONE_ANYONECANPAY,
1413                    SighashType::SINGLE_ANYONECANPAY,
1414                ] {
1415                    let script_pubkey = &bundle.authorization.input_scriptpubkeys[index];
1416                    let signable_input = SignableInput::Transparent(
1417                        ::transparent::sighash::SignableInput::from_parts(
1418                            bundle,
1419                            hash_type,
1420                            index,
1421                            script_pubkey,
1422                            script_pubkey,
1423                            bundle.authorization.input_amounts[index],
1424                        )
1425                        .unwrap(),
1426                    );
1427                    precomputed.signature_hash(&signable_input);
1428                }
1429            }
1430            // One call each to `input_amounts` and `input_scriptpubkeys`.
1431            assert_eq!(bundle.authorization.reads.get(), 2);
1432        }
1433    }
1434}
1435
1436#[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1437#[test]
1438#[ignore = "Historical vectors for the withdrawn ZIP 233 v6-header experiment; \
1439            current ZIP 233 requires ZIP 248 value-pool deltas, which are not implemented."]
1440fn zip_0233() {
1441    fn to_test_txdata(
1442        tv: &self::data::zip_0233::TestVector,
1443    ) -> (
1444        TransactionData<TestUnauthorized>,
1445        Zip244Digests<Blake2bHash>,
1446    ) {
1447        let tx = Transaction::read(tv.tx, BranchId::Nu7).unwrap();
1448
1449        assert_eq!(tx.txid.as_ref(), &tv.txid);
1450        assert_eq!(tx.auth_commitment().as_ref(), &tv.auth_digest);
1451
1452        let txdata = tx.deref();
1453
1454        let input_amounts = tv
1455            .amounts
1456            .iter()
1457            .map(|amount| Zatoshis::from_nonnegative_i64(*amount).unwrap())
1458            .collect();
1459        let input_scriptpubkeys = tv
1460            .script_pubkeys
1461            .iter()
1462            .map(|s| Script(script::Code(s.to_vec())))
1463            .collect();
1464
1465        let test_bundle = txdata
1466            .transparent_bundle
1467            .as_ref()
1468            .map(|b| transparent::Bundle {
1469                // we have to do this map/clone to make the types line up, since the
1470                // Authorization::ScriptSig type is bound to transparent::Authorized, and we need
1471                // it to be bound to TestTransparentAuth.
1472                vin: b
1473                    .vin
1474                    .iter()
1475                    .map(|vin| {
1476                        TxIn::from_parts(
1477                            vin.prevout().clone(),
1478                            vin.script_sig().clone(),
1479                            vin.sequence(),
1480                        )
1481                    })
1482                    .collect(),
1483                vout: b.vout.clone(),
1484                authorization: TestTransparentAuth::new(input_amounts, input_scriptpubkeys),
1485            });
1486
1487        let tdata = TransactionData::from_parts_with_zip233(
1488            txdata.version(),
1489            txdata.consensus_branch_id(),
1490            txdata.lock_time(),
1491            txdata.expiry_height(),
1492            txdata.zip233_amount,
1493            test_bundle,
1494            txdata.sprout_bundle().cloned(),
1495            txdata.sapling_bundle().cloned(),
1496            txdata.orchard_bundle().cloned(),
1497        );
1498
1499        (tdata, txdata.digest(TxIdDigester))
1500    }
1501
1502    for tv in self::data::zip_0233::TEST_VECTORS {
1503        let (txdata, txid_parts) = to_test_txdata(tv);
1504
1505        assert_eq!(
1506            v6_signature_hash(&txdata, &SignableInput::Shielded, &txid_parts, None).as_ref(),
1507            tv.sighash_shielded
1508        );
1509    }
1510}