Skip to main content

zebra_chain/transaction/
arbitrary.rs

1//! Arbitrary data generation for transaction proptests
2
3pub mod shielded;
4
5pub use shielded::{
6    fake_bundle_for_branch, fake_orchard_bundle, fake_orchard_bundle_duplicate_nullifiers,
7    fake_orchard_bundle_with_note, fake_v6_transaction, insert_fake_orchard_shielded_data,
8    outputs_enabled_flags, v6_ironwood_flags_offset, v6_orchard_flags_offset,
9    with_garbage_orchard_authorization, with_orchard_flags, with_orchard_value_balance,
10};
11
12use std::{cmp::max, collections::HashMap, ops::Neg, sync::Arc};
13
14use chrono::{TimeZone, Utc};
15use proptest::{array, collection::vec, option, prelude::*};
16use reddsa::{orchard::Binding, Signature};
17
18use crate::{
19    amount::{self, Amount, NegativeAllowed, NonNegative},
20    block::{self, arbitrary::MAX_PARTIAL_CHAIN_BLOCKS},
21    orchard,
22    parameters::{Network, NetworkUpgrade},
23    primitives::{Halo2Proof, ZkSnarkProof},
24    sapling::{self, AnchorVariant, PerSpendAnchor, SharedAnchor},
25    serialization::{self, ZcashDeserializeInto},
26    sprout, transparent,
27    value_balance::{ValueBalance, ValueBalanceError},
28    LedgerState,
29};
30
31use zcash_primitives::transaction::TxVersion;
32use zcash_transparent;
33
34use super::{
35    FieldNotPresent, JoinSplitData, LockTime, Memo, Transaction, UnminedTx, VerifiedUnminedTx,
36};
37
38/// Returns the librustzcash consensus branch ID selected for the test transaction and its bundles.
39fn branch_id_of(network_upgrade: NetworkUpgrade) -> zcash_protocol::consensus::BranchId {
40    network_upgrade
41        .branch_id()
42        .and_then(|cbid| zcash_protocol::consensus::BranchId::try_from(cbid).ok())
43        .expect("the generated transaction upgrade has a supported consensus branch ID")
44}
45
46/// The maximum number of arbitrary transactions, inputs, or outputs.
47///
48/// This size is chosen to provide interesting behaviour, but not be too large
49/// for debugging.
50pub const MAX_ARBITRARY_ITEMS: usize = 4;
51
52// TODO: if needed, fixup transaction outputs
53//       (currently 0..=9 outputs, consensus rules require 1..)
54// V1 and V2 always get an output, so blocks of them pass the block transaction size check.
55impl Transaction {
56    /// Generate a proptest strategy for V1 Transactions
57    pub fn v1_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
58        (
59            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
60            vec(any::<transparent::Output>(), 1..MAX_ARBITRARY_ITEMS),
61            any::<LockTime>(),
62        )
63            .prop_map(|(inputs, outputs, lock_time)| {
64                Transaction::test_v1(inputs, outputs, lock_time)
65            })
66            .boxed()
67    }
68
69    /// Generate a proptest strategy for V2 Transactions
70    ///
71    /// Note: the new Transaction type doesn't support arbitrary Sprout JoinSplit data
72    /// in proptest strategies, so this generates transparent-only V2 transactions.
73    pub fn v2_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
74        (
75            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
76            vec(any::<transparent::Output>(), 1..MAX_ARBITRARY_ITEMS),
77            any::<LockTime>(),
78        )
79            .prop_map(|(inputs, outputs, lock_time)| {
80                Transaction::test_v2(inputs, outputs, lock_time)
81            })
82            .boxed()
83    }
84
85    /// Generate a proptest strategy for V3 Transactions
86    ///
87    /// Note: the new Transaction type doesn't support arbitrary Sprout JoinSplit data
88    /// in proptest strategies, so this generates transparent-only V3 transactions.
89    pub fn v3_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
90        (
91            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
92            vec(any::<transparent::Output>(), 0..MAX_ARBITRARY_ITEMS),
93            any::<LockTime>(),
94            any::<block::Height>(),
95        )
96            .prop_map(|(inputs, outputs, lock_time, expiry_height)| {
97                Transaction::test_v3(inputs, outputs, lock_time, expiry_height)
98            })
99            .boxed()
100    }
101
102    /// Generate a proptest strategy for V4 Transactions
103    ///
104    /// Note: the new Transaction type doesn't support arbitrary Sapling/Sprout shielded
105    /// data in proptest strategies, so this generates transparent-only V4 transactions.
106    pub fn v4_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
107        (
108            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
109            vec(any::<transparent::Output>(), 0..MAX_ARBITRARY_ITEMS),
110            any::<LockTime>(),
111            any::<block::Height>(),
112        )
113            .prop_map(|(inputs, outputs, lock_time, expiry_height)| {
114                Transaction::test_v4(inputs, outputs, lock_time, expiry_height)
115            })
116            .boxed()
117    }
118
119    /// Generate a proptest strategy for V5 Transactions
120    ///
121    /// Note: the new Transaction type doesn't support arbitrary Sapling/Orchard shielded
122    /// data in proptest strategies, so this generates transparent-only V5 transactions.
123    pub fn v5_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
124        (
125            NetworkUpgrade::nu5_branch_id_strategy(),
126            any::<LockTime>(),
127            any::<block::Height>(),
128            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
129            vec(any::<transparent::Output>(), 0..MAX_ARBITRARY_ITEMS),
130            option::of((1usize..=2usize, any::<u64>())),
131        )
132            .prop_map(
133                move |(network_upgrade, lock_time, expiry_height, inputs, outputs, orchard)| {
134                    let nu = if ledger_state.transaction_has_valid_network_upgrade() {
135                        // Use the ledger's network upgrade if it has a consensus branch ID
136                        // (V5 transactions can only embed known branch IDs).
137                        let ledger_nu = ledger_state.network_upgrade();
138                        if ledger_nu.branch_id().is_some() {
139                            ledger_nu
140                        } else {
141                            network_upgrade
142                        }
143                    } else {
144                        network_upgrade
145                    };
146
147                    // The genesis block must not contain any shielded data.
148                    let orchard_bundle = (!ledger_state.height.is_min())
149                        .then_some(orchard)
150                        .flatten()
151                        .and_then(|(n_actions, seed)| {
152                            shielded::fake_bundle_for_branch(
153                                branch_id_of(nu),
154                                ::orchard::ValuePool::Orchard,
155                                n_actions,
156                                seed,
157                            )
158                        });
159
160                    Transaction::test_v5_with_orchard(
161                        nu,
162                        inputs,
163                        outputs,
164                        lock_time,
165                        expiry_height,
166                        orchard_bundle,
167                    )
168                },
169            )
170            .boxed()
171    }
172
173    /// Generate a proptest strategy for V6 Transactions
174    ///
175    /// Note: like [`Self::v5_strategy`], the new Transaction type doesn't support arbitrary
176    /// shielded data in proptest strategies, so this generates transparent-only V6 transactions.
177    pub fn v6_strategy(ledger_state: LedgerState) -> BoxedStrategy<Self> {
178        (
179            NetworkUpgrade::nu6_3_branch_id_strategy(),
180            any::<LockTime>(),
181            any::<block::Height>(),
182            transparent::Input::vec_strategy(&ledger_state, MAX_ARBITRARY_ITEMS),
183            vec(any::<transparent::Output>(), 0..MAX_ARBITRARY_ITEMS),
184            option::of((1usize..=2usize, any::<u64>())),
185            option::of((1usize..=2usize, any::<u64>())),
186        )
187            .prop_map(
188                move |(
189                    network_upgrade,
190                    lock_time,
191                    expiry_height,
192                    inputs,
193                    outputs,
194                    orchard,
195                    ironwood,
196                )| {
197                    let nu = if ledger_state.transaction_has_valid_network_upgrade() {
198                        let ledger_nu = ledger_state.network_upgrade();
199                        if ledger_nu.branch_id().is_some() {
200                            ledger_nu
201                        } else {
202                            network_upgrade
203                        }
204                    } else {
205                        network_upgrade
206                    };
207
208                    // The genesis block must not contain any shielded data.
209                    let is_genesis = ledger_state.height.is_min();
210
211                    let orchard_bundle =
212                        (!is_genesis)
213                            .then_some(orchard)
214                            .flatten()
215                            .and_then(|(n_actions, seed)| {
216                                shielded::fake_bundle_for_branch(
217                                    branch_id_of(nu),
218                                    ::orchard::ValuePool::Orchard,
219                                    n_actions,
220                                    seed,
221                                )
222                            });
223
224                    // Offset the Ironwood seeds so the two pools in one transaction never share
225                    // nullifiers (they are disjoint sets, but the tests read more clearly when
226                    // the generated values differ too).
227                    let ironwood_bundle = (!is_genesis).then_some(ironwood).flatten().and_then(
228                        |(n_actions, seed)| {
229                            shielded::fake_bundle_for_branch(
230                                branch_id_of(nu),
231                                ::orchard::ValuePool::Ironwood,
232                                n_actions,
233                                seed ^ 0xEEEE_0000_u64,
234                            )
235                        },
236                    );
237
238                    Transaction::test_v6_with_bundles(
239                        nu,
240                        inputs,
241                        outputs,
242                        lock_time,
243                        expiry_height,
244                        orchard_bundle,
245                        ironwood_bundle,
246                    )
247                },
248            )
249            .boxed()
250    }
251
252    /// Proptest Strategy for creating a Vector of transactions where the first
253    /// transaction is always the only coinbase transaction
254    pub fn vec_strategy(
255        mut ledger_state: LedgerState,
256        len: usize,
257    ) -> BoxedStrategy<Vec<Arc<Self>>> {
258        // TODO: fixup coinbase miner subsidy
259        let coinbase = Transaction::arbitrary_with(ledger_state.clone()).prop_map(Arc::new);
260        ledger_state.has_coinbase = false;
261        let remainder = vec(
262            Transaction::arbitrary_with(ledger_state).prop_map(Arc::new),
263            0..=len,
264        );
265
266        (coinbase, remainder)
267            .prop_map(|(first, mut remainder)| {
268                remainder.insert(0, first);
269                remainder
270            })
271            .boxed()
272    }
273
274    /// Apply `f` to the transparent output values in this transaction.
275    ///
276    /// Note: Sprout/sapling/orchard value mutations are not supported with
277    /// the new Transaction type (proptest strategies generate transparent-only txs).
278    pub fn for_each_value_mut<F>(&mut self, mut f: F)
279    where
280        F: FnMut(&mut Amount<NonNegative>),
281    {
282        let mut outputs = self.outputs();
283        let mut changed = false;
284        for output in &mut outputs {
285            let old = output.value;
286            f(&mut output.value);
287            if output.value != old {
288                changed = true;
289            }
290        }
291        if changed {
292            *self = self.clone().with_transparent_outputs(outputs);
293        }
294    }
295
296    /// Apply `f` to the sapling value balance and orchard value balance.
297    ///
298    /// Note: Not implemented for the new Transaction type since proptest strategies
299    /// generate transparent-only transactions. This is a no-op.
300    pub fn for_each_value_balance_mut<F>(&mut self, _f: F)
301    where
302        F: FnMut(&mut Amount<NegativeAllowed>),
303    {
304        // The shielded bundles our strategies build always have a zero value balance
305        // (see `shielded::fake_bundle_for_branch`), so there is nothing to scale.
306        // If a strategy ever generates a non-zero one, this must rebuild the bundle:
307        // `zcash_primitives` bundles are immutable, so there is no value balance to take
308        // a `&mut` to.
309    }
310
311    /// Fixup transparent values and shielded value balances,
312    /// so that transaction and chain value pools won't overflow MAX_MONEY.
313    ///
314    /// These fixes are applied to coinbase and non-coinbase transactions.
315    //
316    // TODO: do we want to allow overflow, based on an arbitrary bool?
317    pub fn fix_overflow(&mut self) {
318        fn scale_to_avoid_overflow<C: amount::Constraint>(amount: &mut Amount<C>)
319        where
320            Amount<C>: Copy,
321        {
322            // transparent, sprout, sapling, orchard, and ironwood
323            const POOL_COUNT: u64 = 5;
324
325            let max_arbitrary_items: u64 = MAX_ARBITRARY_ITEMS.try_into().unwrap();
326            let max_partial_chain_blocks: u64 = MAX_PARTIAL_CHAIN_BLOCKS.try_into().unwrap();
327
328            // inputs/joinsplits/spends|outputs/actions * pools * transactions
329            let transaction_pool_scaling_divisor =
330                max_arbitrary_items * POOL_COUNT * max_arbitrary_items;
331            // inputs/joinsplits/spends|outputs/actions * transactions * blocks
332            let chain_pool_scaling_divisor =
333                max_arbitrary_items * max_arbitrary_items * max_partial_chain_blocks;
334            let scaling_divisor = max(transaction_pool_scaling_divisor, chain_pool_scaling_divisor);
335
336            *amount = (*amount / scaling_divisor).expect("divisor is not zero");
337        }
338
339        self.for_each_value_mut(scale_to_avoid_overflow);
340        // Shielded value balances are zero in proptest transactions, no fixup needed.
341    }
342
343    /// Fixup transparent values and shielded value balances,
344    /// so that this transaction passes the "non-negative chain value pool" checks.
345    /// (These checks use the sum of unspent outputs for each transparent and shielded pool.)
346    ///
347    /// These fixes are applied to coinbase and non-coinbase transactions.
348    ///
349    /// `chain_value_pools` contains the chain value pool balances,
350    /// as of the previous transaction in this block
351    /// (or the last transaction in the previous block).
352    ///
353    /// `outputs` must contain all the [`transparent::Output`]s spent in this transaction.
354    ///
355    /// Currently, these fixes almost always leave some remaining value in each transparent
356    /// and shielded chain value pool.
357    ///
358    /// Before fixing the chain value balances, this method calls `fix_overflow`
359    /// to make sure that transaction and chain value pools don't overflow MAX_MONEY.
360    ///
361    /// After fixing the chain value balances, this method calls `fix_remaining_value`
362    /// to fix the remaining value in the transaction value pool.
363    ///
364    /// Returns the remaining transaction value, and the updated chain value balances.
365    ///
366    /// # Panics
367    ///
368    /// If any spent [`transparent::Output`] is missing from
369    /// [`transparent::OutPoint`]s.
370    //
371    // TODO: take some extra arbitrary flags, which select between zero and non-zero
372    //       remaining value in each chain value pool
373    pub fn fix_chain_value_pools(
374        &mut self,
375        chain_value_pools: ValueBalance<NonNegative>,
376        outputs: &HashMap<transparent::OutPoint, transparent::Output>,
377    ) -> Result<(Amount<NonNegative>, ValueBalance<NonNegative>), ValueBalanceError> {
378        self.fix_overflow();
379
380        // a temporary value used to check that inputs don't break the chain value balance
381        // consensus rules
382        let mut input_chain_value_pools = chain_value_pools;
383
384        for input in self.inputs() {
385            input_chain_value_pools = input_chain_value_pools
386                .add_transparent_input(input, outputs)
387                .expect("find_valid_utxo_for_spend only spends unspent transparent outputs");
388        }
389
390        // update the input chain value pools,
391        // zeroing any inputs that would exceed the input value
392        //
393        // Note: Sprout, Sapling, Orchard, and Ironwood pool mutations are skipped here
394        // because proptest strategies generate transparent-only transactions.
395        // Those value balances are always zero and never exceed the chain pool.
396
397        let remaining_transaction_value = self.fix_remaining_value(outputs)?;
398
399        // check our calculations are correct
400        let transaction_chain_value_pool_change =
401            self
402            .transparent_value_balance_from_outputs(outputs)
403            .expect("chain value pool and remaining transaction value fixes produce valid transaction value balances")
404            .neg();
405
406        let chain_value_pools = chain_value_pools
407            .add_transaction(self, outputs)
408            .unwrap_or_else(|err| {
409                panic!(
410                    "unexpected chain value pool error: {err:?}, \n\
411                     original chain value pools: {chain_value_pools:?}, \n\
412                     transaction chain value change: {transaction_chain_value_pool_change:?}, \n\
413                     input-only transaction chain value pools: {input_chain_value_pools:?}, \n\
414                     calculated remaining transaction value: {remaining_transaction_value:?}",
415                )
416            });
417
418        Ok((remaining_transaction_value, chain_value_pools))
419    }
420
421    /// Returns the total input value of this transaction's value pool.
422    ///
423    /// This is the sum of transparent inputs, sprout input values,
424    /// and if positive, the sapling, orchard, and ironwood value balances.
425    ///
426    /// `outputs` must contain all the [`transparent::Output`]s spent in this transaction.
427    fn input_value_pool(
428        &self,
429        outputs: &HashMap<transparent::OutPoint, transparent::Output>,
430    ) -> Result<Amount<NonNegative>, ValueBalanceError> {
431        let transparent_inputs = self
432            .inputs()
433            .iter()
434            .map(|input| input.value_from_outputs(outputs))
435            .sum::<Result<Amount<NonNegative>, amount::Error>>()
436            .map_err(ValueBalanceError::Transparent)?;
437        // TODO: fix callers which cause overflows, check for:
438        //       cached `outputs` that don't go through `fix_overflow`, and
439        //       values much larger than MAX_MONEY
440        //.expect("chain is limited to MAX_MONEY");
441
442        // Proptest transactions don't have Sprout joinsplits, so sprout_inputs is always zero.
443        let sprout_inputs = Amount::<NonNegative>::zero();
444
445        // positive value balances add to the transaction value pool
446        let sapling_input = self
447            .sapling_value_balance()
448            .sapling_amount()
449            .constrain::<NonNegative>()
450            .unwrap_or_else(|_| Amount::zero());
451
452        let orchard_input = self
453            .orchard_value_balance()
454            .orchard_amount()
455            .constrain::<NonNegative>()
456            .unwrap_or_else(|_| Amount::zero());
457
458        let ironwood_input = self
459            .ironwood_value_balance()
460            .ironwood_amount()
461            .constrain::<NonNegative>()
462            .unwrap_or_else(|_| Amount::zero());
463
464        let transaction_input_value_pool =
465            (transparent_inputs + sprout_inputs + sapling_input + orchard_input + ironwood_input)
466                .expect("chain is limited to MAX_MONEY");
467
468        Ok(transaction_input_value_pool)
469    }
470
471    /// Fixup non-coinbase transparent values and shielded value balances,
472    /// so that this transaction passes the "non-negative remaining transaction value"
473    /// check. (This check uses the sum of inputs minus outputs.)
474    ///
475    /// Returns the remaining transaction value.
476    ///
477    /// `outputs` must contain all the [`transparent::Output`]s spent in this transaction.
478    ///
479    /// Currently, these fixes almost always leave some remaining value in the
480    /// transaction value pool.
481    ///
482    /// # Panics
483    ///
484    /// If any spent [`transparent::Output`] is missing from
485    /// [`transparent::OutPoint`]s.
486    //
487    // TODO: split this method up, after we've implemented chain value balance adjustments
488    //
489    // TODO: take an extra arbitrary bool, which selects between zero and non-zero
490    //       remaining value in the transaction value pool
491    pub fn fix_remaining_value(
492        &mut self,
493        outputs: &HashMap<transparent::OutPoint, transparent::Output>,
494    ) -> Result<Amount<NonNegative>, ValueBalanceError> {
495        if self.is_coinbase() {
496            // TODO: if needed, fixup coinbase:
497            // - miner subsidy
498            // - founders reward or funding streams (hopefully not?)
499            // - remaining transaction value
500
501            // Act as if the generated test case spends all the miner subsidy, miner fees, and
502            // founders reward / funding stream correctly.
503            return Ok(Amount::zero());
504        }
505
506        let mut remaining_input_value = self.input_value_pool(outputs)?;
507
508        // assign remaining input value to outputs,
509        // zeroing any outputs that would exceed the input value
510        let mut tx_outputs = self.outputs();
511        let mut outputs_changed = false;
512        for output in &mut tx_outputs {
513            if remaining_input_value >= output.value {
514                remaining_input_value = (remaining_input_value - output.value)
515                    .expect("input >= output so result is always non-negative");
516            } else {
517                output.value = Amount::zero();
518                outputs_changed = true;
519            }
520        }
521        if outputs_changed {
522            *self = self.clone().with_transparent_outputs(tx_outputs);
523        }
524
525        // Sprout, Sapling, Orchard, and Ironwood output values are zero in proptest
526        // transactions, so there is nothing to fix up for the shielded pools.
527
528        // check our calculations are correct
529        let remaining_transaction_value = self
530            .transparent_value_balance_from_outputs(outputs)
531            .expect("chain is limited to MAX_MONEY")
532            .remaining_transaction_value()
533            .unwrap_or_else(|err| {
534                panic!(
535                    "unexpected remaining transaction value: {err:?}, \
536                     calculated remaining input value: {remaining_input_value:?}"
537                )
538            });
539        assert_eq!(
540            remaining_input_value,
541            remaining_transaction_value,
542            "fix_remaining_value and remaining_transaction_value calculated different remaining values"
543        );
544
545        Ok(remaining_transaction_value)
546    }
547}
548
549impl Arbitrary for Memo {
550    type Parameters = ();
551
552    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
553        (vec(any::<u8>(), 512))
554            .prop_map(|v| {
555                let mut bytes = [0; 512];
556                bytes.copy_from_slice(v.as_slice());
557                Memo(Box::new(bytes))
558            })
559            .boxed()
560    }
561
562    type Strategy = BoxedStrategy<Self>;
563}
564
565/// Generates arbitrary [`LockTime`]s.
566impl Arbitrary for LockTime {
567    type Parameters = ();
568
569    fn arbitrary_with(_args: ()) -> Self::Strategy {
570        prop_oneof![
571            (block::Height::MIN.0..=LockTime::MAX_HEIGHT.0)
572                .prop_map(|n| LockTime::Height(block::Height(n))),
573            (LockTime::MIN_TIMESTAMP..=LockTime::MAX_TIMESTAMP).prop_map(|n| {
574                LockTime::Time(
575                    Utc.timestamp_opt(n, 0)
576                        .single()
577                        .expect("in-range number of seconds and valid nanosecond"),
578                )
579            })
580        ]
581        .boxed()
582    }
583
584    type Strategy = BoxedStrategy<Self>;
585}
586
587impl<P: ZkSnarkProof + Arbitrary + 'static> Arbitrary for JoinSplitData<P> {
588    type Parameters = ();
589
590    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
591        (
592            any::<sprout::JoinSplit<P>>(),
593            vec(any::<sprout::JoinSplit<P>>(), 0..MAX_ARBITRARY_ITEMS),
594            array::uniform32(any::<u8>()),
595            vec(any::<u8>(), 64),
596        )
597            .prop_map(|(first, rest, pub_key_bytes, sig_bytes)| Self {
598                first,
599                rest,
600                pub_key: ed25519_zebra::VerificationKeyBytes::from(pub_key_bytes),
601                sig: ed25519_zebra::Signature::from({
602                    let mut b = [0u8; 64];
603                    b.copy_from_slice(sig_bytes.as_slice());
604                    b
605                }),
606            })
607            .boxed()
608    }
609
610    type Strategy = BoxedStrategy<Self>;
611}
612
613impl<AnchorV> Arbitrary for sapling::ShieldedData<AnchorV>
614where
615    AnchorV: AnchorVariant + Clone + std::fmt::Debug + 'static,
616    sapling::TransferData<AnchorV>: Arbitrary,
617{
618    type Parameters = ();
619
620    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
621        (
622            any::<Amount>(),
623            any::<sapling::TransferData<AnchorV>>(),
624            vec(any::<u8>(), 64),
625        )
626            .prop_map(|(value_balance, transfers, sig_bytes)| Self {
627                value_balance,
628                transfers,
629                binding_sig: redjubjub::Signature::from({
630                    let mut b = [0u8; 64];
631                    b.copy_from_slice(sig_bytes.as_slice());
632                    b
633                }),
634            })
635            .boxed()
636    }
637
638    type Strategy = BoxedStrategy<Self>;
639}
640
641impl Arbitrary for sapling::TransferData<PerSpendAnchor> {
642    type Parameters = ();
643
644    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
645        vec(any::<sapling::Output>(), 0..MAX_ARBITRARY_ITEMS)
646            .prop_flat_map(|outputs| {
647                (
648                    if outputs.is_empty() {
649                        // must have at least one spend or output
650                        vec(
651                            any::<sapling::Spend<PerSpendAnchor>>(),
652                            1..MAX_ARBITRARY_ITEMS,
653                        )
654                    } else {
655                        vec(
656                            any::<sapling::Spend<PerSpendAnchor>>(),
657                            0..MAX_ARBITRARY_ITEMS,
658                        )
659                    },
660                    Just(outputs),
661                )
662            })
663            .prop_map(|(spends, outputs)| {
664                if !spends.is_empty() {
665                    sapling::TransferData::SpendsAndMaybeOutputs {
666                        shared_anchor: FieldNotPresent,
667                        spends: spends.try_into().unwrap(),
668                        maybe_outputs: outputs,
669                    }
670                } else if !outputs.is_empty() {
671                    sapling::TransferData::JustOutputs {
672                        outputs: outputs.try_into().unwrap(),
673                    }
674                } else {
675                    unreachable!("there must be at least one generated spend or output")
676                }
677            })
678            .boxed()
679    }
680
681    type Strategy = BoxedStrategy<Self>;
682}
683
684impl Arbitrary for sapling::TransferData<SharedAnchor> {
685    type Parameters = ();
686
687    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
688        vec(any::<sapling::Output>(), 0..MAX_ARBITRARY_ITEMS)
689            .prop_flat_map(|outputs| {
690                (
691                    any::<sapling::tree::Root>(),
692                    if outputs.is_empty() {
693                        // must have at least one spend or output
694                        vec(
695                            any::<sapling::Spend<SharedAnchor>>(),
696                            1..MAX_ARBITRARY_ITEMS,
697                        )
698                    } else {
699                        vec(
700                            any::<sapling::Spend<SharedAnchor>>(),
701                            0..MAX_ARBITRARY_ITEMS,
702                        )
703                    },
704                    Just(outputs),
705                )
706            })
707            .prop_map(|(shared_anchor, spends, outputs)| {
708                if !spends.is_empty() {
709                    sapling::TransferData::SpendsAndMaybeOutputs {
710                        shared_anchor,
711                        spends: spends.try_into().unwrap(),
712                        maybe_outputs: outputs,
713                    }
714                } else if !outputs.is_empty() {
715                    sapling::TransferData::JustOutputs {
716                        outputs: outputs.try_into().unwrap(),
717                    }
718                } else {
719                    unreachable!("there must be at least one generated spend or output")
720                }
721            })
722            .boxed()
723    }
724
725    type Strategy = BoxedStrategy<Self>;
726}
727
728impl Arbitrary for orchard::ShieldedData {
729    type Parameters = ();
730
731    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
732        (
733            any::<orchard::shielded_data::Flags>(),
734            any::<Amount>(),
735            any::<orchard::tree::Root>(),
736            vec(
737                any::<orchard::shielded_data::AuthorizedAction>(),
738                1..MAX_ARBITRARY_ITEMS,
739            ),
740            any::<BindingSignature>(),
741        )
742            .prop_flat_map(
743                |(flags, value_balance, shared_anchor, actions, binding_sig)| {
744                    // Since NU6.2, an Orchard proof must have the canonical length for its number of
745                    // actions (`2272 * num_actions + 2720` bytes), otherwise it is rejected as
746                    // non-canonical (GHSA-jfw5-j458-pfv6). The V5 txid is computed by round-tripping
747                    // through `librustzcash`, which enforces this length, so a proof of any other
748                    // size makes the round-trip (and thus `Transaction::hash`) fail. Generate a proof
749                    // of exactly the expected length, which depends on the number of actions.
750                    let proof_size = orchard::shielded_data::expected_proof_size(actions.len());
751                    (
752                        Just(flags),
753                        Just(value_balance),
754                        Just(shared_anchor),
755                        vec(any::<u8>(), proof_size).prop_map(Halo2Proof),
756                        Just(actions),
757                        Just(binding_sig),
758                    )
759                },
760            )
761            .prop_map(
762                |(flags, value_balance, shared_anchor, proof, actions, binding_sig)| Self {
763                    flags,
764                    value_balance,
765                    shared_anchor,
766                    proof,
767                    actions: actions
768                        .try_into()
769                        .expect("arbitrary vector size range produces at least one action"),
770                    binding_sig: binding_sig.0,
771                },
772            )
773            .boxed()
774    }
775
776    type Strategy = BoxedStrategy<Self>;
777}
778
779impl Arbitrary for orchard::ShieldedDataV6 {
780    type Parameters = ();
781
782    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
783        // The v6 Orchard-pool bundle reserves `enableCrossAddress` exactly like v5, so the base
784        // `ShieldedData` strategy (which only generates the pre-NU6.3 flag bits) is reused as-is.
785        // Only the Ironwood bundle permits that flag; see the `ironwood::ShieldedData` strategy.
786        any::<orchard::ShieldedData>()
787            .prop_map(orchard::ShieldedDataV6::new)
788            .boxed()
789    }
790
791    type Strategy = BoxedStrategy<Self>;
792}
793
794#[derive(Copy, Clone, Debug, Eq, PartialEq)]
795struct BindingSignature(pub(crate) Signature<Binding>);
796
797impl Arbitrary for BindingSignature {
798    type Parameters = ();
799
800    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
801        (vec(any::<u8>(), 64))
802            .prop_filter_map(
803                "zero Signature::<Binding> values are invalid",
804                |sig_bytes| {
805                    let mut b = [0u8; 64];
806                    b.copy_from_slice(sig_bytes.as_slice());
807                    if b == [0u8; 64] {
808                        return None;
809                    }
810                    Some(BindingSignature(Signature::<Binding>::from(b)))
811                },
812            )
813            .boxed()
814    }
815
816    type Strategy = BoxedStrategy<Self>;
817}
818
819impl Arbitrary for Transaction {
820    type Parameters = LedgerState;
821
822    fn arbitrary_with(ledger_state: Self::Parameters) -> Self::Strategy {
823        match ledger_state.transaction_version_override() {
824            Some(1) => return Self::v1_strategy(ledger_state),
825            Some(2) => return Self::v2_strategy(ledger_state),
826            Some(3) => return Self::v3_strategy(ledger_state),
827            Some(4) => return Self::v4_strategy(ledger_state),
828            Some(5) => return Self::v5_strategy(ledger_state),
829            Some(6) => return Self::v6_strategy(ledger_state),
830            Some(_) => unreachable!("invalid transaction version in override"),
831            None => {}
832        }
833
834        match ledger_state.network_upgrade() {
835            NetworkUpgrade::Genesis | NetworkUpgrade::BeforeOverwinter => {
836                Self::v1_strategy(ledger_state)
837            }
838            NetworkUpgrade::Overwinter => Self::v2_strategy(ledger_state),
839            NetworkUpgrade::Sapling => Self::v3_strategy(ledger_state),
840            NetworkUpgrade::Blossom | NetworkUpgrade::Heartwood | NetworkUpgrade::Canopy => {
841                Self::v4_strategy(ledger_state)
842            }
843            NetworkUpgrade::Nu5
844            | NetworkUpgrade::Nu6
845            | NetworkUpgrade::Nu6_1
846            | NetworkUpgrade::Nu6_2 => prop_oneof![
847                Self::v4_strategy(ledger_state.clone()),
848                Self::v5_strategy(ledger_state)
849            ]
850            .boxed(),
851
852            // V6 transactions are only valid from NU6.3; v4 and v5 remain valid alongside them.
853            NetworkUpgrade::Nu6_3 => prop_oneof![
854                Self::v4_strategy(ledger_state.clone()),
855                Self::v5_strategy(ledger_state.clone()),
856                Self::v6_strategy(ledger_state)
857            ]
858            .boxed(),
859            // ZIP 2003 removes V4 from NU7 onward.
860            NetworkUpgrade::Nu7 => prop_oneof![
861                Self::v5_strategy(ledger_state.clone()),
862                Self::v6_strategy(ledger_state)
863            ]
864            .boxed(),
865
866            #[cfg(zcash_unstable = "zfuture")]
867            NetworkUpgrade::ZFuture => prop_oneof![
868                Self::v4_strategy(ledger_state.clone()),
869                Self::v5_strategy(ledger_state)
870            ]
871            .boxed(),
872        }
873    }
874
875    type Strategy = BoxedStrategy<Self>;
876}
877
878impl Arbitrary for UnminedTx {
879    type Parameters = ();
880
881    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
882        any::<Transaction>()
883            .prop_map(|tx| UnminedTx::from(Arc::new(tx)))
884            .boxed()
885    }
886
887    type Strategy = BoxedStrategy<Self>;
888}
889
890impl Arbitrary for VerifiedUnminedTx {
891    type Parameters = ();
892
893    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
894        (
895            any::<UnminedTx>(),
896            any::<Amount<NonNegative>>(),
897            any::<u32>(),
898            any::<u32>(),
899            any::<(u16, u16)>().prop_map(|(unpaid_actions, conventional_actions)| {
900                (
901                    unpaid_actions % conventional_actions.saturating_add(1),
902                    conventional_actions,
903                )
904            }),
905            any::<f32>(),
906            serialization::arbitrary::datetime_u32(),
907            any::<block::Height>(),
908        )
909            .prop_map(
910                |(
911                    transaction,
912                    miner_fee,
913                    sigops,
914                    p2sh_sigops,
915                    (conventional_actions, mut unpaid_actions),
916                    fee_weight_ratio,
917                    time,
918                    height,
919                )| {
920                    if unpaid_actions > conventional_actions {
921                        unpaid_actions = conventional_actions;
922                    }
923
924                    let conventional_actions = conventional_actions as u32;
925                    let unpaid_actions = unpaid_actions as u32;
926
927                    Self {
928                        transaction,
929                        miner_fee,
930                        legacy_sigop_count: sigops,
931                        p2sh_sigop_count: p2sh_sigops,
932                        conventional_actions,
933                        unpaid_actions,
934                        fee_weight_ratio,
935                        time: Some(time),
936                        height: Some(height),
937                        spent_outputs: std::sync::Arc::new(vec![]),
938                    }
939                },
940            )
941            .boxed()
942    }
943    type Strategy = BoxedStrategy<Self>;
944}
945
946// Utility functions
947
948/// Convert `trans` into a fake v5 transaction.
949///
950/// Takes the transparent inputs/outputs from `trans` and builds a new V5
951/// transaction at the given height. Used to test V5 sighash/serialization
952/// with real transparent data from the test vector blocks.
953pub fn transaction_to_fake_v5(
954    trans: &Transaction,
955    network: &Network,
956    height: block::Height,
957) -> Transaction {
958    let block_nu = NetworkUpgrade::current(network, height);
959
960    match trans.tx_version() {
961        // V5+ already in the right format; just clone
962        TxVersion::V5 | TxVersion::V6 => trans.clone(),
963        // For V1-V4: build a V5 with the same transparent data
964        _ => {
965            use crate::transaction::compat;
966            use zcash_primitives::transaction::{self as zp_tx, TxVersion};
967            use zcash_protocol::consensus::BranchId;
968
969            let branch_id = block_nu
970                .branch_id()
971                .map(|id| BranchId::try_from(id).expect("known branch IDs are supported"))
972                .unwrap_or(BranchId::Nu5);
973
974            let inputs = trans.inputs();
975            let outputs = trans.outputs();
976            let vin = inputs.iter().map(compat::input_to_txin).collect();
977            let vout = outputs.iter().map(compat::output_to_txout).collect();
978
979            let lock_time_u32 =
980                compat::lock_time_to_u32(&trans.lock_time().unwrap_or(LockTime::unlocked()));
981
982            let transparent_bundle = Some(zcash_transparent::bundle::Bundle {
983                vin,
984                vout,
985                authorization: zcash_transparent::bundle::Authorized,
986            });
987
988            // For V4, carry over the sapling bundle (already in zcash_primitives format)
989            let sapling_bundle = trans.0.sapling_bundle().cloned();
990
991            let tx_data = zp_tx::TransactionData::from_parts(
992                TxVersion::V5,
993                branch_id,
994                lock_time_u32,
995                zcash_protocol::consensus::BlockHeight::from_u32(height.0),
996                transparent_bundle,
997                None,
998                sapling_bundle,
999                None,
1000            );
1001
1002            Transaction(tx_data.freeze().expect("rebuilt from valid transaction"))
1003        }
1004    }
1005}
1006
1007/// Iterate over transactions in the block test vectors for the specified `network`.
1008pub fn test_transactions(
1009    network: &Network,
1010) -> impl DoubleEndedIterator<Item = (block::Height, Arc<Transaction>)> {
1011    let blocks = network.block_iter();
1012
1013    transactions_from_blocks(blocks)
1014}
1015
1016/// Returns an iterator over V5 transactions extracted from the given blocks.
1017pub fn v5_transactions<'b>(
1018    blocks: impl DoubleEndedIterator<Item = (&'b u32, &'b &'static [u8])> + 'b,
1019) -> impl DoubleEndedIterator<Item = Transaction> + 'b {
1020    transactions_from_blocks(blocks).filter_map(|(_, tx)| match tx.tx_version() {
1021        TxVersion::V5 | TxVersion::V6 => Some((*tx).clone()),
1022        _ => None,
1023    })
1024}
1025
1026/// Generate an iterator over ([`block::Height`], [`Arc<Transaction>`]).
1027pub fn transactions_from_blocks<'a>(
1028    blocks: impl DoubleEndedIterator<Item = (&'a u32, &'a &'static [u8])> + 'a,
1029) -> impl DoubleEndedIterator<Item = (block::Height, Arc<Transaction>)> + 'a {
1030    blocks.flat_map(|(&block_height, &block_bytes)| {
1031        let block = block_bytes
1032            .zcash_deserialize_into::<block::Block>()
1033            .expect("block is structurally valid");
1034
1035        block
1036            .transactions
1037            .into_iter()
1038            .map(move |transaction| (block::Height(block_height), transaction))
1039    })
1040}