Skip to main content

zebra_consensus/primitives/
redpallas.rs

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