Skip to main content

zebra_chain/block/
arbitrary.rs

1//! Randomised property testing for [`Block`]s.
2
3use proptest::prelude::*;
4
5use crate::{
6    amount::NonNegative,
7    block,
8    fmt::{HexDebug, SummaryDebug},
9    history_tree::HistoryTree,
10    parameters::{
11        subsidy::scheduled_block_subsidy, NetworkUpgrade::*, GENESIS_PREVIOUS_BLOCK_HASH,
12    },
13    primitives::zcash_history::BlockCommitmentTreeRoots,
14    serialization::{self, BytesInDisplayOrder},
15    transaction::arbitrary::MAX_ARBITRARY_ITEMS,
16    transparent::{
17        new_transaction_ordered_outputs, CoinbaseSpendRestriction,
18        MIN_TRANSPARENT_COINBASE_MATURITY,
19    },
20    work::{difficulty::CompactDifficulty, equihash},
21};
22
23use super::*;
24
25/// The chain length for most zebra-chain proptests.
26///
27/// Most generated chains will contain transparent spends at or before this height.
28///
29/// This height was chosen a tradeoff between chains with no spends,
30/// and chains which spend outputs created by previous spends.
31///
32/// The raw probability of having no spends during a test run is:
33/// ```text
34/// shielded_input = shielded_pool_count / pool_count
35/// expected_transactions = expected_inputs = MAX_ARBITRARY_ITEMS/2
36/// shielded_input^(expected_transactions * expected_inputs * (PREVOUTS_CHAIN_HEIGHT - 1))
37/// ```
38///
39/// This probability is approximately 3%. However, proptest generation and
40/// minimisation strategies can create additional chains with no transparent spends.
41///
42/// To increase the proportion of test runs with proptest spends, increase `PREVOUTS_CHAIN_HEIGHT`.
43pub const PREVOUTS_CHAIN_HEIGHT: usize = 4;
44
45/// The chain length for most zebra-state proptests.
46///
47/// Most generated chains will contain transparent spends at or before this height.
48///
49/// This height was chosen as a tradeoff between chains with no transparent spends,
50/// and chains which spend outputs created by previous spends.
51///
52/// See [`block::arbitrary::PREVOUTS_CHAIN_HEIGHT`] for details.
53pub const MAX_PARTIAL_CHAIN_BLOCKS: usize =
54    MIN_TRANSPARENT_COINBASE_MATURITY as usize + PREVOUTS_CHAIN_HEIGHT;
55
56impl Arbitrary for Height {
57    type Parameters = ();
58
59    fn arbitrary_with(_args: ()) -> Self::Strategy {
60        (Height::MIN.0..=Height::MAX.0).prop_map(Height).boxed()
61    }
62
63    type Strategy = BoxedStrategy<Self>;
64}
65
66#[derive(Debug, Clone)]
67#[non_exhaustive]
68/// The configuration data for proptest when generating arbitrary chains
69pub struct LedgerState {
70    /// The height of the generated block, or the start height of the generated chain.
71    ///
72    /// To get the network upgrade, use the `network_upgrade` method.
73    ///
74    /// If `network_upgrade_override` is not set, the network upgrade is derived
75    /// from the `height` and `network`.
76    pub height: Height,
77
78    /// The network to generate fake blocks for.
79    pub network: Network,
80
81    /// Overrides the network upgrade calculated from `height` and `network`.
82    ///
83    /// To get the network upgrade, use the `network_upgrade` method.
84    network_upgrade_override: Option<NetworkUpgrade>,
85
86    /// Overrides the previous block hashes in blocks generated by this ledger.
87    previous_block_hash_override: Option<block::Hash>,
88
89    /// Regardless of tip height and network, every transaction is this version.
90    transaction_version_override: Option<u32>,
91
92    /// Every V5 and later transaction has a valid `network_upgrade` field.
93    ///
94    /// If `false`, zero or more transactions may have invalid network upgrades.
95    transaction_has_valid_network_upgrade: bool,
96
97    /// Generate coinbase transactions.
98    ///
99    /// In a block or transaction vector, make the first transaction a coinbase
100    /// transaction.
101    ///
102    /// For an individual transaction, make the transaction a coinbase
103    /// transaction.
104    pub(crate) has_coinbase: bool,
105}
106
107/// Overrides for arbitrary [`LedgerState`]s.
108#[derive(Debug, Clone)]
109pub struct LedgerStateOverride {
110    /// Use the given network instead of Mainnet
111    pub network_override: Option<Network>,
112
113    /// Every chain starts at this block. Single blocks have this height.
114    pub height_override: Option<Height>,
115
116    /// Every chain starts with a block with this previous block hash.
117    /// Single blocks have this previous block hash.
118    pub previous_block_hash_override: Option<block::Hash>,
119
120    /// Regardless of tip height and network, every block has features from this
121    /// network upgrade.
122    pub network_upgrade_override: Option<NetworkUpgrade>,
123
124    /// Regardless of tip height and network, every transaction is this version.
125    pub transaction_version_override: Option<u32>,
126
127    /// Every V5 and later transaction has a valid `network_upgrade` field.
128    ///
129    /// If `false`, zero or more transactions may have invalid network upgrades.
130    pub transaction_has_valid_network_upgrade: bool,
131
132    /// Every block has exactly one coinbase transaction.
133    /// Transactions are always coinbase transactions.
134    pub always_has_coinbase: bool,
135}
136
137impl LedgerState {
138    /// Returns the default strategy for creating arbitrary `LedgerState`s.
139    pub fn default_strategy() -> BoxedStrategy<Self> {
140        Self::arbitrary_with(LedgerStateOverride::default())
141    }
142
143    /// Returns a strategy for creating arbitrary `LedgerState`s, without any
144    /// overrides.
145    pub fn no_override_strategy() -> BoxedStrategy<Self> {
146        Self::arbitrary_with(LedgerStateOverride {
147            network_override: None,
148            height_override: None,
149            previous_block_hash_override: None,
150            network_upgrade_override: None,
151            transaction_version_override: None,
152            transaction_has_valid_network_upgrade: false,
153            always_has_coinbase: false,
154        })
155    }
156
157    /// Returns a strategy for creating `LedgerState`s with features from
158    /// `network_upgrade_override`.
159    ///
160    /// These features ignore the actual tip height and network.
161    pub fn network_upgrade_strategy(
162        network_upgrade_override: NetworkUpgrade,
163        transaction_version_override: impl Into<Option<u32>>,
164        transaction_has_valid_network_upgrade: bool,
165    ) -> BoxedStrategy<Self> {
166        Self::arbitrary_with(LedgerStateOverride {
167            network_override: None,
168            height_override: None,
169            previous_block_hash_override: None,
170            network_upgrade_override: Some(network_upgrade_override),
171            transaction_version_override: transaction_version_override.into(),
172            transaction_has_valid_network_upgrade,
173            always_has_coinbase: false,
174        })
175    }
176
177    /// Returns a strategy for creating `LedgerState`s that always have coinbase
178    /// transactions.
179    ///
180    /// Also applies `network_upgrade_override`, if present.
181    pub fn coinbase_strategy(
182        network_upgrade_override: impl Into<Option<NetworkUpgrade>>,
183        transaction_version_override: impl Into<Option<u32>>,
184        transaction_has_valid_network_upgrade: bool,
185    ) -> BoxedStrategy<Self> {
186        Self::arbitrary_with(LedgerStateOverride {
187            network_override: None,
188            height_override: None,
189            previous_block_hash_override: None,
190            network_upgrade_override: network_upgrade_override.into(),
191            transaction_version_override: transaction_version_override.into(),
192            transaction_has_valid_network_upgrade,
193            always_has_coinbase: true,
194        })
195    }
196
197    /// Returns a strategy for creating `LedgerState`s that start with a genesis
198    /// block.
199    ///
200    /// These strategies also have coinbase transactions, and an optional network
201    /// upgrade override.
202    ///
203    /// Use the `Genesis` network upgrade to get a random genesis block, with
204    /// Zcash genesis features.
205    pub fn genesis_strategy(
206        network_override: impl Into<Option<Network>>,
207        network_upgrade_override: impl Into<Option<NetworkUpgrade>>,
208        transaction_version_override: impl Into<Option<u32>>,
209        transaction_has_valid_network_upgrade: bool,
210    ) -> BoxedStrategy<Self> {
211        Self::arbitrary_with(LedgerStateOverride {
212            network_override: network_override.into(),
213            height_override: Some(Height(0)),
214            previous_block_hash_override: Some(GENESIS_PREVIOUS_BLOCK_HASH),
215            network_upgrade_override: network_upgrade_override.into(),
216            transaction_version_override: transaction_version_override.into(),
217            transaction_has_valid_network_upgrade,
218            always_has_coinbase: true,
219        })
220    }
221
222    /// Returns a strategy for creating `LedgerState`s that start at `height`.
223    ///
224    /// These strategies also have coinbase transactions, and an optional network
225    /// upgrade override.
226    pub fn height_strategy(
227        height: Height,
228        network_upgrade_override: impl Into<Option<NetworkUpgrade>>,
229        transaction_version_override: impl Into<Option<u32>>,
230        transaction_has_valid_network_upgrade: bool,
231    ) -> BoxedStrategy<Self> {
232        Self::arbitrary_with(LedgerStateOverride {
233            network_override: None,
234            height_override: Some(height),
235            previous_block_hash_override: None,
236            network_upgrade_override: network_upgrade_override.into(),
237            transaction_version_override: transaction_version_override.into(),
238            transaction_has_valid_network_upgrade,
239            always_has_coinbase: true,
240        })
241    }
242
243    /// Returns the network upgrade for this ledger state.
244    ///
245    /// If `network_upgrade_override` is set, it replaces the upgrade calculated
246    /// using `height` and `network`.
247    pub fn network_upgrade(&self) -> NetworkUpgrade {
248        if let Some(network_upgrade_override) = self.network_upgrade_override {
249            network_upgrade_override
250        } else {
251            NetworkUpgrade::current(&self.network, self.height)
252        }
253    }
254
255    /// Returns the transaction version override.
256    pub fn transaction_version_override(&self) -> Option<u32> {
257        self.transaction_version_override
258    }
259
260    /// Returns `true` if all transactions have valid network upgrade fields.
261    ///
262    /// If `false`, some transactions have invalid network upgrades.
263    pub fn transaction_has_valid_network_upgrade(&self) -> bool {
264        self.transaction_has_valid_network_upgrade
265    }
266}
267
268impl Default for LedgerState {
269    fn default() -> Self {
270        // TODO: stop having a default network
271        let default_network = Network::default();
272        let default_override = LedgerStateOverride::default();
273
274        let most_recent_nu = NetworkUpgrade::current(&default_network, Height::MAX);
275        let most_recent_activation_height =
276            most_recent_nu.activation_height(&default_network).unwrap();
277
278        LedgerState {
279            height: most_recent_activation_height,
280            network: default_network,
281            network_upgrade_override: default_override.network_upgrade_override,
282            previous_block_hash_override: default_override.previous_block_hash_override,
283            transaction_version_override: default_override.transaction_version_override,
284            transaction_has_valid_network_upgrade: default_override
285                .transaction_has_valid_network_upgrade,
286            has_coinbase: default_override.always_has_coinbase,
287        }
288    }
289}
290
291impl Default for LedgerStateOverride {
292    fn default() -> Self {
293        let default_network = Network::default();
294
295        // TODO: dynamically select any future network upgrade (#1974)
296        let nu5_activation_height = Nu5.activation_height(&default_network);
297        let nu5_override = if nu5_activation_height.is_some() {
298            None
299        } else {
300            Some(Nu5)
301        };
302
303        LedgerStateOverride {
304            network_override: None,
305            height_override: None,
306            previous_block_hash_override: None,
307            network_upgrade_override: nu5_override,
308            transaction_version_override: None,
309            transaction_has_valid_network_upgrade: false,
310            always_has_coinbase: true,
311        }
312    }
313}
314
315impl Arbitrary for LedgerState {
316    type Parameters = LedgerStateOverride;
317
318    /// Generate an arbitrary [`LedgerState`].
319    ///
320    /// The default strategy arbitrarily skips some coinbase transactions, and
321    /// has an arbitrary start height. To override, use a specific [`LedgerState`]
322    /// strategy method.
323    fn arbitrary_with(ledger_override: Self::Parameters) -> Self::Strategy {
324        (
325            any::<Height>(),
326            any::<Network>(),
327            any::<bool>(),
328            any::<bool>(),
329        )
330            .prop_map(
331                move |(height, network, transaction_has_valid_network_upgrade, has_coinbase)| {
332                    LedgerState {
333                        height: ledger_override.height_override.unwrap_or(height),
334                        network: ledger_override
335                            .network_override
336                            .as_ref()
337                            .unwrap_or(&network)
338                            .clone(),
339                        network_upgrade_override: ledger_override.network_upgrade_override,
340                        previous_block_hash_override: ledger_override.previous_block_hash_override,
341                        transaction_version_override: ledger_override.transaction_version_override,
342                        transaction_has_valid_network_upgrade: ledger_override
343                            .transaction_has_valid_network_upgrade
344                            || transaction_has_valid_network_upgrade,
345                        has_coinbase: ledger_override.always_has_coinbase || has_coinbase,
346                    }
347                },
348            )
349            .boxed()
350    }
351
352    type Strategy = BoxedStrategy<Self>;
353}
354
355impl Arbitrary for Block {
356    type Parameters = LedgerState;
357
358    fn arbitrary_with(ledger_state: Self::Parameters) -> Self::Strategy {
359        let transactions_strategy = {
360            let ledger_state = ledger_state.clone();
361            // Generate a random number transactions. A coinbase tx is always generated, so if
362            // `transaction_count` is zero, the block will contain only the coinbase tx.
363            (0..MAX_ARBITRARY_ITEMS).prop_flat_map(move |transaction_count| {
364                Transaction::vec_strategy(ledger_state.clone(), transaction_count)
365            })
366        };
367
368        // TODO: if needed, fixup:
369        // - history and authorizing data commitments
370        // - the transaction merkle root
371
372        (Header::arbitrary_with(ledger_state), transactions_strategy)
373            .prop_map(move |(header, transactions)| Self {
374                header: header.into(),
375                transactions,
376            })
377            .boxed()
378    }
379
380    type Strategy = BoxedStrategy<Self>;
381}
382
383/// Skip checking transparent coinbase spends in [`Block::partial_chain_strategy`].
384#[allow(clippy::result_unit_err)]
385pub fn allow_all_transparent_coinbase_spends(
386    _: transparent::OutPoint,
387    _: transparent::CoinbaseSpendRestriction,
388    _: &transparent::Utxo,
389) -> Result<(), ()> {
390    Ok(())
391}
392
393impl Block {
394    /// Returns a strategy for creating vectors of blocks with increasing height.
395    ///
396    /// Each vector is `count` blocks long.
397    /// Coinbase outputs are bounded by the scheduled subsidy; fees and NSM reissuance
398    /// are left unclaimed.
399    ///
400    /// `check_transparent_coinbase_spend` is used to check if
401    /// transparent coinbase UTXOs are valid, before using them in blocks.
402    /// Use [`allow_all_transparent_coinbase_spends`] to disable this check.
403    ///
404    /// `generate_valid_commitments` specifies if the generated blocks
405    /// should have valid commitments. This makes it much slower so it's better
406    /// to enable only when needed.
407    pub fn partial_chain_strategy<F, E>(
408        mut current: LedgerState,
409        count: usize,
410        check_transparent_coinbase_spend: F,
411        generate_valid_commitments: bool,
412    ) -> BoxedStrategy<SummaryDebug<Vec<Arc<Self>>>>
413    where
414        F: Fn(
415                transparent::OutPoint,
416                transparent::CoinbaseSpendRestriction,
417                &transparent::Utxo,
418            ) -> Result<(), E>
419            + Copy
420            + 'static,
421    {
422        let mut vec = Vec::with_capacity(count);
423
424        // generate block strategies with the correct heights
425        for _ in 0..count {
426            vec.push((Just(current.height), Block::arbitrary_with(current.clone())));
427            current.height.0 += 1;
428        }
429
430        // after the vec strategy generates blocks, fixup invalid parts of the blocks
431        vec.prop_map(move |mut vec| {
432            let mut previous_block_hash = None;
433            let mut utxos = HashMap::new();
434            let mut chain_value_pools = ValueBalance::zero();
435            let mut sapling_tree = sapling::tree::NoteCommitmentTree::default();
436            let mut orchard_tree = orchard::tree::NoteCommitmentTree::default();
437            // Ironwood reuses the Orchard note commitment tree type. Generated v6 transactions
438            // (NU6.3+) can carry Ironwood bundles, whose note commitments are appended below and
439            // threaded through the V3 history node so commitments match validation. For pre-NU6.3
440            // chains this stays empty, and its real empty-tree root is used the same way.
441            let mut ironwood_tree = orchard::tree::NoteCommitmentTree::default();
442            // The history tree usually takes care of "creating itself". But this
443            // only works when blocks are pushed into it starting from genesis
444            // (or at least pre-Heartwood, where the tree is not required).
445            // However, this strategy can generate blocks from an arbitrary height,
446            // so we must wait for the first block to create the history tree from it.
447            // This is why `Option` is used here.
448            let mut history_tree: Option<HistoryTree> = None;
449
450            for (height, block) in vec.iter_mut() {
451                // fixup the previous block hash
452                if let Some(previous_block_hash) = previous_block_hash {
453                    Arc::make_mut(&mut block.header).previous_block_hash = previous_block_hash;
454                }
455
456                let mut new_transactions = Vec::new();
457                for (tx_index_in_block, transaction) in block.transactions.drain(..).enumerate() {
458                    let mut transaction = (*transaction).clone();
459                    if transaction.is_coinbase() {
460                        if NetworkUpgrade::current(&current.network, *height) >= NetworkUpgrade::Nu5
461                        {
462                            transaction.set_expiry_height(*height);
463                        }
464
465                        // Arbitrary output values must not mint more than scheduled issuance.
466                        // Generated shielded bundles have zero value balance; leave fees unclaimed.
467                        let mut remaining_subsidy =
468                            scheduled_block_subsidy(*height, &current.network)
469                                .expect("generated heights have a valid scheduled subsidy");
470                        transaction.for_each_value_mut(|value| {
471                            *value = (*value).min(remaining_subsidy);
472                            remaining_subsidy = (remaining_subsidy - *value)
473                                .expect("output is bounded by the remaining subsidy");
474                        });
475                    }
476                    if let Some(transaction) = fix_generated_transaction(
477                        transaction,
478                        tx_index_in_block,
479                        *height,
480                        &mut chain_value_pools,
481                        &mut utxos,
482                        check_transparent_coinbase_spend,
483                    ) {
484                        // The FinalizedState does not update the note commitment trees with the genesis block,
485                        // because it doesn't need to (the trees are not used at that point) and updating them
486                        // would be awkward since the genesis block is handled separately there.
487                        // This forces us to skip the genesis block here too in order to able to use
488                        // this to test the finalized state.
489                        //
490                        // TODO: run note commitment tree updates in parallel rayon threads,
491                        //       using `NoteCommitmentTrees::update_trees_parallel()`
492                        if generate_valid_commitments && *height != Height(0) {
493                            for sapling_note_commitment in transaction.sapling_note_commitments() {
494                                sapling_tree.append(sapling_note_commitment).unwrap();
495                            }
496                            for orchard_note_commitment in transaction.orchard_note_commitments() {
497                                use halo2::pasta::group::ff::PrimeField;
498                                let cm =
499                                    pallas::Base::from_repr(orchard_note_commitment.to_bytes())
500                                        .expect("valid orchard note commitment");
501                                orchard_tree.append(cm).unwrap();
502                            }
503                            for ironwood_note_commitment in transaction.ironwood_note_commitments()
504                            {
505                                use halo2::pasta::group::ff::PrimeField;
506                                let cm =
507                                    pallas::Base::from_repr(ironwood_note_commitment.to_bytes())
508                                        .expect("valid ironwood note commitment");
509                                ironwood_tree.append(cm).unwrap();
510                            }
511                        }
512                        new_transactions.push(Arc::new(transaction));
513                    }
514                }
515
516                // delete invalid transactions
517                block.transactions = new_transactions;
518
519                // fix commitment (must be done after finishing changing the block)
520                if generate_valid_commitments {
521                    // The history tree commits to the block hash, so the merkle root must
522                    // already match the fixed transactions.
523                    Arc::make_mut(&mut block.header).merkle_root =
524                        block.transactions.iter().collect();
525
526                    let current_height = block.coinbase_height().unwrap();
527                    let heartwood_height = NetworkUpgrade::Heartwood
528                        .activation_height(&current.network)
529                        .unwrap();
530                    let nu5_height = NetworkUpgrade::Nu5.activation_height(&current.network);
531
532                    match current_height.cmp(&heartwood_height) {
533                        std::cmp::Ordering::Less => {
534                            // In pre-Heartwood blocks this is the Sapling note commitment tree root.
535                            // We don't validate it since we checkpoint on Canopy, but it
536                            // needs to be well-formed, i.e. smaller than 𝑞_J, so we
537                            // arbitrarily set it to 1.
538                            let block_header = Arc::make_mut(&mut block.header);
539                            block_header.commitment_bytes = [0u8; 32].into();
540                            block_header.commitment_bytes[0] = 1;
541                        }
542                        std::cmp::Ordering::Equal => {
543                            // The Heartwood activation block has a hardcoded all-zeroes commitment.
544                            let block_header = Arc::make_mut(&mut block.header);
545                            block_header.commitment_bytes = [0u8; 32].into();
546                        }
547                        std::cmp::Ordering::Greater => {
548                            // Set the correct commitment bytes according to the network upgrade.
549                            let history_tree_root = match &history_tree {
550                                Some(tree) => tree.hash().unwrap_or_else(|| [0u8; 32].into()),
551                                None => [0u8; 32].into(),
552                            };
553                            if nu5_height.is_some() && current_height >= nu5_height.unwrap() {
554                                // From zebra-state/src/service/check.rs
555                                let auth_data_root = block.auth_data_root();
556                                let hash_block_commitments =
557                                    ChainHistoryBlockTxAuthCommitmentHash::from_commitments(
558                                        &history_tree_root,
559                                        &auth_data_root,
560                                    );
561                                let block_header = Arc::make_mut(&mut block.header);
562                                block_header.commitment_bytes =
563                                    hash_block_commitments.bytes_in_serialized_order().into();
564                            } else {
565                                let block_header = Arc::make_mut(&mut block.header);
566                                block_header.commitment_bytes =
567                                    history_tree_root.bytes_in_serialized_order().into();
568                            }
569                        }
570                    }
571                    // update history tree for the next block
572                    if let Some(history_tree) = history_tree.as_mut() {
573                        history_tree
574                            .push(
575                                &current.network,
576                                Arc::new(block.clone()),
577                                BlockCommitmentTreeRoots {
578                                    sapling: &sapling_tree.root(),
579                                    orchard: &orchard_tree.root(),
580                                    ironwood: &ironwood_tree.root(),
581                                },
582                            )
583                            .unwrap();
584                    } else {
585                        history_tree = Some(
586                            HistoryTree::from_block(
587                                &current.network,
588                                Arc::new(block.clone()),
589                                BlockCommitmentTreeRoots {
590                                    sapling: &sapling_tree.root(),
591                                    orchard: &orchard_tree.root(),
592                                    ironwood: &ironwood_tree.root(),
593                                },
594                            )
595                            .unwrap(),
596                        );
597                    }
598                }
599
600                // now that we've made all the changes, calculate our block hash,
601                // so the next block can use it
602                previous_block_hash = Some(block.hash());
603            }
604            SummaryDebug(
605                vec.into_iter()
606                    .map(|(_height, block)| Arc::new(block))
607                    .collect(),
608            )
609        })
610        .boxed()
611    }
612}
613
614/// Fix `transaction` so it obeys more consensus rules.
615///
616/// Spends [`transparent::OutPoint`]s from `utxos`, and adds newly created outputs.
617///
618/// If the transaction can't be fixed, returns `None`.
619pub fn fix_generated_transaction<F, E>(
620    mut transaction: Transaction,
621    tx_index_in_block: usize,
622    height: Height,
623    chain_value_pools: &mut ValueBalance<NonNegative>,
624    utxos: &mut HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
625    check_transparent_coinbase_spend: F,
626) -> Option<Transaction>
627where
628    F: Fn(
629            transparent::OutPoint,
630            transparent::CoinbaseSpendRestriction,
631            &transparent::Utxo,
632        ) -> Result<(), E>
633        + Copy
634        + 'static,
635{
636    // Coinbase transactions must not contain Sapling spends (GHSA-rgwx-8r98-p34c).
637    // The arbitrary `Transaction` strategies generate transparent-only transactions, so there
638    // is no generated Sapling shielded data to clear here. The deserialization rejection path
639    // is still exercised by the `transaction_roundtrip` proptest and the GHSA-rgwx-8r98-p34c
640    // reproduction vector in `zebra-chain`.
641
642    let mut spend_restriction = transaction.coinbase_spend_restriction(&Network::Mainnet, height);
643    let mut new_inputs = Vec::new();
644    let mut spent_outputs = HashMap::new();
645
646    // fixup the transparent spends
647    let original_inputs = transaction.inputs().to_vec();
648    for mut input in original_inputs.into_iter() {
649        if input.outpoint().is_some() {
650            // the transparent chain value pool is the sum of unspent UTXOs,
651            // so we don't need to check it separately, because we only spend unspent UTXOs
652            if let Some(selected_outpoint) = find_valid_utxo_for_spend(
653                &mut transaction,
654                &mut spend_restriction,
655                height,
656                utxos,
657                check_transparent_coinbase_spend,
658            ) {
659                input.set_outpoint(selected_outpoint);
660                new_inputs.push(input);
661
662                let spent_utxo = utxos.remove(&selected_outpoint)?;
663                spent_outputs.insert(selected_outpoint, spent_utxo.utxo.output);
664            }
665            // otherwise, drop the invalid input, because it has no valid UTXOs to spend
666        } else {
667            // preserve coinbase inputs
668            new_inputs.push(input.clone());
669        }
670    }
671
672    // delete invalid inputs
673    transaction = transaction.with_transparent_inputs(new_inputs);
674
675    let (_remaining_transaction_value, new_chain_value_pools) = transaction
676        .fix_chain_value_pools(*chain_value_pools, &spent_outputs)
677        .expect("value fixes produce valid chain value pools and remaining transaction values");
678
679    // TODO: if needed, check output count here as well
680    if transaction.has_transparent_or_shielded_inputs() {
681        // consensus rule: skip genesis created UTXOs
682        // Zebra implementation: also skip shielded chain value pool changes
683        if height > Height(0) {
684            *chain_value_pools = new_chain_value_pools;
685
686            utxos.extend(new_transaction_ordered_outputs(
687                &transaction,
688                transaction.hash(),
689                tx_index_in_block,
690                height,
691            ));
692        }
693
694        Some(transaction)
695    } else {
696        None
697    }
698}
699
700/// Find a valid [`transparent::OutPoint`] in `utxos` to spend in `transaction`.
701///
702/// Modifies `transaction` and updates `spend_restriction` if needed.
703///
704/// If there is no valid output, or many search attempts have failed, returns `None`.
705pub fn find_valid_utxo_for_spend<F, E>(
706    transaction: &mut Transaction,
707    spend_restriction: &mut CoinbaseSpendRestriction,
708    spend_height: Height,
709    utxos: &HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
710    check_transparent_coinbase_spend: F,
711) -> Option<transparent::OutPoint>
712where
713    F: Fn(
714            transparent::OutPoint,
715            transparent::CoinbaseSpendRestriction,
716            &transparent::Utxo,
717        ) -> Result<(), E>
718        + Copy
719        + 'static,
720{
721    let has_shielded_outputs = transaction.has_shielded_outputs();
722    let delete_transparent_outputs =
723        CoinbaseSpendRestriction::CheckCoinbaseMaturity { spend_height };
724    // choose an arbitrary spendable UTXO, in hash set order, with a bounded scan
725    for (candidate_outpoint, candidate_utxo) in utxos.iter().take(100) {
726        // Avoid O(n^2) algorithmic complexity by limiting the number of checks
727
728        // try the utxo as-is, then try it with deleted transparent outputs
729        if check_transparent_coinbase_spend(
730            *candidate_outpoint,
731            *spend_restriction,
732            candidate_utxo.as_ref(),
733        )
734        .is_ok()
735        {
736            return Some(*candidate_outpoint);
737        } else if has_shielded_outputs
738            && check_transparent_coinbase_spend(
739                *candidate_outpoint,
740                delete_transparent_outputs,
741                candidate_utxo.as_ref(),
742            )
743            .is_ok()
744        {
745            *transaction = transaction.clone().with_transparent_outputs(vec![]);
746            *spend_restriction = delete_transparent_outputs;
747
748            return Some(*candidate_outpoint);
749        }
750    }
751
752    None
753}
754
755impl Arbitrary for Commitment {
756    type Parameters = ();
757
758    fn arbitrary_with(_args: ()) -> Self::Strategy {
759        (any::<[u8; 32]>(), any::<Network>(), any::<Height>())
760            .prop_map(|(commitment_bytes, network, block_height)| {
761                if block_height == Heartwood.activation_height(&network).unwrap() {
762                    Commitment::ChainHistoryActivationReserved
763                } else {
764                    Commitment::from_bytes(commitment_bytes, &network, block_height)
765                        .expect("unexpected failure in from_bytes parsing")
766                }
767            })
768            .boxed()
769    }
770
771    type Strategy = BoxedStrategy<Self>;
772}
773
774impl Arbitrary for Header {
775    type Parameters = LedgerState;
776
777    fn arbitrary_with(ledger_state: Self::Parameters) -> Self::Strategy {
778        (
779            // version is interpreted as i32 in the spec, so we are limited to i32::MAX here
780            (4u32..(i32::MAX as u32)),
781            any::<Hash>(),
782            any::<merkle::Root>(),
783            any::<HexDebug<[u8; 32]>>(),
784            serialization::arbitrary::datetime_u32(),
785            any::<CompactDifficulty>(),
786            any::<HexDebug<[u8; 32]>>(),
787            any::<equihash::Solution>(),
788        )
789            .prop_map(
790                move |(
791                    version,
792                    mut previous_block_hash,
793                    merkle_root,
794                    commitment_bytes,
795                    time,
796                    difficulty_threshold,
797                    nonce,
798                    solution,
799                )| {
800                    if let Some(previous_block_hash_override) =
801                        ledger_state.previous_block_hash_override
802                    {
803                        previous_block_hash = previous_block_hash_override;
804                    } else if ledger_state.height == Height(0) {
805                        previous_block_hash = GENESIS_PREVIOUS_BLOCK_HASH;
806                    }
807
808                    Header {
809                        version,
810                        previous_block_hash,
811                        merkle_root,
812                        commitment_bytes,
813                        time,
814                        difficulty_threshold,
815                        nonce,
816                        solution,
817                    }
818                },
819            )
820            .boxed()
821    }
822
823    type Strategy = BoxedStrategy<Self>;
824}