Skip to main content

zebra_consensus/primitives/
ed25519.rs

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