Skip to main content

zebra_consensus/
transaction.rs

1//! Asynchronous verification of transactions.
2
3use std::{
4    collections::HashMap,
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    serialization::DateTime32,
33    transaction::{
34        self, HashType, SigHash, Transaction, TxVersion, UnminedTx, UnminedTxId, VerifiedUnminedTx,
35    },
36    transparent,
37};
38
39use zebra_node_services::mempool;
40use zebra_script::{CachedFfiTransaction, Sigops};
41use zebra_state as zs;
42
43use crate::{error::TransactionError, primitives, script, BoxError};
44
45pub mod check;
46#[cfg(test)]
47mod tests;
48
49/// A timeout applied to UTXO lookup requests.
50///
51/// The exact value is non-essential, but this should be long enough to allow
52/// out-of-order verification of blocks (UTXOs are not required to be ready
53/// immediately) while being short enough to:
54///   * prune blocks that are too far in the future to be worth keeping in the
55///     queue,
56///   * fail blocks that reference invalid UTXOs, and
57///   * fail blocks that reference UTXOs from blocks that have temporarily failed
58///     to download, because a peer sent Zebra a bad list of block hashes. (The
59///     UTXO verification failure will restart the sync, and re-download the
60///     chain in the correct order.)
61const UTXO_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(6 * 60);
62
63/// A timeout applied to output lookup requests sent to the mempool. This is shorter than the
64/// timeout for the state UTXO lookups because a block is likely to be mined every 75 seconds
65/// after Blossom is active, changing the best chain tip and requiring re-verification of transactions
66/// in the mempool.
67///
68/// This is how long Zebra will wait for an output to be added to the mempool before verification
69/// of the transaction that spends it will fail.
70const MEMPOOL_OUTPUT_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
71
72/// How long to wait after responding to a mempool request with a transaction that creates new
73/// transparent outputs before polling the mempool service so that it will try adding the verified
74/// transaction and responding to any potential `AwaitOutput` requests.
75///
76/// This should be long enough for the mempool service's `Downloads` to finish processing the
77/// response from the transaction verifier.
78const POLL_MEMPOOL_DELAY: std::time::Duration = Duration::from_millis(50);
79
80/// Asynchronous verification of block transactions.
81///
82/// # Correctness
83///
84/// Transaction verification requests should be wrapped in a timeout, so that
85/// out-of-order and invalid requests do not hang indefinitely. See the [`router`](`crate::router`)
86/// module documentation for details.
87pub struct BlockTxVerifier<ZS> {
88    network: Network,
89    state: Timeout<ZS>,
90    script_verifier: script::Verifier,
91}
92
93impl<ZS> BlockTxVerifier<ZS>
94where
95    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
96    ZS::Future: Send + 'static,
97{
98    /// Creates a new block transaction verifier.
99    pub fn new(network: &Network, state: ZS) -> Self {
100        Self {
101            network: network.clone(),
102            state: Timeout::new(state, UTXO_LOOKUP_TIMEOUT),
103            script_verifier: script::Verifier,
104        }
105    }
106}
107
108/// Asynchronous verification of mempool transactions.
109///
110/// # Correctness
111///
112/// Transaction verification requests should be wrapped in a timeout, so that
113/// out-of-order and invalid requests do not hang indefinitely. See the [`router`](`crate::router`)
114/// module documentation for details.
115pub struct MempoolTxVerifier<ZS, Mempool> {
116    network: Network,
117    state: Timeout<ZS>,
118    mempool: Option<Timeout<Mempool>>,
119    script_verifier: script::Verifier,
120    mempool_setup_rx: oneshot::Receiver<Mempool>,
121}
122
123impl<ZS, Mempool> MempoolTxVerifier<ZS, Mempool>
124where
125    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
126    ZS::Future: Send + 'static,
127    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
128        + Send
129        + Clone
130        + 'static,
131    Mempool::Future: Send + 'static,
132{
133    /// Creates a new mempool transaction verifier.
134    pub fn new(network: &Network, state: ZS, mempool_setup_rx: oneshot::Receiver<Mempool>) -> Self {
135        Self {
136            network: network.clone(),
137            state: Timeout::new(state, UTXO_LOOKUP_TIMEOUT),
138            mempool: None,
139            script_verifier: script::Verifier,
140            mempool_setup_rx,
141        }
142    }
143}
144
145impl<ZS>
146    MempoolTxVerifier<
147        ZS,
148        Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>,
149    >
150where
151    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
152    ZS::Future: Send + 'static,
153{
154    /// Creates a new mempool transaction verifier for tests using a closed
155    /// mempool setup channel receiver.
156    #[cfg(test)]
157    pub fn new_for_tests(network: &Network, state: ZS) -> Self {
158        Self {
159            network: network.clone(),
160            state: Timeout::new(state, UTXO_LOOKUP_TIMEOUT),
161            mempool: None,
162            script_verifier: script::Verifier,
163            mempool_setup_rx: oneshot::channel().1,
164        }
165    }
166}
167
168/// A request to verify a transaction as part of a block.
169#[derive(Clone, Debug, Eq, PartialEq)]
170pub struct BlockRequest {
171    /// The mined transaction ID of `transaction`.
172    /// Used for efficiency: callers should already have this,
173    /// so no need to recompute it in the verifier.
174    pub transaction_hash: transaction::Hash,
175    /// The transaction itself.
176    pub transaction: Arc<Transaction>,
177    /// Additional UTXOs which are known at the time of verification.
178    pub known_utxos: Arc<HashMap<transparent::OutPoint, transparent::OrderedUtxo>>,
179    /// The height of the block containing this transaction.
180    pub height: block::Height,
181    /// The time that the block was mined.
182    pub time: DateTime<Utc>,
183}
184
185/// A request to verify a transaction as part of the mempool.
186///
187/// Mempool transactions do not have any additional UTXOs.
188///
189/// Note: coinbase transactions are invalid in the mempool.
190#[derive(Clone, Debug, Eq, PartialEq)]
191pub struct MempoolRequest {
192    /// The transaction itself.
193    pub transaction: UnminedTx,
194    /// The height of the next block.
195    ///
196    /// The next block is the first block that could possibly contain a
197    /// mempool transaction.
198    pub height: block::Height,
199}
200
201/// A response to a block transaction verification request.
202#[derive(Clone, Debug, PartialEq)]
203pub struct BlockResponse {
204    /// The witnessed transaction ID for this transaction.
205    ///
206    /// [`BlockResponse`] responses can be uniquely identified by
207    /// [`UnminedTxId::mined_id`], because the block's authorizing data root
208    /// will be checked during contextual validation.
209    pub tx_id: UnminedTxId,
210
211    /// The miner fee for this transaction.
212    ///
213    /// `None` for coinbase transactions.
214    ///
215    /// # Consensus
216    ///
217    /// > The remaining value in the transparent transaction value pool
218    /// > of a coinbase transaction is destroyed.
219    ///
220    /// <https://zips.z.cash/protocol/protocol.pdf#transactions>
221    pub miner_fee: Option<Amount<NonNegative>>,
222
223    /// The total number of transparent signature operations counted for block
224    /// verification in this transaction: legacy sigops plus P2SH sigops.
225    ///
226    /// This value is used to enforce the block-level `MAX_BLOCK_SIGOPS` limit.
227    pub sigops: u32,
228}
229
230/// A response to a mempool transaction verification request.
231#[derive(Clone, Debug, PartialEq)]
232pub struct MempoolResponse {
233    /// The full content of the verified mempool transaction.
234    /// Also contains the transaction fee and other associated fields.
235    ///
236    /// Mempool transactions always have a transaction fee,
237    /// because coinbase transactions are rejected from the mempool.
238    ///
239    /// [`MempoolResponse`] responses are uniquely identified by the
240    /// [`UnminedTxId`] variant for their transaction version.
241    pub transaction: VerifiedUnminedTx,
242
243    /// A list of spent [`transparent::OutPoint`]s that were found in
244    /// the mempool's list of `created_outputs`.
245    ///
246    /// Used by the mempool to determine dependencies between transactions
247    /// in the mempool and to avoid adding transactions with missing spends
248    /// to its verified set.
249    pub spent_mempool_outpoints: Vec<transparent::OutPoint>,
250}
251
252#[cfg(any(test, feature = "proptest-impl"))]
253impl From<VerifiedUnminedTx> for MempoolResponse {
254    fn from(transaction: VerifiedUnminedTx) -> Self {
255        MempoolResponse {
256            transaction,
257            spent_mempool_outpoints: Vec::new(),
258        }
259    }
260}
261
262impl<ZS> Service<BlockRequest> for BlockTxVerifier<ZS>
263where
264    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
265    ZS::Future: Send + 'static,
266{
267    type Response = BlockResponse;
268    type Error = TransactionError;
269    type Future =
270        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
271
272    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
273        // Block verification has no deferred startup dependencies: all required state is
274        // provided at construction, and any missing UTXOs are handled during request
275        // processing via state lookups.
276        Poll::Ready(Ok(()))
277    }
278
279    fn call(&mut self, req: BlockRequest) -> Self::Future {
280        let script_verifier = self.script_verifier;
281        let network = self.network.clone();
282        let state = self.state.clone();
283
284        let tx = req.transaction.clone();
285        // Reuse the caller's precomputed hash instead of calling `Transaction::unmined_id()`,
286        // which would re-serialize and re-hash the whole transaction.
287        // `Transaction::auth_digest()` returns `None` for exactly the versions that
288        // `UnminedTxId::from(&Transaction)` maps to `Legacy` (v1-v4), and `Some` for those it
289        // maps to `Witnessed` (v5 onward), so deriving the variant from it stays correct if a
290        // later transaction version is added.
291        let tx_id = match tx.auth_digest() {
292            None => UnminedTxId::Legacy(req.transaction_hash),
293            Some(auth_digest) => UnminedTxId::Witnessed(transaction::WtxId {
294                id: req.transaction_hash,
295                auth_digest,
296            }),
297        };
298        let height = req.height;
299        let time = req.time;
300        let known_utxos = req.known_utxos.clone();
301        let nu = NetworkUpgrade::current(&network, height);
302        let span = tracing::debug_span!("tx", ?tx_id);
303
304        async move {
305            tracing::trace!(?tx_id, ?req, "got tx verify request");
306
307            // Do quick checks first
308            check_common_consensus_rules(tx.as_ref(), height, &network)?;
309
310            tracing::trace!(?tx_id, "passed quick checks");
311
312            // Block transactions are checked against the block's own time directly.
313            check::lock_time_has_passed(&tx, height, time)?;
314
315            // "The consensus rules applied to valueBalance, vShieldedOutput, and bindingSig
316            // in non-coinbase transactions MUST also be applied to coinbase transactions."
317            //
318            // This rule is implicitly implemented during Sapling and Orchard verification,
319            // because they do not distinguish between coinbase and non-coinbase transactions.
320            //
321            // Note: this rule originally applied to Sapling, but we assume it also applies to Orchard.
322            //
323            // https://zips.z.cash/zip-0213#specification
324
325            // Load spent UTXOs from the block context and state.
326            // The UTXOs are required for almost all the async checks.
327            let (spent_utxos, spent_outputs) =
328                Self::block_spent_utxos(tx.clone(), known_utxos, state.clone()).await?;
329
330            let cached_ffi_transaction =
331                Arc::new(CachedFfiTransaction::new(tx.clone(), Arc::new(spent_outputs), nu).map_err(|_| TransactionError::UnsupportedByNetworkUpgrade(tx.version(), nu))?);
332
333            tracing::trace!(?tx_id, "got state UTXOs");
334
335            // Select version-specific async verification pipeline
336            let async_checks = dispatch_version_verification(
337                tx.as_ref(),
338                nu,
339                script_verifier,
340                cached_ffi_transaction.clone(),
341                tx_id,
342            )?;
343
344            tracing::trace!(?tx_id, "awaiting async checks...");
345
346            async_checks.check().await?;
347
348            tracing::trace!(?tx_id, "finished async checks");
349
350            let miner_fee = if tx.is_coinbase() {
351                None
352            } else {
353                Some(miner_fee(tx.as_ref(), &spent_utxos)?)
354            };
355            let sigops = tx.sigops().map_err(zebra_script::Error::from)?;
356
357            Ok(BlockResponse {
358                tx_id,
359                miner_fee,
360                // In block validation, the consensus sigop total must include P2SH
361                // redeem-script sigops, matching zcashd's `ConnectBlock` which sums
362                // `GetLegacySigOpCount` and `GetP2SHSigOpCount` per transaction before
363                // comparing against `MAX_BLOCK_SIGOPS`. Coinbase inputs contribute zero P2SH
364                // sigops. See
365                // <https://github.com/ZcashFoundation/zebra/security/advisories/GHSA-jv4h-j224-23cc>.
366                sigops: sigops.saturating_add(cached_ffi_transaction.p2sh_sigops()),
367            })
368        }
369            .inspect(move |result| {
370                // Hide the transaction data to avoid filling the logs
371                tracing::trace!(?tx_id, result = ?result.as_ref().map(|_tx| ()), "got tx verify result");
372            })
373            .instrument(span)
374            .boxed()
375    }
376}
377
378impl<ZS> BlockTxVerifier<ZS>
379where
380    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
381    ZS::Future: Send + 'static,
382{
383    /// Looks up UTXOs spent by `tx` from the best chain state, also checking
384    /// `known_utxos` for UTXOs from earlier transactions in the same block.
385    ///
386    /// Returns an `OutPoint -> Utxo` map and a vec of `Output`s in the same
387    /// order as the matching inputs in `tx`.
388    async fn block_spent_utxos(
389        tx: Arc<Transaction>,
390        known_utxos: Arc<HashMap<transparent::OutPoint, transparent::OrderedUtxo>>,
391        state: Timeout<ZS>,
392    ) -> Result<
393        (
394            HashMap<transparent::OutPoint, transparent::Utxo>,
395            Vec<transparent::Output>,
396        ),
397        TransactionError,
398    > {
399        let inputs = tx.inputs();
400        let mut spent_utxos = HashMap::new();
401        // Pre-allocate with None so we can fill each slot by input index, preserving input order.
402        let mut spent_outputs: Vec<Option<transparent::Output>> = vec![None; inputs.len()];
403
404        for (input_idx, input) in inputs.iter().enumerate() {
405            if let transparent::Input::PrevOut { outpoint, .. } = input {
406                tracing::trace!("awaiting outpoint lookup");
407
408                let utxo = if let Some(output) = known_utxos.get(outpoint) {
409                    tracing::trace!("UTXO in known_utxos, discarding query");
410                    output.utxo.clone()
411                } else {
412                    let response = state
413                        .clone()
414                        .oneshot(zebra_state::Request::AwaitUtxo(*outpoint))
415                        .await
416                        .map_err(|boxed_error| match boxed_error.downcast::<Elapsed>() {
417                            Ok(_) => TransactionError::TransparentInputNotFound,
418                            Err(boxed_error) => TransactionError::from(boxed_error),
419                        })?;
420
421                    if let zebra_state::Response::Utxo(utxo) = response {
422                        utxo
423                    } else {
424                        unreachable!("AwaitUtxo always responds with Utxo")
425                    }
426                };
427                tracing::trace!(?utxo, "got UTXO");
428                spent_outputs[input_idx] = Some(utxo.output.clone());
429                spent_utxos.insert(*outpoint, utxo);
430            }
431        }
432
433        let spent_outputs: Vec<transparent::Output> = spent_outputs.into_iter().flatten().collect();
434
435        Ok((spent_utxos, spent_outputs))
436    }
437}
438
439impl<ZS, Mempool> Service<MempoolRequest> for MempoolTxVerifier<ZS, Mempool>
440where
441    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
442    ZS::Future: Send + 'static,
443    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
444        + Send
445        + Clone
446        + 'static,
447    Mempool::Future: Send + 'static,
448{
449    type Response = MempoolResponse;
450    type Error = TransactionError;
451    type Future =
452        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
453
454    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
455        // Opportunistically install the mempool service once startup wiring provides it.
456        // The verifier remains ready even before that happens: requests that require
457        // mempool-only outputs will fail during verification if the mempool handle is
458        // still unavailable.
459        if self.mempool.is_none() {
460            if let Ok(mempool) = self.mempool_setup_rx.try_recv() {
461                self.mempool = Some(Timeout::new(mempool, MEMPOOL_OUTPUT_LOOKUP_TIMEOUT));
462            }
463        }
464
465        Poll::Ready(Ok(()))
466    }
467
468    fn call(&mut self, req: MempoolRequest) -> Self::Future {
469        let script_verifier = self.script_verifier;
470        let network = self.network.clone();
471        let state = self.state.clone();
472        let mempool = self.mempool.clone();
473
474        let tx = req.transaction.transaction.clone();
475        let tx_id = req.transaction.id;
476        let height = req.height;
477        let unmined_tx = req.transaction.clone();
478        let nu = NetworkUpgrade::current(&network, height);
479        let span = tracing::debug_span!("tx", ?tx_id);
480
481        async move {
482            tracing::trace!(?tx_id, ?req, "got tx verify request");
483
484            if tx.is_coinbase() {
485                return Err(TransactionError::CoinbaseInMempool);
486            }
487
488            // A mempool transaction must fit in the next block's ZIP 218 shielded budget.
489            // Reject it before state lookups or proof verification; block verification checks
490            // the aggregate budget separately, including the coinbase.
491            if nu >= NetworkUpgrade::Nu7 {
492                if let Some((pool, count, limit)) =
493                    crate::block::ShieldedActionCounts::from_transaction(tx.as_ref()).exceeded_limit()
494                {
495                    return Err(TransactionError::TooManyShieldedActions { pool, count, limit });
496                }
497            }
498
499            // Do quick checks first
500            check_common_consensus_rules(tx.as_ref(), height, &network)?;
501
502            tracing::trace!(?tx_id, "passed quick checks");
503
504            // Mempool transactions are checked against the next median-time-past from state.
505            Self::verify_mempool_lock_time(tx.as_ref(), height, state.clone()).await?;
506
507            // "The consensus rules applied to valueBalance, vShieldedOutput, and bindingSig
508            // in non-coinbase transactions MUST also be applied to coinbase transactions."
509            //
510            // This rule is implicitly implemented during Sapling and Orchard verification,
511            // because they do not distinguish between coinbase and non-coinbase transactions.
512            //
513            // Note: this rule originally applied to Sapling, but we assume it also applies to Orchard.
514            //
515            // https://zips.z.cash/zip-0213#specification
516
517            // Load spent UTXOs from state.
518            // The UTXOs are required for almost all the async checks.
519            let (spent_utxos, spent_outputs, spent_mempool_outpoints) =
520                Self::mempool_spent_utxos(tx.clone(), height, state.clone(), mempool.clone()).await?;
521
522            // Mempool transactions have no block context, so there are no outputs from
523            // earlier transactions in the same block to consider.
524            check_maturity_height(tx.clone(), height, &network, &spent_utxos)?;
525
526            // Reject non-standard input scripts (oversized or non-push-only
527            // scriptSigs, and high-sigop P2SH redeem scripts) *before*
528            // doing expensive script verification, to avoid DoS attacks on
529            // the script interpreter.
530            check::mempool_standard_input_scripts(tx.as_ref(), &spent_outputs)?;
531
532            // Reject transactions above the standard sigop limit before script verification
533            // checks every one of their signatures, in the same order as zcashd:
534            // https://github.com/zcash/zcash/blob/v6.11.0/src/main.cpp#L1901-L1905
535            let sigops = tx.sigops().map_err(zebra_script::Error::from)?;
536            let p2sh_sigops = zebra_script::p2sh_sigop_count(tx.as_ref(), &spent_outputs);
537            let total_sigops = sigops.saturating_add(p2sh_sigops);
538            if total_sigops > check::MAX_STANDARD_TX_SIGOPS {
539                return Err(TransactionError::NonStandardSigops { sigops: total_sigops });
540            }
541
542            // Apply ZIP-317 policy before expensive cryptographic verification.
543            let miner_fee = miner_fee(tx.as_ref(), &spent_utxos)?;
544            let unpaid_actions = transaction::zip317::unpaid_actions(&unmined_tx, miner_fee);
545            transaction::zip317::mempool_checks(unpaid_actions, miner_fee, unmined_tx.size)?;
546
547            let cached_ffi_transaction =
548                Arc::new(CachedFfiTransaction::new(tx.clone(), Arc::new(spent_outputs), nu).map_err(|_| TransactionError::UnsupportedByNetworkUpgrade(tx.version(), nu))?);
549
550            tracing::trace!(?tx_id, "got state UTXOs");
551
552            // Select version-specific async verification pipeline
553            let async_checks = dispatch_version_verification(
554                tx.as_ref(),
555                nu,
556                script_verifier,
557                cached_ffi_transaction.clone(),
558                tx_id,
559            )?;
560
561            // The async checks are lazy: nothing reaches a verifier until they are polled. Check
562            // nullifiers and anchors first, because returning early does not remove items that are
563            // already queued in a batch verifier. Include service readiness in the state deadline.
564            let response = tokio::time::timeout(
565                UTXO_LOOKUP_TIMEOUT,
566                state.clone().oneshot(zs::Request::CheckBestChainTipNullifiersAndAnchors(
567                    unmined_tx.clone(),
568                )),
569            )
570            .await
571            .map_err(BoxError::from)??;
572            assert!(
573                response == zs::Response::ValidBestChainTipNullifiersAndAnchors,
574                "unexpected response to CheckBestChainTipNullifiersAndAnchors request"
575            );
576
577            tracing::trace!(?tx_id, "awaiting async checks...");
578
579            async_checks.check().await?;
580
581            tracing::trace!(?tx_id, "finished async checks");
582
583            // TODO: `spent_outputs` may not align with `tx.inputs()` when a transaction
584            // spends both chain and mempool UTXOs (mempool outputs are appended last by
585            // `mempool_spent_utxos()`), causing policy checks to pair the wrong input with
586            // the wrong spent output.
587            // https://github.com/ZcashFoundation/zebra/issues/10346
588            let spent_outputs = cached_ffi_transaction.all_previous_outputs().clone();
589
590            let transaction = VerifiedUnminedTx::new(
591                unmined_tx,
592                miner_fee,
593                sigops,
594                p2sh_sigops,
595                spent_outputs.into(),
596            )?;
597
598            if let Some(mut mempool) = mempool {
599                tokio::spawn(async move {
600                    // Best-effort poll of the mempool to provide a timely response to
601                    // `sendrawtransaction` RPC calls or `AwaitOutput` mempool calls.
602                    tokio::time::sleep(POLL_MEMPOOL_DELAY).await;
603                    let _ = mempool
604                        .ready()
605                        .await
606                        .expect("mempool poll_ready() method should not return an error")
607                        .call(mempool::Request::CheckForVerifiedTransactions)
608                        .await;
609                });
610            }
611
612            Ok(MempoolResponse { transaction, spent_mempool_outpoints })
613        }
614            .inspect(move |result| {
615                // Hide the transaction data to avoid filling the logs
616                tracing::trace!(?tx_id, result = ?result.as_ref().map(|_tx| ()), "got tx verify result");
617            })
618            .instrument(span)
619            .boxed()
620    }
621}
622
623impl<ZS, Mempool> MempoolTxVerifier<ZS, Mempool>
624where
625    ZS: Service<zs::Request, Response = zs::Response, Error = BoxError> + Send + Clone + 'static,
626    ZS::Future: Send + 'static,
627    Mempool: Service<mempool::Request, Response = mempool::Response, Error = BoxError>
628        + Send
629        + Clone
630        + 'static,
631    Mempool::Future: Send + 'static,
632{
633    /// Validates mempool lock-time consensus rules.
634    ///
635    /// Queries state only for time-based lock times.
636    async fn verify_mempool_lock_time(
637        tx: &Transaction,
638        height: block::Height,
639        state: Timeout<ZS>,
640    ) -> Result<(), TransactionError> {
641        // Skip the state query if we don't need the time for this check.
642        let next_median_time_past = if tx.lock_time_is_time() {
643            // This state query is much faster than loading UTXOs from the database,
644            // so it doesn't need to be executed in parallel
645            Some(
646                Self::mempool_best_chain_next_median_time_past(state)
647                    .await?
648                    .to_chrono(),
649            )
650        } else {
651            None
652        };
653
654        // This consensus check makes sure Zebra produces valid block templates.
655        check::lock_time_has_passed(tx, height, next_median_time_past)?;
656
657        Ok(())
658    }
659
660    /// Fetches the median-time-past of the *next* block after the best state tip.
661    ///
662    /// This is used to verify that the lock times of mempool transactions
663    /// can be included in any valid next block.
664    async fn mempool_best_chain_next_median_time_past(
665        state: Timeout<ZS>,
666    ) -> Result<DateTime32, TransactionError> {
667        let query = state
668            .clone()
669            .oneshot(zs::Request::BestChainNextMedianTimePast);
670
671        if let zebra_state::Response::BestChainNextMedianTimePast(median_time_past) = query
672            .await
673            .map_err(|e| TransactionError::ValidateMempoolLockTimeError(e.to_string()))?
674        {
675            Ok(median_time_past)
676        } else {
677            unreachable!("Request::BestChainNextMedianTimePast always responds with BestChainNextMedianTimePast")
678        }
679    }
680
681    /// Looks up UTXOs spent by a mempool `tx`, first querying the best chain state
682    /// and then the mempool for inputs whose outputs are not present in the best chain.
683    ///
684    /// `height` is the next block height, used to construct `Utxo` values for
685    /// outputs sourced from the mempool.
686    ///
687    /// Returns an `OutPoint -> Utxo` map, a vec of `Output`s in the same order
688    /// as the matching inputs in `tx`, and a vec of `OutPoint`s that were
689    /// sourced from the mempool rather than the best chain.
690    async fn mempool_spent_utxos(
691        tx: Arc<Transaction>,
692        height: block::Height,
693        state: Timeout<ZS>,
694        mempool: Option<Timeout<Mempool>>,
695    ) -> Result<
696        (
697            HashMap<transparent::OutPoint, transparent::Utxo>,
698            Vec<transparent::Output>,
699            Vec<transparent::OutPoint>,
700        ),
701        TransactionError,
702    > {
703        let inputs = tx.inputs();
704        let mut spent_utxos = HashMap::new();
705        // Pre-allocate with None so we can fill each slot by input index, preserving input order
706        // even when chain and mempool UTXOs are fetched in separate passes.
707        let mut spent_outputs: Vec<Option<transparent::Output>> = vec![None; inputs.len()];
708        // Stores (input_idx, outpoint) for UTXOs not found in the best chain (fetched from mempool later).
709        let mut spent_mempool_outpoints: Vec<(usize, transparent::OutPoint)> = Vec::new();
710
711        for (input_idx, input) in inputs.iter().enumerate() {
712            if let transparent::Input::PrevOut { outpoint, .. } = input {
713                tracing::trace!("awaiting outpoint lookup");
714
715                let query = state
716                    .clone()
717                    .oneshot(zs::Request::UnspentBestChainUtxo(*outpoint));
718
719                let zebra_state::Response::UnspentBestChainUtxo(utxo) = query
720                    .await
721                    .map_err(|_| TransactionError::TransparentInputNotFound)?
722                else {
723                    unreachable!("UnspentBestChainUtxo always responds with Option<Utxo>")
724                };
725
726                let Some(utxo) = utxo else {
727                    spent_mempool_outpoints.push((input_idx, *outpoint));
728                    continue;
729                };
730
731                tracing::trace!(?utxo, "got UTXO");
732                spent_outputs[input_idx] = Some(utxo.output.clone());
733                spent_utxos.insert(*outpoint, utxo);
734            }
735        }
736
737        if let Some(mempool) = mempool {
738            for &(input_idx, spent_mempool_outpoint) in &spent_mempool_outpoints {
739                let query = mempool
740                    .clone()
741                    .oneshot(mempool::Request::AwaitOutput(spent_mempool_outpoint));
742
743                let output = match query.await {
744                    Ok(mempool::Response::UnspentOutput(output)) => output,
745                    Ok(_) => unreachable!("UnspentOutput always responds with UnspentOutput"),
746                    Err(err) => {
747                        return match err.downcast::<Elapsed>() {
748                            Ok(_) => Err(TransactionError::TransparentInputNotFound),
749                            Err(err) => Err(err.into()),
750                        };
751                    }
752                };
753
754                spent_outputs[input_idx] = Some(output.clone());
755                spent_utxos.insert(
756                    spent_mempool_outpoint,
757                    // Assume the Utxo height will be next height after the best chain tip height
758                    //
759                    // # Correctness
760                    //
761                    // If the tip height changes while an unmined transaction is being verified,
762                    // the transaction must be re-verified before being added to the mempool.
763                    transparent::Utxo::new(output, height, false),
764                );
765            }
766        } else if !spent_mempool_outpoints.is_empty() {
767            return Err(TransactionError::TransparentInputNotFound);
768        }
769
770        // Convert back to return types; slots are in input order.
771        let spent_outputs: Vec<transparent::Output> = spent_outputs.into_iter().flatten().collect();
772        let spent_mempool_outpoints: Vec<transparent::OutPoint> = spent_mempool_outpoints
773            .into_iter()
774            .map(|(_, op)| op)
775            .collect();
776
777        Ok((spent_utxos, spent_outputs, spent_mempool_outpoints))
778    }
779}
780
781/// Applies every consensus rule that a transaction must satisfy in both block and mempool
782/// context.
783///
784/// # Correctness
785///
786/// [`BlockTxVerifier`] and [`MempoolTxVerifier`] are separate services with no shared code
787/// path, so a rule added to only one of them silently makes the two disagree. When the
788/// mempool accepts a transaction that block verification would reject, that transaction
789/// reaches block templates but makes the resulting block unmineable, stalling block
790/// production for every pool running Zebra. See
791/// <https://github.com/ZcashFoundation/zebra/issues/9301>.
792///
793/// Any new rule that applies to a transaction regardless of where it is being verified
794/// belongs here, so that both verifiers pick it up. Rules that only apply to one context
795/// (mempool policy such as ZIP-317 and input standardness, or whole-block context such as
796/// the block's own time) stay in the respective service.
797///
798/// The `is_coinbase` branches are unreachable from mempool verification, which rejects
799/// coinbase transactions before calling this.
800fn check_common_consensus_rules(
801    tx: &Transaction,
802    height: block::Height,
803    network: &Network,
804) -> Result<(), TransactionError> {
805    check_structure_and_network_rules(tx, height, network)?;
806
807    if tx.is_coinbase() {
808        check::coinbase_tx_no_prevout_joinsplit_spend(tx)?;
809    } else if !tx.is_valid_non_coinbase() {
810        return Err(TransactionError::NonCoinbaseHasCoinbaseInput);
811    }
812
813    // Validate `nExpiryHeight` consensus rules
814    if tx.is_coinbase() {
815        check::coinbase_expiry_height(&height, tx, network)?;
816    } else {
817        check::non_coinbase_expiry_height(&height, tx)?;
818    }
819
820    // Transaction invariants that apply regardless of request type or transaction version.
821    // These are pure consensus rules over the transaction structure and must always hold.
822    check_transaction_invariants(tx, height, network)?;
823
824    Ok(())
825}
826
827/// Performs basic structural validation and Orchard-related network upgrade rules.
828fn check_structure_and_network_rules(
829    tx: &Transaction,
830    height: block::Height,
831    network: &Network,
832) -> Result<(), TransactionError> {
833    // The network upgrade active at this height is used by several of the checks below;
834    // `NetworkUpgrade::current` rebuilds the activation-height map on each call, so compute it
835    // once and share it rather than recomputing it per check.
836    let network_upgrade = NetworkUpgrade::current(network, height);
837
838    check::has_inputs_and_outputs(tx)?;
839    check::has_enough_orchard_flags(tx)?;
840    // NU6.3 / Ironwood flag rules (no-ops for pre-v6 transactions).
841    check::has_enough_ironwood_flags(tx)?;
842    check::orchard_cross_address_disabled(tx)?;
843    // [NU6.3 onward] valueBalanceOrchard must be non-negative (Orchard pool frozen against new
844    // inflows; see `orchard_value_balance_non_negative`).
845    check::orchard_value_balance_non_negative(tx, network_upgrade)?;
846    // [NU6.3 onward] Coinbase transactions must have an empty Orchard component (new shielded
847    // coinbase value is routed to the Ironwood pool instead).
848    check::coinbase_orchard_component_empty(tx, network_upgrade)?;
849    check::consensus_branch_id(tx, height, network)?;
850
851    // Soft fork: temporarily require transactions to not contain Orchard actions.
852    //
853    // This soft fork was added while NU 6.1 was the active epoch on the Zcash
854    // chain, but we apply it uniformly even if NU 6.1 is not active in case it is
855    // ported to other chains with a different sequence of NUs.
856    //
857    // This will be treated as "Rules that apply generally before the next NU"
858    // when we add the NU that re-enables Orchard actions.
859    if network.is_orchard_temporarily_disabled(height) && tx.has_orchard_shielded_data() {
860        return Err(TransactionError::Other(
861            "transaction has Orchard actions (temporarily disabled)".into(),
862        ));
863    }
864
865    // From the network upgrade that re-enables Orchard actions (NU6.2), require
866    // that any Orchard proof has the canonical length for its number of actions.
867    // A proof that is present but not canonically sized can be padded with
868    // arbitrary trailing data without affecting its validity, allowing excess
869    // bandwidth and storage costs to be imposed while paying only fees sized to a
870    // canonical proof (GHSA-jfw5-j458-pfv6).
871    //
872    // This is a constricting rule, so it is gated on that network upgrade:
873    // Orchard actions mined before it, under earlier rules that did not enforce
874    // the proof size, must remain valid so that nodes can sync and reindex the
875    // chain before the soft fork that temporarily disabled Orchard. Orchard
876    // bundles are deserialized leniently, so the size is checked here, where the
877    // block height is available, rather than during parsing.
878    //
879    // The gate activates at the NU6.2 activation height committed in
880    // MAINNET/TESTNET_ACTIVATION_HEIGHTS. See
881    // `Network::orchard_canonical_proof_size_rule_active`.
882    if network.orchard_canonical_proof_size_rule_active(height)
883        && !tx.orchard_proof_size_is_canonical()
884    {
885        return Err(TransactionError::OrchardProofSize);
886    }
887
888    // The Ironwood bundle's Halo2 proof must also have a canonical size. Ironwood only exists
889    // from NU6.3 onward (there is no legacy lenient period as there was for Orchard), so this is
890    // enforced unconditionally whenever an Ironwood bundle is present. Like the Orchard bundle,
891    // Ironwood bundles are deserialized leniently, so the size is checked here rather than during
892    // parsing.
893    if !tx.ironwood_proof_size_is_canonical() {
894        return Err(TransactionError::IronwoodProofSize);
895    }
896
897    Ok(())
898}
899
900/// Validates transaction invariants.
901fn check_transaction_invariants(
902    tx: &Transaction,
903    height: block::Height,
904    network: &Network,
905) -> Result<(), TransactionError> {
906    // Consensus rule:
907    //
908    // > Either v_{pub}^{old} or v_{pub}^{new} MUST be zero.
909    //
910    // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
911    check::joinsplit_has_vpub_zero(tx)?;
912
913    // [Canopy onward]: `vpub_old` MUST be zero.
914    // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
915    check::disabled_add_to_sprout_pool(tx, height, network)?;
916
917    check::spend_conflicts(tx)?;
918
919    Ok(())
920}
921
922/// Checks that every transparent coinbase output spent by `tx` has matured
923/// by `height`.
924///
925/// This check applies only to mempool transactions. Block transactions are
926/// checked during contextual validation in the state (see #2336).
927///
928/// Calls [`check::tx_transparent_coinbase_spends_maturity`] with an empty
929/// `block_new_outputs` map, since mempool transactions have no block context.
930///
931/// Returns `Ok(())` if every transparent coinbase output spent by the transaction is
932/// mature and valid for the given height, or a [`TransactionError`] if the transaction
933/// spends transparent coinbase outputs that are immature and invalid for the given height.
934fn check_maturity_height(
935    tx: Arc<Transaction>,
936    height: block::Height,
937    network: &Network,
938    spent_utxos: &HashMap<transparent::OutPoint, transparent::Utxo>,
939) -> Result<(), TransactionError> {
940    check::tx_transparent_coinbase_spends_maturity(
941        network,
942        &tx,
943        height,
944        Arc::new(HashMap::new()),
945        spent_utxos,
946    )
947}
948
949/// Dispatches version-specific async verification checks for `tx`.
950///
951/// `nu` is the network upgrade active at the transaction's verification height,
952/// pre-computed by the caller using [`NetworkUpgrade::current`].
953///
954/// `tx_id` must be the unmined ID of `tx`: the shielded verifiers key their caches on it, so an
955/// ID that does not identify `tx` would let one transaction's bundle be answered from another's
956/// verification. A v5 or v6 transaction's witnessed ID is passed down to the Halo2 verifier,
957/// which needs the transaction's authorizing-data digest; a legacy ID has none, so those bundles
958/// are verified without consulting the Halo2 cache.
959///
960/// Returns [`TransactionError::WrongVersion`] for V1-V3 transactions, which
961/// are not supported by any network upgrade Zebra verifies.
962fn dispatch_version_verification(
963    tx: &Transaction,
964    nu: NetworkUpgrade,
965    script_verifier: script::Verifier,
966    cached_ffi_transaction: Arc<CachedFfiTransaction>,
967    tx_id: UnminedTxId,
968) -> Result<AsyncChecks, TransactionError> {
969    // V5 and V6 transactions always have a witnessed ID, so this is `Some` for the versions that
970    // reach the Orchard verifiers below. It stays an `Option` rather than an assertion because a
971    // missing ID only costs a cache miss, and consensus code must not panic on transaction data.
972    let wtx_id = match tx_id {
973        UnminedTxId::Witnessed(wtx_id) => Some(wtx_id),
974        UnminedTxId::Legacy(_) => None,
975    };
976
977    match tx.tx_version() {
978        TxVersion::Sprout(_) | TxVersion::V3 => {
979            tracing::debug!(?tx, "got transaction with wrong version");
980            Err(TransactionError::WrongVersion)
981        }
982        TxVersion::V4 => {
983            verify_v4_transaction(tx, nu, script_verifier, cached_ffi_transaction, tx_id)
984        }
985        TxVersion::V5 => verify_v5_transaction(
986            tx,
987            nu,
988            script_verifier,
989            cached_ffi_transaction,
990            tx_id,
991            wtx_id,
992        ),
993        TxVersion::V6 => verify_v6_transaction(
994            tx,
995            nu,
996            script_verifier,
997            cached_ffi_transaction,
998            tx_id,
999            wtx_id,
1000        ),
1001        #[allow(unreachable_patterns)]
1002        _ => {
1003            tracing::debug!(?tx, "got transaction with unsupported version");
1004            Err(TransactionError::WrongVersion)
1005        }
1006    }
1007}
1008
1009/// Verify a V4 transaction.
1010///
1011/// Returns a set of asynchronous checks that must all succeed for the transaction to be
1012/// considered valid. These checks include:
1013///
1014/// - transparent transfers
1015/// - sprout shielded data
1016/// - sapling shielded data
1017///
1018/// The parameters of this method are:
1019///
1020/// - the `tx` transaction to verify
1021/// - the `nu` network upgrade active at the transaction's verification height
1022/// - the `script_verifier` to use for verifying the transparent transfers
1023/// - the prepared `cached_ffi_transaction` used by the script verifier
1024/// - the transaction's `tx_id`, used by the Sapling verification cache
1025#[allow(clippy::unwrap_in_result)]
1026fn verify_v4_transaction(
1027    tx: &Transaction,
1028    nu: NetworkUpgrade,
1029    script_verifier: script::Verifier,
1030    cached_ffi_transaction: Arc<CachedFfiTransaction>,
1031    tx_id: UnminedTxId,
1032) -> Result<AsyncChecks, TransactionError> {
1033    verify_v4_transaction_network_upgrade(tx, nu)?;
1034
1035    let sapling_bundle = cached_ffi_transaction.sighasher().sapling_bundle();
1036
1037    let sighash = cached_ffi_transaction
1038        .sighasher()
1039        .sighash(HashType::ALL, None);
1040
1041    Ok(
1042        verify_transparent_inputs_and_outputs(tx, script_verifier, cached_ffi_transaction)?
1043            .and(verify_sprout_shielded_data(tx, &sighash)?)
1044            .and(verify_sapling_bundle(sapling_bundle, &sighash, tx_id)),
1045    )
1046}
1047
1048/// Verifies if a V4 `transaction` is supported by `network_upgrade`.
1049fn verify_v4_transaction_network_upgrade(
1050    transaction: &Transaction,
1051    network_upgrade: NetworkUpgrade,
1052) -> Result<(), TransactionError> {
1053    match network_upgrade {
1054        // Supports V4 transactions
1055        //
1056        // # Consensus
1057        //
1058        // > [Sapling to Canopy inclusive, pre-NU5] The transaction version number MUST be 4,
1059        // > and the version group ID MUST be 0x892F2085.
1060        //
1061        // > [NU5 onward] The transaction version number MUST be 4 or 5.
1062        // > If the transaction version number is 4 then the version group ID MUST be 0x892F2085.
1063        // > If the transaction version number is 5 then the version group ID MUST be 0x26A7270A.
1064        //
1065        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1066        //
1067        // Note: Here we verify the transaction version number of the above two rules, the group
1068        // id is checked in zebra-chain crate, in the transaction serialize.
1069        NetworkUpgrade::Sapling
1070        | NetworkUpgrade::Blossom
1071        | NetworkUpgrade::Heartwood
1072        | NetworkUpgrade::Canopy
1073        | NetworkUpgrade::Nu5
1074        | NetworkUpgrade::Nu6
1075        | NetworkUpgrade::Nu6_1
1076        | NetworkUpgrade::Nu6_2
1077        | NetworkUpgrade::Nu6_3 => Ok(()),
1078
1079        // Does not support V4 transactions
1080        //
1081        // # Consensus
1082        //
1083        // > [NU7 onward] The transaction version number MUST be 5 or 6.
1084        //
1085        // <https://zips.z.cash/zip-2003>
1086        //
1087        // `ZFuture` follows NU7, so it inherits the V4 rejection.
1088        //
1089        // This rule is deliberately not gated behind `zcash_unstable = "nu7"`: it is a no-op
1090        // until NU7 has an activation height on a network, so gating it would only make the
1091        // gated and ungated builds diverge without changing behaviour on any live network.
1092        NetworkUpgrade::Genesis
1093        | NetworkUpgrade::BeforeOverwinter
1094        | NetworkUpgrade::Overwinter
1095        | NetworkUpgrade::Nu7 => Err(TransactionError::UnsupportedByNetworkUpgrade(
1096            transaction.version(),
1097            network_upgrade,
1098        )),
1099
1100        #[cfg(zcash_unstable = "zfuture")]
1101        NetworkUpgrade::ZFuture => Err(TransactionError::UnsupportedByNetworkUpgrade(
1102            transaction.version(),
1103            network_upgrade,
1104        )),
1105    }
1106}
1107
1108/// Verify a V5 transaction.
1109///
1110/// Returns a set of asynchronous checks that must all succeed for the transaction to be
1111/// considered valid. These checks include:
1112///
1113/// - transaction support by the selected network upgrade, as checked by
1114///   [`verify_v5_transaction_network_upgrade`]
1115/// - transparent transfers
1116/// - sapling shielded data (TODO)
1117/// - orchard shielded data (TODO)
1118///
1119/// The parameters of this method are:
1120///
1121/// - the `tx` transaction to verify
1122/// - the `nu` network upgrade active at the transaction's verification height
1123/// - the `script_verifier` to use for verifying the transparent transfers
1124/// - the prepared `cached_ffi_transaction` used by the script verifier
1125/// - the transaction's `tx_id` and `wtx_id`, used by the shielded verification caches
1126#[allow(clippy::unwrap_in_result)]
1127fn verify_v5_transaction(
1128    tx: &Transaction,
1129    nu: NetworkUpgrade,
1130    script_verifier: script::Verifier,
1131    cached_ffi_transaction: Arc<CachedFfiTransaction>,
1132    tx_id: UnminedTxId,
1133    wtx_id: Option<transaction::WtxId>,
1134) -> Result<AsyncChecks, TransactionError> {
1135    verify_v5_transaction_network_upgrade(tx, nu)?;
1136
1137    let sapling_bundle = cached_ffi_transaction.sighasher().sapling_bundle();
1138    let orchard_bundle = cached_ffi_transaction.sighasher().orchard_bundle();
1139
1140    let sighash = cached_ffi_transaction
1141        .sighasher()
1142        .sighash(HashType::ALL, None);
1143
1144    Ok(
1145        verify_transparent_inputs_and_outputs(tx, script_verifier, cached_ffi_transaction)?
1146            .and(verify_sapling_bundle(sapling_bundle, &sighash, tx_id))
1147            .and(verify_orchard_bundle(orchard_bundle, &sighash, nu, wtx_id)),
1148    )
1149}
1150
1151/// Verifies if a V5 `transaction` is supported by `network_upgrade`.
1152fn verify_v5_transaction_network_upgrade(
1153    transaction: &Transaction,
1154    network_upgrade: NetworkUpgrade,
1155) -> Result<(), TransactionError> {
1156    match network_upgrade {
1157        // Supports V5 transactions
1158        //
1159        // # Consensus
1160        //
1161        // > [NU5 onward] The transaction version number MUST be 4 or 5.
1162        // > If the transaction version number is 4 then the version group ID MUST be 0x892F2085.
1163        // > If the transaction version number is 5 then the version group ID MUST be 0x26A7270A.
1164        //
1165        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1166        //
1167        // Note: Here we verify the transaction version number of the above rule, the group
1168        // id is checked in zebra-chain crate, in the transaction serialize.
1169        NetworkUpgrade::Nu5
1170        | NetworkUpgrade::Nu6
1171        | NetworkUpgrade::Nu6_1
1172        | NetworkUpgrade::Nu6_2
1173        | NetworkUpgrade::Nu6_3
1174        | NetworkUpgrade::Nu7 => Ok(()),
1175
1176        #[cfg(zcash_unstable = "zfuture")]
1177        NetworkUpgrade::ZFuture => Ok(()),
1178
1179        // Does not support V5 transactions
1180        NetworkUpgrade::Genesis
1181        | NetworkUpgrade::BeforeOverwinter
1182        | NetworkUpgrade::Overwinter
1183        | NetworkUpgrade::Sapling
1184        | NetworkUpgrade::Blossom
1185        | NetworkUpgrade::Heartwood
1186        | NetworkUpgrade::Canopy => Err(TransactionError::UnsupportedByNetworkUpgrade(
1187            transaction.version(),
1188            network_upgrade,
1189        )),
1190    }
1191}
1192
1193/// Verifies a V6 (NU6.3 / Ironwood) transaction's shielded data.
1194///
1195/// Differs from [`verify_v5_transaction`] in the Orchard verifier: a v6 Orchard bundle
1196/// commits to the NU6.3 cross-address circuit, so it (and the Ironwood bundle) verify under the
1197/// NU6.3 key, not the v5 fixed key.
1198fn verify_v6_transaction(
1199    tx: &Transaction,
1200    nu: NetworkUpgrade,
1201    script_verifier: script::Verifier,
1202    cached_ffi_transaction: Arc<CachedFfiTransaction>,
1203    tx_id: UnminedTxId,
1204    wtx_id: Option<transaction::WtxId>,
1205) -> Result<AsyncChecks, TransactionError> {
1206    verify_v6_transaction_network_upgrade(tx, nu)?;
1207
1208    let sapling_bundle = cached_ffi_transaction.sighasher().sapling_bundle();
1209    let orchard_bundle = cached_ffi_transaction.sighasher().orchard_bundle();
1210    let ironwood_bundle = cached_ffi_transaction.sighasher().ironwood_bundle();
1211
1212    let sighash = cached_ffi_transaction
1213        .sighasher()
1214        .sighash(HashType::ALL, None);
1215
1216    // The Ironwood bundle reuses the Orchard Action proof system and the NU6.3 circuit key, so
1217    // it is verified the same way as the v6 Orchard bundle (against the NU6.3 key).
1218    Ok(
1219        verify_transparent_inputs_and_outputs(tx, script_verifier, cached_ffi_transaction)?
1220            .and(verify_sapling_bundle(sapling_bundle, &sighash, tx_id))
1221            .and(verify_orchard_v6_bundle(orchard_bundle, &sighash, wtx_id))
1222            .and(verify_orchard_v6_bundle(ironwood_bundle, &sighash, wtx_id)),
1223    )
1224}
1225
1226/// Verifies that a V6 `transaction` is supported by `network_upgrade`.
1227///
1228/// V6 transactions are only valid from NU6.3 onward.
1229fn verify_v6_transaction_network_upgrade(
1230    transaction: &Transaction,
1231    network_upgrade: NetworkUpgrade,
1232) -> Result<(), TransactionError> {
1233    match network_upgrade {
1234        NetworkUpgrade::Nu6_3 | NetworkUpgrade::Nu7 => Ok(()),
1235
1236        #[cfg(zcash_unstable = "zfuture")]
1237        NetworkUpgrade::ZFuture => Ok(()),
1238
1239        // V6 transactions are not valid before NU6.3.
1240        NetworkUpgrade::Genesis
1241        | NetworkUpgrade::BeforeOverwinter
1242        | NetworkUpgrade::Overwinter
1243        | NetworkUpgrade::Sapling
1244        | NetworkUpgrade::Blossom
1245        | NetworkUpgrade::Heartwood
1246        | NetworkUpgrade::Canopy
1247        | NetworkUpgrade::Nu5
1248        | NetworkUpgrade::Nu6
1249        | NetworkUpgrade::Nu6_1
1250        | NetworkUpgrade::Nu6_2 => Err(TransactionError::UnsupportedByNetworkUpgrade(
1251            transaction.version(),
1252            network_upgrade,
1253        )),
1254    }
1255}
1256
1257/// Verifies if a transaction's transparent inputs are valid using the provided
1258/// `script_verifier` and `cached_ffi_transaction`.
1259///
1260/// Returns the asynchronous script verification checks for transparent inputs in `tx`.
1261fn verify_transparent_inputs_and_outputs(
1262    tx: &Transaction,
1263    script_verifier: script::Verifier,
1264    cached_ffi_transaction: Arc<CachedFfiTransaction>,
1265) -> Result<AsyncChecks, TransactionError> {
1266    if tx.is_coinbase() {
1267        // The script verifier only verifies PrevOut inputs and their corresponding UTXOs.
1268        // Coinbase transactions don't have any PrevOut inputs.
1269        Ok(AsyncChecks::new())
1270    } else {
1271        // feed all of the inputs to the script verifier
1272        let inputs = tx.inputs();
1273
1274        let script_checks = (0..inputs.len())
1275            .map(move |input_index| {
1276                let request = script::Request {
1277                    cached_ffi_transaction: cached_ffi_transaction.clone(),
1278                    input_index,
1279                };
1280
1281                script_verifier.oneshot(request)
1282            })
1283            .collect();
1284
1285        Ok(script_checks)
1286    }
1287}
1288
1289/// Verifies a transaction's Sprout shielded join split data.
1290fn verify_sprout_shielded_data(
1291    tx: &Transaction,
1292    shielded_sighash: &SigHash,
1293) -> Result<AsyncChecks, TransactionError> {
1294    let mut checks = AsyncChecks::new();
1295
1296    if let Some(sprout_bundle) = tx.sprout_bundle() {
1297        for joinsplit in &sprout_bundle.joinsplits {
1298            // # Consensus
1299            //
1300            // > The proof π_ZKJoinSplit MUST be valid given a
1301            // > primary input formed from the relevant other fields and h_{Sig}
1302            //
1303            // https://zips.z.cash/protocol/protocol.pdf#joinsplitdesc
1304            //
1305            // Queue the verification of the Groth16 spend proof
1306            // for each JoinSplit description while adding the
1307            // resulting future to our collection of async
1308            // checks that (at a minimum) must pass for the
1309            // transaction to verify.
1310            checks.push(primitives::groth16::JOINSPLIT_VERIFIER.oneshot(
1311                primitives::groth16::joinsplit_to_item(joinsplit, &sprout_bundle.joinsplit_pubkey)?,
1312            ));
1313        }
1314
1315        // # Consensus
1316        //
1317        // > If effectiveVersion ≥ 2 and nJoinSplit > 0, then:
1318        // > - joinSplitPubKey MUST be a valid encoding of an Ed25519 validating key
1319        // > - joinSplitSig MUST represent a valid signature under
1320        //     joinSplitPubKey of dataToBeSigned, as defined in § 4.11
1321        //
1322        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1323        //
1324        // The `if` part is indirectly enforced, since the `joinsplit_data`
1325        // is only parsed if those conditions apply in
1326        // [`Transaction::zcash_deserialize`].
1327        //
1328        // The valid encoding is defined in
1329        //
1330        // > A valid Ed25519 validating key is defined as a sequence of 32
1331        // > bytes encoding a point on the Ed25519 curve
1332        //
1333        // https://zips.z.cash/protocol/protocol.pdf#concreteed25519
1334        //
1335        // which is enforced during signature verification, in both batched
1336        // and single verification, when decompressing the encoded point.
1337        //
1338        // Queue the validation of the JoinSplit signature while
1339        // adding the resulting future to our collection of
1340        // async checks that (at a minimum) must pass for the
1341        // transaction to verify.
1342        //
1343        // https://zips.z.cash/protocol/protocol.pdf#sproutnonmalleability
1344        // https://zips.z.cash/protocol/protocol.pdf#txnencodingandconsensus
1345        let ed25519_verifier = primitives::ed25519::VERIFIER.clone();
1346        let pub_key = zebra_chain::primitives::ed25519::VerificationKeyBytes::from(
1347            sprout_bundle.joinsplit_pubkey,
1348        );
1349        let sig = zebra_chain::primitives::ed25519::Signature::from(sprout_bundle.joinsplit_sig);
1350        let ed25519_item = (pub_key, sig, shielded_sighash).into();
1351
1352        checks.push(ed25519_verifier.oneshot(ed25519_item));
1353    }
1354
1355    Ok(checks)
1356}
1357
1358/// Verifies a transaction's Sapling shielded data.
1359///
1360/// `tx_id` must identify the transaction containing `bundle`; the verifier's cache adds it to the
1361/// key that lets a mempool verification be reused for the block that mines it.
1362fn verify_sapling_bundle(
1363    bundle: Option<sapling_crypto::Bundle<sapling_crypto::bundle::Authorized, ZatBalance>>,
1364    sighash: &SigHash,
1365    tx_id: UnminedTxId,
1366) -> AsyncChecks {
1367    let mut async_checks = AsyncChecks::new();
1368
1369    // The Sapling batch verifier checks the following consensus rules:
1370    //
1371    // # Consensus
1372    //
1373    // > The proof π_ZKSpend MUST be valid given a primary input formed from the other fields
1374    // > except spendAuthSig.
1375    //
1376    // > The spend authorization signature MUST be a valid SpendAuthSig signature over SigHash
1377    // > using rk as the validating key.
1378    //
1379    // > [NU5 onward] As specified in § 5.4.7 ‘RedDSA, RedJubjub, and RedPallas’ on p. 88, the
1380    // > validation of the 𝑅 component of the signature changes to prohibit non-canonical
1381    // > encodings.
1382    //
1383    // https://zips.z.cash/protocol/protocol.pdf#spenddesc
1384    //
1385    // # Consensus
1386    //
1387    // > The proof π_ZKOutput MUST be valid given a primary input formed from the other fields
1388    // > except C^enc and C^out.
1389    //
1390    // https://zips.z.cash/protocol/protocol.pdf#outputdesc
1391    //
1392    // # Consensus
1393    //
1394    // > The Spend transfers and Action transfers of a transaction MUST be consistent with its
1395    // > vbalanceSapling value as specified in § 4.13 ‘Balance and Binding Signature (Sapling)’.
1396    //
1397    // https://zips.z.cash/protocol/protocol.pdf#spendsandoutputs
1398    //
1399    // # Consensus
1400    //
1401    // > [Sapling onward] If effectiveVersion ≥ 4 and nSpendsSapling + nOutputsSapling > 0,
1402    // > then:
1403    // >
1404    // > – let bvk^{Sapling} and SigHash be as defined in § 4.13;
1405    // > – bindingSigSapling MUST represent a valid signature under the transaction binding
1406    // >   validating key bvk Sapling of SigHash — i.e.
1407    // >   BindingSig^{Sapling}.Validate_{bvk^{Sapling}}(SigHash, bindingSigSapling ) = 1.
1408    //
1409    // Note that the `if` part is indirectly enforced, since the `sapling_shielded_data` is only
1410    // parsed if those conditions apply in [`Transaction::zcash_deserialize`].
1411    //
1412    // > [NU5 onward] As specified in § 5.4.7, the validation of the 𝑅 component of the
1413    // > signature changes to prohibit non-canonical encodings.
1414    //
1415    // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
1416    if let Some(bundle) = bundle {
1417        let verifier = primitives::sapling::VERIFIER.clone();
1418        #[cfg(test)]
1419        let verifier = tests::SAPLING_CACHE_VERIFIER
1420            .try_with(Clone::clone)
1421            .unwrap_or(verifier);
1422        async_checks
1423            .push(verifier.oneshot(primitives::sapling::Item::new(bundle, *sighash, tx_id)));
1424    }
1425
1426    async_checks
1427}
1428
1429/// Verifies a **v5** transaction's Orchard bundle.
1430///
1431/// A v5 Orchard bundle commits to the Orchard Action circuit of the block's era, so the
1432/// verifying key is selected by `network_upgrade` via
1433/// [`primitives::halo2::orchard_v5_verifier_for`]: the historical insecure key before NU6.2, the
1434/// fixed key from NU6.2 until NU6.3, and the NU6.3 key from NU6.3 onward. The Orchard-pool
1435/// cross-address restriction applies to every Orchard Action from NU6.3 onward regardless of
1436/// transaction version (ZIP 229), so a v5 bundle at NU6.3 uses the NU6.3 circuit — the same key
1437/// as v6 Orchard and Ironwood bundles — not the fixed one.
1438fn verify_orchard_bundle(
1439    bundle: Option<::orchard::bundle::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1440    sighash: &SigHash,
1441    network_upgrade: NetworkUpgrade,
1442    wtx_id: Option<transaction::WtxId>,
1443) -> AsyncChecks {
1444    queue_orchard_bundle(
1445        || primitives::halo2::cached_orchard_v5_verifier_for(network_upgrade),
1446        bundle,
1447        sighash,
1448        wtx_id,
1449    )
1450}
1451
1452/// Verifies a **v6** transaction's Orchard bundle.
1453///
1454/// A v6 Orchard bundle commits to the NU6.3 cross-address circuit, so it always verifies under
1455/// the NU6.3 key ([`primitives::halo2::orchard_v6_verifier`]), independent of the block's
1456/// network upgrade (v6 transactions only exist from NU6.3 onward). The Ironwood bundle reuses
1457/// the same verifier.
1458fn verify_orchard_v6_bundle(
1459    bundle: Option<::orchard::bundle::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1460    sighash: &SigHash,
1461    wtx_id: Option<transaction::WtxId>,
1462) -> AsyncChecks {
1463    queue_orchard_bundle(
1464        primitives::halo2::cached_orchard_v6_verifier,
1465        bundle,
1466        sighash,
1467        wtx_id,
1468    )
1469}
1470
1471/// Queues an Orchard-shaped bundle's single aggregated Halo2 proof against a verifier.
1472///
1473/// # Consensus
1474///
1475/// > The proof 𝜋 MUST be valid given a primary input (cv, rt^{Orchard}, nf, rk, cm_x,
1476/// > enableSpends, enableOutputs)
1477///
1478/// <https://zips.z.cash/protocol/protocol.pdf#actiondesc>
1479///
1480/// Unlike Sapling, Orchard shielded transactions have a single aggregated Halo2 proof per
1481/// transaction, even with multiple Actions, so it is queued for verification only once instead
1482/// of once per Action description. The choice of verifying key is the caller's; see
1483/// [`verify_orchard_bundle`] and [`verify_orchard_v6_bundle`].
1484///
1485/// `select_verifier` is only invoked when a bundle is present, so a bundle-less transaction
1486/// never forces the (lazily initialized) verifier services.
1487///
1488/// `wtx_id` must identify the transaction containing `bundle`; the verifier's cache keys on it,
1489/// together with the sighash and the bundle's value pool, so that a bundle verified from the
1490/// mempool is not verified again in the block that mines it. Without one the item is verified
1491/// every time.
1492fn queue_orchard_bundle(
1493    select_verifier: impl FnOnce() -> &'static primitives::halo2::CachedVerifierService,
1494    bundle: Option<::orchard::bundle::Bundle<::orchard::bundle::Authorized, ZatBalance>>,
1495    sighash: &SigHash,
1496    wtx_id: Option<transaction::WtxId>,
1497) -> AsyncChecks {
1498    let mut async_checks = AsyncChecks::new();
1499
1500    if let Some(bundle) = bundle {
1501        let item = match wtx_id {
1502            Some(wtx_id) => primitives::halo2::Item::new_with_wtx_id(bundle, *sighash, wtx_id),
1503            None => primitives::halo2::Item::new(bundle, *sighash),
1504        };
1505
1506        let verifier = select_verifier().clone();
1507        #[cfg(test)]
1508        let verifier = tests::HALO2_CACHE_VERIFIER
1509            .try_with(Clone::clone)
1510            .unwrap_or(verifier);
1511        async_checks.push(verifier.oneshot(item));
1512    }
1513
1514    async_checks
1515}
1516
1517/// Calculates the miner fee from the transaction's value balance.
1518fn miner_fee(
1519    tx: &Transaction,
1520    spent_utxos: &HashMap<transparent::OutPoint, transparent::Utxo>,
1521) -> Result<Amount<NonNegative>, TransactionError> {
1522    match tx.value_balance(spent_utxos) {
1523        Ok(value_balance) => value_balance
1524            .remaining_transaction_value()
1525            .map_err(|_| TransactionError::IncorrectFee),
1526        Err(_) => Err(TransactionError::IncorrectFee),
1527    }
1528}
1529
1530/// A set of unordered asynchronous checks that should succeed.
1531///
1532/// A wrapper around [`FuturesUnordered`] with some auxiliary methods.
1533struct AsyncChecks(FuturesUnordered<Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>>>);
1534
1535impl AsyncChecks {
1536    /// Create an empty set of unordered asynchronous checks.
1537    pub fn new() -> Self {
1538        AsyncChecks(FuturesUnordered::new())
1539    }
1540
1541    /// Push a check into the set.
1542    pub fn push(&mut self, check: impl Future<Output = Result<(), BoxError>> + Send + 'static) {
1543        self.0.push(check.boxed());
1544    }
1545
1546    /// Push a set of checks into the set.
1547    ///
1548    /// This method can be daisy-chained.
1549    pub fn and(mut self, checks: AsyncChecks) -> Self {
1550        self.0.extend(checks.0);
1551        self
1552    }
1553
1554    /// Wait until all checks in the set finish.
1555    ///
1556    /// If any of the checks fail, this method immediately returns the error and cancels all other
1557    /// checks by dropping them.
1558    async fn check(mut self) -> Result<(), BoxError> {
1559        // Wait for all asynchronous checks to complete
1560        // successfully, or fail verification if they error.
1561        while let Some(check) = self.0.next().await {
1562            tracing::trace!(?check, remaining = self.0.len());
1563            check?;
1564        }
1565
1566        Ok(())
1567    }
1568}
1569
1570impl<F> FromIterator<F> for AsyncChecks
1571where
1572    F: Future<Output = Result<(), BoxError>> + Send + 'static,
1573{
1574    fn from_iter<I>(iterator: I) -> Self
1575    where
1576        I: IntoIterator<Item = F>,
1577    {
1578        AsyncChecks(iterator.into_iter().map(FutureExt::boxed).collect())
1579    }
1580}