zebra_consensus/primitives/sapling.rs
1//! Async Sapling batch verifier service
2
3use core::fmt;
4use std::{
5 future::Future,
6 mem,
7 pin::Pin,
8 task::{Context, Poll},
9};
10
11use futures::{future::BoxFuture, FutureExt};
12use once_cell::sync::Lazy;
13use tokio::sync::watch;
14use tower::{util::ServiceFn, Service};
15use tower_batch_control::{Batch, BatchControl, RequestWeight};
16use tower_fallback::Fallback;
17
18use sapling_crypto::{bundle::Authorized, BatchValidator, Bundle};
19use zcash_proofs::prover::LocalTxProver;
20use zcash_protocol::value::ZatBalance;
21use zebra_chain::transaction::{SigHash, UnminedTxId};
22
23use crate::{error::TransactionError, BoxError};
24
25use super::cache::{CacheKey, Cached, CachedItem, ShieldedPool, CACHE_CAPACITY};
26
27#[cfg(test)]
28mod tests;
29
30/// Sapling prover containing spend and output params for the Sapling circuit.
31///
32/// Used to:
33///
34/// - construct Sapling outputs in coinbase txs, and
35/// - verify Sapling shielded data in the tx verifier.
36static SAPLING: Lazy<LocalTxProver> = Lazy::new(LocalTxProver::bundled);
37
38/// Returns the shared Sapling prover.
39///
40/// Parsing the bundled Sapling parameters takes time, so callers that build Sapling
41/// outputs share this prover instead of parsing the parameters again.
42pub fn prover() -> &'static LocalTxProver {
43 &SAPLING
44}
45
46/// A Sapling verification item, used as the request type of the service.
47///
48/// Every item carries the cache key its successful verification is remembered under, derived from
49/// its transaction's ID and sighash.
50#[derive(Clone)]
51pub struct Item {
52 /// The bundle containing the Sapling shielded data to verify.
53 bundle: Bundle<Authorized, ZatBalance>,
54 /// The sighash of the transaction that contains the Sapling shielded data.
55 sighash: SigHash,
56 /// The key this item's successful verification is remembered under.
57 cache_key: CacheKey,
58}
59
60impl Item {
61 /// Creates a new [`Item`] from a Sapling bundle, its sighash, and its transaction's ID.
62 ///
63 /// `tx_id` must identify the transaction containing `bundle`, because the cache treats it as
64 /// determining the bundle — see this type's [`CachedItem`] implementation. The transaction
65 /// verifier passes the ID it derived from its own request, whose caller must preserve this
66 /// invariant.
67 pub fn new(
68 bundle: Bundle<Authorized, ZatBalance>,
69 sighash: SigHash,
70 tx_id: UnminedTxId,
71 ) -> Self {
72 Self {
73 bundle,
74 sighash,
75 cache_key: CacheKey::new(tx_id, sighash.0, ShieldedPool::Sapling),
76 }
77 }
78}
79
80impl CachedItem for Item {
81 /// Returns the key this item's successful verification is remembered under.
82 ///
83 /// The transaction ID commits to the bundle, in both of the forms it takes. A v5 or v6
84 /// transaction's [`WtxId`](zebra_chain::transaction::WtxId) pairs a txid over the effecting
85 /// data with a ZIP 244 authorizing-data digest over the proofs and signatures; a v4
86 /// transaction's legacy ID is the hash of its whole serialization, which contains the same
87 /// authorizing data. So unlike Orchard, which only exists in v5 and v6 transactions, Sapling
88 /// caches v4 bundles too.
89 ///
90 /// The sighash is keyed separately because it is not always a function of the transaction
91 /// alone. A v5 or v6 sighash also commits to the amounts and scripts of the spent transparent
92 /// outputs, which the verification context supplies. A v4 shielded sighash does not — it is
93 /// computed with no input index, so ZIP 143 and ZIP 243 leave the spent output out — but it
94 /// does commit to the consensus branch id of the block, which the transaction ID of a v4
95 /// transaction does not carry.
96 ///
97 /// The verifying keys are absent on purpose: Sapling has one spend and one output verifying
98 /// key for all of history, so unlike Orchard it has no circuit eras to keep apart, and every
99 /// entry in this cache was written under the same keys it is read back under.
100 fn cache_key(&self) -> Option<CacheKey> {
101 Some(self.cache_key)
102 }
103}
104
105impl RequestWeight for Item {}
106
107/// A service that verifies Sapling shielded data in batches.
108///
109/// Handles batching incoming requests, driving batches to completion, and reporting results.
110#[derive(Default)]
111pub struct Verifier {
112 /// A batch verifier for Sapling shielded data.
113 batch: BatchValidator,
114
115 /// A channel for broadcasting the verification result of the batch.
116 ///
117 /// Each batch gets a newly created channel, so there is only ever one result sent per channel.
118 /// Tokio doesn't have a oneshot multi-consumer channel, so we use a watch channel.
119 tx: watch::Sender<Option<bool>>,
120}
121
122impl fmt::Debug for Verifier {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_struct("Verifier")
125 .field("batch", &"..")
126 .field("tx", &self.tx)
127 .finish()
128 }
129}
130
131impl Drop for Verifier {
132 // Flush the current batch in case there are still any pending futures.
133 //
134 // Flushing the batch means we need to validate it. This function fires off the validation and
135 // returns immediately, usually before the validation finishes.
136 fn drop(&mut self) {
137 let batch = mem::take(&mut self.batch);
138 let tx = mem::take(&mut self.tx);
139
140 // The validation is CPU-intensive; do it on a dedicated thread so it does not block.
141 rayon::spawn_fifo(move || {
142 let (spend_vk, output_vk) = SAPLING.verifying_keys();
143
144 // Validate the batch and send the result through the channel.
145 let res = batch.validate(&spend_vk, &output_vk, rand::rng());
146 let _ = tx.send(Some(res));
147 });
148 }
149}
150
151impl Service<BatchControl<Item>> for Verifier {
152 type Response = ();
153 type Error = Box<dyn std::error::Error + Send + Sync>;
154 type Future = Pin<Box<dyn Future<Output = Result<(), Self::Error>> + Send>>;
155
156 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
157 Poll::Ready(Ok(()))
158 }
159
160 fn call(&mut self, req: BatchControl<Item>) -> Self::Future {
161 match req {
162 BatchControl::Item(item) => {
163 let mut rx = self.tx.subscribe();
164
165 let bundle_check = self
166 .batch
167 .check_bundle(item.bundle, item.sighash.into())
168 .then_some(())
169 .ok_or(TransactionError::SaplingVerificationFailed);
170
171 async move {
172 bundle_check.map_err(BoxError::from)?;
173
174 rx.changed()
175 .await
176 .map_err(|_| BoxError::from("verifier was dropped without flushing"))?;
177
178 // We use a new channel for each batch, so we always get the correct
179 // batch result here.
180 let is_valid = rx.borrow().ok_or_else(|| {
181 BoxError::from("threadpool unexpectedly dropped channel sender")
182 })?;
183
184 if is_valid {
185 metrics::counter!("proofs.sapling.verified").increment(1);
186 Ok(())
187 } else {
188 metrics::counter!("proofs.sapling.invalid").increment(1);
189 Err(BoxError::from(TransactionError::SaplingVerificationFailed))
190 }
191 }
192 .boxed()
193 }
194
195 BatchControl::Flush => {
196 let batch = mem::take(&mut self.batch);
197 let tx = mem::take(&mut self.tx);
198
199 async move {
200 let start = std::time::Instant::now();
201 let spawn_result = tokio::task::spawn_blocking(move || {
202 let (spend_vk, output_vk) = SAPLING.verifying_keys();
203 batch.validate(&spend_vk, &output_vk, rand::rng())
204 })
205 .await;
206 let duration = start.elapsed().as_secs_f64();
207
208 let result_label = match &spawn_result {
209 Ok(true) => "success",
210 _ => "failure",
211 };
212 metrics::histogram!(
213 "zebra.consensus.batch.duration_seconds",
214 "verifier" => "groth16_sapling",
215 "result" => result_label
216 )
217 .record(duration);
218
219 // Extract the value before consuming spawn_result
220 let is_valid = spawn_result.as_ref().ok().copied();
221 let _ = tx.send(is_valid);
222 spawn_result.map(|_| ()).map_err(Self::Error::from)
223 }
224 .boxed()
225 }
226 }
227 }
228}
229
230/// Verifies a single [`Item`].
231pub fn verify_single(
232 item: Item,
233) -> Pin<Box<dyn Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>> + Send>> {
234 async move {
235 let mut verifier = Verifier::default();
236
237 let check = verifier
238 .batch
239 .check_bundle(item.bundle, item.sighash.into())
240 .then_some(())
241 .ok_or(TransactionError::SaplingVerificationFailed);
242 check.map_err(BoxError::from)?;
243
244 let is_valid = tokio::task::spawn_blocking(move || {
245 let (spend_vk, output_vk) = SAPLING.verifying_keys();
246
247 mem::take(&mut verifier.batch).validate(&spend_vk, &output_vk, rand::rng())
248 })
249 .await
250 .map_err(|_| BoxError::from("Sapling bundle validation thread panicked"))?;
251
252 if is_valid {
253 Ok(())
254 } else {
255 Err(BoxError::from(TransactionError::SaplingVerificationFailed))
256 }
257 }
258 .boxed()
259}
260
261/// The batching-and-fallback stack for Sapling bundle verification, before caching.
262type BatchFallbackService = Fallback<
263 Batch<Verifier, Item>,
264 ServiceFn<fn(Item) -> BoxFuture<'static, Result<(), Box<dyn std::error::Error + Send + Sync>>>>,
265>;
266
267/// The concrete type of the global Sapling verification service.
268pub(crate) type VerifierService = Cached<BatchFallbackService>;
269
270/// Global batch verification context for Sapling shielded data.
271///
272/// The stack is wrapped in a [`Cached`] so that a bundle verified when its transaction was
273/// gossiped into the mempool does not have to be verified again when the block that mines it
274/// arrives. One cache covers all of Sapling: its spend and output verifying keys have never
275/// changed, so unlike Orchard there are no circuit eras to keep apart.
276pub(crate) static VERIFIER: Lazy<VerifierService> =
277 Lazy::new(|| Cached::new(batch_fallback_verifier(), CACHE_CAPACITY, "groth16_sapling"));
278
279/// Returns how many times `item` reached this verifier's inner service.
280#[cfg(test)]
281pub(crate) fn inner_calls_for(verifier: &VerifierService, item: &Item) -> usize {
282 verifier.inner_calls_for(item)
283}
284
285/// Builds the uncached batching-and-fallback stack.
286fn batch_fallback_verifier() -> BatchFallbackService {
287 Fallback::new(
288 Batch::new(
289 Verifier::default(),
290 super::MAX_BATCH_SIZE,
291 None,
292 super::MAX_BATCH_LATENCY,
293 ),
294 tower::service_fn(verify_single as fn(Item) -> _),
295 )
296}