1use std::{
2 cmp::Reverse,
3 collections::{BinaryHeap, HashSet},
4};
5
6use alloy_consensus::BlockHeader;
7use alloy_eips::BlockNumHash;
8use alloy_primitives::{map::FbHashMap, BlockNumber, B256};
9use reth_exex_types::ExExNotification;
10use reth_node_api::NodePrimitives;
11
12#[derive(Debug, Default)]
17pub struct BlockCache {
18 pub(super) notification_max_blocks: BinaryHeap<Reverse<(BlockNumber, u32)>>,
23 pub(super) committed_blocks: FbHashMap<32, (u32, CachedBlock)>,
28 pub(super) lowest_committed_block_height: Option<BlockNumber>,
30 pub(super) highest_committed_block_height: Option<BlockNumber>,
32}
33
34impl BlockCache {
35 pub(super) fn is_empty(&self) -> bool {
37 self.notification_max_blocks.is_empty()
38 }
39
40 pub(super) fn num_blocks(&self) -> usize {
42 self.committed_blocks.len()
43 }
44
45 pub(super) fn remove_before(
52 &mut self,
53 block_number: BlockNumber,
54 retain_from: Option<u32>,
55 ) -> HashSet<u32> {
56 let mut file_ids = HashSet::default();
57 let mut retained = Vec::new();
58
59 while let Some(block @ Reverse((max_block, file_id))) =
60 self.notification_max_blocks.peek().copied()
61 {
62 if max_block <= block_number {
63 let popped_block = self.notification_max_blocks.pop().unwrap();
64 debug_assert_eq!(popped_block, block);
65 if retain_from.is_some_and(|retain_from| file_id >= retain_from) {
66 retained.push(block);
67 } else {
68 file_ids.insert(file_id);
69 }
70 } else {
71 break
72 }
73 }
74 self.notification_max_blocks.extend(retained);
75
76 let (mut lowest_committed_block_height, mut highest_committed_block_height) = (None, None);
77 self.committed_blocks.retain(|_, (file_id, block)| {
78 let retain = !file_ids.contains(file_id);
79
80 if retain {
81 lowest_committed_block_height = Some(
82 lowest_committed_block_height
83 .map_or(block.block.number, |lowest| block.block.number.min(lowest)),
84 );
85 highest_committed_block_height = Some(
86 highest_committed_block_height
87 .map_or(block.block.number, |highest| block.block.number.max(highest)),
88 );
89 }
90
91 retain
92 });
93 self.lowest_committed_block_height = lowest_committed_block_height;
94 self.highest_committed_block_height = highest_committed_block_height;
95
96 file_ids
97 }
98
99 pub(super) fn get_file_id_by_committed_block_hash(&self, block_hash: &B256) -> Option<u32> {
102 self.committed_blocks.get(block_hash).map(|entry| entry.0)
103 }
104
105 pub(super) fn insert_notification_blocks_with_file_id<N: NodePrimitives>(
107 &mut self,
108 file_id: u32,
109 notification: &ExExNotification<N>,
110 ) {
111 let reverted_chain = notification.reverted_chain();
112 let committed_chain = notification.committed_chain();
113
114 let max_block =
115 reverted_chain.iter().chain(&committed_chain).map(|chain| chain.tip().number()).max();
116 if let Some(max_block) = max_block {
117 self.notification_max_blocks.push(Reverse((max_block, file_id)));
118 }
119
120 if let Some(committed_chain) = &committed_chain {
121 for block in committed_chain.blocks().values() {
122 let cached_block = CachedBlock {
123 block: (block.number(), block.hash()).into(),
124 parent_hash: block.parent_hash(),
125 };
126 self.committed_blocks.insert(block.hash(), (file_id, cached_block));
127 }
128
129 let first_block_number = committed_chain.first().number();
130 self.lowest_committed_block_height = Some(
131 self.lowest_committed_block_height
132 .map_or(first_block_number, |lowest| lowest.min(first_block_number)),
133 );
134 self.highest_committed_block_height = Some(committed_chain.tip().number());
135 }
136 }
137
138 #[cfg(test)]
139 pub(super) fn blocks_sorted(&self) -> Vec<(BlockNumber, u32)> {
140 self.notification_max_blocks
141 .clone()
142 .into_sorted_vec()
143 .into_iter()
144 .map(|entry| entry.0)
145 .collect()
146 }
147
148 #[cfg(test)]
149 pub(super) fn committed_blocks_sorted(&self) -> Vec<(B256, u32, CachedBlock)> {
150 use itertools::Itertools;
151
152 self.committed_blocks
153 .iter()
154 .map(|(hash, (file_id, block))| (*hash, *file_id, *block))
155 .sorted_by_key(|(_, _, block)| (block.block.number, block.block.hash))
156 .collect()
157 }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub(super) struct CachedBlock {
162 pub(super) block: BlockNumHash,
164 pub(super) parent_hash: B256,
166}