1use alloy_eip7928::BAL_RETENTION_PERIOD_SLOTS;
2use alloy_eips::NumHash;
3use alloy_primitives::{BlockHash, BlockNumber, Bytes};
4use parking_lot::RwLock;
5use reth_prune_types::PruneMode;
6use reth_storage_api::{
7 BalNotification, BalNotificationStream, BalStore, GetBlockAccessListLimit, RawBal,
8};
9use reth_storage_errors::provider::ProviderResult;
10use reth_tokio_util::EventSender;
11use std::{
12 collections::{BTreeMap, HashMap},
13 sync::Arc,
14};
15
16#[derive(Debug, Clone)]
18pub struct InMemoryBalStore {
19 config: BalConfig,
20 inner: Arc<RwLock<InMemoryBalStoreInner>>,
21 notifications: EventSender<BalNotification>,
22}
23
24impl InMemoryBalStore {
25 pub fn new(config: BalConfig) -> Self {
27 let notifications = EventSender::new(DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE);
28 Self {
29 config,
30 inner: Arc::new(RwLock::new(InMemoryBalStoreInner::default())),
31 notifications,
32 }
33 }
34}
35
36const DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE: usize = 256;
39
40impl Default for InMemoryBalStore {
41 fn default() -> Self {
42 Self::new(BalConfig::default())
43 }
44}
45
46#[derive(Debug, Clone, Copy, Eq, PartialEq)]
48pub struct BalConfig {
49 in_memory_retention: Option<PruneMode>,
51}
52
53impl BalConfig {
54 pub const DEFAULT_IN_MEMORY_RETENTION_DISTANCE: u64 = BAL_RETENTION_PERIOD_SLOTS;
56
57 pub const fn unbounded() -> Self {
59 Self { in_memory_retention: None }
60 }
61
62 pub const fn with_in_memory_retention_distance(blocks: u64) -> Self {
64 Self::with_in_memory_retention(PruneMode::Distance(blocks))
65 }
66
67 pub const fn with_in_memory_retention(in_memory_retention: PruneMode) -> Self {
69 Self { in_memory_retention: Some(in_memory_retention) }
70 }
71}
72
73impl Default for BalConfig {
74 fn default() -> Self {
75 Self::with_in_memory_retention_distance(Self::DEFAULT_IN_MEMORY_RETENTION_DISTANCE)
76 }
77}
78
79#[derive(Debug, Default)]
80struct InMemoryBalStoreInner {
81 entries: HashMap<BlockHash, BalEntry>,
82 hashes_by_number: BTreeMap<BlockNumber, Vec<BlockHash>>,
83 highest_block_number: Option<BlockNumber>,
84}
85
86impl InMemoryBalStoreInner {
87 fn insert(&mut self, block_hash: BlockHash, block_number: BlockNumber, bal: Bytes) {
89 let empty_block_number =
90 self.entries.insert(block_hash, BalEntry { block_number, bal }).and_then(|entry| {
91 let hashes = self.hashes_by_number.get_mut(&entry.block_number)?;
92 hashes.retain(|hash| *hash != block_hash);
93 hashes.is_empty().then_some(entry.block_number)
94 });
95
96 if let Some(block_number) = empty_block_number {
97 self.hashes_by_number.remove(&block_number);
98 }
99
100 self.hashes_by_number.entry(block_number).or_default().push(block_hash);
101 self.highest_block_number = Some(
102 self.highest_block_number.map_or(block_number, |highest| highest.max(block_number)),
103 );
104 }
105
106 fn prune(&mut self, prune_mode: Option<PruneMode>, tip: BlockNumber) -> usize {
108 let Some(prune_mode) = prune_mode else { return 0 };
109
110 let mut pruned = 0;
111 while let Some((&block_number, _)) = self.hashes_by_number.first_key_value() {
112 if !prune_mode.should_prune(block_number, tip) {
113 break
114 }
115
116 let Some((_, hashes)) = self.hashes_by_number.pop_first() else { break };
117 for hash in hashes {
118 pruned += usize::from(self.entries.remove(&hash).is_some());
119 }
120 }
121 pruned
122 }
123}
124
125#[derive(Debug)]
126struct BalEntry {
127 block_number: BlockNumber,
128 bal: Bytes,
129}
130
131impl BalStore for InMemoryBalStore {
132 fn insert(&self, num_hash: NumHash, bal: RawBal) -> ProviderResult<()> {
133 let mut inner = self.inner.write();
134 inner.insert(num_hash.hash, num_hash.number, bal.as_raw().clone());
135 if let Some(highest_block_number) = inner.highest_block_number {
136 inner.prune(self.config.in_memory_retention, highest_block_number);
138 }
139 self.notifications.notify(BalNotification::new(num_hash, bal));
140 Ok(())
141 }
142
143 fn insert_many(&self, entries: Vec<(NumHash, RawBal)>) -> ProviderResult<()> {
144 if entries.is_empty() {
145 return Ok(())
146 }
147
148 let mut inner = self.inner.write();
149 inner.entries.reserve(entries.len());
150 for (num_hash, bal) in &entries {
151 inner.insert(num_hash.hash, num_hash.number, bal.as_raw().clone());
152 }
153 if let Some(highest_block_number) = inner.highest_block_number {
154 inner.prune(self.config.in_memory_retention, highest_block_number);
155 }
156 drop(inner);
157
158 for (num_hash, bal) in entries {
159 self.notifications.notify(BalNotification::new(num_hash, bal));
160 }
161 Ok(())
162 }
163
164 fn flush(&self) -> ProviderResult<()> {
165 Ok(())
166 }
167
168 fn prune(&self, tip: BlockNumber) -> ProviderResult<usize> {
169 Ok(self.inner.write().prune(self.config.in_memory_retention, tip))
170 }
171
172 fn get_by_hashes(&self, block_hashes: &[BlockHash]) -> ProviderResult<Vec<Option<Bytes>>> {
173 let inner = self.inner.read();
174 let mut result = Vec::with_capacity(block_hashes.len());
175
176 for hash in block_hashes {
177 result.push(inner.entries.get(hash).map(|entry| entry.bal.clone()));
178 }
179
180 Ok(result)
181 }
182
183 fn append_by_hashes_with_limit(
184 &self,
185 block_hashes: &[BlockHash],
186 limit: GetBlockAccessListLimit,
187 out: &mut Vec<Option<Bytes>>,
188 ) -> ProviderResult<()> {
189 let inner = self.inner.read();
190 let mut size = 0;
191
192 for hash in block_hashes {
193 let bal = inner.entries.get(hash).map(|entry| entry.bal.clone());
194 size += bal.as_ref().map_or(1, |bytes| bytes.len());
195 out.push(bal);
196
197 if limit.exceeds(size) {
198 break
199 }
200 }
201
202 Ok(())
203 }
204
205 fn bal_stream(&self) -> BalNotificationStream {
206 self.notifications.new_listener()
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use alloy_primitives::B256;
214 use tokio_stream::StreamExt;
215
216 #[test]
217 fn insert_and_lookup_by_hash() {
218 let store = InMemoryBalStore::default();
219 let hash = B256::random();
220 let missing = B256::random();
221 let bal = Bytes::from_static(b"bal");
222
223 store.insert(NumHash::new(1, hash), RawBal::from(bal.clone())).unwrap();
224
225 assert_eq!(store.get_by_hashes(&[hash, missing]).unwrap(), vec![Some(bal), None]);
226 }
227
228 #[test]
229 fn insert_many_and_lookup_by_hash() {
230 let store = InMemoryBalStore::default();
231 let hash0 = B256::random();
232 let hash1 = B256::random();
233 let bal0 = RawBal::from(Bytes::from_static(b"bal0"));
234 let bal1 = RawBal::from(Bytes::from_static(b"bal1"));
235
236 store
237 .insert_many(vec![
238 (NumHash::new(1, hash0), bal0.clone()),
239 (NumHash::new(2, hash1), bal1),
240 ])
241 .unwrap();
242
243 assert_eq!(
244 store.get_by_hashes(&[hash0, hash1]).unwrap(),
245 vec![Some(bal0.as_raw().clone()), Some(Bytes::from_static(b"bal1"))]
246 );
247 }
248
249 #[test]
250 fn flush_is_noop() {
251 let store = InMemoryBalStore::default();
252
253 store.flush().unwrap();
254 }
255
256 #[test]
257 fn limited_lookup_returns_prefix() {
258 let store = InMemoryBalStore::default();
259 let hash0 = B256::random();
260 let hash1 = B256::random();
261 let hash2 = B256::random();
262 let bal0 = Bytes::from_static(&[0xc1, 0x01]);
263 let bal1 = Bytes::from_static(&[0xc1, 0x02]);
264 let bal2 = Bytes::from_static(&[0xc1, 0x03]);
265
266 store.insert(NumHash::new(1, hash0), RawBal::from(bal0.clone())).unwrap();
267 store.insert(NumHash::new(2, hash1), RawBal::from(bal1.clone())).unwrap();
268 store.insert(NumHash::new(3, hash2), RawBal::from(bal2)).unwrap();
269
270 let limited = store
271 .get_by_hashes_with_limit(
272 &[hash0, hash1, hash2],
273 GetBlockAccessListLimit::ResponseSizeSoftLimit(2),
274 )
275 .unwrap();
276
277 assert_eq!(limited, vec![Some(bal0), Some(bal1)]);
278 }
279
280 #[test]
281 fn default_retention_prunes_old_bals() {
282 let store = InMemoryBalStore::default();
283 let old_hash = B256::random();
284 let retained_hash = B256::random();
285 let tip_hash = B256::random();
286 let old_bal = Bytes::from_static(b"old");
287 let retained_bal = Bytes::from_static(b"retained");
288 let tip_bal = Bytes::from_static(b"tip");
289
290 store.insert(NumHash::new(1, old_hash), RawBal::from(old_bal)).unwrap();
291 store
292 .insert(
293 NumHash::new(BAL_RETENTION_PERIOD_SLOTS, retained_hash),
294 RawBal::from(retained_bal.clone()),
295 )
296 .unwrap();
297 store
298 .insert(
299 NumHash::new(BAL_RETENTION_PERIOD_SLOTS + 2, tip_hash),
300 RawBal::from(tip_bal.clone()),
301 )
302 .unwrap();
303
304 assert_eq!(
305 store.get_by_hashes(&[old_hash, retained_hash, tip_hash]).unwrap(),
306 vec![None, Some(retained_bal), Some(tip_bal)]
307 );
308 }
309
310 #[test]
311 fn prune_uses_chain_tip() {
312 let store =
313 InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Distance(2)));
314 let old_hash = B256::random();
315 let retained_hash = B256::random();
316 let old_bal = Bytes::from_static(b"old");
317 let retained_bal = Bytes::from_static(b"retained");
318
319 store.insert(NumHash::new(7, old_hash), RawBal::from(old_bal)).unwrap();
320 store.insert(NumHash::new(8, retained_hash), RawBal::from(retained_bal.clone())).unwrap();
321
322 assert_eq!(store.prune(10).unwrap(), 1);
323 assert_eq!(
324 store.get_by_hashes(&[old_hash, retained_hash]).unwrap(),
325 vec![None, Some(retained_bal)]
326 );
327 }
328
329 #[test]
330 fn insert_prunes_from_highest_inserted_block() {
331 let store =
332 InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Distance(2)));
333 let old_hash = B256::random();
334 let high_hash = B256::random();
335 let late_hash = B256::random();
336 let high_bal = Bytes::from_static(b"high");
337 let late_bal = Bytes::from_static(b"late");
338
339 store.insert(NumHash::new(7, old_hash), RawBal::from(Bytes::from_static(b"old"))).unwrap();
340 store.insert(NumHash::new(10, high_hash), RawBal::from(high_bal.clone())).unwrap();
341 store.insert(NumHash::new(8, late_hash), RawBal::from(late_bal.clone())).unwrap();
342
343 assert_eq!(
344 store.get_by_hashes(&[old_hash, high_hash, late_hash]).unwrap(),
345 vec![None, Some(high_bal), Some(late_bal)]
346 );
347 }
348
349 #[test]
350 fn unbounded_retention_keeps_old_bals() {
351 let store = InMemoryBalStore::new(BalConfig::unbounded());
352 let old_hash = B256::random();
353 let tip_hash = B256::random();
354 let old_bal = Bytes::from_static(b"old");
355 let tip_bal = Bytes::from_static(b"tip");
356
357 store.insert(NumHash::new(1, old_hash), RawBal::from(old_bal.clone())).unwrap();
358 store
359 .insert(
360 NumHash::new(BAL_RETENTION_PERIOD_SLOTS + 1, tip_hash),
361 RawBal::from(tip_bal.clone()),
362 )
363 .unwrap();
364
365 assert_eq!(
366 store.get_by_hashes(&[old_hash, tip_hash]).unwrap(),
367 vec![Some(old_bal), Some(tip_bal)]
368 );
369 assert_eq!(store.prune(BAL_RETENTION_PERIOD_SLOTS + 2).unwrap(), 0);
370 }
371
372 #[test]
373 fn in_memory_retention_distance_prunes_old_bals() {
374 let store = InMemoryBalStore::new(BalConfig::with_in_memory_retention_distance(2));
375 let old_hash = B256::random();
376 let retained_hash = B256::random();
377 let tip_hash = B256::random();
378 let old_bal = Bytes::from_static(b"old");
379 let retained_bal = Bytes::from_static(b"retained");
380 let tip_bal = Bytes::from_static(b"tip");
381
382 store.insert(NumHash::new(1, old_hash), RawBal::from(old_bal)).unwrap();
383 store.insert(NumHash::new(2, retained_hash), RawBal::from(retained_bal.clone())).unwrap();
384 store.insert(NumHash::new(4, tip_hash), RawBal::from(tip_bal.clone())).unwrap();
385
386 assert_eq!(
387 store.get_by_hashes(&[old_hash, retained_hash, tip_hash]).unwrap(),
388 vec![None, Some(retained_bal), Some(tip_bal)]
389 );
390 }
391
392 #[test]
393 fn reinserting_hash_updates_number_index() {
394 let store =
395 InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Before(2)));
396 let hash = B256::random();
397 let bal = Bytes::from_static(b"bal");
398
399 store.insert(NumHash::new(1, hash), RawBal::from(Bytes::from_static(b"old"))).unwrap();
400 store.insert(NumHash::new(2, hash), RawBal::from(bal.clone())).unwrap();
401
402 assert_eq!(store.get_by_hashes(&[hash]).unwrap(), vec![Some(bal)]);
403 }
404
405 #[tokio::test]
406 async fn insert_notifies_subscribers() {
407 let store = InMemoryBalStore::default();
408 let hash = B256::random();
409 let block_number = 7;
410 let bal = Bytes::from_static(b"bal");
411 let mut stream = store.bal_stream();
412
413 let raw_bal = RawBal::from(bal);
414
415 store.insert(NumHash::new(block_number, hash), raw_bal.clone()).unwrap();
416
417 assert_eq!(
418 stream.next().await.unwrap(),
419 BalNotification::new(NumHash::new(block_number, hash), raw_bal)
420 );
421 }
422
423 #[tokio::test]
424 async fn insert_many_notifies_subscribers() {
425 let store = InMemoryBalStore::default();
426 let mut stream = store.bal_stream();
427 let hash0 = B256::random();
428 let hash1 = B256::random();
429 let bal0 = RawBal::from(Bytes::from_static(b"bal0"));
430 let bal1 = RawBal::from(Bytes::from_static(b"bal1"));
431
432 store
433 .insert_many(vec![
434 (NumHash::new(1, hash0), bal0.clone()),
435 (NumHash::new(2, hash1), bal1.clone()),
436 ])
437 .unwrap();
438
439 assert_eq!(
440 stream.next().await.unwrap(),
441 BalNotification::new(NumHash::new(1, hash0), bal0)
442 );
443 assert_eq!(
444 stream.next().await.unwrap(),
445 BalNotification::new(NumHash::new(2, hash1), bal1)
446 );
447 }
448
449 #[test]
450 fn insert_without_subscribers_still_succeeds() {
451 let store = InMemoryBalStore::default();
452
453 assert!(store
454 .insert(NumHash::new(1, B256::random()), RawBal::from(Bytes::from_static(b"bal")))
455 .is_ok());
456 }
457
458 #[tokio::test]
459 async fn bal_stream_skips_lagged_notifications() {
460 let store = InMemoryBalStore::new(BalConfig::unbounded());
461 let mut stream = store.bal_stream();
462
463 for number in 0..=DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE as u64 {
464 store
465 .insert(
466 NumHash::new(number, B256::random()),
467 RawBal::from(Bytes::from(vec![number as u8])),
468 )
469 .unwrap();
470 }
471
472 let first = stream.next().await.unwrap();
473 let second = stream.next().await.unwrap();
474
475 assert_eq!(first.num_hash.number, 1);
476 assert_eq!(second.num_hash.number, 2);
477 }
478
479 #[tokio::test]
480 async fn cloned_store_shares_notification_channel() {
481 let store = InMemoryBalStore::default();
482 let clone = store.clone();
483 let hash = B256::random();
484 let block_number = 9;
485 let bal = Bytes::from_static(b"bal");
486 let mut stream = clone.bal_stream();
487
488 let raw_bal = RawBal::from(bal);
489
490 store.insert(NumHash::new(block_number, hash), raw_bal.clone()).unwrap();
491
492 assert_eq!(
493 stream.next().await.unwrap(),
494 BalNotification::new(NumHash::new(block_number, hash), raw_bal)
495 );
496 }
497}