Skip to main content

zebra_state/service/
queued_blocks.rs

1//! Queued blocks that are awaiting their parent block for verification.
2
3use std::{
4    collections::{BTreeMap, HashMap, HashSet, VecDeque},
5    iter, mem,
6};
7
8use tokio::sync::oneshot;
9use tracing::instrument;
10
11use zebra_chain::{
12    block, parameters::checkpoint::constants::MAX_CHECKPOINT_BYTE_COUNT, transparent,
13};
14
15use crate::{
16    constants::{MAX_BLOCK_REORG_HEIGHT, MAX_NON_FINALIZED_CHAIN_FORKS},
17    error::{CommitBlockError, CommitCheckpointVerifiedError},
18    request::new_outputs_retained_bytes,
19    CheckpointVerifiedBlock, CommitSemanticallyVerifiedError, ContextuallyVerifiedBlock,
20    KnownBlock, NonFinalizedState, SemanticallyVerifiedBlock,
21};
22
23#[cfg(test)]
24mod tests;
25
26/// A queued checkpoint verified block, and its corresponding [`Result`] channel.
27pub type QueuedCheckpointVerified = (
28    CheckpointVerifiedBlock,
29    oneshot::Sender<Result<block::Hash, CommitCheckpointVerifiedError>>,
30);
31
32/// A queued semantically verified block, and its corresponding [`Result`] channel.
33pub type QueuedSemanticallyVerified = (
34    SemanticallyVerifiedBlock,
35    oneshot::Sender<Result<block::Hash, CommitSemanticallyVerifiedError>>,
36    // The result of validating the block as a block proposal, if it solves one. A block only
37    // keeps it until the end of the call that queues it.
38    Option<Box<ContextuallyVerifiedBlock>>,
39);
40
41/// The maximum number of blocks in a [`QueuedBlocks`].
42// The reorg height fits in usize on every supported platform.
43const MAX_QUEUED_BLOCKS: usize = MAX_BLOCK_REORG_HEIGHT as usize;
44
45/// The maximum memory used by the blocks in a [`QueuedBlocks`], in bytes: one maximum-size
46/// checkpoint range for each supported chain fork.
47// 32 MiB fits in usize on every supported platform.
48const MAX_QUEUED_BYTES: usize = MAX_CHECKPOINT_BYTE_COUNT as usize * MAX_NON_FINALIZED_CHAIN_FORKS;
49
50/// A queue of blocks, awaiting the arrival of parent blocks.
51///
52/// The queue holds at most [`MAX_QUEUED_BLOCKS`] blocks, which use at most [`MAX_QUEUED_BYTES`].
53#[derive(Debug, Default)]
54pub struct QueuedBlocks {
55    /// Blocks awaiting their parent blocks for contextual verification, with their memory use.
56    blocks: HashMap<block::Hash, (QueuedSemanticallyVerified, usize)>,
57    /// Hashes from `queued_blocks`, indexed by parent hash.
58    by_parent: HashMap<block::Hash, HashSet<block::Hash>>,
59    /// Hashes from `queued_blocks`, indexed by block height.
60    by_height: BTreeMap<block::Height, HashSet<block::Hash>>,
61    /// Known UTXOs.
62    known_utxos: KnownUtxos,
63    /// The total memory used by `blocks`.
64    queued_bytes: usize,
65}
66
67/// UTXOs created by queued or sent blocks, with the number of those blocks that create each one.
68///
69/// Blocks with the same transaction create the same outpoints, so an outpoint is only
70/// forgotten when the last block that creates it is removed. Each outpoint keeps a single
71/// copy of its UTXO, so repeating a transaction in more blocks doesn't add more copies.
72#[derive(Debug, Default)]
73struct KnownUtxos(HashMap<transparent::OutPoint, (transparent::Utxo, usize)>);
74
75impl KnownUtxos {
76    /// Records that one more block creates `outpoint`.
77    fn insert(&mut self, outpoint: transparent::OutPoint, utxo: transparent::Utxo) {
78        self.0.entry(outpoint).or_insert((utxo, 0)).1 += 1;
79    }
80
81    /// Records that one fewer block creates `outpoint`, and forgets it when none do.
82    fn remove(&mut self, outpoint: &transparent::OutPoint) {
83        if let Some((_utxo, owners)) = self.0.get_mut(outpoint) {
84            *owners -= 1;
85            if *owners == 0 {
86                self.0.remove(outpoint);
87            }
88        }
89    }
90
91    fn get(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
92        self.0.get(outpoint).map(|(utxo, _owners)| utxo.clone())
93    }
94
95    #[cfg(test)]
96    fn len(&self) -> usize {
97        self.0.len()
98    }
99}
100
101impl QueuedBlocks {
102    /// Queue a block for eventual verification and commit.
103    ///
104    /// The queue can go over its limits until the caller calls [`Self::prune_overflow`].
105    #[instrument(skip(self, new), fields(height = ?new.0.height, hash = %new.0.hash))]
106    pub fn queue(&mut self, new: QueuedSemanticallyVerified) {
107        let new_hash = new.0.hash;
108        let new_height = new.0.height;
109        let parent_hash = new.0.block.header.previous_block_hash;
110
111        if self.blocks.contains_key(&new_hash) {
112            // Skip queueing the block and return early if the hash is not unique
113            return;
114        }
115
116        // Track known UTXOs in queued blocks.
117        for (outpoint, ordered_utxo) in new.0.new_outputs.iter() {
118            self.known_utxos
119                .insert(*outpoint, ordered_utxo.utxo.clone());
120        }
121
122        // Count the block, and the copy of its outputs in `known_utxos`.
123        let bytes = new.0.retained_bytes() + new_outputs_retained_bytes(&new.0.new_outputs);
124        self.queued_bytes += bytes;
125        self.blocks.insert(new_hash, (new, bytes));
126        self.by_height
127            .entry(new_height)
128            .or_default()
129            .insert(new_hash);
130        self.by_parent
131            .entry(parent_hash)
132            .or_default()
133            .insert(new_hash);
134
135        tracing::trace!(%parent_hash, queued = %self.blocks.len(), "queued block");
136        self.update_metrics();
137    }
138
139    /// Fails abandoned leaves, then the highest queued blocks, with
140    /// [`CommitBlockError::OrphanQueueFull`] until the queue is within its limits.
141    ///
142    /// Callers should send the queued blocks that are ready to commit first, so they aren't failed.
143    pub fn prune_overflow(&mut self) {
144        if self.blocks.len() <= MAX_QUEUED_BLOCKS && self.queued_bytes <= MAX_QUEUED_BYTES {
145            return;
146        }
147
148        while self.blocks.len() > MAX_QUEUED_BLOCKS || self.queued_bytes > MAX_QUEUED_BYTES {
149            // Prefer leaves whose callers stopped waiting, then the highest block.
150            let hash = *self
151                .by_height
152                .values()
153                .rev()
154                .flatten()
155                .find(|hash| {
156                    self.blocks[*hash].0 .1.is_closed() && !self.by_parent.contains_key(*hash)
157                })
158                .or_else(|| self.by_height.values().next_back()?.iter().next())
159                .expect("a queue over its limits has blocks");
160            let (_block, rsp_tx, _contextual) = self.remove(&hash);
161
162            // The caller might have stopped waiting for the block.
163            let _ = rsp_tx.send(Err(CommitBlockError::OrphanQueueFull.into()));
164        }
165
166        tracing::debug!(queued = %self.blocks.len(), "failed queued blocks over the queue limits");
167        self.update_metrics();
168    }
169
170    /// Removes a queued block, its indexes, and its outputs.
171    fn remove(&mut self, hash: &block::Hash) -> QueuedSemanticallyVerified {
172        let (queued, bytes) = self.blocks.remove(hash).expect("indexed blocks are queued");
173        self.queued_bytes -= bytes;
174
175        let parent_hash = queued.0.block.header.previous_block_hash;
176        if let Some(hashes) = self.by_parent.get_mut(&parent_hash) {
177            hashes.remove(hash);
178            if hashes.is_empty() {
179                self.by_parent.remove(&parent_hash);
180            }
181        }
182
183        if let Some(hashes) = self.by_height.get_mut(&queued.0.height) {
184            hashes.remove(hash);
185            if hashes.is_empty() {
186                self.by_height.remove(&queued.0.height);
187            }
188        }
189
190        for outpoint in queued.0.new_outputs.keys() {
191            self.known_utxos.remove(outpoint);
192        }
193
194        queued
195    }
196
197    /// Returns `true` if there are any queued children of `parent_hash`.
198    #[instrument(skip(self), fields(%parent_hash))]
199    pub fn has_queued_children(&self, parent_hash: block::Hash) -> bool {
200        self.by_parent.contains_key(&parent_hash)
201    }
202
203    /// Returns the parent hashes of every queued block.
204    pub fn parent_hashes(&self) -> Vec<block::Hash> {
205        self.by_parent.keys().copied().collect()
206    }
207
208    /// Returns `true` if there is a block with the provided hash present.
209    #[instrument(skip(self), fields(%hash))]
210    pub fn has(&self, hash: block::Hash) -> bool {
211        self.blocks.contains_key(&hash)
212    }
213
214    /// Dequeue and return all blocks that were waiting for the arrival of
215    /// `parent`.
216    #[instrument(skip(self), fields(%parent_hash))]
217    pub fn dequeue_children(
218        &mut self,
219        parent_hash: block::Hash,
220    ) -> Vec<QueuedSemanticallyVerified> {
221        let queued_children = self
222            .by_parent
223            .remove(&parent_hash)
224            .unwrap_or_default()
225            .into_iter()
226            .map(|hash| self.remove(&hash))
227            .collect::<Vec<_>>();
228
229        tracing::trace!(
230            dequeued = queued_children.len(),
231            remaining = self.blocks.len(),
232            "dequeued blocks"
233        );
234        self.update_metrics();
235
236        queued_children
237    }
238
239    /// Remove all queued blocks whose height is less than or equal to the given
240    /// `finalized_tip_height`.
241    #[instrument(skip(self))]
242    pub fn prune_by_height(&mut self, finalized_tip_height: block::Height) {
243        while let Some(lowest) = self.by_height.first_entry() {
244            if *lowest.key() > finalized_tip_height {
245                break;
246            }
247
248            for hash in lowest.remove() {
249                let (expired_block, expired_sender, _contextual) = self.remove(&hash);
250
251                // we don't care if the receiver was dropped
252                let _ = expired_sender.send(Err(CommitBlockError::new_duplicate(
253                    Some(expired_block.height.into()),
254                    KnownBlock::Finalized,
255                )
256                .into()));
257            }
258        }
259
260        tracing::trace!(num_blocks = %self.blocks.len(), "Finished pruning blocks at or beneath the finalized tip height");
261        self.update_metrics();
262    }
263
264    /// Drops the proposal validation result of the block `hash`, if that block is still queued.
265    ///
266    /// A block that waits for its parent is validated as usual when the parent arrives. So a
267    /// validation result, which the queue's memory limit doesn't count, is never kept here.
268    pub fn drop_proposal_result(&mut self, hash: &block::Hash) {
269        if let Some(((_, _, contextual), _)) = self.blocks.get_mut(hash) {
270            *contextual = None;
271        }
272    }
273
274    /// Removes a queued block, its indexes, its outputs and its memory charge, if it is queued.
275    pub fn remove_queued(&mut self, hash: &block::Hash) -> Option<QueuedSemanticallyVerified> {
276        if !self.blocks.contains_key(hash) {
277            return None;
278        }
279        let queued = self.remove(hash);
280        self.update_metrics();
281        Some(queued)
282    }
283
284    /// Update metrics after the queue is modified
285    fn update_metrics(&self) {
286        if let Some(min_height) = self.by_height.keys().next() {
287            metrics::gauge!("state.memory.queued.min.height").set(min_height.0 as f64);
288        } else {
289            // use f64::NAN as a sentinel value for "None", because 0 is a valid height
290            metrics::gauge!("state.memory.queued.min.height").set(f64::NAN);
291        }
292        if let Some(max_height) = self.by_height.keys().next_back() {
293            metrics::gauge!("state.memory.queued.max.height").set(max_height.0 as f64);
294        } else {
295            // use f64::NAN as a sentinel value for "None", because 0 is a valid height
296            metrics::gauge!("state.memory.queued.max.height").set(f64::NAN);
297        }
298
299        metrics::gauge!("state.memory.queued.block.count").set(self.blocks.len() as f64);
300    }
301
302    /// Try to look up this UTXO in any queued block.
303    #[instrument(level = "trace", skip(self))]
304    pub fn utxo(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
305        self.known_utxos.get(outpoint)
306    }
307
308    /// Clears known_utxos, by_parent, and by_height, then drains blocks.
309    /// Returns all key-value pairs of blocks as an iterator.
310    ///
311    /// Doesn't update the metrics, because it is only used when the state is being dropped.
312    pub fn drain(
313        &mut self,
314    ) -> impl Iterator<Item = (block::Hash, QueuedSemanticallyVerified)> + '_ {
315        self.known_utxos.0.clear();
316        self.known_utxos.0.shrink_to_fit();
317        self.by_parent.clear();
318        self.by_parent.shrink_to_fit();
319        self.by_height.clear();
320        self.queued_bytes = 0;
321
322        self.blocks
323            .drain()
324            .map(|(hash, (queued, _bytes))| (hash, queued))
325    }
326}
327
328#[derive(Debug, Default)]
329pub(crate) struct SentHashes {
330    /// A list of previously sent block batches, each batch is in increasing height order.
331    /// We use this list to efficiently prune outdated hashes that are at or below the finalized tip.
332    bufs: Vec<VecDeque<(block::Hash, block::Height)>>,
333
334    /// The list of blocks sent in the current batch, in increasing height order.
335    curr_buf: VecDeque<(block::Hash, block::Height)>,
336
337    /// Stores a set of hashes that have been sent to the block write task but
338    /// may not be in the finalized state yet.
339    pub sent: HashMap<block::Hash, Vec<transparent::OutPoint>>,
340
341    /// Known UTXOs.
342    known_utxos: KnownUtxos,
343
344    /// Whether the hashes in this struct can be used check if the chain can be forked.
345    /// This is set to false until all checkpoint-verified block hashes have been pruned.
346    pub(crate) can_fork_chain_at_hashes: bool,
347}
348
349impl SentHashes {
350    /// Creates a new [`SentHashes`] with the block hashes in the provided non-finalized state.
351    ///
352    /// The blocks are already committed, so UTXO lookups find their outputs in that state, and
353    /// this doesn't copy them.
354    pub fn new(non_finalized_state: &NonFinalizedState) -> Self {
355        let mut sent_hashes = Self::default();
356        for block in non_finalized_state
357            .chain_iter()
358            .flat_map(|chain| chain.blocks.values())
359        {
360            sent_hashes.add_outputs(block.hash, block.height, std::iter::empty());
361        }
362
363        if !sent_hashes.sent.is_empty() {
364            sent_hashes.can_fork_chain_at_hashes = true;
365        }
366
367        sent_hashes
368    }
369
370    /// Stores the `block`'s hash, height, and UTXOs, so they can be used to check if a block or UTXO
371    /// is available in the state.
372    ///
373    /// Assumes that blocks are added in the order of their height between `finish_batch` calls
374    /// for efficient pruning.
375    pub fn add(&mut self, block: &SemanticallyVerifiedBlock) {
376        self.add_outputs(block.hash, block.height, block.new_outputs.iter());
377    }
378
379    /// Stores borrowed block metadata without materializing another verified block.
380    fn add_outputs<'a>(
381        &mut self,
382        hash: block::Hash,
383        height: block::Height,
384        new_outputs: impl IntoIterator<Item = (&'a transparent::OutPoint, &'a transparent::OrderedUtxo)>,
385    ) {
386        // Track known UTXOs in sent blocks.
387        let outpoints = new_outputs
388            .into_iter()
389            .map(|(outpoint, ordered_utxo)| {
390                self.known_utxos
391                    .insert(*outpoint, ordered_utxo.utxo.clone());
392                outpoint
393            })
394            .cloned()
395            .collect();
396
397        self.curr_buf.push_back((hash, height));
398        self.insert_sent(hash, outpoints);
399
400        self.update_metrics_for_block(height);
401    }
402
403    /// Stores the checkpoint verified `block`'s hash, height, and UTXOs, so they can be used to check if a
404    /// block or UTXO is available in the state.
405    ///
406    /// Used for checkpoint verified blocks close to the final checkpoint, so the semantic block verifier can look up
407    /// their UTXOs.
408    ///
409    /// Assumes that blocks are added in the order of their height between `finish_batch` calls
410    /// for efficient pruning.
411    ///
412    /// For more details see `add()`.
413    pub fn add_finalized(&mut self, block: &CheckpointVerifiedBlock) {
414        // Track known UTXOs in sent blocks.
415        let outpoints = block
416            .new_outputs
417            .iter()
418            .map(|(outpoint, ordered_utxo)| {
419                self.known_utxos
420                    .insert(*outpoint, ordered_utxo.utxo.clone());
421                outpoint
422            })
423            .cloned()
424            .collect();
425
426        self.curr_buf.push_back((block.hash, block.height));
427        self.insert_sent(block.hash, outpoints);
428
429        self.update_metrics_for_block(block.height);
430    }
431
432    /// Records `hash` as sent, releasing the outpoints of any earlier entry for the same hash.
433    fn insert_sent(&mut self, hash: block::Hash, outpoints: Vec<transparent::OutPoint>) {
434        if let Some(old_outpoints) = self.sent.insert(hash, outpoints) {
435            for outpoint in &old_outpoints {
436                self.known_utxos.remove(outpoint);
437            }
438        }
439    }
440
441    /// Forgets the UTXOs of the sent block `hash`, but still treats the block as sent.
442    ///
443    /// Called once the block is committed to a non-finalized chain that readers can see, because
444    /// UTXO lookups then find its outputs in that chain.
445    pub fn forget_utxos(&mut self, hash: &block::Hash) {
446        let Some(outpoints) = self.sent.get_mut(hash) else {
447            return;
448        };
449
450        for outpoint in mem::take(outpoints) {
451            self.known_utxos.remove(&outpoint);
452        }
453    }
454
455    /// Try to look up this UTXO in any sent block.
456    #[instrument(level = "trace", skip(self))]
457    pub fn utxo(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
458        self.known_utxos.get(outpoint)
459    }
460
461    /// Finishes the current block batch, and stores it for efficient pruning.
462    pub fn finish_batch(&mut self) {
463        if !self.curr_buf.is_empty() {
464            self.bufs.push(std::mem::take(&mut self.curr_buf));
465        }
466    }
467
468    /// Prunes sent blocks at or below `height_bound`.
469    ///
470    /// Finishes the batch if `finish_batch()` hasn't been called already.
471    ///
472    /// Assumes that blocks will be added in order of their heights between each `finish_batch()` call,
473    /// so that blocks can be efficiently and reliably removed by height.
474    pub fn prune_by_height(&mut self, height_bound: block::Height) {
475        self.finish_batch();
476
477        // Iterates over each buf in `sent_bufs`, removing sent blocks until reaching
478        // the first block with a height above the `height_bound`.
479        self.bufs.retain_mut(|buf| {
480            while let Some((hash, height)) = buf.pop_front() {
481                if height > height_bound {
482                    buf.push_front((hash, height));
483                    return true;
484                } else if let Some(expired_outpoints) = self.sent.remove(&hash) {
485                    for outpoint in expired_outpoints.iter() {
486                        self.known_utxos.remove(outpoint);
487                    }
488                }
489            }
490
491            false
492        });
493
494        self.sent.shrink_to_fit();
495        self.known_utxos.0.shrink_to_fit();
496        self.bufs.shrink_to_fit();
497
498        self.update_metrics_for_cache();
499    }
500
501    /// Returns true if SentHashes contains the `hash`
502    pub fn contains(&self, hash: &block::Hash) -> bool {
503        self.sent.contains_key(hash)
504    }
505
506    /// Removes `hashes` from `SentHashes`, dropping their outpoints from `known_utxos`
507    /// and their entries from whichever batch buffers hold them.
508    ///
509    /// Called when the block write task rejects or evicts blocks, so that a subsequent
510    /// re-delivery of a block with the same hash is not short-circuited as a
511    /// "duplicate" against a block that is no longer in any chain.
512    ///
513    /// Each batch buffer is scanned once for the whole set, because evicting a long
514    /// fork can remove many hashes at a time.
515    pub fn remove_all(&mut self, hashes: impl IntoIterator<Item = block::Hash>) {
516        let mut removed = HashSet::new();
517
518        for hash in hashes {
519            let Some(outpoints) = self.sent.remove(&hash) else {
520                continue;
521            };
522
523            for outpoint in &outpoints {
524                self.known_utxos.remove(outpoint);
525            }
526
527            removed.insert(hash);
528        }
529
530        if removed.is_empty() {
531            return;
532        }
533
534        self.curr_buf.retain(|(h, _)| !removed.contains(h));
535        for buf in &mut self.bufs {
536            buf.retain(|(h, _)| !removed.contains(h));
537        }
538    }
539
540    /// Returns true if the chain can be forked at the provided hash
541    pub fn can_fork_chain_at(&self, hash: &block::Hash) -> bool {
542        self.can_fork_chain_at_hashes && self.contains(hash)
543    }
544
545    /// Update sent block metrics after a block is sent.
546    fn update_metrics_for_block(&self, height: block::Height) {
547        metrics::counter!("state.memory.sent.block.count").increment(1);
548        metrics::gauge!("state.memory.sent.block.height").set(height.0 as f64);
549
550        self.update_metrics_for_cache();
551    }
552
553    /// Update sent block cache metrics after the sent blocks are modified.
554    fn update_metrics_for_cache(&self) {
555        let batch_iter = || self.bufs.iter().chain(iter::once(&self.curr_buf));
556
557        if let Some(min_height) = batch_iter()
558            .flat_map(|batch| batch.front().map(|(_hash, height)| height))
559            .min()
560        {
561            metrics::gauge!("state.memory.sent.cache.min.height").set(min_height.0 as f64);
562        } else {
563            // use f64::NAN as a sentinel value for "None", because 0 is a valid height
564            metrics::gauge!("state.memory.sent.cache.min.height").set(f64::NAN);
565        }
566
567        if let Some(max_height) = batch_iter()
568            .flat_map(|batch| batch.back().map(|(_hash, height)| height))
569            .max()
570        {
571            metrics::gauge!("state.memory.sent.cache.max.height").set(max_height.0 as f64);
572        } else {
573            // use f64::NAN as a sentinel value for "None", because 0 is a valid height
574            metrics::gauge!("state.memory.sent.cache.max.height").set(f64::NAN);
575        }
576
577        metrics::gauge!("state.memory.sent.cache.block.count")
578            .set(batch_iter().flatten().count() as f64);
579
580        metrics::gauge!("state.memory.sent.cache.batch.count").set(batch_iter().count() as f64);
581    }
582}