Skip to main content

zebra_consensus/primitives/
redjubjub.rs

1//! Async RedJubjub batch verifier service
2
3use std::{
4    future::Future,
5    mem,
6    pin::Pin,
7    task::{Context, Poll},
8};
9
10use futures::{future::BoxFuture, FutureExt};
11use once_cell::sync::Lazy;
12
13use tokio::sync::watch;
14use tower::{util::ServiceFn, Service};
15use tower_batch_control::{Batch, BatchControl, RequestWeight};
16use tower_fallback::Fallback;
17
18use zebra_chain::primitives::redjubjub::*;
19
20use crate::BoxError;
21
22use super::{spawn_fifo, spawn_fifo_and_convert};
23
24#[cfg(test)]
25mod tests;
26
27/// The type of the batch verifier.
28type BatchVerifier = batch::Verifier;
29
30/// The type of verification results.
31type VerifyResult = Result<(), Error>;
32
33/// The type of the batch sender channel.
34type Sender = watch::Sender<Option<VerifyResult>>;
35
36/// The type of the batch item.
37/// This is a newtype around a `RedJubjubItem`.
38#[derive(Clone, Debug)]
39pub struct Item(batch::Item);
40
41impl RequestWeight for Item {}
42
43impl<T: Into<batch::Item>> From<T> for Item {
44    fn from(value: T) -> Self {
45        Self(value.into())
46    }
47}
48
49impl Item {
50    fn verify_single(self) -> VerifyResult {
51        self.0.verify_single()
52    }
53}
54
55/// Global batch verification context for RedJubjub signatures.
56///
57/// This service transparently batches contemporaneous signature verifications,
58/// handling batch failures by falling back to individual verification.
59///
60/// Note that making a `Service` call requires mutable access to the service, so
61/// you should call `.clone()` on the global handle to create a local, mutable
62/// handle.
63pub static VERIFIER: Lazy<
64    Fallback<
65        Batch<Verifier, Item>,
66        ServiceFn<fn(Item) -> BoxFuture<'static, Result<(), BoxError>>>,
67    >,
68> = Lazy::new(|| {
69    Fallback::new(
70        Batch::new(
71            Verifier::default(),
72            super::MAX_BATCH_SIZE,
73            None,
74            super::MAX_BATCH_LATENCY,
75        ),
76        // We want to fallback to individual verification if batch verification fails,
77        // so we need a Service to use.
78        //
79        // Because we have to specify the type of a static, we need to be able to
80        // write the type of the closure and its return value. But both closures and
81        // async blocks have unnameable types. So instead we cast the closure to a function
82        // (which is possible because it doesn't capture any state), and use a BoxFuture
83        // to erase the result type.
84        // (We can't use BoxCloneService to erase the service type, because it is !Sync.)
85        tower::service_fn(
86            (|item: Item| Verifier::verify_single_spawning(item).boxed()) as fn(_) -> _,
87        ),
88    )
89});
90
91/// RedJubjub signature verifier service
92pub struct Verifier {
93    /// A batch verifier for RedJubjub signatures.
94    batch: BatchVerifier,
95
96    /// A channel for broadcasting the result of a batch to the futures for each batch item.
97    ///
98    /// Each batch gets a newly created channel, so there is only ever one result sent per channel.
99    /// Tokio doesn't have a oneshot multi-consumer channel, so we use a watch channel.
100    tx: Sender,
101}
102
103impl Default for Verifier {
104    fn default() -> Self {
105        let batch = BatchVerifier::default();
106        let (tx, _) = watch::channel(None);
107        Self { batch, tx }
108    }
109}
110
111impl Verifier {
112    /// Returns the batch verifier and channel sender from `self`,
113    /// replacing them with a new empty batch.
114    fn take(&mut self) -> (BatchVerifier, Sender) {
115        // Use a new verifier and channel for each batch.
116        let batch = mem::take(&mut self.batch);
117
118        let (tx, _) = watch::channel(None);
119        let tx = mem::replace(&mut self.tx, tx);
120
121        (batch, tx)
122    }
123
124    /// Synchronously process the batch, and send the result using the channel sender.
125    /// This function blocks until the batch is completed.
126    fn verify(batch: BatchVerifier, tx: Sender) {
127        let result = batch.verify(rand::rng());
128        let _ = tx.send(Some(result));
129    }
130
131    /// Flush the batch using a thread pool, and return the result via the channel.
132    /// This returns immediately, usually before the batch is completed.
133    fn flush_blocking(&mut self) {
134        let (batch, tx) = self.take();
135
136        // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
137        //
138        // We don't care about execution order here, because this method is only called on drop.
139        tokio::task::block_in_place(|| rayon::spawn_fifo(|| Self::verify(batch, tx)));
140    }
141
142    /// Flush the batch using a thread pool, and return the result via the channel.
143    /// This function returns a future that becomes ready when the batch is completed.
144    async fn flush_spawning(batch: BatchVerifier, tx: Sender) {
145        // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
146        let start = std::time::Instant::now();
147        let result = spawn_fifo(move || batch.verify(rand::rng())).await;
148        let duration = start.elapsed().as_secs_f64();
149
150        let result_label = match &result {
151            Ok(Ok(())) => "success",
152            _ => "failure",
153        };
154        metrics::histogram!(
155            "zebra.consensus.batch.duration_seconds",
156            "verifier" => "redjubjub",
157            "result" => result_label
158        )
159        .record(duration);
160
161        let _ = tx.send(result.ok());
162    }
163
164    /// Verify a single item using a thread pool, and return the result.
165    async fn verify_single_spawning(item: Item) -> Result<(), BoxError> {
166        // Correctness: Do CPU-intensive work on a dedicated thread, to avoid blocking other futures.
167        spawn_fifo_and_convert(move || item.verify_single()).await
168    }
169}
170
171impl Service<BatchControl<Item>> for Verifier {
172    type Response = ();
173    type Error = BoxError;
174    type Future = Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send + 'static>>;
175
176    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
177        Poll::Ready(Ok(()))
178    }
179
180    fn call(&mut self, req: BatchControl<Item>) -> Self::Future {
181        match req {
182            BatchControl::Item(item) => {
183                tracing::trace!("got item");
184                self.batch.queue(item.0);
185                let mut rx = self.tx.subscribe();
186
187                Box::pin(async move {
188                    match rx.changed().await {
189                        Ok(()) => {
190                            // We use a new channel for each batch,
191                            // so we always get the correct batch result here.
192                            let result = rx.borrow()
193                                .ok_or("threadpool unexpectedly dropped response channel sender. Is Zebra shutting down?")?;
194
195                            if result.is_ok() {
196                                tracing::trace!(?result, "validated redjubjub signature");
197                                metrics::counter!("signatures.redjubjub.validated").increment(1);
198                            } else {
199                                tracing::trace!(?result, "invalid redjubjub signature");
200                                metrics::counter!("signatures.redjubjub.invalid").increment(1);
201                            }
202
203                            result.map_err(BoxError::from)
204                        }
205                        Err(_recv_error) => panic!("verifier was dropped without flushing"),
206                    }
207                })
208            }
209
210            BatchControl::Flush => {
211                tracing::trace!("got redjubjub flush command");
212
213                let (batch, tx) = self.take();
214
215                Box::pin(Self::flush_spawning(batch, tx).map(Ok))
216            }
217        }
218    }
219}
220
221impl Drop for Verifier {
222    fn drop(&mut self) {
223        // We need to flush the current batch in case there are still any pending futures.
224        // This returns immediately, usually before the batch is completed.
225        self.flush_blocking();
226    }
227}