Skip to main content

zebra_consensus/primitives/
cache.rs

1//! A bounded cache of shielded bundle verifications that have already succeeded.
2//!
3//! Zebra verifies a transaction's shielded proofs and signatures when the transaction arrives
4//! over mempool gossip, and again when it arrives in a block. This service skips the second
5//! verification. The Halo2 Orchard and Ironwood verifiers ([`super::halo2`]) and the Sapling
6//! verifier ([`super::sapling`]) share it, and key their entries the same way.
7//!
8//! # Why this is not the mempool bypass
9//!
10//! Zebra once skipped whole-transaction verification for transactions already in the mempool, and
11//! removed it as a security fix (PR #10494). Transaction validity depends on height, block time
12//! and spent outputs, and that cache's key named none of them.
13//!
14//! This cache remembers successful bundle verification by transaction ID, sighash and shielded
15//! pool. A hit still runs the whole transaction verifier against the block's height, time and
16//! spent outputs, and skips only the proof and signature checks. Each Orchard circuit era has its
17//! own cache, which binds an entry to its verifying key (see [`super::halo2::orchard_v5_verifier_for`]);
18//! Sapling has one verifying key pair for all of history, so one cache covers it.
19//!
20//! Only `Ok` results are cached. A batch error is not per-item evidence, because
21//! [`Fallback`](tower_fallback::Fallback) re-verifies failures singly, and it may not be a verdict
22//! at all — a shut-down batch worker reports the same way. Caching it would reject a valid block.
23
24use std::{
25    collections::{HashSet, VecDeque},
26    future,
27    sync::{Arc, Mutex},
28    task::{Context, Poll},
29};
30
31use futures::{future::BoxFuture, FutureExt};
32use tower::{Service, ServiceExt};
33use zebra_chain::transaction::UnminedTxId;
34
35use crate::BoxError;
36
37#[cfg(test)]
38mod tests;
39
40/// The number of verified-bundle keys retained per cache.
41///
42/// Sized to hold several blocks of history plus a full mempool, so that a transaction gossiped
43/// well before the block that mines it is still remembered.
44///
45/// Each key is a 98-byte transaction ID, sighash and pool tag, held twice — once in the lookup
46/// set and once in the eviction queue — so a full cache costs about 5 MiB, and about 20 MiB
47/// across the three Orchard circuit eras and Sapling. Only the eras a node actually verifies pay
48/// it, because each cache is built with its verifier on first use.
49pub(super) const CACHE_CAPACITY: usize = 20_000;
50
51/// The label naming which verifier's cache a metric belongs to.
52///
53/// One cache instance per Orchard circuit era and one for Sapling all report under the same
54/// metric names, so every series carries this label. Its values are `halo2_pre_nu6_2`,
55/// `halo2_nu6_2`, `halo2_nu6_3_onward` and `groth16_sapling`. Only Sapling's matches the
56/// `verifier` label of its `zebra.consensus.batch.duration_seconds` series as well; the Halo2
57/// batch metric reports all three eras as one `halo2` series.
58const VERIFIER_LABEL: &str = "verifier";
59
60/// Counts verifications answered from a cache.
61const CACHE_HIT: &str = "zebra.consensus.cache.hit";
62
63/// Counts verifications that reached a cache's inner service.
64const CACHE_MISS: &str = "zebra.consensus.cache.miss";
65
66/// Counts keys recorded as verified.
67const CACHE_INSERT: &str = "zebra.consensus.cache.insert";
68
69/// Counts keys dropped to stay within a cache's capacity.
70const CACHE_EVICT: &str = "zebra.consensus.cache.evict";
71
72/// Reports how many keys a cache currently remembers.
73const CACHE_SIZE: &str = "zebra.consensus.cache.size";
74
75/// The shielded bundle slot a cache entry was verified for.
76///
77/// One v6 transaction has an Orchard bundle, an Ironwood bundle and a Sapling bundle, all under
78/// one transaction ID and one sighash, so the key names which one it stands for. The Orchard and
79/// Ironwood caches at NU6.3 onward are the same cache, so this tag is what keeps their entries
80/// apart; Sapling has its own cache and its tag is defence in depth.
81#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
82pub(super) enum ShieldedPool {
83    /// The Sapling value pool.
84    Sapling,
85
86    /// The Orchard value pool.
87    Orchard,
88
89    /// The Ironwood value pool.
90    Ironwood,
91}
92
93impl From<orchard::ValuePool> for ShieldedPool {
94    fn from(pool: orchard::ValuePool) -> Self {
95        match pool {
96            orchard::ValuePool::Orchard => Self::Orchard,
97            orchard::ValuePool::Ironwood => Self::Ironwood,
98        }
99    }
100}
101
102/// A transaction, sighash and shielded pool whose bundle has verified.
103///
104/// # Correctness
105///
106/// A hit replaces a verification, so the key must determine every input that verification reads:
107/// the bundle and the sighash.
108///
109/// The transaction ID determines the bundle, in both of the forms it takes:
110///
111///   * [`UnminedTxId::Witnessed`] carries a [`WtxId`](zebra_chain::transaction::WtxId), whose
112///     txid commits to the transaction's effecting data and whose ZIP 244 authorizing-data digest
113///     commits to its proofs and signatures. The txid alone would not: it excludes authorizing
114///     data, which is what CVE-2026-34377 exploited.
115///   * [`UnminedTxId::Legacy`] is a v1-v4 transaction ID, the hash of the whole serialized
116///     transaction, so it commits to the Sapling proofs and signatures directly. V4 transactions
117///     have no witnessed ID, and this is why they do not need one here.
118///
119/// The sighash is named separately because it is not always a function of the transaction alone.
120/// A v5 or v6 sighash also commits to the amounts and `scriptPubKey`s of the spent transparent
121/// outputs, which the verification context supplies. A v4 shielded sighash does not — it is
122/// computed with no input index, so ZIP 143 and ZIP 243 leave the spent output out — but it does
123/// commit to the block's consensus branch id, which a v4 transaction ID does not carry, and which
124/// selects the verification a bundle is checked against.
125///
126/// The verifying key is absent on purpose. Each Orchard circuit era has its own cache, so an
127/// entry is only ever read back under the key it was written against, and Sapling has one key
128/// pair for all of history.
129#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
130pub(super) struct CacheKey {
131    /// The ID of the transaction the bundle was parsed from.
132    tx_id: UnminedTxId,
133
134    /// The signature digest used to verify the bundle's signatures.
135    sighash: [u8; 32],
136
137    /// The bundle slot verified for this transaction.
138    pool: ShieldedPool,
139}
140
141impl CacheKey {
142    /// Returns the key for `pool`'s bundle in the transaction identified by `tx_id`, verified
143    /// against `sighash`.
144    pub(super) fn new(tx_id: UnminedTxId, sighash: [u8; 32], pool: ShieldedPool) -> Self {
145        Self {
146            tx_id,
147            sighash,
148            pool,
149        }
150    }
151}
152
153/// An item whose successful verification can be remembered.
154///
155/// Items without a key are verified normally and never cached, which is how a caller that has no
156/// transaction identity to offer stays correct.
157///
158/// # Correctness
159///
160/// An implementer promises that the returned key determines every input the item's verification
161/// reads: the bundle, and the sighash it is checked against. [`Cached`] answers any later item
162/// with an equal key from the remembered `Ok` without verifying it, so a key that two different
163/// bundles can share accepts a bundle this node never checked. An implementer that cannot offer
164/// a complete key returns `None`, and the item is verified every time.
165pub(super) trait CachedItem {
166    /// Returns the key this item's successful verification is remembered under, or `None` if the
167    /// item must always be verified.
168    ///
169    /// The key is a pure function of the item: two calls on one item return the same key, and two
170    /// items with equal keys have identical verification inputs. [`CacheKey`] derives why a
171    /// transaction ID, a sighash and a shielded pool are enough.
172    fn cache_key(&self) -> Option<CacheKey>;
173}
174
175/// What one [`VerifiedBundles::insert`] did, so the caller can report it after releasing the
176/// lock.
177///
178/// Metrics are emitted outside the critical section so recorder code never runs under the cache
179/// lock.
180#[derive(Clone, Copy, Debug)]
181struct InsertOutcome {
182    /// Whether this key was new, rather than a concurrent duplicate.
183    inserted: bool,
184
185    /// How many keys were evicted to make room for it.
186    evicted: usize,
187
188    /// How many keys the cache holds now.
189    size: usize,
190}
191
192/// A bounded set of keys for bundles that have already verified successfully.
193///
194/// Eviction is first-in-first-out rather than least-recently-used: the working set is the
195/// mempool, which turns over in arrival order anyway, and FIFO needs no bookkeeping on the read
196/// path. Evicting an entry only costs a re-verification, never correctness.
197///
198/// # Correctness
199///
200/// `keys` and `insertion_order` hold the same keys. `keys` answers [`Self::contains`], and
201/// `insertion_order` chooses which key to drop. Only [`Self::insert`] and `Self::clear` change
202/// them, and each changes both, so no caller can leave them holding different keys.
203#[derive(Debug)]
204struct VerifiedBundles {
205    /// The keys currently remembered.
206    keys: HashSet<CacheKey>,
207
208    /// The same keys in insertion order, so the oldest can be evicted.
209    insertion_order: VecDeque<CacheKey>,
210
211    /// The maximum number of keys to retain.
212    capacity: usize,
213}
214
215impl VerifiedBundles {
216    /// Creates an empty cache that retains at most `capacity` keys.
217    fn new(capacity: usize) -> Self {
218        Self {
219            keys: HashSet::with_capacity(capacity),
220            insertion_order: VecDeque::with_capacity(capacity),
221            capacity,
222        }
223    }
224
225    /// Returns `true` if `key` has already verified.
226    fn contains(&self, key: &CacheKey) -> bool {
227        self.keys.contains(key)
228    }
229
230    /// Records that `key` has verified, evicting the oldest keys to stay within the capacity.
231    fn insert(&mut self, key: CacheKey) -> InsertOutcome {
232        // Concurrent verifications of the same item both miss and both insert. The second is a
233        // no-op, and must not push a duplicate into the eviction queue.
234        if !self.keys.insert(key) {
235            return InsertOutcome {
236                inserted: false,
237                evicted: 0,
238                size: self.keys.len(),
239            };
240        }
241
242        // Evict before pushing, so the queue never has to grow past the capacity it was built
243        // with. Pushing first would take it to `capacity + 1` and double its allocation for the
244        // rest of the process.
245        let mut evicted = 0;
246        while self.insertion_order.len() >= self.capacity {
247            // The queue is non-empty whenever its length reaches a capacity of one or more, which
248            // is what every caller passes. Breaking rather than unwrapping keeps a capacity of
249            // zero from looping forever.
250            let Some(oldest) = self.insertion_order.pop_front() else {
251                break;
252            };
253            self.keys.remove(&oldest);
254            evicted += 1;
255        }
256
257        self.insertion_order.push_back(key);
258
259        InsertOutcome {
260            inserted: true,
261            evicted,
262            size: self.keys.len(),
263        }
264    }
265
266    /// Forgets every key.
267    ///
268    /// Test-only: it lets a test start from a cold cache. Forgetting a key only costs a
269    /// re-verification, so it is always safe.
270    #[cfg(test)]
271    fn clear(&mut self) {
272        self.keys.clear();
273        self.insertion_order.clear();
274    }
275}
276
277impl InsertOutcome {
278    /// Reports this insert using the cache's metric handles.
279    ///
280    /// [`Cached::call`] calls this after it releases the cache lock.
281    fn report(self, metrics: &CacheMetrics) {
282        if !self.inserted {
283            return;
284        }
285
286        metrics.insert.increment(1);
287
288        if self.evicted > 0 {
289            // Cast is safe: at most `capacity` keys are evicted by one insert.
290            metrics.evict.increment(self.evicted as u64);
291        }
292
293        // Cast is safe: the length is bounded by `capacity`, far below f64's exact integer range.
294        metrics.size.set(self.size as f64);
295    }
296}
297
298/// Metric handles registered once when a cache is created.
299#[derive(Clone)]
300struct CacheMetrics {
301    hit: metrics::Counter,
302    miss: metrics::Counter,
303    insert: metrics::Counter,
304    evict: metrics::Counter,
305    size: metrics::Gauge,
306}
307
308impl CacheMetrics {
309    fn new(verifier_name: &'static str) -> Self {
310        Self {
311            hit: metrics::counter!(CACHE_HIT, VERIFIER_LABEL => verifier_name),
312            miss: metrics::counter!(CACHE_MISS, VERIFIER_LABEL => verifier_name),
313            insert: metrics::counter!(CACHE_INSERT, VERIFIER_LABEL => verifier_name),
314            evict: metrics::counter!(CACHE_EVICT, VERIFIER_LABEL => verifier_name),
315            size: metrics::gauge!(CACHE_SIZE, VERIFIER_LABEL => verifier_name),
316        }
317    }
318}
319
320/// A service that skips inner verification for items whose bundle has already verified.
321///
322/// This wraps one verifier's batch-and-fallback stack. The cache is shared between clones, so
323/// every handle to a global verifier sees the same set of verified bundles.
324///
325/// The public Halo2 services retain their uncached types.
326pub(crate) struct Cached<S> {
327    /// The verification service to consult on a miss.
328    inner: S,
329
330    /// The keys of items that have already verified under this cache's verifying key.
331    verified: Arc<Mutex<VerifiedBundles>>,
332
333    /// The metric handles shared by clones of this cache.
334    metrics: CacheMetrics,
335
336    /// The keys of the items that reached the inner service, in call order.
337    ///
338    /// Test-only. See [`Self::inner_calls_for`].
339    #[cfg(test)]
340    inner_calls: Arc<Mutex<Vec<CacheKey>>>,
341}
342
343impl<S: Clone> Clone for Cached<S> {
344    fn clone(&self) -> Self {
345        Self {
346            inner: self.inner.clone(),
347            verified: self.verified.clone(),
348            metrics: self.metrics.clone(),
349            #[cfg(test)]
350            inner_calls: self.inner_calls.clone(),
351        }
352    }
353}
354
355impl<S> Cached<S> {
356    /// Wraps `inner` in a cache that retains at most `capacity` verified-bundle keys and reports
357    /// its metrics under the `verifier` label `verifier_name`.
358    pub(super) fn new(inner: S, capacity: usize, verifier_name: &'static str) -> Self {
359        Self {
360            inner,
361            verified: Arc::new(Mutex::new(VerifiedBundles::new(capacity))),
362            metrics: CacheMetrics::new(verifier_name),
363            #[cfg(test)]
364            inner_calls: Arc::new(Mutex::new(Vec::new())),
365        }
366    }
367
368    /// Returns a cold cache with independent call records and the same inner verifier.
369    #[cfg(test)]
370    pub(crate) fn isolated(&self) -> Self
371    where
372        S: Clone,
373    {
374        Self {
375            inner: self.inner.clone(),
376            verified: Arc::new(Mutex::new(VerifiedBundles::new(CACHE_CAPACITY))),
377            metrics: self.metrics.clone(),
378            inner_calls: Arc::new(Mutex::new(Vec::new())),
379        }
380    }
381
382    /// Returns the wrapped verification service.
383    ///
384    /// Test-only: it lets a test read back the inner service it installed with
385    /// [`Self::with_inner`].
386    #[cfg(test)]
387    pub(super) fn inner(&self) -> &S {
388        &self.inner
389    }
390
391    /// Returns how many times an item equivalent to `item` has reached the inner service.
392    ///
393    /// Test-only. It counts calls for one key so tests can distinguish the original transaction
394    /// from a transaction with different authorizing data. Use [`Self::isolated`] to avoid
395    /// sharing the cache and call records with other tests.
396    ///
397    /// Readiness failures are not counted: an item that never reached the inner service was never
398    /// verified by it.
399    #[cfg(test)]
400    pub(super) fn inner_calls_for<I: CachedItem>(&self, item: &I) -> usize {
401        let Some(key) = item.cache_key() else {
402            return 0;
403        };
404
405        self.inner_calls
406            .lock()
407            .expect("inner call record mutex should not be poisoned")
408            .iter()
409            .filter(|called| **called == key)
410            .count()
411    }
412
413    /// Returns a cache sharing this one's remembered keys, but consulting `inner` on a miss.
414    ///
415    /// Test-only. It exists so a test can warm the cache through a healthy service and then swap
416    /// in a broken one, which is how the hit path is exercised in isolation from the inner
417    /// service.
418    #[cfg(test)]
419    pub(super) fn with_inner<T>(&self, inner: T) -> Cached<T> {
420        Cached {
421            inner,
422            verified: self.verified.clone(),
423            metrics: self.metrics.clone(),
424            inner_calls: self.inner_calls.clone(),
425        }
426    }
427}
428
429impl<S, I> Service<I> for Cached<S>
430where
431    // `Send + 'static` because a miss moves the item into the boxed future that awaits inner
432    // readiness — see `poll_ready`.
433    I: CachedItem + Send + 'static,
434    S: Service<I, Response = (), Error = BoxError> + Clone + Send + 'static,
435    S::Future: Send + 'static,
436{
437    type Response = ();
438    type Error = BoxError;
439    type Future = BoxFuture<'static, Result<(), BoxError>>;
440
441    /// Always ready.
442    ///
443    /// This does not delegate to the inner service, because the item is not known yet, so neither
444    /// is whether the inner service will be used at all. Delegating would reserve inner capacity
445    /// for every request, including the hits that never spend it:
446    ///
447    ///   * [`Batch::poll_ready`](tower_batch_control::Batch) holds a semaphore permit until
448    ///     `Batch::call` consumes it. A hit never calls, so it holds that permit until the handle
449    ///     drops, denying capacity to a genuine miss.
450    ///   * `Batch::poll_ready` also errors once its worker exits. Callers poll before they call,
451    ///     so that error would surface for an item this cache already holds, reporting a verified
452    ///     proof as a verification failure.
453    ///
454    /// [`Self::call`] awaits readiness on the miss path instead. The semaphore still bounds
455    /// concurrent batch requests; only the timing of the wait changes.
456    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
457        Poll::Ready(Ok(()))
458    }
459
460    fn call(&mut self, item: I) -> Self::Future {
461        // Copied once here, outside `Fallback`, which clones every request eagerly.
462        let key = item.cache_key();
463
464        // A poisoned cache is bypassed: its set and eviction queue may disagree.
465        // Verification remains authoritative even when caching is unavailable.
466        if let Some(key) = key {
467            if self
468                .verified
469                .lock()
470                .is_ok_and(|verified| verified.contains(&key))
471            {
472                self.metrics.hit.increment(1);
473                return future::ready(Ok(())).boxed();
474            }
475        }
476
477        self.metrics.miss.increment(1);
478
479        let verified = self.verified.clone();
480        let metrics = self.metrics.clone();
481        let mut inner = self.inner.clone();
482
483        #[cfg(test)]
484        let inner_calls = self.inner_calls.clone();
485
486        async move {
487            // Readiness is acquired here rather than in `poll_ready` so that only misses reserve
488            // inner capacity. See `poll_ready`.
489            let result = match inner.ready().await {
490                Ok(inner) => {
491                    #[cfg(test)]
492                    if let Some(key) = key {
493                        inner_calls
494                            .lock()
495                            .expect("inner call record mutex should not be poisoned")
496                            .push(key);
497                    }
498
499                    inner.call(item).await
500                }
501                Err(error) => Err(error),
502            };
503
504            // Only successes are recorded: see the module docs.
505            if let (Ok(()), Some(key)) = (&result, key) {
506                let outcome = verified
507                    .lock()
508                    .ok()
509                    .map(|mut verified| verified.insert(key));
510                if let Some(outcome) = outcome {
511                    outcome.report(&metrics);
512                }
513            }
514
515            result
516        }
517        .boxed()
518    }
519}