Skip to main content

zebra_consensus/
transaction.rs

1//! Asynchronous verification of transactions.
2
3use std::{
4    collections::{HashMap, HashSet},
5    future::Future,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9    time::Duration,
10};
11
12use chrono::{DateTime, Utc};
13use futures::{
14    stream::{FuturesUnordered, StreamExt},
15    FutureExt,
16};
17use tokio::sync::oneshot;
18use tower::{
19    buffer::Buffer,
20    timeout::{error::Elapsed, Timeout},
21    util::BoxService,
22    Service, ServiceExt,
23};
24use tracing::Instrument;
25
26use zcash_protocol::value::ZatBalance;
27
28use zebra_chain::{
29    amount::{Amount, NonNegative},
30    block,
31    parameters::{Network, NetworkUpgrade},
32    primitives::Groth16Proof,
33    serialization::DateTime32,
34    transaction::{
35        self, HashType, SigHash, Transaction, UnminedTx, UnminedTxId, VerifiedUnminedTx,
36    },
37    transparent,
38};
39
40use zebra_node_services::mempool;
41use zebra_script::{CachedFfiTransaction, Sigops};
42use zebra_state as zs;
43
44use crate::{error::TransactionError, primitives, script, BoxError};
45
46pub mod check;
47#[cfg(test)]
48mod tests;
49
50/// A timeout applied to UTXO lookup requests.
51///
52/// The exact value is non-essential, but this should be long enough to allow
53/// out-of-order verification of blocks (UTXOs are not required to be ready
54/// immediately) while being short enough to:
55///   * prune blocks that are too far in the future to be worth keeping in the
56///     queue,
57///   * fail blocks that reference invalid UTXOs, and
58///   * fail blocks that reference UTXOs from blocks that have temporarily failed
59///     to download, because a peer sent Zebra a bad list of block hashes. (The
60///     UTXO verification failure will restart the sync, and re-download the
61///     chain in the correct order.)
62const UTXO_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(6 * 60);
63
64/// A timeout applied to output lookup requests sent to the mempool. This is shorter than the
65/// timeout for the state UTXO lookups because a block is likely to be mined every 75 seconds
66/// after Blossom is active, changing the best chain tip and requiring re-verification of transactions
67/// in the mempool.
68///
69/// This is how long Zebra will wait for an output to be added to the mempool before verification
70/// of the transaction that spends it will fail.
71const MEMPOOL_OUTPUT_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
72
73/// How long to wait after responding to a mempool request with a transaction that creates new
74/// transparent outputs before polling the mempool service so that it will try adding the verified
75/// transaction and responding to any potential `AwaitOutput` requests.
76///
77/// This should be long enough for the mempool service's `Downloads` to finish processing the
78/// response from the transaction verifier.
79const POLL_MEMPOOL_DELAY: std::time::Duration = Duration::from_millis(50);
80
81/// Asynchronous transaction verification.
82///
83/// # Correctness
84///
85/// Transaction verification requests should be wrapped in a timeout, so that
86/// out-of-order and invalid requests do not hang indefinitely. See the [`router`](`crate::router`)
87/// module documentation for details.
88pub struct Verifier<ZS, Mempool> {
89    network: Network,
90    state: Timeout<ZS>,
91    // TODO: Use an enum so that this can either be Pending(oneshot::Receiver) or Initialized(MempoolService)
92    mempool: Option<Timeout<Mempool>>,
93    script_verifier: script::Verifier,
94    mempool_setup_rx: oneshot::Receiver<Mempool>,
95}
96
97impl<ZS, Mempool> Verifier<ZS, Mempool>
98where
99    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
100    ZS::Future: Send + 'static,
101    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
102        + Send
103        + Clone
104        + 'static,
105    Mempool::Future: Send + 'static,
106{
107    /// Create a new transaction verifier.
108    pub fn new(network: &Network, state: ZS, mempool_setup_rx: oneshot::Receiver<Mempool>) -> Self {
109        Self {
110            network: network.clone(),
111            state: Timeout::new(state, UTXO_LOOKUP_TIMEOUT),
112            mempool: None,
113            script_verifier: script::Verifier,
114            mempool_setup_rx,
115        }
116    }
117}
118
119impl<ZS>
120    Verifier<
121        ZS,
122        Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>,
123    >
124where
125    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
126    ZS::Future: Send + 'static,
127{
128    /// Create a new transaction verifier with a closed channel receiver for mempool setup for tests.
129    #[cfg(test)]
130    pub fn new_for_tests(network: &Network, state: ZS) -> Self {
131        Self {
132            network: network.clone(),
133            state: Timeout::new(state, UTXO_LOOKUP_TIMEOUT),
134            mempool: None,
135            script_verifier: script::Verifier,
136            mempool_setup_rx: oneshot::channel().1,
137        }
138    }
139}
140
141/// Specifies whether a transaction should be verified as part of a block or as
142/// part of the mempool.
143///
144/// Transaction verification has slightly different consensus rules, depending on
145/// whether the transaction is to be included in a block on in the mempool.
146#[derive(Clone, Debug, Eq, PartialEq)]
147pub enum Request {
148    /// Verify the supplied transaction as part of a block.
149    Block {
150        /// The transaction hash.
151        transaction_hash: transaction::Hash,
152        /// The transaction itself.
153        transaction: Arc<Transaction>,
154        /// Set of transaction hashes that create new transparent outputs.
155        known_outpoint_hashes: Arc<HashSet<transaction::Hash>>,
156        /// Additional UTXOs which are known at the time of verification.
157        known_utxos: Arc<HashMap<transparent::OutPoint, transparent::OrderedUtxo>>,
158        /// The height of the block containing this transaction.
159        height: block::Height,
160        /// The time that the block was mined.
161        time: DateTime<Utc>,
162    },
163    /// Verify the supplied transaction as part of the mempool.
164    ///
165    /// Mempool transactions do not have any additional UTXOs.
166    ///
167    /// Note: coinbase transactions are invalid in the mempool
168    Mempool {
169        /// The transaction itself.
170        transaction: UnminedTx,
171        /// The height of the next block.
172        ///
173        /// The next block is the first block that could possibly contain a
174        /// mempool transaction.
175        height: block::Height,
176    },
177}
178
179/// The response type for the transaction verifier service.
180/// Responses identify the transaction that was verified.
181#[derive(Clone, Debug, PartialEq)]
182pub enum Response {
183    /// A response to a block transaction verification request.
184    Block {
185        /// The witnessed transaction ID for this transaction.
186        ///
187        /// [`Response::Block`] responses can be uniquely identified by
188        /// [`UnminedTxId::mined_id`], because the block's authorizing data root
189        /// will be checked during contextual validation.
190        tx_id: UnminedTxId,
191
192        /// The miner fee for this transaction.
193        ///
194        /// `None` for coinbase transactions.
195        ///
196        /// # Consensus
197        ///
198        /// > The remaining value in the transparent transaction value pool
199        /// > of a coinbase transaction is destroyed.
200        ///
201        /// <https://zips.z.cash/protocol/protocol.pdf#transactions>
202        miner_fee: Option<Amount<NonNegative>>,
203
204        /// The number of legacy signature operations in this transaction's
205        /// transparent inputs and outputs.
206        sigops: u32,
207    },
208
209    /// A response to a mempool transaction verification request.
210    Mempool {
211        /// The full content of the verified mempool transaction.
212        /// Also contains the transaction fee and other associated fields.
213        ///
214        /// Mempool transactions always have a transaction fee,
215        /// because coinbase transactions are rejected from the mempool.
216        ///
217        /// [`Response::Mempool`] responses are uniquely identified by the
218        /// [`UnminedTxId`] variant for their transaction version.
219        transaction: VerifiedUnminedTx,
220
221        /// A list of spent [`transparent::OutPoint`]s that were found in
222        /// the mempool's list of `created_outputs`.
223        ///
224        /// Used by the mempool to determine dependencies between transactions
225        /// in the mempool and to avoid adding transactions with missing spends
226        /// to its verified set.
227        spent_mempool_outpoints: Vec<transparent::OutPoint>,
228    },
229}
230
231#[cfg(any(test, feature = "proptest-impl"))]
232impl From<VerifiedUnminedTx> for Response {
233    fn from(transaction: VerifiedUnminedTx) -> Self {
234        Response::Mempool {
235            transaction,
236            spent_mempool_outpoints: Vec::new(),
237        }
238    }
239}
240
241impl Request {
242    /// The transaction to verify that's in this request.
243    pub fn transaction(&self) -> Arc<Transaction> {
244        match self {
245            Request::Block { transaction, .. } => transaction.clone(),
246            Request::Mempool { transaction, .. } => transaction.transaction.clone(),
247        }
248    }
249
250    /// The unverified mempool transaction, if this is a mempool request.
251    pub fn mempool_transaction(&self) -> Option<UnminedTx> {
252        match self {
253            Request::Block { .. } => None,
254            Request::Mempool { transaction, .. } => Some(transaction.clone()),
255        }
256    }
257
258    /// The unmined transaction ID for the transaction in this request.
259    pub fn tx_id(&self) -> UnminedTxId {
260        match self {
261            // TODO: get the precalculated ID from the block verifier
262            Request::Block { transaction, .. } => transaction.unmined_id(),
263            Request::Mempool { transaction, .. } => transaction.id,
264        }
265    }
266
267    /// The mined transaction ID for the transaction in this request.
268    pub fn tx_mined_id(&self) -> transaction::Hash {
269        match self {
270            Request::Block {
271                transaction_hash, ..
272            } => *transaction_hash,
273            Request::Mempool { transaction, .. } => transaction.id.mined_id(),
274        }
275    }
276
277    /// The set of additional known unspent transaction outputs that's in this request.
278    pub fn known_utxos(&self) -> Arc<HashMap<transparent::OutPoint, transparent::OrderedUtxo>> {
279        match self {
280            Request::Block { known_utxos, .. } => known_utxos.clone(),
281            Request::Mempool { .. } => HashMap::new().into(),
282        }
283    }
284
285    /// The set of additional known [`transparent::OutPoint`]s of unspent transaction outputs that's in this request.
286    pub fn known_outpoint_hashes(&self) -> Arc<HashSet<transaction::Hash>> {
287        match self {
288            Request::Block {
289                known_outpoint_hashes,
290                ..
291            } => known_outpoint_hashes.clone(),
292            Request::Mempool { .. } => HashSet::new().into(),
293        }
294    }
295
296    /// The height used to select the consensus rules for verifying this transaction.
297    pub fn height(&self) -> block::Height {
298        match self {
299            Request::Block { height, .. } | Request::Mempool { height, .. } => *height,
300        }
301    }
302
303    /// The block time used for lock time consensus rules validation.
304    pub fn block_time(&self) -> Option<DateTime<Utc>> {
305        match self {
306            Request::Block { time, .. } => Some(*time),
307            Request::Mempool { .. } => None,
308        }
309    }
310
311    /// The network upgrade to consider for the verification.
312    ///
313    /// This is based on the block height from the request, and the supplied `network`.
314    pub fn upgrade(&self, network: &Network) -> NetworkUpgrade {
315        NetworkUpgrade::current(network, self.height())
316    }
317
318    /// Returns true if the request is a mempool request.
319    pub fn is_mempool(&self) -> bool {
320        matches!(self, Request::Mempool { .. })
321    }
322}
323
324impl Response {
325    /// The unmined transaction ID for the transaction in this response.
326    pub fn tx_id(&self) -> UnminedTxId {
327        match self {
328            Response::Block { tx_id, .. } => *tx_id,
329            Response::Mempool { transaction, .. } => transaction.transaction.id,
330        }
331    }
332
333    /// The miner fee for the transaction in this response.
334    ///
335    /// Coinbase transactions do not have a miner fee,
336    /// and they don't need UTXOs to calculate their value balance,
337    /// because they don't spend any inputs.
338    pub fn miner_fee(&self) -> Option<Amount<NonNegative>> {
339        match self {
340            Response::Block { miner_fee, .. } => *miner_fee,
341            Response::Mempool { transaction, .. } => Some(transaction.miner_fee),
342        }
343    }
344
345    /// The number of legacy transparent signature operations in this transaction's
346    /// inputs and outputs.
347    pub fn sigops(&self) -> u32 {
348        match self {
349            Response::Block { sigops, .. } => *sigops,
350            Response::Mempool { transaction, .. } => transaction.legacy_sigop_count,
351        }
352    }
353
354    /// Returns true if the request is a mempool request.
355    pub fn is_mempool(&self) -> bool {
356        match self {
357            Response::Block { .. } => false,
358            Response::Mempool { .. } => true,
359        }
360    }
361}
362
363impl<ZS, Mempool> Service<Request> for Verifier<ZS, Mempool>
364where
365    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
366    ZS::Future: Send + 'static,
367    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
368        + Send
369        + Clone
370        + 'static,
371    Mempool::Future: Send + 'static,
372{
373    type Response = Response;
374    type Error = TransactionError;
375    type Future =
376        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
377
378    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
379        // Note: The block verifier expects the transaction verifier to always be ready.
380
381        if self.mempool.is_none() {
382            if let Ok(mempool) = self.mempool_setup_rx.try_recv() {
383                self.mempool = Some(Timeout::new(mempool, MEMPOOL_OUTPUT_LOOKUP_TIMEOUT));
384            }
385        }
386
387        Poll::Ready(Ok(()))
388    }
389
390    // TODO: break up each chunk into its own method
391    fn call(&mut self, req: Request) -> Self::Future {
392        let script_verifier = self.script_verifier;
393        let network = self.network.clone();
394        let state = self.state.clone();
395        let mempool = self.mempool.clone();
396
397        let tx = req.transaction();
398        let tx_id = req.tx_id();
399        let span = tracing::debug_span!("tx", ?tx_id);
400
401        async move {
402            tracing::trace!(?tx_id, ?req, "got tx verify request");
403
404            // Do quick checks first
405            check::has_inputs_and_outputs(&tx)?;
406            check::has_enough_orchard_flags(&tx)?;
407            check::consensus_branch_id(&tx, req.height(), &network)?;
408
409            // Soft fork: temporarily require transactions to not contain Orchard actions.
410            //
411            // This soft fork was added while NU 6.1 was the active epoch on the Zcash
412            // chain, but we apply it uniformly even if NU 6.1 is not active in case it is
413            // ported to other chains with a different sequence of NUs.
414            //
415            // This will be treated as "Rules that apply generally before the next NU"
416            // when we add the NU that re-enables Orchard actions.
417            if network.is_orchard_temporarily_disabled(req.height()) && tx.orchard_shielded_data().is_some() {
418                return Err(TransactionError::Other("transaction has Orchard actions (temporarily disabled)".into()));
419            }
420
421            // From the network upgrade that re-enables Orchard actions (NU6.2), require
422            // that any Orchard proof has the canonical length for its number of actions.
423            // A proof that is present but not canonically sized can be padded with
424            // arbitrary trailing data without affecting its validity, allowing excess
425            // bandwidth and storage costs to be imposed while paying only fees sized to a
426            // canonical proof (GHSA-jfw5-j458-pfv6).
427            //
428            // This is a constricting rule, so it is gated on that network upgrade:
429            // Orchard actions mined before it, under earlier rules that did not enforce
430            // the proof size, must remain valid so that nodes can sync and reindex the
431            // chain before the soft fork that temporarily disabled Orchard. Orchard
432            // bundles are deserialized leniently, so the size is checked here, where the
433            // block height is available, rather than during parsing.
434            //
435            // The gate activates at the NU6.2 activation height committed in
436            // MAINNET/TESTNET_ACTIVATION_HEIGHTS. See
437            // `Network::orchard_canonical_proof_size_rule_active`.
438            if network.orchard_canonical_proof_size_rule_active(req.height()) {
439                if let Some(orchard_shielded_data) = tx.orchard_shielded_data() {
440                    if !orchard_shielded_data.proof_size_is_canonical() {
441                        return Err(TransactionError::OrchardProofSize);
442                    }
443                }
444            }
445
446            // Validate the coinbase input consensus rules
447            if req.is_mempool() && tx.is_coinbase() {
448                return Err(TransactionError::CoinbaseInMempool);
449            }
450
451            if tx.is_coinbase() {
452                check::coinbase_tx_no_prevout_joinsplit_spend(&tx)?;
453            } else if !tx.is_valid_non_coinbase() {
454                return Err(TransactionError::NonCoinbaseHasCoinbaseInput);
455            }
456
457            // Validate `nExpiryHeight` consensus rules
458            if tx.is_coinbase() {
459                check::coinbase_expiry_height(&req.height(), &tx, &network)?;
460            } else {
461                check::non_coinbase_expiry_height(&req.height(), &tx)?;
462            }
463
464            // Consensus rule:
465            //
466            // > Either v_{pub}^{old} or v_{pub}^{new} MUST be zero.
467            //
468            // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
469            check::joinsplit_has_vpub_zero(&tx)?;
470
471            // [Canopy onward]: `vpub_old` MUST be zero.
472            // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
473            check::disabled_add_to_sprout_pool(&tx, req.height(), &network)?;
474
475            check::spend_conflicts(&tx)?;
476
477            tracing::trace!(?tx_id, "passed quick checks");
478
479            if let Some(block_time) = req.block_time() {
480                check::lock_time_has_passed(&tx, req.height(), block_time)?;
481            } else {
482                // Skip the state query if we don't need the time for this check.
483                let next_median_time_past = if tx.lock_time_is_time() {
484                    // This state query is much faster than loading UTXOs from the database,
485                    // so it doesn't need to be executed in parallel
486                    let state = state.clone();
487                    Some(Self::mempool_best_chain_next_median_time_past(state).await?.to_chrono())
488                } else {
489                    None
490                };
491
492                // This consensus check makes sure Zebra produces valid block templates.
493                check::lock_time_has_passed(&tx, req.height(), next_median_time_past)?;
494            }
495
496            // "The consensus rules applied to valueBalance, vShieldedOutput, and bindingSig
497            // in non-coinbase transactions MUST also be applied to coinbase transactions."
498            //
499            // This rule is implicitly implemented during Sapling and Orchard verification,
500            // because they do not distinguish between coinbase and non-coinbase transactions.
501            //
502            // Note: this rule originally applied to Sapling, but we assume it also applies to Orchard.
503            //
504            // https://zips.z.cash/zip-0213#specification
505
506            // Load spent UTXOs from state.
507            // The UTXOs are required for almost all the async checks.
508            let load_spent_utxos_fut =
509                Self::spent_utxos(tx.clone(), req.clone(), state.clone(), mempool.clone(),);
510            let (spent_utxos, spent_outputs, spent_mempool_outpoints) = load_spent_utxos_fut.await?;
511
512            // WONTFIX: Return an error for Request::Block as well to replace this check in
513            //       the state once #2336 has been implemented?
514            if req.is_mempool() {
515                Self::check_maturity_height(&network, &req, &spent_utxos)?;
516            }
517
518            let nu = req.upgrade(&network);
519            let cached_ffi_transaction =
520                Arc::new(CachedFfiTransaction::new(tx.clone(), Arc::new(spent_outputs), nu).map_err(|_| TransactionError::UnsupportedByNetworkUpgrade(tx.version(), nu))?);
521
522            tracing::trace!(?tx_id, "got state UTXOs");
523
524            let mut async_checks = match tx.as_ref() {
525                Transaction::V1 { .. } | Transaction::V2 { .. } | Transaction::V3 { .. } => {
526                    tracing::debug!(?tx, "got transaction with wrong version");
527                    return Err(TransactionError::WrongVersion);
528                }
529                Transaction::V4 {
530                    joinsplit_data,
531                    ..
532                } => Self::verify_v4_transaction(
533                    &req,
534                    &network,
535                    script_verifier,
536                    cached_ffi_transaction.clone(),
537                    joinsplit_data,
538                )?,
539                Transaction::V5 {
540                    ..
541                } => Self::verify_v5_transaction(
542                    &req,
543                    &network,
544                    script_verifier,
545                    cached_ffi_transaction.clone(),
546                )?,
547                #[cfg(all(zcash_unstable = "nu7", feature = "tx_v6"))]
548                Transaction::V6 {
549                    ..
550                } => Self::verify_v6_transaction(
551                    &req,
552                    &network,
553                    script_verifier,
554                    cached_ffi_transaction.clone(),
555                )?,
556            };
557
558            if let Some(unmined_tx) = req.mempool_transaction() {
559                let check_anchors_and_revealed_nullifiers_query = state
560                    .clone()
561                    .oneshot(zs::Request::CheckBestChainTipNullifiersAndAnchors(
562                        unmined_tx,
563                    ))
564                    .map(|res| {
565                        assert!(
566                            res? == zs::Response::ValidBestChainTipNullifiersAndAnchors,
567                            "unexpected response to CheckBestChainTipNullifiersAndAnchors request"
568                        );
569                        Ok(())
570                    }
571                    );
572
573                async_checks.push(check_anchors_and_revealed_nullifiers_query);
574            }
575
576            tracing::trace!(?tx_id, "awaiting async checks...");
577
578            async_checks.check().await?;
579
580            tracing::trace!(?tx_id, "finished async checks");
581
582            // Get the `value_balance` to calculate the transaction fee.
583            let value_balance = tx.value_balance(&spent_utxos);
584
585            let zip233_amount = match *tx {
586            	#[cfg(all(zcash_unstable = "nu7", feature = "tx_v6"))]
587                Transaction::V6{ .. } => tx.zip233_amount(),
588                _ => Amount::zero()
589            };
590
591            // Calculate the fee only for non-coinbase transactions.
592            let mut miner_fee = None;
593            if !tx.is_coinbase() {
594                // TODO: deduplicate this code with remaining_transaction_value()?
595                miner_fee = match value_balance {
596                    Ok(vb) => match vb.remaining_transaction_value() {
597                        Ok(tx_rtv) => match tx_rtv - zip233_amount {
598                            Ok(fee) => Some(fee),
599                            Err(_) => return Err(TransactionError::IncorrectFee),
600                        }
601                        Err(_) => return Err(TransactionError::IncorrectFee),
602                    },
603                    Err(_) => return Err(TransactionError::IncorrectFee),
604                };
605            }
606
607            let sigops = tx.sigops().map_err(zebra_script::Error::from)?;
608
609            let rsp = match req {
610                Request::Block { .. } => Response::Block {
611                    tx_id,
612                    miner_fee,
613                    // In block validation, the consensus sigop total must include P2SH
614                    // redeem-script sigops, matching zcashd's `ConnectBlock` which sums
615                    // `GetLegacySigOpCount` and `GetP2SHSigOpCount` per transaction before
616                    // comparing against `MAX_BLOCK_SIGOPS`. Coinbase inputs contribute zero P2SH
617                    // sigops. See
618                    // <https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-jv4h-j224-23cc>.
619                    sigops: sigops.saturating_add(cached_ffi_transaction.p2sh_sigops()),
620                },
621                Request::Mempool { transaction: tx, .. } => {
622                    // TODO: `spent_outputs` may not align with `tx.inputs()` when a transaction
623                    // spends both chain and mempool UTXOs (mempool outputs are appended last by
624                    // `spent_utxos()`), causing policy checks to pair the wrong input with
625                    // the wrong spent output.
626                    // https://github.com/ZcashFoundation/zebra/issues/10346
627                    let spent_outputs = cached_ffi_transaction.all_previous_outputs().clone();
628                    let transaction = VerifiedUnminedTx::new(
629                        tx,
630                        miner_fee.expect("fee should have been checked earlier"),
631                        sigops,
632                        cached_ffi_transaction.p2sh_sigops(),
633                        spent_outputs.into(),
634                    )?;
635
636                    if let Some(mut mempool) = mempool {
637                        tokio::spawn(async move {
638                            // Best-effort poll of the mempool to provide a timely response to
639                            // `sendrawtransaction` RPC calls or `AwaitOutput` mempool calls.
640                            tokio::time::sleep(POLL_MEMPOOL_DELAY).await;
641                            let _ = mempool
642                                .ready()
643                                .await
644                                .expect("mempool poll_ready() method should not return an error")
645                                .call(mempool::Request::CheckForVerifiedTransactions)
646                                .await;
647                        });
648                    }
649
650                    Response::Mempool { transaction, spent_mempool_outpoints }
651                },
652            };
653
654            Ok(rsp)
655        }
656            .inspect(move |result| {
657                // Hide the transaction data to avoid filling the logs
658                tracing::trace!(?tx_id, result = ?result.as_ref().map(|_tx| ()), "got tx verify result");
659            })
660            .instrument(span)
661            .boxed()
662    }
663}
664
665impl<ZS, Mempool> Verifier<ZS, Mempool>
666where
667    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
668    ZS::Future: Send + 'static,
669    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
670        + Send
671        + Clone
672        + 'static,
673    Mempool::Future: Send + 'static,
674{
675    /// Fetches the median-time-past of the *next* block after the best state tip.
676    ///
677    /// This is used to verify that the lock times of mempool transactions
678    /// can be included in any valid next block.
679    async fn mempool_best_chain_next_median_time_past(
680        state: Timeout<ZS>,
681    ) -> Result<DateTime32, TransactionError> {
682        let query = state
683            .clone()
684            .oneshot(zs::Request::BestChainNextMedianTimePast);
685
686        if let zebra_state::Response::BestChainNextMedianTimePast(median_time_past) = query
687            .await
688            .map_err(|e| TransactionError::ValidateMempoolLockTimeError(e.to_string()))?
689        {
690            Ok(median_time_past)
691        } else {
692            unreachable!("Request::BestChainNextMedianTimePast always responds with BestChainNextMedianTimePast")
693        }
694    }
695
696    /// Wait for the UTXOs that are being spent by the given transaction.
697    ///
698    /// Looks up UTXOs that are being spent by the given transaction in the state or waits
699    /// for them to be added to the mempool for [`Mempool`](Request::Mempool) requests.
700    ///
701    /// Returns a triple containing:
702    /// - `OutPoint` -> `Utxo` map,
703    /// - vec of `Output`s in the same order as the matching inputs in the `tx`,
704    /// - vec of `Outpoint`s spent by a mempool `tx` that were not found in the best chain's utxo set.
705    async fn spent_utxos(
706        tx: Arc<Transaction>,
707        req: Request,
708        state: Timeout<ZS>,
709        mempool: Option<Timeout<Mempool>>,
710    ) -> Result<
711        (
712            HashMap<transparent::OutPoint, transparent::Utxo>,
713            Vec<transparent::Output>,
714            Vec<transparent::OutPoint>,
715        ),
716        TransactionError,
717    > {
718        let is_mempool = req.is_mempool();
719        // Additional UTXOs known at the time of validation,
720        // i.e., from previous transactions in the block.
721        let known_utxos = req.known_utxos();
722
723        let inputs = tx.inputs();
724        let mut spent_utxos = HashMap::new();
725        // Pre-allocate with None so we can fill each slot by input index, preserving input order
726        // even when chain and mempool UTXOs are fetched in separate passes.
727        let mut spent_outputs: Vec<Option<transparent::Output>> = vec![None; inputs.len()];
728        // Stores (input_idx, outpoint) for UTXOs not found in the best chain (fetched from mempool later).
729        let mut spent_mempool_outpoints: Vec<(usize, transparent::OutPoint)> = Vec::new();
730
731        for (input_idx, input) in inputs.iter().enumerate() {
732            if let transparent::Input::PrevOut { outpoint, .. } = input {
733                tracing::trace!("awaiting outpoint lookup");
734                let utxo = if let Some(output) = known_utxos.get(outpoint) {
735                    tracing::trace!("UXTO in known_utxos, discarding query");
736                    output.utxo.clone()
737                } else if is_mempool {
738                    let query = state
739                        .clone()
740                        .oneshot(zs::Request::UnspentBestChainUtxo(*outpoint));
741
742                    let zebra_state::Response::UnspentBestChainUtxo(utxo) = query
743                        .await
744                        .map_err(|_| TransactionError::TransparentInputNotFound)?
745                    else {
746                        unreachable!("UnspentBestChainUtxo always responds with Option<Utxo>")
747                    };
748
749                    let Some(utxo) = utxo else {
750                        spent_mempool_outpoints.push((input_idx, *outpoint));
751                        continue;
752                    };
753
754                    utxo
755                } else {
756                    let query = state
757                        .clone()
758                        .oneshot(zebra_state::Request::AwaitUtxo(*outpoint));
759                    if let zebra_state::Response::Utxo(utxo) = query.await? {
760                        utxo
761                    } else {
762                        unreachable!("AwaitUtxo always responds with Utxo")
763                    }
764                };
765                tracing::trace!(?utxo, "got UTXO");
766                spent_outputs[input_idx] = Some(utxo.output.clone());
767                spent_utxos.insert(*outpoint, utxo);
768            } else {
769                continue;
770            }
771        }
772
773        if let Some(mempool) = mempool {
774            for &(input_idx, spent_mempool_outpoint) in &spent_mempool_outpoints {
775                let query = mempool
776                    .clone()
777                    .oneshot(mempool::Request::AwaitOutput(spent_mempool_outpoint));
778
779                let output = match query.await {
780                    Ok(mempool::Response::UnspentOutput(output)) => output,
781                    Ok(_) => unreachable!("UnspentOutput always responds with UnspentOutput"),
782                    Err(err) => {
783                        return match err.downcast::<Elapsed>() {
784                            Ok(_) => Err(TransactionError::TransparentInputNotFound),
785                            Err(err) => Err(err.into()),
786                        };
787                    }
788                };
789
790                spent_outputs[input_idx] = Some(output.clone());
791                spent_utxos.insert(
792                    spent_mempool_outpoint,
793                    // Assume the Utxo height will be next height after the best chain tip height
794                    //
795                    // # Correctness
796                    //
797                    // If the tip height changes while an umined transaction is being verified,
798                    // the transaction must be re-verified before being added to the mempool.
799                    transparent::Utxo::new(output, req.height(), false),
800                );
801            }
802        } else if !spent_mempool_outpoints.is_empty() {
803            return Err(TransactionError::TransparentInputNotFound);
804        }
805
806        // Convert back to return types; slots are in input order.
807        let spent_outputs: Vec<transparent::Output> = spent_outputs.into_iter().flatten().collect();
808        let spent_mempool_outpoints: Vec<transparent::OutPoint> = spent_mempool_outpoints
809            .into_iter()
810            .map(|(_, op)| op)
811            .collect();
812
813        Ok((spent_utxos, spent_outputs, spent_mempool_outpoints))
814    }
815
816    /// Accepts `request`, a transaction verifier [`&Request`](Request),
817    /// and `spent_utxos`, a HashMap of UTXOs in the chain that are spent by this transaction.
818    ///
819    /// Gets the `transaction`, `height`, and `known_utxos` for the request and checks calls
820    /// [`check::tx_transparent_coinbase_spends_maturity`] to verify that every transparent
821    /// coinbase output spent by the transaction will have matured by `height`.
822    ///
823    /// Returns `Ok(())` if every transparent coinbase output spent by the transaction is
824    /// mature and valid for the request height, or a [`TransactionError`] if the transaction
825    /// spends transparent coinbase outputs that are immature and invalid for the request height.
826    pub fn check_maturity_height(
827        network: &Network,
828        request: &Request,
829        spent_utxos: &HashMap<transparent::OutPoint, transparent::Utxo>,
830    ) -> Result<(), TransactionError> {
831        check::tx_transparent_coinbase_spends_maturity(
832            network,
833            request.transaction(),
834            request.height(),
835            request.known_utxos(),
836            spent_utxos,
837        )
838    }
839
840    /// Verify a V4 transaction.
841    ///
842    /// Returns a set of asynchronous checks that must all succeed for the transaction to be
843    /// considered valid. These checks include:
844    ///
845    /// - transparent transfers
846    /// - sprout shielded data
847    /// - sapling shielded data
848    ///
849    /// The parameters of this method are:
850    ///
851    /// - the `request` to verify (that contains the transaction and other metadata, see [`Request`]
852    ///   for more information)
853    /// - the `network` to consider when verifying
854    /// - the `script_verifier` to use for verifying the transparent transfers
855    /// - the prepared `cached_ffi_transaction` used by the script verifier
856    /// - the Sprout `joinsplit_data` shielded data in the transaction
857    /// - the `sapling_shielded_data` in the transaction
858    #[allow(clippy::unwrap_in_result)]
859    fn verify_v4_transaction(
860        request: &Request,
861        network: &Network,
862        script_verifier: script::Verifier,
863        cached_ffi_transaction: Arc<CachedFfiTransaction>,
864        joinsplit_data: &Option<transaction::JoinSplitData<Groth16Proof>>,
865    ) -> Result<AsyncChecks, TransactionError> {
866        let tx = request.transaction();
867        let nu = request.upgrade(network);
868
869        Self::verify_v4_transaction_network_upgrade(&tx, nu)?;
870
871        let sapling_bundle = cached_ffi_transaction.sighasher().sapling_bundle();
872
873        let sighash = cached_ffi_transaction
874            .sighasher()
875            .sighash(HashType::ALL, None);
876
877        Ok(Self::verify_transparent_inputs_and_outputs(
878            request,
879            script_verifier,
880            cached_ffi_transaction,
881        )?
882        .and(Self::verify_sprout_shielded_data(joinsplit_data, &sighash)?)
883        .and(Self::verify_sapling_bundle(sapling_bundle, &sighash)))
884    }
885
886    /// Verifies if a V4 `transaction` is supported by `network_upgrade`.
887    fn verify_v4_transaction_network_upgrade(
888        transaction: &Transaction,
889        network_upgrade: NetworkUpgrade,
890    ) -> Result<(), TransactionError> {
891        match network_upgrade {
892            // Supports V4 transactions
893            //
894            // # Consensus
895            //
896            // > [Sapling to Canopy inclusive, pre-NU5] The transaction version number MUST be 4,
897            // > and the version group ID MUST be 0x892F2085.
898            //
899            // > [NU5 onward] The transaction version number MUST be 4 or 5.
900            // > If the transaction version number is 4 then the version group ID MUST be 0x892F2085.
901            // > If the transaction version number is 5 then the version group ID MUST be 0x26A7270A.
902            //
903            // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
904            //
905            // Note: Here we verify the transaction version number of the above two rules, the group
906            // id is checked in zebra-chain crate, in the transaction serialize.
907            NetworkUpgrade::Sapling
908            | NetworkUpgrade::Blossom
909            | NetworkUpgrade::Heartwood
910            | NetworkUpgrade::Canopy
911            | NetworkUpgrade::Nu5
912            | NetworkUpgrade::Nu6
913            | NetworkUpgrade::Nu6_1
914            | NetworkUpgrade::Nu6_2 => Ok(()),
915
916            #[cfg(zcash_unstable = "zfuture")]
917            NetworkUpgrade::ZFuture => Ok(()),
918
919            // Does not support V4 transactions
920            NetworkUpgrade::Genesis
921            | NetworkUpgrade::BeforeOverwinter
922            | NetworkUpgrade::Overwinter
923            | NetworkUpgrade::Nu7 => Err(TransactionError::UnsupportedByNetworkUpgrade(
924                transaction.version(),
925                network_upgrade,
926            )),
927        }
928    }
929
930    /// Verify a V5 transaction.
931    ///
932    /// Returns a set of asynchronous checks that must all succeed for the transaction to be
933    /// considered valid. These checks include:
934    ///
935    /// - transaction support by the considered network upgrade (see [`Request::upgrade`])
936    /// - transparent transfers
937    /// - sapling shielded data (TODO)
938    /// - orchard shielded data (TODO)
939    ///
940    /// The parameters of this method are:
941    ///
942    /// - the `request` to verify (that contains the transaction and other metadata, see [`Request`]
943    ///   for more information)
944    /// - the `network` to consider when verifying
945    /// - the `script_verifier` to use for verifying the transparent transfers
946    /// - the prepared `cached_ffi_transaction` used by the script verifier
947    /// - the sapling shielded data of the transaction, if any
948    /// - the orchard shielded data of the transaction, if any
949    #[allow(clippy::unwrap_in_result)]
950    fn verify_v5_transaction(
951        request: &Request,
952        network: &Network,
953        script_verifier: script::Verifier,
954        cached_ffi_transaction: Arc<CachedFfiTransaction>,
955    ) -> Result<AsyncChecks, TransactionError> {
956        let transaction = request.transaction();
957        let nu = request.upgrade(network);
958
959        Self::verify_v5_transaction_network_upgrade(&transaction, nu)?;
960
961        let sapling_bundle = cached_ffi_transaction.sighasher().sapling_bundle();
962        let orchard_bundle = cached_ffi_transaction.sighasher().orchard_bundle();
963
964        let sighash = cached_ffi_transaction
965            .sighasher()
966            .sighash(HashType::ALL, None);
967
968        Ok(Self::verify_transparent_inputs_and_outputs(
969            request,
970            script_verifier,
971            cached_ffi_transaction,
972        )?
973        .and(Self::verify_sapling_bundle(sapling_bundle, &sighash))
974        .and(Self::verify_orchard_bundle(orchard_bundle, &sighash, nu)))
975    }
976
977    /// Verifies if a V5 `transaction` is supported by `network_upgrade`.
978    fn verify_v5_transaction_network_upgrade(
979        transaction: &Transaction,
980        network_upgrade: NetworkUpgrade,
981    ) -> Result<(), TransactionError> {
982        match network_upgrade {
983            // Supports V5 transactions
984            //
985            // # Consensus
986            //
987            // > [NU5 onward] The transaction version number MUST be 4 or 5.
988            // > If the transaction version number is 4 then the version group ID MUST be 0x892F2085.
989            // > If the transaction version number is 5 then the version group ID MUST be 0x26A7270A.
990            //
991            // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
992            //
993            // Note: Here we verify the transaction version number of the above rule, the group
994            // id is checked in zebra-chain crate, in the transaction serialize.
995            NetworkUpgrade::Nu5
996            | NetworkUpgrade::Nu6
997            | NetworkUpgrade::Nu6_1
998            | NetworkUpgrade::Nu6_2
999            | NetworkUpgrade::Nu7 => Ok(()),
1000
1001            #[cfg(zcash_unstable = "zfuture")]
1002            NetworkUpgrade::ZFuture => Ok(()),
1003
1004            // Does not support V5 transactions
1005            NetworkUpgrade::Genesis
1006            | NetworkUpgrade::BeforeOverwinter
1007            | NetworkUpgrade::Overwinter
1008            | NetworkUpgrade::Sapling
1009            | NetworkUpgrade::Blossom
1010            | NetworkUpgrade::Heartwood
1011            | NetworkUpgrade::Canopy => Err(TransactionError::UnsupportedByNetworkUpgrade(
1012                transaction.version(),
1013                network_upgrade,
1014            )),
1015        }
1016    }
1017
1018    /// Passthrough to verify_v5_transaction, but for V6 transactions.
1019    #[cfg(all(zcash_unstable = "nu7", feature = "tx_v6"))]
1020    fn verify_v6_transaction(
1021        request: &Request,
1022        network: &Network,
1023        script_verifier: script::Verifier,
1024        cached_ffi_transaction: Arc<CachedFfiTransaction>,
1025    ) -> Result<AsyncChecks, TransactionError> {
1026        Self::verify_v5_transaction(request, network, script_verifier, cached_ffi_transaction)
1027    }
1028
1029    /// Verifies if a transaction's transparent inputs are valid using the provided
1030    /// `script_verifier` and `cached_ffi_transaction`.
1031    ///
1032    /// Returns script verification responses via the `utxo_sender`.
1033    fn verify_transparent_inputs_and_outputs(
1034        request: &Request,
1035        script_verifier: script::Verifier,
1036        cached_ffi_transaction: Arc<CachedFfiTransaction>,
1037    ) -> Result<AsyncChecks, TransactionError> {
1038        let transaction = request.transaction();
1039
1040        if transaction.is_coinbase() {
1041            // The script verifier only verifies PrevOut inputs and their corresponding UTXOs.
1042            // Coinbase transactions don't have any PrevOut inputs.
1043            Ok(AsyncChecks::new())
1044        } else {
1045            // feed all of the inputs to the script verifier
1046            let inputs = transaction.inputs();
1047
1048            let script_checks = (0..inputs.len())
1049                .map(move |input_index| {
1050                    let request = script::Request {
1051                        cached_ffi_transaction: cached_ffi_transaction.clone(),
1052                        input_index,
1053                    };
1054
1055                    script_verifier.oneshot(request)
1056                })
1057                .collect();
1058
1059            Ok(script_checks)
1060        }
1061    }
1062
1063    /// Verifies a transaction's Sprout shielded join split data.
1064    fn verify_sprout_shielded_data(
1065        joinsplit_data: &Option<transaction::JoinSplitData<Groth16Proof>>,
1066        shielded_sighash: &SigHash,
1067    ) -> Result<AsyncChecks, TransactionError> {
1068        let mut checks = AsyncChecks::new();
1069
1070        if let Some(joinsplit_data) = joinsplit_data {
1071            for joinsplit in joinsplit_data.joinsplits() {
1072                // # Consensus
1073                //
1074                // > The proof π_ZKJoinSplit MUST be valid given a
1075                // > primary input formed from the relevant other fields and h_{Sig}
1076                //
1077                // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
1078                //
1079                // Queue the verification of the Groth16 spend proof
1080                // for each JoinSplit description while adding the
1081                // resulting future to our collection of async
1082                // checks that (at a minimum) must pass for the
1083                // transaction to verify.
1084                checks.push(primitives::groth16::JOINSPLIT_VERIFIER.oneshot(
1085                    primitives::groth16::Item::from_joinsplit(joinsplit, &joinsplit_data.pub_key)?,
1086                ));
1087            }
1088
1089            // # Consensus
1090            //
1091            // > If effectiveVersion ≥ 2 and nJoinSplit > 0, then:
1092            // > - joinSplitPubKey MUST be a valid encoding of an Ed25519 validating key
1093            // > - joinSplitSig MUST represent a valid signature under
1094            //     joinSplitPubKey of dataToBeSigned, as defined in § 4.11
1095            //
1096            // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1097            //
1098            // The `if` part is indirectly enforced, since the `joinsplit_data`
1099            // is only parsed if those conditions apply in
1100            // [`Transaction::zcash_deserialize`].
1101            //
1102            // The valid encoding is defined in
1103            //
1104            // > A valid Ed25519 validating key is defined as a sequence of 32
1105            // > bytes encoding a point on the Ed25519 curve
1106            //
1107            // https://zips.z.cash/protocol/protocol.pdf#concreteed25519
1108            //
1109            // which is enforced during signature verification, in both batched
1110            // and single verification, when decompressing the encoded point.
1111            //
1112            // Queue the validation of the JoinSplit signature while
1113            // adding the resulting future to our collection of
1114            // async checks that (at a minimum) must pass for the
1115            // transaction to verify.
1116            //
1117            // https://zips.z.cash/protocol/protocol.pdf#sproutnonmalleability
1118            // https://zips.z.cash/protocol/protocol.pdf#txnencodingandconsensus
1119            let ed25519_verifier = primitives::ed25519::VERIFIER.clone();
1120            let ed25519_item =
1121                (joinsplit_data.pub_key, joinsplit_data.sig, shielded_sighash).into();
1122
1123            checks.push(ed25519_verifier.oneshot(ed25519_item));
1124        }
1125
1126        Ok(checks)
1127    }
1128
1129    /// Verifies a transaction's Sapling shielded data.
1130    fn verify_sapling_bundle(
1131        bundle: Option<sapling_crypto::Bundle<sapling_crypto::bundle::Authorized, ZatBalance>>,
1132        sighash: &SigHash,
1133    ) -> AsyncChecks {
1134        let mut async_checks = AsyncChecks::new();
1135
1136        // The Sapling batch verifier checks the following consensus rules:
1137        //
1138        // # Consensus
1139        //
1140        // > The proof π_ZKSpend MUST be valid given a primary input formed from the other fields
1141        // > except spendAuthSig.
1142        //
1143        // > The spend authorization signature MUST be a valid SpendAuthSig signature over SigHash
1144        // > using rk as the validating key.
1145        //
1146        // > [NU5 onward] As specified in § 5.4.7 ‘RedDSA, RedJubjub, and RedPallas’ on p. 88, the
1147        // > validation of the 𝑅 component of the signature changes to prohibit non-canonical
1148        // > encodings.
1149        //
1150        // https://zips.z.cash/protocol/protocol.pdf#spenddesc
1151        //
1152        // # Consensus
1153        //
1154        // > The proof π_ZKOutput MUST be valid given a primary input formed from the other fields
1155        // > except C^enc and C^out.
1156        //
1157        // https://zips.z.cash/protocol/protocol.pdf#outputdesc
1158        //
1159        // # Consensus
1160        //
1161        // > The Spend transfers and Action transfers of a transaction MUST be consistent with its
1162        // > vbalanceSapling value as specified in § 4.13 ‘Balance and Binding Signature (Sapling)’.
1163        //
1164        // https://zips.z.cash/protocol/protocol.pdf#spendsandoutputs
1165        //
1166        // # Consensus
1167        //
1168        // > [Sapling onward] If effectiveVersion ≥ 4 and nSpendsSapling + nOutputsSapling > 0,
1169        // > then:
1170        // >
1171        // > – let bvk^{Sapling} and SigHash be as defined in § 4.13;
1172        // > – bindingSigSapling MUST represent a valid signature under the transaction binding
1173        // >   validating key bvk Sapling of SigHash — i.e.
1174        // >   BindingSig^{Sapling}.Validate_{bvk^{Sapling}}(SigHash, bindingSigSapling ) = 1.
1175        //
1176        // Note that the `if` part is indirectly enforced, since the `sapling_shielded_data` is only
1177        // parsed if those conditions apply in [`Transaction::zcash_deserialize`].
1178        //
1179        // > [NU5 onward] As specified in § 5.4.7, the validation of the 𝑅 component of the
1180        // > signature changes to prohibit non-canonical encodings.
1181        //
1182        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1183        if let Some(bundle) = bundle {
1184            async_checks.push(
1185                primitives::sapling::VERIFIER
1186                    .clone()
1187                    .oneshot(primitives::sapling::Item::new(bundle, *sighash)),
1188            );
1189        }
1190
1191        async_checks
1192    }
1193
1194    /// Verifies a transaction's Orchard shielded data.
1195    ///
1196    /// `network_upgrade` is the network upgrade active at the verified transaction's block
1197    /// height. It selects the Orchard verifier: the Orchard Action circuit (and its verifying
1198    /// key) changed at NU6.2 to fix the variable-base scalar-multiplication bug
1199    /// (GHSA-jfw5-j458-pfv6), so pre-NU6.2 bundles must be verified against the historical
1200    /// (insecure) key and NU6.2+ bundles against the fixed key. A proof from one era does not
1201    /// verify under the other era's key. [`primitives::halo2::verifier_for`] maps the upgrade to
1202    /// the verifier holding the matching key; the two verifiers keep separate batches, so eras
1203    /// are never mixed.
1204    fn verify_orchard_bundle(
1205        bundle: Option<::orchard::bundle::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1206        sighash: &SigHash,
1207        network_upgrade: NetworkUpgrade,
1208    ) -> AsyncChecks {
1209        let mut async_checks = AsyncChecks::new();
1210
1211        if let Some(bundle) = bundle {
1212            // # Consensus
1213            //
1214            // > The proof 𝜋 MUST be valid given a primary input (cv, rt^{Orchard},
1215            // > nf, rk, cm_x, enableSpends, enableOutputs)
1216            //
1217            // https://zips.z.cash/protocol/protocol.pdf#actiondesc
1218            //
1219            // Unlike Sapling, Orchard shielded transactions have a single
1220            // aggregated Halo2 proof per transaction, even with multiple
1221            // Actions in one transaction. So we queue it for verification
1222            // only once instead of queuing it up for every Action description.
1223            //
1224            // Route the bundle to the verifier for its circuit era: pre-NU6.2 bundles only
1225            // verify under the insecure key, NU6.2+ bundles only under the fixed key.
1226            async_checks.push(
1227                primitives::halo2::verifier_for(network_upgrade)
1228                    .clone()
1229                    .oneshot(primitives::halo2::Item::new(bundle, *sighash)),
1230            );
1231        }
1232
1233        async_checks
1234    }
1235}
1236
1237/// A set of unordered asynchronous checks that should succeed.
1238///
1239/// A wrapper around [`FuturesUnordered`] with some auxiliary methods.
1240struct AsyncChecks(FuturesUnordered<Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>>>);
1241
1242impl AsyncChecks {
1243    /// Create an empty set of unordered asynchronous checks.
1244    pub fn new() -> Self {
1245        AsyncChecks(FuturesUnordered::new())
1246    }
1247
1248    /// Push a check into the set.
1249    pub fn push(&mut self, check: impl Future<Output = Result<(), BoxError>> + Send + 'static) {
1250        self.0.push(check.boxed());
1251    }
1252
1253    /// Push a set of checks into the set.
1254    ///
1255    /// This method can be daisy-chained.
1256    pub fn and(mut self, checks: AsyncChecks) -> Self {
1257        self.0.extend(checks.0);
1258        self
1259    }
1260
1261    /// Wait until all checks in the set finish.
1262    ///
1263    /// If any of the checks fail, this method immediately returns the error and cancels all other
1264    /// checks by dropping them.
1265    async fn check(mut self) -> Result<(), BoxError> {
1266        // Wait for all asynchronous checks to complete
1267        // successfully, or fail verification if they error.
1268        while let Some(check) = self.0.next().await {
1269            tracing::trace!(?check, remaining = self.0.len());
1270            check?;
1271        }
1272
1273        Ok(())
1274    }
1275}
1276
1277impl<F> FromIterator<F> for AsyncChecks
1278where
1279    F: Future<Output = Result<(), BoxError>> + Send + 'static,
1280{
1281    fn from_iter<I>(iterator: I) -> Self
1282    where
1283        I: IntoIterator<Item = F>,
1284    {
1285        AsyncChecks(iterator.into_iter().map(FutureExt::boxed).collect())
1286    }
1287}