zebra_consensus/primitives/halo2.rs
1//! Async Halo2 batch verifier service
2
3use std::{
4 fmt,
5 future::Future,
6 mem,
7 pin::Pin,
8 sync::Arc,
9 task::{Context, Poll},
10};
11
12use futures::{future::BoxFuture, FutureExt};
13use once_cell::sync::Lazy;
14use orchard::{
15 bundle::BatchValidator,
16 circuit::{OrchardCircuitVersion, VerifyingKey},
17};
18use zcash_protocol::value::ZatBalance;
19use zebra_chain::{
20 parameters::NetworkUpgrade,
21 transaction::{SigHash, UnminedTxId, WtxId},
22};
23
24use crate::{error::TransactionError, BoxError};
25use thiserror::Error;
26use tokio::sync::watch;
27use tower::Service;
28use tower_batch_control::{Batch, BatchControl, RequestWeight};
29use tower_fallback::Fallback;
30
31use super::{
32 cache::{CacheKey, Cached, CachedItem, ShieldedPool, CACHE_CAPACITY},
33 spawn_fifo,
34};
35
36#[cfg(test)]
37mod tests;
38
39/// Adjusted batch size for halo2 batches.
40///
41/// Unlike other batch verifiers, halo2 has aggregate proofs.
42/// This means that there can be hundreds of actions verified by some proofs,
43/// but just one action in others.
44///
45/// To compensate for larger proofs, we process the batch once there are over
46/// [`HALO2_MAX_BATCH_SIZE`] total actions among pending items in the queue.
47const HALO2_MAX_BATCH_SIZE: usize = super::MAX_BATCH_SIZE;
48
49/// The type of verification results.
50type VerifyResult = bool;
51
52/// The type of the batch sender channel.
53type Sender = watch::Sender<Option<VerifyResult>>;
54
55/// The type of a prepared verifying key.
56/// This is the key used to verify individual items.
57pub type ItemVerifyingKey = VerifyingKey;
58
59// The Orchard Action circuit — and therefore its verifying key — has changed across upgrades, and
60// a proof produced under one circuit version does not verify under another. We keep one key per
61// circuit version, each in its own dedicated verifier, and route each bundle to the correct one by
62// the block era (network upgrade) it was mined in. The circuit era is a function of the Orchard
63// pool and the block's upgrade, NOT of the transaction version (v5 vs v6): an Orchard-pool bundle
64// mined at NU6.3 commits to the NU6.3 circuit whether it is carried in a v5 or a v6 transaction
65// (see [`orchard_v5_verifier_for`] / [`orchard_v6_verifier`]):
66//
67// * Orchard bundles before NU6.2 (NU5..NU6.2) were produced by the historical, insecure circuit
68// and only verify under the [`InsecurePreNu6_2`] key. These must keep verifying so that nodes
69// can re-sync and reindex pre-soft-fork Orchard history.
70//
71// * Orchard bundles from NU6.2 until NU6.3 use the fixed circuit and only verify under the
72// [`FixedPostNu6_2`] key.
73//
74// * Every Orchard Action from NU6.3 onward uses the NU6.3 cross-address circuit and only verifies
75// under the [`PostNu6_3`] key. The NU6.3 circuit extends the fixed circuit with the
76// `disableCrossAddress` constraint that enforces the Orchard-pool cross-address restriction. Per
77// ZIP 229 that restriction applies to every Orchard-pool Action "regardless of transaction
78// version ... so that it cannot be bypassed by using a version 5 transaction", so v5 Orchard
79// bundles at NU6.3, v6 Orchard bundles, and Ironwood bundles all share this one key.
80//
81// Routing therefore depends on the block era (network upgrade), not the transaction version.
82//
83// NOTE: this deliberately does NOT copy zcashd PR #176's WIP shortcut of validating everything
84// against the fixed key; that is incorrect both for re-syncing pre-soft-fork Orchard blocks (whose
85// proofs only verify under the insecure key) and for NU6.3 Orchard Actions (whose cross-address
86// restriction the fixed key cannot enforce).
87lazy_static::lazy_static! {
88 /// The Orchard Action verifying key for the **pre-NU6.2** (insecure) circuit.
89 ///
90 /// Reconstructs the verifying key of the original (NU5..NU6.2) Orchard Action circuit.
91 /// Bundles mined before NU6.2 committed to this circuit and only verify under this key, so it
92 /// MUST be retained to re-verify pre-NU6.2 history on resync. It must never be used to verify
93 /// post-NU6.2 bundles.
94 pub static ref VERIFYING_KEY_PRE_NU6_2: ItemVerifyingKey =
95 ItemVerifyingKey::build(OrchardCircuitVersion::InsecurePreNu6_2);
96
97 /// The Orchard Action verifying key for the **NU6.2-until-NU6.3** (fixed) circuit.
98 ///
99 /// Built from the fixed variable-base scalar-multiplication Orchard Action circuit shipped in
100 /// NU6.2. Orchard bundles mined from the NU6.2 activation height until NU6.3 commit to this
101 /// circuit and only verify under this key. At NU6.3 the Orchard pool moves to
102 /// [`VERIFYING_KEY_NU6_3_ONWARD`]. See [`VERIFYING_KEY_PRE_NU6_2`] for the era split.
103 pub static ref VERIFYING_KEY_NU6_2: ItemVerifyingKey =
104 ItemVerifyingKey::build(OrchardCircuitVersion::FixedPostNu6_2);
105
106 /// The Orchard Action verifying key for the **NU6.3-onward** circuit.
107 ///
108 /// Built from the NU6.3 Action circuit, which extends the fixed circuit with the
109 /// `disableCrossAddress` constraint that enforces the Orchard-pool cross-address restriction.
110 /// Every Orchard Action mined from NU6.3 onward commits to this circuit and only verifies under
111 /// this key: v5 Orchard bundles at NU6.3, v6 Orchard bundles, and Ironwood bundles.
112 pub static ref VERIFYING_KEY_NU6_3_ONWARD: ItemVerifyingKey =
113 ItemVerifyingKey::build(OrchardCircuitVersion::PostNu6_3);
114}
115
116/// A Halo2 verification item, used as the request type of the service.
117///
118/// An [`Item`] is key-agnostic: the circuit era's verifying key is supplied by whichever
119/// [`Verifier`] processes the item, so an item is always validated against exactly one key and
120/// eras are never mixed within a batch. Items built by the transaction verifier also carry a
121/// cache key derived from their transaction's [`WtxId`], sighash, and bundle pool, so a bundle
122/// verified from the mempool is not verified again when the block that mines it arrives.
123#[derive(Clone, Debug)]
124pub struct Item {
125 // `Arc`-wrapped so cloning an `Item` — which `tower-fallback` does eagerly for every request —
126 // shares the bundle instead of deep-copying its actions and multi-KB proof. `add_bundle` only
127 // needs `&Bundle`.
128 bundle: Arc<orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>>,
129 sighash: SigHash,
130 cache_key: Option<CacheKey>,
131}
132
133impl RequestWeight for Item {
134 fn request_weight(&self) -> usize {
135 self.bundle.actions().len()
136 }
137}
138
139impl Item {
140 /// Creates a new [`Item`] from a bundle and sighash.
141 ///
142 /// Items constructed without their transaction's [`WtxId`] are verified normally but are not
143 /// cached. The transaction verifier supplies the witnessed transaction ID through a
144 /// crate-private constructor so its items can reuse successful results.
145 pub fn new(
146 bundle: orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>,
147 sighash: SigHash,
148 ) -> Self {
149 Self {
150 bundle: Arc::new(bundle),
151 sighash,
152 cache_key: None,
153 }
154 }
155
156 /// Creates a cacheable item using its already-computed witnessed transaction ID.
157 ///
158 /// `wtx_id` must identify the transaction containing `bundle`. The transaction verifier
159 /// passes the ID it derived from its own request, whose caller must preserve this invariant.
160 pub(crate) fn new_with_wtx_id(
161 bundle: orchard::bundle::Bundle<orchard::bundle::Authorized, ZatBalance>,
162 sighash: SigHash,
163 wtx_id: WtxId,
164 ) -> Self {
165 let pool = ShieldedPool::from(bundle.bundle_version().value_pool());
166
167 Self {
168 bundle: Arc::new(bundle),
169 sighash,
170 cache_key: Some(CacheKey::new(
171 UnminedTxId::Witnessed(wtx_id),
172 sighash.0,
173 pool,
174 )),
175 }
176 }
177
178 /// Perform non-batched verification of this [`Item`] against `vk`.
179 ///
180 /// This is useful (in combination with `Item::clone`) for implementing
181 /// fallback logic when batch verification fails. The caller supplies the
182 /// verifying key for the item's era.
183 pub fn verify_single(self, vk: &ItemVerifyingKey) -> bool {
184 let mut batch = BatchValidator::new(vk);
185 // `add_bundle` rejects a bundle whose cross-address restriction is not supported by this
186 // era's verifying key; such an item is invalid under this key.
187 if batch.queue(self).is_err() {
188 return false;
189 }
190 batch.validate(rand::rng())
191 }
192}
193
194impl CachedItem for Item {
195 /// Returns this item's cache key, if it was constructed with a witnessed transaction ID.
196 ///
197 /// [`WtxId`] commits to the transaction's effecting and authorizing data. The sighash
198 /// additionally commits to the amounts and scripts of spent transparent outputs, which are
199 /// supplied by the verification context and are not part of the `WtxId`. The pool selects one
200 /// of the two Orchard-shaped bundles a v6 transaction can carry. The verifying key is absent
201 /// on purpose: each Orchard circuit era has its own cache, so an entry is only read back
202 /// under the key it was written against (see [`orchard_v5_verifier_for`]).
203 ///
204 /// The txid alone is insufficient because it excludes authorizing data under ZIP 244
205 /// (CVE-2026-34377). The pool is also required because both bundles in a v6 transaction share
206 /// the same [`WtxId`].
207 fn cache_key(&self) -> Option<CacheKey> {
208 self.cache_key
209 }
210}
211
212trait QueueBatchVerify {
213 fn queue(&mut self, item: Item) -> Result<(), orchard::bundle::BatchError>;
214}
215
216impl QueueBatchVerify for BatchValidator<'_> {
217 fn queue(
218 &mut self,
219 Item {
220 bundle, sighash, ..
221 }: Item,
222 ) -> Result<(), orchard::bundle::BatchError> {
223 self.add_bundle(bundle.as_ref(), sighash.0)
224 }
225}
226
227/// An error that may occur when verifying [Halo2 proofs of Zcash Orchard Action
228/// descriptions][actions].
229///
230/// [actions]: https://zips.z.cash/protocol/protocol.pdf#actiondesc
231// TODO: if halo2::plonk::Error gets the std::error::Error trait derived on it,
232// remove this and just wrap `halo2::plonk::Error` as an enum variant of
233// `crate::transaction::Error`, which does the trait derivation via `thiserror`
234#[derive(Clone, Debug, Error, Eq, PartialEq)]
235#[allow(missing_docs)]
236pub enum Halo2Error {
237 #[error("the constraint system is not satisfied")]
238 ConstraintSystemFailure,
239 #[error("unknown Halo2 error")]
240 Other,
241}
242
243impl From<halo2::plonk::Error> for Halo2Error {
244 fn from(err: halo2::plonk::Error) -> Halo2Error {
245 match err {
246 halo2::plonk::Error::ConstraintSystemFailure => Halo2Error::ConstraintSystemFailure,
247 _ => Halo2Error::Other,
248 }
249 }
250}
251
252/// The single-item fallback service for one Orchard circuit era.
253///
254/// When a batch fails, [`Fallback`] re-runs each item individually through this service. It holds
255/// the *same* verifying key as the batch it backs, so the fallback can never validate an item
256/// against a different era's key than the batch did. The key is named once, when the verifier is
257/// built (see [`batch_verifier`]).
258///
259/// This is a tiny named service rather than a `service_fn` closure because the closure would have
260/// to capture `vk`, and a capturing closure has an unnameable, non-`Clone` type — but the global
261/// verifier must be `Clone` to hand out per-call handles. A `&'static` field keeps this `Copy`.
262#[derive(Clone, Copy)]
263pub struct OrchardFallback {
264 /// The verifying key for this era, shared with the batch verifier it backs.
265 vk: &'static ItemVerifyingKey,
266}
267
268impl Service<Item> for OrchardFallback {
269 type Response = ();
270 type Error = BoxError;
271 type Future = BoxFuture<'static, Result<(), BoxError>>;
272
273 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
274 Poll::Ready(Ok(()))
275 }
276
277 fn call(&mut self, item: Item) -> Self::Future {
278 Verifier::verify_single_spawning(item, self.vk).boxed()
279 }
280}
281
282/// The concrete type of a global Halo2 verification service.
283///
284/// Each Orchard circuit version has its own batch worker and fallback verifier.
285pub type VerifierService = Fallback<Batch<Verifier, Item>, OrchardFallback>;
286
287/// A private cache around one public Halo2 verifier.
288pub(crate) type CachedVerifierService = Cached<VerifierService>;
289
290/// Builds the batching-and-fallback stack for `vk`.
291fn batch_verifier(vk: &'static ItemVerifyingKey) -> VerifierService {
292 Fallback::new(
293 Batch::new(
294 Verifier::new(vk),
295 HALO2_MAX_BATCH_SIZE,
296 None,
297 super::MAX_BATCH_LATENCY,
298 ),
299 OrchardFallback { vk },
300 )
301}
302
303/// Global batch verification context for **pre-NU6.2** Halo2 Action proofs.
304///
305/// Items routed here are verified against [`VERIFYING_KEY_PRE_NU6_2`] (the insecure circuit
306/// retained for historical blocks). This service transparently batches contemporaneous proof
307/// verifications, handling batch failures by falling back to individual verification.
308///
309/// Note that making a `Service` call requires mutable access to the service, so you should call
310/// `.clone()` on the global handle to create a local, mutable handle.
311pub static VERIFIER_PRE_NU6_2: Lazy<VerifierService> =
312 Lazy::new(|| batch_verifier(&VERIFYING_KEY_PRE_NU6_2));
313
314/// Global batch verification context for **NU6.2-until-NU6.3** Halo2 Action proofs.
315///
316/// Items routed here are verified against [`VERIFYING_KEY_NU6_2`] (the fixed circuit). This
317/// service transparently batches contemporaneous proof verifications, handling batch failures by
318/// falling back to individual verification.
319///
320/// Note that making a `Service` call requires mutable access to the service, so you should call
321/// `.clone()` on the global handle to create a local, mutable handle.
322pub static VERIFIER_NU6_2: Lazy<VerifierService> =
323 Lazy::new(|| batch_verifier(&VERIFYING_KEY_NU6_2));
324
325/// Global batch verification context for **NU6.3-onward** Halo2 Action proofs.
326///
327/// Items routed here are verified against [`VERIFYING_KEY_NU6_3_ONWARD`] (the NU6.3 Action circuit, which
328/// adds the `disableCrossAddress` constraint). Every Orchard Action mined from NU6.3 onward routes
329/// here — v5 Orchard bundles at NU6.3, v6 Orchard bundles, and Ironwood bundles. This service
330/// transparently batches contemporaneous proof verifications, handling batch failures by falling
331/// back to individual verification.
332///
333/// Note that making a `Service` call requires mutable access to the service, so you should call
334/// `.clone()` on the global handle to create a local, mutable handle.
335pub static VERIFIER_NU6_3_ONWARD: Lazy<VerifierService> =
336 Lazy::new(|| batch_verifier(&VERIFYING_KEY_NU6_3_ONWARD));
337
338/// Cached verification before NU6.2 using the public verifier's batch worker.
339static CACHED_VERIFIER_PRE_NU6_2: Lazy<CachedVerifierService> = Lazy::new(|| {
340 Cached::new(
341 VERIFIER_PRE_NU6_2.clone(),
342 CACHE_CAPACITY,
343 "halo2_pre_nu6_2",
344 )
345});
346
347/// Cached verification at NU6.2 using the public verifier's batch worker.
348static CACHED_VERIFIER_NU6_2: Lazy<CachedVerifierService> =
349 Lazy::new(|| Cached::new(VERIFIER_NU6_2.clone(), CACHE_CAPACITY, "halo2_nu6_2"));
350
351/// Cached verification from NU6.3 onward using the public verifier's batch worker.
352static CACHED_VERIFIER_NU6_3_ONWARD: Lazy<CachedVerifierService> = Lazy::new(|| {
353 Cached::new(
354 VERIFIER_NU6_3_ONWARD.clone(),
355 CACHE_CAPACITY,
356 "halo2_nu6_3_onward",
357 )
358});
359
360/// Returns the global Halo2 verifier for the **Orchard-pool** bundle of a **v5** transaction in a
361/// block at `network_upgrade`.
362///
363/// The Orchard Action circuit — and therefore its verifying key — changes with the block era, and
364/// a proof produced under one circuit does not verify under another era's key. The era is a
365/// function of the block's network upgrade, **not** the transaction version, so each v5 Orchard
366/// bundle is checked against the key for the upgrade of the block it appears in:
367///
368/// * upgrades before NU6.2 → [`VERIFIER_PRE_NU6_2`] (the historical insecure key), so
369/// pre-soft-fork Orchard history still verifies on re-sync;
370/// * NU6.2 until NU6.3 → [`VERIFIER_NU6_2`] (the fixed key);
371/// * NU6.3 onward → [`VERIFIER_NU6_3_ONWARD`] (the NU6.3 circuit). The Orchard-pool cross-address
372/// restriction is enforced for every Orchard Action from NU6.3 onward regardless of transaction
373/// version, "so that it cannot be bypassed by using a version 5 transaction" (ZIP 229); that
374/// restriction lives in the NU6.3 circuit, which the NU6.2 fixed key cannot verify. So a v5
375/// Orchard bundle at NU6.3 uses the same key as v6 Orchard and Ironwood bundles.
376///
377/// v6 Orchard and Ironwood bundles use [`orchard_v6_verifier`], which returns that same
378/// NU6.3-onward key.
379///
380/// The mapping is an explicit, exhaustive `match` on every [`NetworkUpgrade`] variant: there is no
381/// version-comparison fallthrough and no default arm, so adding a future upgrade is a compile error
382/// here until it is bound to a key on purpose.
383pub fn orchard_v5_verifier_for(network_upgrade: NetworkUpgrade) -> &'static VerifierService {
384 orchard_v5_verifiers_for(network_upgrade).0
385}
386
387/// Returns the cache for the same circuit selected by [`orchard_v5_verifier_for`].
388pub(crate) fn cached_orchard_v5_verifier_for(
389 network_upgrade: NetworkUpgrade,
390) -> &'static CachedVerifierService {
391 orchard_v5_verifiers_for(network_upgrade).1
392}
393
394/// Routes both services together without initializing unused circuit eras.
395fn orchard_v5_verifiers_for(
396 network_upgrade: NetworkUpgrade,
397) -> (
398 &'static Lazy<VerifierService>,
399 &'static Lazy<CachedVerifierService>,
400) {
401 use NetworkUpgrade::*;
402
403 match network_upgrade {
404 // Orchard did not exist before NU5, so these upgrades never carry Orchard bundles. They
405 // are bound to the pre-NU6.2 (insecure) verifier because that is the only key under which
406 // any Orchard history before NU6.2 verifies; routing them anywhere else cannot be correct.
407 Genesis | BeforeOverwinter | Overwinter | Sapling | Blossom | Heartwood | Canopy | Nu5
408 | Nu6 | Nu6_1 => (&VERIFIER_PRE_NU6_2, &CACHED_VERIFIER_PRE_NU6_2),
409
410 // NU6.2 ships the fixed circuit and is the only upgrade that uses it: it is active from the
411 // NU6.2 activation height until NU6.3.
412 Nu6_2 => (&VERIFIER_NU6_2, &CACHED_VERIFIER_NU6_2),
413
414 // NU6.3 adds the `disableCrossAddress` constraint to the Orchard Action circuit. Every
415 // Orchard Action from NU6.3 onward — including those in v5 transactions — commits to this
416 // circuit, so NU6.3 and later route to the NU6.3-onward key. Per ZIP 229 the cross-address
417 // restriction applies "regardless of transaction version ... so that it cannot be bypassed
418 // by using a version 5 transaction". Verifying these under the NU6.2 fixed key would both
419 // reject honest proofs (different key) and fail to enforce the restriction.
420 Nu6_3 | Nu7 => (&VERIFIER_NU6_3_ONWARD, &CACHED_VERIFIER_NU6_3_ONWARD),
421
422 // `ZFuture` only exists under the `zcash_unstable = "zfuture"` cfg. It is a post-NU6.3
423 // upgrade, so it inherits the NU6.3 circuit and is bound to the NU6.3-onward key here on
424 // purpose (rather than via a wildcard) to keep this match exhaustive and fail-closed under
425 // every build configuration.
426 #[cfg(zcash_unstable = "zfuture")]
427 ZFuture => (&VERIFIER_NU6_3_ONWARD, &CACHED_VERIFIER_NU6_3_ONWARD),
428 }
429}
430
431/// Returns how many times `item` reached this verifier's inner service.
432#[cfg(test)]
433pub(crate) fn inner_calls_for(verifier: &CachedVerifierService, item: &Item) -> usize {
434 verifier.inner_calls_for(item)
435}
436
437/// Returns the global Halo2 verifier for **v6** Orchard-pool and Ironwood-pool bundles.
438///
439/// v6 Orchard and Ironwood bundles only exist from NU6.3 onward, so they always use the NU6.3
440/// circuit — the same [`VERIFIER_NU6_3_ONWARD`] key that v5 Orchard bundles at NU6.3 route to.
441pub fn orchard_v6_verifier() -> &'static VerifierService {
442 &VERIFIER_NU6_3_ONWARD
443}
444
445/// Returns the shared Orchard and Ironwood cache for v6 transactions.
446pub(crate) fn cached_orchard_v6_verifier() -> &'static CachedVerifierService {
447 &CACHED_VERIFIER_NU6_3_ONWARD
448}
449
450/// Halo2 proof verifier implementation
451///
452/// This is the core implementation for the batch verification logic of the
453/// Halo2 verifier. It handles batching incoming requests, driving batches to
454/// completion, and reporting results.
455///
456/// Each verifier validates against a single, fixed [`ItemVerifyingKey`]; the three Orchard circuit
457/// eras (pre-NU6.2, NU6.2-until-NU6.3, and NU6.3-onward) are served by three independent verifiers,
458/// so a batch never mixes proofs from different eras.
459pub struct Verifier {
460 /// The verifying key that every batch and fallback from this verifier uses.
461 vk: &'static ItemVerifyingKey,
462
463 /// The synchronous Halo2 batch validator.
464 ///
465 /// Borrows `vk` (which is `'static`), so the validator is `BatchValidator<'static>`.
466 batch: BatchValidator<'static>,
467
468 /// A channel for broadcasting the result of a batch to the futures for each batch item.
469 ///
470 /// Each batch gets a newly created channel, so there is only ever one result sent per channel.
471 /// Tokio doesn't have a oneshot multi-consumer channel, so we use a watch channel.
472 tx: Sender,
473}
474
475impl Verifier {
476 /// Creates a verifier that validates every item against `vk`.
477 fn new(vk: &'static ItemVerifyingKey) -> Self {
478 let (tx, _) = watch::channel(None);
479 Self {
480 vk,
481 batch: BatchValidator::new(vk),
482 tx,
483 }
484 }
485
486 /// Returns the batch verifier and channel sender,
487 /// replacing the batch and channel with new empty ones.
488 fn take(&mut self) -> (BatchValidator<'static>, Sender) {
489 // Use a new verifier and channel for each batch.
490 let batch = mem::replace(&mut self.batch, BatchValidator::new(self.vk));
491 let (tx, _) = watch::channel(None);
492 let tx = mem::replace(&mut self.tx, tx);
493
494 (batch, tx)
495 }
496
497 /// Synchronously process the batch (the verifying key is held by the batch), and send the
498 /// result using the channel sender. This function blocks until the batch is completed.
499 fn verify(batch: BatchValidator<'static>, tx: Sender) {
500 let result = batch.validate(rand::rng());
501 let _ = tx.send(Some(result));
502 }
503
504 /// Flush the batch using a thread pool, sending the result via the channel.
505 /// This returns immediately, usually before the batch is completed.
506 fn flush_blocking(&mut self) {
507 let (batch, tx) = self.take();
508
509 // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
510 //
511 // We don't care about execution order here, because this method is only called on drop.
512 tokio::task::block_in_place(|| rayon::spawn_fifo(move || Self::verify(batch, tx)));
513 }
514
515 /// Flush the batch using a thread pool, returning the result via the channel. This function
516 /// returns a future that becomes ready when the batch is completed.
517 async fn flush_spawning(batch: BatchValidator<'static>, tx: Sender) {
518 // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
519 let start = std::time::Instant::now();
520 let result = spawn_fifo(move || batch.validate(rand::rng())).await;
521 let duration = start.elapsed().as_secs_f64();
522
523 let result_label = match &result {
524 Ok(true) => "success",
525 _ => "failure",
526 };
527 metrics::histogram!(
528 "zebra.consensus.batch.duration_seconds",
529 "verifier" => "halo2",
530 "result" => result_label
531 )
532 .record(duration);
533
534 let _ = tx.send(result.ok());
535 }
536
537 /// Verify a single item against `vk` using a thread pool, and return the result.
538 async fn verify_single_spawning(
539 item: Item,
540 vk: &'static ItemVerifyingKey,
541 ) -> Result<(), BoxError> {
542 // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
543 if spawn_fifo(move || item.verify_single(vk)).await? {
544 Ok(())
545 } else {
546 Err(TransactionError::Halo2VerificationFailed.into())
547 }
548 }
549}
550
551impl fmt::Debug for Verifier {
552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553 let name = "Verifier";
554 f.debug_struct(name).field("batch", &"..").finish()
555 }
556}
557
558impl Service<BatchControl<Item>> for Verifier {
559 type Response = ();
560 type Error = BoxError;
561 type Future = Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send + 'static>>;
562
563 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
564 Poll::Ready(Ok(()))
565 }
566
567 fn call(&mut self, req: BatchControl<Item>) -> Self::Future {
568 match req {
569 BatchControl::Item(item) => {
570 tracing::trace!("got item");
571 match self.batch.queue(item) {
572 Ok(()) => {}
573 // Reject the item on its own without poisoning the rest of the batch. In
574 // particular `BatchError::RestrictionUnsupportedByKey` should not be reachable
575 // (it fires only for a bundle with `cross_address_enabled = false` on a key
576 // that does not support the restriction; `VERIFIER_NU6_3_ONWARD`'s key supports
577 // it, and the pre-NU6.3 verifiers only ever see v5-format bundles, which always
578 // report `cross_address_enabled = true`), but failing closed per-item is
579 // strictly safer than panicking this shared, long-lived verifier service if a
580 // future routing change or `#[non_exhaustive]` variant ever reaches here.
581 Err(other) => {
582 return Box::pin(async move {
583 metrics::counter!("proofs.halo2.invalid").increment(1);
584 Err(format!("could not validate halo2 proof: {other}").into())
585 });
586 }
587 }
588 let mut rx = self.tx.subscribe();
589 Box::pin(async move {
590 match rx.changed().await {
591 Ok(()) => {
592 // We use a new channel for each batch,
593 // so we always get the correct batch result here.
594 let is_valid = *rx
595 .borrow()
596 .as_ref()
597 .ok_or("threadpool unexpectedly dropped response channel sender. Is Zebra shutting down?")?;
598
599 if is_valid {
600 tracing::trace!(?is_valid, "verified halo2 proof");
601 metrics::counter!("proofs.halo2.verified").increment(1);
602 Ok(())
603 } else {
604 tracing::trace!(?is_valid, "invalid halo2 proof");
605 metrics::counter!("proofs.halo2.invalid").increment(1);
606 Err(TransactionError::Halo2VerificationFailed.into())
607 }
608 }
609 Err(_recv_error) => panic!("verifier was dropped without flushing"),
610 }
611 })
612 }
613
614 BatchControl::Flush => {
615 tracing::trace!("got halo2 flush command");
616
617 let (batch, tx) = self.take();
618
619 Box::pin(Self::flush_spawning(batch, tx).map(|()| Ok(())))
620 }
621 }
622 }
623}
624
625impl Drop for Verifier {
626 fn drop(&mut self) {
627 // We need to flush the current batch in case there are still any pending futures.
628 // This returns immediately, usually before the batch is completed.
629 self.flush_blocking()
630 }
631}