zebra_consensus/primitives/
redpallas.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::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
27type BatchVerifier = batch::Verifier<orchard::SpendAuth, orchard::Binding>;
29
30type VerifyResult = Result<(), Error>;
32
33type Sender = watch::Sender<Option<VerifyResult>>;
35
36#[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 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 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
73pub 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 tower::service_fn(
104 (|item: Item| Verifier::verify_single_spawning(item).boxed()) as fn(_) -> _,
105 ),
106 )
107});
108
109pub struct Verifier {
111 batch: BatchVerifier,
113
114 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 fn take(&mut self) -> (BatchVerifier, Sender) {
133 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 fn verify(batch: BatchVerifier, tx: Sender) {
145 let result = batch.verify(rand::rng());
146 let _ = tx.send(Some(result));
147 }
148
149 fn flush_blocking(&mut self) {
152 let (batch, tx) = self.take();
153
154 tokio::task::block_in_place(|| rayon::spawn_fifo(|| Self::verify(batch, tx)));
158 }
159
160 async fn flush_spawning(batch: BatchVerifier, tx: Sender) {
163 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 async fn verify_single_spawning(item: Item) -> Result<(), BoxError> {
184 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 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 self.flush_blocking();
243 }
244}