zebra_consensus/primitives/
redjubjub.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;
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
27type BatchVerifier = batch::Verifier;
29
30type VerifyResult = Result<(), Error>;
32
33type Sender = watch::Sender<Option<VerifyResult>>;
35
36#[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
55pub 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 tower::service_fn(
86 (|item: Item| Verifier::verify_single_spawning(item).boxed()) as fn(_) -> _,
87 ),
88 )
89});
90
91pub struct Verifier {
93 batch: BatchVerifier,
95
96 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 fn take(&mut self) -> (BatchVerifier, Sender) {
115 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 fn verify(batch: BatchVerifier, tx: Sender) {
127 let result = batch.verify(rand::rng());
128 let _ = tx.send(Some(result));
129 }
130
131 fn flush_blocking(&mut self) {
134 let (batch, tx) = self.take();
135
136 tokio::task::block_in_place(|| rayon::spawn_fifo(|| Self::verify(batch, tx)));
140 }
141
142 async fn flush_spawning(batch: BatchVerifier, tx: Sender) {
145 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 async fn verify_single_spawning(item: Item) -> Result<(), BoxError> {
166 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 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 self.flush_blocking();
226 }
227}