1use alloy_primitives::{
3 map::{AddressMap, HashMap},
4 Address, BlockNumber, TxNumber, B256,
5};
6use reth_config::config::EtlConfig;
7use reth_db_api::{
8 cursor::{DbCursorRO, DbCursorRW},
9 models::{
10 sharded_key::NUM_OF_INDICES_IN_SHARD, storage_sharded_key::StorageShardedKey,
11 AccountBeforeTx, AddressStorageKey, BlockNumberAddress, ShardedKey,
12 },
13 table::{Decode, Decompress, Key, Table},
14 transaction::DbTx,
15 BlockNumberList,
16};
17use reth_etl::Collector;
18use reth_primitives_traits::NodePrimitives;
19use reth_provider::{
20 providers::StaticFileProvider, to_range, BlockReader, DBProvider, EitherWriter, ProviderError,
21 StaticFileProviderFactory,
22};
23use reth_stages_api::StageError;
24use reth_static_file_types::StaticFileSegment;
25use reth_storage_api::{ChangeSetReader, StorageChangeSetReader};
26use std::{
27 hash::{BuildHasher, Hash},
28 mem::size_of,
29 ops::RangeBounds,
30};
31use tracing::{debug, info};
32
33const DEFAULT_CACHE_THRESHOLD: u64 = 100_000;
35
36pub(crate) fn collect_history_indices<Provider, CS, H, P>(
54 provider: &Provider,
55 range: impl RangeBounds<CS::Key>,
56 sharded_key_factory: impl Fn(P, BlockNumber) -> H::Key,
57 partial_key_factory: impl Fn((CS::Key, CS::Value)) -> (u64, P),
58 etl_config: &EtlConfig,
59) -> Result<Collector<H::Key, H::Value>, StageError>
60where
61 Provider: DBProvider,
62 CS: Table,
63 H: Table<Value = BlockNumberList>,
64 P: Copy + Eq + Hash,
65{
66 let mut changeset_cursor = provider.tx_ref().cursor_read::<CS>()?;
67
68 let mut cache =
69 HistoryIndexCache::new(etl_config, HashMap::<_, _>::default(), sharded_key_factory);
70
71 let total_changesets = provider.tx_ref().entries::<CS>()?;
73 let interval = (total_changesets / 1000).max(1);
74
75 for (idx, entry) in changeset_cursor.walk_range(range)?.enumerate() {
76 let (block_number, key) = partial_key_factory(entry?);
77 cache.insert(block_number, key)?;
78
79 if idx > 0 && idx.is_multiple_of(interval) && total_changesets > 1000 {
80 info!(target: "sync::stages::index_history", progress = %format_args!("{:.4}%", (idx as f64 / total_changesets as f64) * 100.0), "Collecting indices");
81 }
82 }
83
84 cache.finish()
85}
86
87pub(crate) fn collect_account_history_indices<Provider>(
89 provider: &Provider,
90 range: impl RangeBounds<BlockNumber>,
91 etl_config: &EtlConfig,
92) -> Result<Collector<ShardedKey<Address>, BlockNumberList>, StageError>
93where
94 Provider: DBProvider + ChangeSetReader + StaticFileProviderFactory,
95{
96 let mut cache = HistoryIndexCache::new(etl_config, AddressMap::default(), ShardedKey::new);
97
98 let range = to_range(range);
100 let start_block = range.start;
101
102 let static_file_provider = provider.static_file_provider();
104
105 let walker = static_file_provider.walk_account_changeset_range(range);
106
107 for changeset_result in walker {
108 let (block_number, AccountBeforeTx { address, .. }) = changeset_result?;
109 if cache.insert(block_number, address)? {
110 info!(
111 target: "sync::stages::index_history",
112 processed_blocks = block_number.saturating_sub(start_block),
113 current_block = block_number,
114 "Collecting indices"
115 );
116 }
117 }
118
119 cache.finish()
120}
121
122pub(crate) fn collect_storage_history_indices<Provider>(
124 provider: &Provider,
125 range: impl RangeBounds<BlockNumber>,
126 etl_config: &EtlConfig,
127) -> Result<Collector<StorageShardedKey, BlockNumberList>, StageError>
128where
129 Provider: DBProvider + StorageChangeSetReader + StaticFileProviderFactory,
130{
131 let mut cache = HistoryIndexCache::new(
132 etl_config,
133 HashMap::<_, _>::default(),
134 |AddressStorageKey((address, storage_key)), highest_block_number| {
135 StorageShardedKey::new(address, storage_key, highest_block_number)
136 },
137 );
138
139 let range = to_range(range);
140 let start_block = range.start;
141 let static_file_provider = provider.static_file_provider();
142
143 let walker = static_file_provider.walk_storage_changeset_range(range);
144
145 for changeset_result in walker {
146 let (BlockNumberAddress((block_number, address)), storage) = changeset_result?;
147 if cache.insert(block_number, AddressStorageKey((address, storage.key)))? {
148 info!(
149 target: "sync::stages::index_history",
150 processed_blocks = block_number.saturating_sub(start_block),
151 current_block = block_number,
152 "Collecting indices"
153 );
154 }
155 }
156
157 cache.finish()
158}
159
160pub(crate) fn load_account_history<N, CURSOR>(
172 mut collector: Collector<ShardedKey<Address>, BlockNumberList>,
173 append_only: bool,
174 writer: &mut EitherWriter<'_, CURSOR, N>,
175) -> Result<(), StageError>
176where
177 N: NodePrimitives,
178 CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
179 + DbCursorRO<reth_db_api::tables::AccountsHistory>,
180{
181 let mut current_address: Option<Address> = None;
182 let mut current_list = Vec::<u64>::new();
184
185 let total_entries = collector.len();
186 let interval = (total_entries / 10).max(1);
187
188 for (index, element) in collector.iter()?.enumerate() {
189 let (k, v) = element?;
190 let sharded_key = ShardedKey::<Address>::decode_owned(k)?;
191 let new_list = BlockNumberList::decompress_owned(v)?;
192
193 if index > 0 && index.is_multiple_of(interval) && total_entries > 10 {
194 info!(target: "sync::stages::index_history", progress = %format_args!("{:.2}%", (index as f64 / total_entries as f64) * 100.0), "Writing indices");
195 }
196
197 let address = sharded_key.key;
198
199 if current_address != Some(address) {
201 if let Some(prev_addr) = current_address {
203 flush_account_history_shards(prev_addr, &mut current_list, append_only, writer)?;
204 }
205
206 current_address = Some(address);
207 current_list.clear();
208
209 if !append_only &&
212 let Some(last_shard) = writer.get_last_account_history_shard(address)?
213 {
214 current_list.extend(last_shard.iter());
215 }
216 }
217
218 current_list.extend(new_list.iter());
220
221 flush_account_history_shards_partial(address, &mut current_list, append_only, writer)?;
223 }
224
225 if let Some(addr) = current_address {
227 flush_account_history_shards(addr, &mut current_list, append_only, writer)?;
228 }
229
230 Ok(())
231}
232
233fn flush_account_history_shards_partial<N, CURSOR>(
239 address: Address,
240 list: &mut Vec<u64>,
241 append_only: bool,
242 writer: &mut EitherWriter<'_, CURSOR, N>,
243) -> Result<(), StageError>
244where
245 N: NodePrimitives,
246 CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
247 + DbCursorRO<reth_db_api::tables::AccountsHistory>,
248{
249 if list.len() <= NUM_OF_INDICES_IN_SHARD {
251 return Ok(());
252 }
253
254 let num_full_shards = list.len() / NUM_OF_INDICES_IN_SHARD;
255
256 let shards_to_flush = if list.len().is_multiple_of(NUM_OF_INDICES_IN_SHARD) {
259 num_full_shards - 1
260 } else {
261 num_full_shards
262 };
263
264 if shards_to_flush == 0 {
265 return Ok(());
266 }
267
268 let flush_len = shards_to_flush * NUM_OF_INDICES_IN_SHARD;
270 let remainder = list.split_off(flush_len);
271
272 for chunk in list.chunks(NUM_OF_INDICES_IN_SHARD) {
274 let highest = *chunk.last().expect("chunk is non-empty");
275 let key = ShardedKey::new(address, highest);
276 let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
277
278 if append_only {
279 writer.append_account_history(key, &value)?;
280 } else {
281 writer.upsert_account_history(key, &value)?;
282 }
283 }
284
285 *list = remainder;
287 Ok(())
288}
289
290fn flush_account_history_shards<N, CURSOR>(
295 address: Address,
296 list: &mut Vec<u64>,
297 append_only: bool,
298 writer: &mut EitherWriter<'_, CURSOR, N>,
299) -> Result<(), StageError>
300where
301 N: NodePrimitives,
302 CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
303 + DbCursorRO<reth_db_api::tables::AccountsHistory>,
304{
305 if list.is_empty() {
306 return Ok(());
307 }
308
309 let num_chunks = list.len().div_ceil(NUM_OF_INDICES_IN_SHARD);
310
311 for (i, chunk) in list.chunks(NUM_OF_INDICES_IN_SHARD).enumerate() {
312 let is_last = i == num_chunks - 1;
313
314 let highest = if is_last { u64::MAX } else { *chunk.last().expect("chunk is non-empty") };
317
318 let key = ShardedKey::new(address, highest);
319 let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
320
321 if append_only {
322 writer.append_account_history(key, &value)?;
323 } else {
324 writer.upsert_account_history(key, &value)?;
325 }
326 }
327
328 list.clear();
329 Ok(())
330}
331
332pub(crate) fn missing_static_data_error<Provider>(
335 last_tx_num: TxNumber,
336 static_file_provider: &StaticFileProvider<Provider::Primitives>,
337 provider: &Provider,
338 segment: StaticFileSegment,
339) -> Result<StageError, ProviderError>
340where
341 Provider: BlockReader + StaticFileProviderFactory,
342{
343 let mut last_block =
344 static_file_provider.get_highest_static_file_block(segment).unwrap_or_default();
345
346 loop {
349 if let Some(indices) = provider.block_body_indices(last_block)? &&
350 indices.last_tx_num() <= last_tx_num
351 {
352 break
353 }
354 if last_block == 0 {
355 break
356 }
357 last_block -= 1;
358 }
359
360 let missing_block = Box::new(provider.sealed_header(last_block + 1)?.unwrap_or_default());
361
362 Ok(StageError::MissingStaticFileData {
363 block: Box::new(missing_block.block_with_parent()),
364 segment,
365 })
366}
367
368pub(crate) fn load_storage_history<N, CURSOR>(
380 mut collector: Collector<StorageShardedKey, BlockNumberList>,
381 append_only: bool,
382 writer: &mut EitherWriter<'_, CURSOR, N>,
383) -> Result<(), StageError>
384where
385 N: NodePrimitives,
386 CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
387 + DbCursorRO<reth_db_api::tables::StoragesHistory>,
388{
389 let mut current_key: Option<(Address, B256)> = None;
390 let mut current_list = Vec::<u64>::new();
392
393 let total_entries = collector.len();
394 let interval = (total_entries / 10).max(1);
395
396 for (index, element) in collector.iter()?.enumerate() {
397 let (k, v) = element?;
398 let sharded_key = StorageShardedKey::decode_owned(k)?;
399 let new_list = BlockNumberList::decompress_owned(v)?;
400
401 if index > 0 && index.is_multiple_of(interval) && total_entries > 10 {
402 info!(target: "sync::stages::index_history", progress = %format_args!("{:.2}%", (index as f64 / total_entries as f64) * 100.0), "Writing indices");
403 }
404
405 let partial_key = (sharded_key.address, sharded_key.sharded_key.key);
406
407 if current_key != Some(partial_key) {
409 if let Some((prev_addr, prev_storage_key)) = current_key {
411 flush_storage_history_shards(
412 prev_addr,
413 prev_storage_key,
414 &mut current_list,
415 append_only,
416 writer,
417 )?;
418 }
419
420 current_key = Some(partial_key);
421 current_list.clear();
422
423 if !append_only &&
426 let Some(last_shard) =
427 writer.get_last_storage_history_shard(partial_key.0, partial_key.1)?
428 {
429 current_list.extend(last_shard.iter());
430 }
431 }
432
433 current_list.extend(new_list.iter());
435
436 flush_storage_history_shards_partial(
438 partial_key.0,
439 partial_key.1,
440 &mut current_list,
441 append_only,
442 writer,
443 )?;
444 }
445
446 if let Some((addr, storage_key)) = current_key {
448 flush_storage_history_shards(addr, storage_key, &mut current_list, append_only, writer)?;
449 }
450
451 Ok(())
452}
453
454fn flush_storage_history_shards_partial<N, CURSOR>(
460 address: Address,
461 storage_key: B256,
462 list: &mut Vec<u64>,
463 append_only: bool,
464 writer: &mut EitherWriter<'_, CURSOR, N>,
465) -> Result<(), StageError>
466where
467 N: NodePrimitives,
468 CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
469 + DbCursorRO<reth_db_api::tables::StoragesHistory>,
470{
471 if list.len() <= NUM_OF_INDICES_IN_SHARD {
473 return Ok(());
474 }
475
476 let num_full_shards = list.len() / NUM_OF_INDICES_IN_SHARD;
477
478 let shards_to_flush = if list.len().is_multiple_of(NUM_OF_INDICES_IN_SHARD) {
481 num_full_shards - 1
482 } else {
483 num_full_shards
484 };
485
486 if shards_to_flush == 0 {
487 return Ok(());
488 }
489
490 let flush_len = shards_to_flush * NUM_OF_INDICES_IN_SHARD;
492 let remainder = list.split_off(flush_len);
493
494 for chunk in list.chunks(NUM_OF_INDICES_IN_SHARD) {
496 let highest = *chunk.last().expect("chunk is non-empty");
497 let key = StorageShardedKey::new(address, storage_key, highest);
498 let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
499
500 if append_only {
501 writer.append_storage_history(key, &value)?;
502 } else {
503 writer.upsert_storage_history(key, &value)?;
504 }
505 }
506
507 *list = remainder;
509 Ok(())
510}
511
512fn flush_storage_history_shards<N, CURSOR>(
518 address: Address,
519 storage_key: B256,
520 list: &mut Vec<u64>,
521 append_only: bool,
522 writer: &mut EitherWriter<'_, CURSOR, N>,
523) -> Result<(), StageError>
524where
525 N: NodePrimitives,
526 CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
527 + DbCursorRO<reth_db_api::tables::StoragesHistory>,
528{
529 if list.is_empty() {
530 return Ok(());
531 }
532
533 let num_chunks = list.len().div_ceil(NUM_OF_INDICES_IN_SHARD);
534
535 for (i, chunk) in list.chunks(NUM_OF_INDICES_IN_SHARD).enumerate() {
536 let is_last = i == num_chunks - 1;
537
538 let highest = if is_last { u64::MAX } else { *chunk.last().expect("chunk is non-empty") };
541
542 let key = StorageShardedKey::new(address, storage_key, highest);
543 let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
544
545 if append_only {
546 writer.append_storage_history(key, &value)?;
547 } else {
548 writer.upsert_storage_history(key, &value)?;
549 }
550 }
551
552 list.clear();
553 Ok(())
554}
555
556struct HistoryIndexCache<P, K: Key, F, S> {
564 collector: Collector<K, BlockNumberList>,
565 sharded_key: F,
567 indices: HashMap<P, Vec<u64>, S>,
568 size_bytes: usize,
570 max_size_bytes: usize,
572 blocks: u64,
574 current_block: Option<BlockNumber>,
576}
577
578impl<P, K, F, S> HistoryIndexCache<P, K, F, S>
579where
580 P: Eq + Hash,
581 K: Key,
582 F: Fn(P, BlockNumber) -> K,
583 S: BuildHasher,
584{
585 fn new(etl_config: &EtlConfig, indices: HashMap<P, Vec<u64>, S>, sharded_key: F) -> Self {
586 Self {
587 collector: Collector::new(etl_config.file_size, etl_config.dir.clone()),
588 sharded_key,
589 indices,
590 size_bytes: 0,
591 max_size_bytes: etl_config.file_size / 2,
592 blocks: 0,
593 current_block: None,
594 }
595 }
596
597 fn insert(&mut self, block_number: BlockNumber, key: P) -> Result<bool, StageError> {
604 let mut flushed = false;
605 if self.current_block != Some(block_number) {
606 if self.blocks >= DEFAULT_CACHE_THRESHOLD {
607 self.flush()?;
608 self.blocks = 0;
609 flushed = true;
610 } else if self.size_bytes >= self.max_size_bytes {
611 debug!(
612 target: "sync::stages::index_history",
613 current_block = block_number,
614 size_bytes = self.size_bytes,
615 "Flushing history index cache at size bound"
616 );
617 self.flush()?;
618 }
619 self.current_block = Some(block_number);
620 self.blocks += 1;
621 }
622
623 let indices = self.indices.entry(key).or_default();
624 let capacity = indices.capacity();
625 if capacity == 0 {
626 self.size_bytes += size_of::<(P, Vec<u64>)>() + 1;
628 }
629 indices.push(block_number);
630 self.size_bytes += (indices.capacity() - capacity) * size_of::<u64>();
631
632 Ok(flushed)
633 }
634
635 fn flush(&mut self) -> Result<(), StageError> {
637 for (key, indices) in self.indices.drain() {
638 let last = *indices.last().expect("indices is non-empty");
639 self.collector
640 .insert((self.sharded_key)(key, last), BlockNumberList::new_pre_sorted(indices))?;
641 }
642 self.size_bytes = 0;
643 Ok(())
644 }
645
646 fn finish(mut self) -> Result<Collector<K, BlockNumberList>, StageError> {
648 self.flush()?;
649 Ok(self.collector)
650 }
651}
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656 use rand::Rng;
657 use reth_testing_utils::generators;
658 use std::collections::{BTreeMap, BTreeSet};
659
660 #[test]
661 fn history_index_cache_flushes_by_size() {
662 const KEYS_PER_BLOCK: usize = 50;
663 const BLOCKS: u64 = 2_000;
664
665 let mut rng = generators::rng();
666 let mut cache = HistoryIndexCache::new(
667 &EtlConfig::new(None, 128 * 1024),
668 AddressMap::default(),
669 ShardedKey::new,
670 );
671 let mut history = BTreeMap::<Address, Vec<u64>>::new();
672 let mut flushes = 0;
673 for block in 0..BLOCKS {
674 let addresses = (0..KEYS_PER_BLOCK)
675 .map(|_| Address::left_padding_from(&rng.random_range(0..20_000u64).to_be_bytes()))
676 .collect::<BTreeSet<_>>();
677 for address in addresses {
678 let size_bytes = cache.size_bytes;
679 assert!(!cache.insert(block, address).unwrap());
682 flushes += (cache.size_bytes < size_bytes) as usize;
683 history.entry(address).or_default().push(block);
684 }
685 }
686 assert!(flushes > 10, "cache flushed {flushes} times");
687
688 let mut collector = cache.finish().unwrap();
690 let mut collected = BTreeMap::<Address, Vec<u64>>::new();
691 for entry in collector.iter().unwrap() {
692 let (key, value) = entry.unwrap();
693 let key = ShardedKey::<Address>::decode_owned(key).unwrap();
694 let blocks =
695 BlockNumberList::decompress_owned(value).unwrap().iter().collect::<Vec<_>>();
696 assert_eq!(key.highest_block_number, *blocks.last().unwrap());
697 collected.entry(key.key).or_default().extend(blocks);
698 }
699 assert_eq!(collected, history);
700 }
701}