1use 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
26pub type QueuedCheckpointVerified = (
28 CheckpointVerifiedBlock,
29 oneshot::Sender<Result<block::Hash, CommitCheckpointVerifiedError>>,
30);
31
32pub type QueuedSemanticallyVerified = (
34 SemanticallyVerifiedBlock,
35 oneshot::Sender<Result<block::Hash, CommitSemanticallyVerifiedError>>,
36 Option<Box<ContextuallyVerifiedBlock>>,
39);
40
41const MAX_QUEUED_BLOCKS: usize = MAX_BLOCK_REORG_HEIGHT as usize;
44
45const MAX_QUEUED_BYTES: usize = MAX_CHECKPOINT_BYTE_COUNT as usize * MAX_NON_FINALIZED_CHAIN_FORKS;
49
50#[derive(Debug, Default)]
54pub struct QueuedBlocks {
55 blocks: HashMap<block::Hash, (QueuedSemanticallyVerified, usize)>,
57 by_parent: HashMap<block::Hash, HashSet<block::Hash>>,
59 by_height: BTreeMap<block::Height, HashSet<block::Hash>>,
61 known_utxos: KnownUtxos,
63 queued_bytes: usize,
65}
66
67#[derive(Debug, Default)]
73struct KnownUtxos(HashMap<transparent::OutPoint, (transparent::Utxo, usize)>);
74
75impl KnownUtxos {
76 fn insert(&mut self, outpoint: transparent::OutPoint, utxo: transparent::Utxo) {
78 self.0.entry(outpoint).or_insert((utxo, 0)).1 += 1;
79 }
80
81 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 #[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 return;
114 }
115
116 for (outpoint, ordered_utxo) in new.0.new_outputs.iter() {
118 self.known_utxos
119 .insert(*outpoint, ordered_utxo.utxo.clone());
120 }
121
122 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 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 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 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 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 #[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 pub fn parent_hashes(&self) -> Vec<block::Hash> {
205 self.by_parent.keys().copied().collect()
206 }
207
208 #[instrument(skip(self), fields(%hash))]
210 pub fn has(&self, hash: block::Hash) -> bool {
211 self.blocks.contains_key(&hash)
212 }
213
214 #[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 #[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 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 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 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 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 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 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 #[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 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 bufs: Vec<VecDeque<(block::Hash, block::Height)>>,
333
334 curr_buf: VecDeque<(block::Hash, block::Height)>,
336
337 pub sent: HashMap<block::Hash, Vec<transparent::OutPoint>>,
340
341 known_utxos: KnownUtxos,
343
344 pub(crate) can_fork_chain_at_hashes: bool,
347}
348
349impl SentHashes {
350 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 pub fn add(&mut self, block: &SemanticallyVerifiedBlock) {
376 self.add_outputs(block.hash, block.height, block.new_outputs.iter());
377 }
378
379 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 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 pub fn add_finalized(&mut self, block: &CheckpointVerifiedBlock) {
414 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 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 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 #[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 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 pub fn prune_by_height(&mut self, height_bound: block::Height) {
475 self.finish_batch();
476
477 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 pub fn contains(&self, hash: &block::Hash) -> bool {
503 self.sent.contains_key(hash)
504 }
505
506 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 pub fn can_fork_chain_at(&self, hash: &block::Hash) -> bool {
542 self.can_fork_chain_at_hashes && self.contains(hash)
543 }
544
545 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 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 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 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}