1use alloy_primitives::{b256, bytes::BufMut, keccak256, Address, B256};
2use itertools::Itertools;
3use reth_concurrency::sync::{
4 channel::mpsc::{self, Receiver},
5 rayon,
6};
7use reth_config::config::{EtlConfig, HashingConfig};
8use reth_db_api::{
9 cursor::{DbCursorRO, DbDupCursorRW},
10 models::{BlockNumberAddress, CompactU256},
11 table::Decompress,
12 tables,
13 transaction::{DbTx, DbTxMut},
14};
15use reth_etl::Collector;
16use reth_primitives_traits::StorageEntry;
17use reth_provider::{DBProvider, HashingWriter, StatsReader, StorageReader};
18use reth_stages_api::{
19 BlockRangeOutput, EntitiesCheckpoint, ExecInput, ExecOutput, Stage, StageCheckpoint,
20 StageError, StageId, StorageHashingCheckpoint, UnwindInput, UnwindOutput,
21};
22use reth_storage_api::StorageSettingsCache;
23use reth_storage_errors::provider::ProviderResult;
24use std::{
25 collections::{BTreeMap, BTreeSet},
26 fmt::Debug,
27};
28use tracing::*;
29
30const MAXIMUM_CHANNELS: usize = 10_000;
32
33const WORKER_CHUNK_SIZE: usize = 100;
35
36const HASHED_ZERO_ADDRESS: B256 =
38 b256!("0x5380c7b7ae81a58eb98d9c78de4a1fd7fd9535fc953ed2be602daaa41767312a");
39
40#[derive(Debug)]
43pub struct StorageHashingStage {
44 pub clean_threshold: u64,
47 pub commit_threshold: u64,
49 pub commit_entries: u64,
52 pub etl_config: EtlConfig,
54}
55
56impl StorageHashingStage {
57 pub const fn new(config: HashingConfig, etl_config: EtlConfig) -> Self {
59 Self {
60 clean_threshold: config.clean_threshold,
61 commit_threshold: config.commit_threshold,
62 commit_entries: config.commit_entries,
63 etl_config,
64 }
65 }
66}
67
68impl Default for StorageHashingStage {
69 fn default() -> Self {
70 Self {
71 clean_threshold: 500_000,
72 commit_threshold: 100_000,
73 commit_entries: 30_000_000,
74 etl_config: EtlConfig::default(),
75 }
76 }
77}
78
79impl<Provider> Stage<Provider> for StorageHashingStage
80where
81 Provider: DBProvider<Tx: DbTxMut>
82 + StorageReader
83 + HashingWriter
84 + StatsReader
85 + StorageSettingsCache,
86{
87 fn id(&self) -> StageId {
89 StageId::StorageHashing
90 }
91
92 fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
94 let tx = provider.tx_ref();
95 if input.target_reached() {
96 return Ok(ExecOutput::done(input.checkpoint()))
97 }
98
99 if provider.cached_storage_settings().use_hashed_state() {
102 return Ok(ExecOutput::done(input.checkpoint().with_block_number(input.target())));
103 }
104
105 let total_range = input.target() - input.checkpoint().block_number;
107 let from_block = input.next_block();
108
109 if total_range > self.clean_threshold || from_block == 1 {
110 tx.clear::<tables::HashedStorages>()?;
118
119 let mut storage_cursor = tx.cursor_read::<tables::PlainStorageState>()?;
120 let mut collector =
121 Collector::new(self.etl_config.file_size, self.etl_config.dir.clone());
122 let mut channels = Vec::with_capacity(MAXIMUM_CHANNELS);
123
124 for chunk in &storage_cursor.walk(None)?.chunks(WORKER_CHUNK_SIZE) {
125 let chunk = chunk.collect::<Result<Vec<_>, _>>()?;
127 let (tx, rx) = mpsc::sync_channel(chunk.len());
128 channels.push(rx);
129 rayon::spawn(move || {
131 let (mut last_addr, mut hashed_addr) = (Address::ZERO, HASHED_ZERO_ADDRESS);
133 for (address, slot) in chunk {
134 if address != last_addr {
135 last_addr = address;
136 hashed_addr = keccak256(address);
137 }
138 let mut addr_key = Vec::with_capacity(64);
139 addr_key.put_slice(hashed_addr.as_slice());
140 addr_key.put_slice(keccak256(slot.key).as_slice());
141 let _ = tx.send((addr_key, CompactU256::from(slot.value)));
142 }
143 });
144
145 if !channels.is_empty() && channels.len().is_multiple_of(MAXIMUM_CHANNELS) {
147 collect(&mut channels, &mut collector)?;
148 }
149 }
150
151 collect(&mut channels, &mut collector)?;
152
153 let total_hashes = collector.len();
154 let interval = (total_hashes / 10).max(1);
155 let mut cursor = tx.cursor_dup_write::<tables::HashedStorages>()?;
156 for (index, item) in collector.iter()?.enumerate() {
157 if index > 0 && index.is_multiple_of(interval) {
158 info!(
159 target: "sync::stages::hashing_storage",
160 progress = %format_args!("{:.2}%", (index as f64 / total_hashes as f64) * 100.0),
161 "Inserting hashes"
162 );
163 }
164
165 let (addr_key, value) = item?;
166 cursor.append_dup(
167 B256::from_slice(&addr_key[..32]),
168 StorageEntry {
169 key: B256::from_slice(&addr_key[32..]),
170 value: CompactU256::decompress_owned(value)?.into(),
171 },
172 )?;
173 }
174
175 let checkpoint = StageCheckpoint::new(input.target())
176 .with_storage_hashing_stage_checkpoint(StorageHashingCheckpoint {
177 progress: stage_checkpoint_progress(provider)?,
178 ..Default::default()
179 });
180
181 Ok(ExecOutput::done(checkpoint))
182 } else {
183 let BlockRangeOutput { block_range, is_final_range } =
186 input.next_block_range_with_threshold(self.commit_threshold);
187 let (from_block, to_block) = block_range.into_inner();
188
189 let mut changeset_cursor = tx.cursor_read::<tables::StorageChangeSets>()?;
190 let mut changed: BTreeMap<Address, BTreeSet<B256>> = BTreeMap::new();
191 let mut total_entries = 0u64;
192 let mut last_block = from_block;
193
194 for entry in
195 changeset_cursor.walk_range(BlockNumberAddress::range(from_block..=to_block))?
196 {
197 let (BlockNumberAddress((block_number, address)), storage_entry) = entry?;
198
199 if block_number != last_block && total_entries >= self.commit_entries {
203 break;
204 }
205
206 last_block = block_number;
207 changed.entry(address).or_default().insert(storage_entry.key);
208 total_entries += 1;
209 }
210
211 let storages = provider.plain_state_storages(changed)?;
212 provider.insert_storage_for_hashing(storages)?;
213
214 let exhausted = total_entries < self.commit_entries;
215 let done = exhausted && is_final_range;
216 let progress_block = if exhausted { to_block } else { last_block };
217
218 let checkpoint = StageCheckpoint::new(progress_block)
219 .with_storage_hashing_stage_checkpoint(StorageHashingCheckpoint {
220 progress: stage_checkpoint_progress(provider)?,
221 ..Default::default()
222 });
223
224 Ok(ExecOutput { checkpoint, done })
225 }
226 }
227
228 fn unwind(
230 &mut self,
231 provider: &Provider,
232 input: UnwindInput,
233 ) -> Result<UnwindOutput, StageError> {
234 let (range, unwind_progress, _) =
240 input.unwind_block_range_with_threshold(self.commit_threshold);
241
242 provider.unwind_storage_hashing_range(range)?;
243
244 let mut stage_checkpoint =
245 input.checkpoint.storage_hashing_stage_checkpoint().unwrap_or_default();
246
247 stage_checkpoint.progress = stage_checkpoint_progress(provider)?;
248
249 Ok(UnwindOutput {
250 checkpoint: StageCheckpoint::new(unwind_progress)
251 .with_storage_hashing_stage_checkpoint(stage_checkpoint),
252 })
253 }
254}
255
256fn collect(
258 channels: &mut Vec<Receiver<(Vec<u8>, CompactU256)>>,
259 collector: &mut Collector<Vec<u8>, CompactU256>,
260) -> Result<(), StageError> {
261 for channel in channels.iter_mut() {
262 while let Ok((key, v)) = channel.recv() {
263 collector.insert(key, v)?;
264 }
265 }
266 info!(target: "sync::stages::hashing_storage", "Hashed {} entries", collector.len());
267 channels.clear();
268 Ok(())
269}
270
271fn stage_checkpoint_progress(provider: &impl StatsReader) -> ProviderResult<EntitiesCheckpoint> {
272 Ok(EntitiesCheckpoint {
273 processed: provider.count_entries::<tables::HashedStorages>()? as u64,
274 total: provider.count_entries::<tables::PlainStorageState>()? as u64,
275 })
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use crate::test_utils::{
282 stage_test_suite_ext, ExecuteStageTestRunner, StageTestRunner, TestRunnerError,
283 TestStageDB, UnwindStageTestRunner,
284 };
285 use alloy_primitives::{Address, U256};
286 use assert_matches::assert_matches;
287 use rand::Rng;
288 use reth_db_api::{
289 cursor::{DbCursorRW, DbDupCursorRO},
290 models::{BlockNumberAddress, StoredBlockBodyIndices},
291 };
292 use reth_ethereum_primitives::Block;
293 use reth_primitives_traits::SealedBlock;
294 use reth_provider::providers::StaticFileWriter;
295 use reth_testing_utils::generators::{
296 self, random_block_range, random_contract_account_range, BlockRangeParams,
297 };
298
299 stage_test_suite_ext!(StorageHashingTestRunner, storage_hashing);
300
301 #[tokio::test]
303 async fn execute_clean_storage_hashing() {
304 let (previous_stage, stage_progress) = (500, 100);
305
306 let mut runner = StorageHashingTestRunner::default();
308
309 runner.set_clean_threshold(1);
311
312 runner.set_commit_threshold(1);
315
316 let mut input = ExecInput {
317 target: Some(previous_stage),
318 checkpoint: Some(StageCheckpoint::new(stage_progress)),
319 };
320
321 runner.seed_execution(input).expect("failed to seed execution");
322
323 loop {
324 if let Ok(result @ ExecOutput { checkpoint, done }) =
325 runner.execute(input).await.unwrap()
326 {
327 if !done {
328 let previous_checkpoint = input
329 .checkpoint
330 .and_then(|checkpoint| checkpoint.storage_hashing_stage_checkpoint())
331 .unwrap_or_default();
332 assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint {
333 progress: EntitiesCheckpoint {
334 processed,
335 total,
336 },
337 ..
338 }) if processed == previous_checkpoint.progress.processed + 1 &&
339 total == runner.db.count_entries::<tables::PlainStorageState>().unwrap() as u64);
340
341 input.checkpoint = Some(checkpoint);
343 continue
344 }
345 assert_eq!(checkpoint.block_number, previous_stage);
346 assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint {
347 progress: EntitiesCheckpoint {
348 processed,
349 total,
350 },
351 ..
352 }) if processed == total &&
353 total == runner.db.count_entries::<tables::PlainStorageState>().unwrap() as u64);
354
355 assert!(
357 runner.validate_execution(input, Some(result)).is_ok(),
358 "execution validation"
359 );
360
361 break
362 }
363 panic!("Failed execution");
364 }
365 }
366
367 struct StorageHashingTestRunner {
368 db: TestStageDB,
369 commit_threshold: u64,
370 clean_threshold: u64,
371 commit_entries: u64,
372 etl_config: EtlConfig,
373 }
374
375 impl Default for StorageHashingTestRunner {
376 fn default() -> Self {
377 Self {
378 db: TestStageDB::default(),
379 commit_threshold: 1000,
380 clean_threshold: 1000,
381 commit_entries: u64::MAX,
382 etl_config: EtlConfig::default(),
383 }
384 }
385 }
386
387 impl StageTestRunner for StorageHashingTestRunner {
388 type S = StorageHashingStage;
389
390 fn db(&self) -> &TestStageDB {
391 &self.db
392 }
393
394 fn stage(&self) -> Self::S {
395 Self::S {
396 commit_threshold: self.commit_threshold,
397 clean_threshold: self.clean_threshold,
398 commit_entries: self.commit_entries,
399 etl_config: self.etl_config.clone(),
400 }
401 }
402 }
403
404 impl ExecuteStageTestRunner for StorageHashingTestRunner {
405 type Seed = Vec<SealedBlock<Block>>;
406
407 fn seed_execution(&mut self, input: ExecInput) -> Result<Self::Seed, TestRunnerError> {
408 let stage_progress = input.next_block();
409 let end = input.target();
410 let mut rng = generators::rng();
411
412 let n_accounts = 31;
413 let mut accounts = random_contract_account_range(&mut rng, &mut (0..n_accounts));
414
415 let blocks = random_block_range(
416 &mut rng,
417 stage_progress..=end,
418 BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..3, ..Default::default() },
419 );
420
421 self.db.insert_headers(blocks.iter().map(|block| block.sealed_header()))?;
422 let mut tx_hash_numbers = Vec::new();
423
424 let iter = blocks.iter();
425 let mut next_tx_num = 0;
426 let mut first_tx_num = next_tx_num;
427 for progress in iter {
428 let block_number = progress.number;
430 self.db.commit(|tx| {
431 progress.body().transactions.iter().try_for_each(
432 |transaction| -> Result<(), reth_db::DatabaseError> {
433 tx_hash_numbers.push((*transaction.tx_hash(), next_tx_num));
434 tx.put::<tables::Transactions>(next_tx_num, transaction.clone())?;
435
436 let (addr, _) = accounts
437 .get_mut((rng.random::<u64>() % n_accounts) as usize)
438 .unwrap();
439
440 for _ in 0..2 {
441 let new_entry = StorageEntry {
442 key: keccak256([rng.random::<u8>()]),
443 value: U256::from(rng.random::<u8>() % 30 + 1),
444 };
445 self.insert_storage_entry(
446 tx,
447 (block_number, *addr).into(),
448 new_entry,
449 progress.number == stage_progress,
450 )?;
451 }
452
453 next_tx_num += 1;
454 Ok(())
455 },
456 )?;
457
458 let has_reward: bool = rng.random();
460 if has_reward {
461 self.insert_storage_entry(
462 tx,
463 (block_number, Address::random()).into(),
464 StorageEntry {
465 key: keccak256("mining"),
466 value: U256::from(rng.random::<u32>()),
467 },
468 progress.number == stage_progress,
469 )?;
470 }
471
472 let body = StoredBlockBodyIndices {
473 first_tx_num,
474 tx_count: progress.transaction_count() as u64,
475 };
476
477 first_tx_num = next_tx_num;
478
479 tx.put::<tables::BlockBodyIndices>(progress.number, body)?;
480 Ok(())
481 })?;
482 }
483 self.db.insert_tx_hash_numbers(tx_hash_numbers)?;
484
485 Ok(blocks)
486 }
487
488 fn validate_execution(
489 &self,
490 input: ExecInput,
491 output: Option<ExecOutput>,
492 ) -> Result<(), TestRunnerError> {
493 if let Some(output) = output {
494 let start_block = input.checkpoint().block_number + 1;
495 let end_block = output.checkpoint.block_number;
496 if start_block > end_block {
497 return Ok(())
498 }
499 }
500 self.check_hashed_storage()
501 }
502 }
503
504 impl UnwindStageTestRunner for StorageHashingTestRunner {
505 fn validate_unwind(&self, input: UnwindInput) -> Result<(), TestRunnerError> {
506 self.unwind_storage(input)?;
507 self.check_hashed_storage()
508 }
509 }
510
511 impl StorageHashingTestRunner {
512 fn set_clean_threshold(&mut self, threshold: u64) {
513 self.clean_threshold = threshold;
514 }
515
516 fn set_commit_threshold(&mut self, threshold: u64) {
517 self.commit_threshold = threshold;
518 }
519
520 fn check_hashed_storage(&self) -> Result<(), TestRunnerError> {
521 self.db
522 .query(|tx| {
523 let mut storage_cursor = tx.cursor_dup_read::<tables::PlainStorageState>()?;
524 let mut hashed_storage_cursor =
525 tx.cursor_dup_read::<tables::HashedStorages>()?;
526
527 let mut expected = 0;
528
529 while let Some((address, entry)) = storage_cursor.next()? {
530 let key = keccak256(entry.key);
531 let got =
532 hashed_storage_cursor.seek_by_key_subkey(keccak256(address), key)?;
533 assert_eq!(
534 got,
535 Some(StorageEntry { key, ..entry }),
536 "{expected}: {address:?}"
537 );
538 expected += 1;
539 }
540 let count = tx.cursor_dup_read::<tables::HashedStorages>()?.walk(None)?.count();
541
542 assert_eq!(count, expected);
543 Ok(())
544 })
545 .map_err(|e| e.into())
546 }
547
548 fn insert_storage_entry<TX: DbTxMut>(
549 &self,
550 tx: &TX,
551 bn_address: BlockNumberAddress,
552 entry: StorageEntry,
553 hash: bool,
554 ) -> Result<(), reth_db::DatabaseError> {
555 let mut storage_cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
556 let prev_entry =
557 match storage_cursor.seek_by_key_subkey(bn_address.address(), entry.key)? {
558 Some(e) if e.key == entry.key => {
559 tx.delete::<tables::PlainStorageState>(bn_address.address(), Some(e))
560 .expect("failed to delete entry");
561 e
562 }
563 _ => StorageEntry { key: entry.key, value: U256::ZERO },
564 };
565 tx.put::<tables::PlainStorageState>(bn_address.address(), entry)?;
566
567 if hash {
568 let hashed_address = keccak256(bn_address.address());
569 let hashed_entry = StorageEntry { key: keccak256(entry.key), value: entry.value };
570
571 if let Some(e) = tx
572 .cursor_dup_write::<tables::HashedStorages>()?
573 .seek_by_key_subkey(hashed_address, hashed_entry.key)?
574 .filter(|e| e.key == hashed_entry.key)
575 {
576 tx.delete::<tables::HashedStorages>(hashed_address, Some(e))
577 .expect("failed to delete entry");
578 }
579
580 tx.put::<tables::HashedStorages>(hashed_address, hashed_entry)?;
581 }
582
583 tx.put::<tables::StorageChangeSets>(bn_address, prev_entry)?;
584 Ok(())
585 }
586
587 fn unwind_storage(&self, input: UnwindInput) -> Result<(), TestRunnerError> {
588 tracing::debug!("unwinding storage...");
589 let target_block = input.unwind_to;
590 self.db.commit(|tx| {
591 let mut storage_cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
592 let mut changeset_cursor = tx.cursor_dup_read::<tables::StorageChangeSets>()?;
593
594 let mut rev_changeset_walker = changeset_cursor.walk_back(None)?;
595
596 while let Some((bn_address, entry)) = rev_changeset_walker.next().transpose()? {
597 if bn_address.block_number() < target_block {
598 break
599 }
600
601 if storage_cursor
602 .seek_by_key_subkey(bn_address.address(), entry.key)?
603 .is_some_and(|e| e.key == entry.key)
604 {
605 storage_cursor.delete_current()?;
606 }
607
608 if !entry.value.is_zero() {
609 storage_cursor.upsert(bn_address.address(), &entry)?;
610 }
611 }
612 Ok(())
613 })?;
614 Ok(())
615 }
616 }
617}