zebra_consensus/primitives/
ed25519.rs1use 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
26type BatchVerifier = batch::Verifier;
28
29type VerifyResult = Result<(), Error>;
31
32type Sender = watch::Sender<Option<VerifyResult>>;
34
35#[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
60pub 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 tower::service_fn(
91 (|item: Item| Verifier::verify_single_spawning(item).boxed()) as fn(_) -> _,
92 ),
93 )
94});
95
96pub struct Verifier {
98 batch: BatchVerifier,
100
101 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 fn take(&mut self) -> (BatchVerifier, Sender) {
120 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 fn verify(batch: BatchVerifier, tx: Sender) {
132 let result = batch.verify(rand::rng());
133 let _ = tx.send(Some(result));
134 }
135
136 fn flush_blocking(&mut self) {
139 let (batch, tx) = self.take();
140
141 tokio::task::block_in_place(|| rayon::spawn_fifo(|| Self::verify(batch, tx)));
145 }
146
147 async fn flush_spawning(batch: BatchVerifier, tx: Sender) {
150 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 async fn verify_single_spawning(item: Item) -> Result<(), BoxError> {
171 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 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 self.flush_blocking();
230 }
231}