1use alloy_primitives::{keccak256, 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, DbCursorRW},
10 tables,
11 transaction::{DbTx, DbTxMut},
12 RawKey, RawTable, RawValue,
13};
14use reth_etl::Collector;
15use reth_primitives_traits::Account;
16use reth_provider::{
17 AccountExtReader, DBProvider, HashingWriter, StatsReader, StorageSettingsCache,
18};
19use reth_stages_api::{
20 AccountHashingCheckpoint, BlockRangeOutput, EntitiesCheckpoint, ExecInput, ExecOutput, Stage,
21 StageCheckpoint, StageError, StageId, UnwindInput, UnwindOutput,
22};
23use reth_storage_errors::provider::ProviderResult;
24use std::{
25 collections::BTreeSet,
26 fmt::Debug,
27 ops::{Range, RangeInclusive},
28};
29use tracing::*;
30
31const MAXIMUM_CHANNELS: usize = 10_000;
33
34const WORKER_CHUNK_SIZE: usize = 100;
36
37#[derive(Clone, Debug)]
40pub struct AccountHashingStage {
41 pub clean_threshold: u64,
44 pub commit_threshold: u64,
46 pub commit_entries: u64,
49 pub etl_config: EtlConfig,
51}
52
53impl AccountHashingStage {
54 pub const fn new(config: HashingConfig, etl_config: EtlConfig) -> Self {
56 Self {
57 clean_threshold: config.clean_threshold,
58 commit_threshold: config.commit_threshold,
59 commit_entries: config.commit_entries,
60 etl_config,
61 }
62 }
63}
64
65#[cfg(any(test, feature = "test-utils"))]
66impl AccountHashingStage {
67 pub fn seed<Tx: DbTx + DbTxMut + 'static, N: reth_provider::providers::ProviderNodeTypes>(
73 provider: &reth_provider::DatabaseProvider<Tx, N>,
74 opts: SeedOpts,
75 ) -> Result<Vec<(alloy_primitives::Address, Account)>, StageError>
76 where
77 N::Primitives: reth_primitives_traits::NodePrimitives<
78 Block = reth_ethereum_primitives::Block,
79 BlockHeader = reth_primitives_traits::Header,
80 >,
81 {
82 use alloy_primitives::U256;
83 use reth_db_api::models::AccountBeforeTx;
84 use reth_provider::{BlockWriter, StaticFileProviderFactory, StaticFileWriter};
85 use reth_testing_utils::{
86 generators,
87 generators::{random_block_range, random_eoa_accounts, BlockRangeParams},
88 };
89
90 let mut rng = generators::rng();
91
92 let blocks = random_block_range(
93 &mut rng,
94 opts.blocks.clone(),
95 BlockRangeParams { parent: Some(B256::ZERO), tx_count: opts.txs, ..Default::default() },
96 );
97
98 for block in blocks {
99 provider.insert_block(&block.try_recover().unwrap()).unwrap();
100 }
101 provider
102 .static_file_provider()
103 .latest_writer(reth_static_file_types::StaticFileSegment::Headers)
104 .unwrap()
105 .commit()
106 .unwrap();
107 let mut accounts = random_eoa_accounts(&mut rng, opts.accounts);
108 {
109 let mut account_cursor =
111 provider.tx_ref().cursor_write::<tables::PlainAccountState>()?;
112 accounts.sort_by_key(|a| a.0);
113 for (addr, acc) in &accounts {
114 account_cursor.append(*addr, acc)?;
115 }
116
117 let mut acc_changeset_cursor =
118 provider.tx_ref().cursor_write::<tables::AccountChangeSets>()?;
119 for (t, (addr, acc)) in opts.blocks.zip(&accounts) {
120 let Account { nonce, balance, .. } = acc;
121 let prev_acc = Account {
122 nonce: nonce - 1,
123 balance: balance - U256::ONE,
124 ..Default::default()
125 };
126 let acc_before_tx = AccountBeforeTx { address: *addr, info: Some(prev_acc) };
127 acc_changeset_cursor.append(t, &acc_before_tx)?;
128 }
129 }
130
131 Ok(accounts)
132 }
133}
134
135impl Default for AccountHashingStage {
136 fn default() -> Self {
137 Self {
138 clean_threshold: 500_000,
139 commit_threshold: 100_000,
140 commit_entries: 30_000_000,
141 etl_config: EtlConfig::default(),
142 }
143 }
144}
145
146impl<Provider> Stage<Provider> for AccountHashingStage
147where
148 Provider: DBProvider<Tx: DbTxMut>
149 + HashingWriter
150 + AccountExtReader
151 + StatsReader
152 + StorageSettingsCache,
153{
154 fn id(&self) -> StageId {
156 StageId::AccountHashing
157 }
158
159 fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
165 if input.target_reached() {
166 return Ok(ExecOutput::done(input.checkpoint()))
167 }
168
169 if provider.cached_storage_settings().use_hashed_state() {
172 return Ok(ExecOutput::done(input.checkpoint().with_block_number(input.target())));
173 }
174
175 let total_range = input.target() - input.checkpoint().block_number;
177 let from_block = input.next_block();
178
179 if total_range > self.clean_threshold || from_block == 1 {
180 let tx = provider.tx_ref();
185
186 tx.clear::<tables::HashedAccounts>()?;
188
189 let mut accounts_cursor = tx.cursor_read::<RawTable<tables::PlainAccountState>>()?;
190 let mut collector =
191 Collector::new(self.etl_config.file_size, self.etl_config.dir.clone());
192 let mut channels = Vec::with_capacity(MAXIMUM_CHANNELS);
193
194 for chunk in &accounts_cursor.walk(None)?.chunks(WORKER_CHUNK_SIZE) {
196 let chunk = chunk.collect::<Result<Vec<_>, _>>()?;
198 let (tx, rx) = mpsc::sync_channel(chunk.len());
199 channels.push(rx);
200 rayon::spawn(move || {
202 for (address, account) in chunk {
203 let address = address.key().unwrap();
204 let _ = tx.send((RawKey::new(keccak256(address)), account));
205 }
206 });
207
208 if !channels.is_empty() && channels.len().is_multiple_of(MAXIMUM_CHANNELS) {
210 collect(&mut channels, &mut collector)?;
211 }
212 }
213
214 collect(&mut channels, &mut collector)?;
215
216 let mut hashed_account_cursor =
217 tx.cursor_write::<RawTable<tables::HashedAccounts>>()?;
218
219 let total_hashes = collector.len();
220 let interval = (total_hashes / 10).max(1);
221 for (index, item) in collector.iter()?.enumerate() {
222 if index > 0 && index.is_multiple_of(interval) {
223 info!(
224 target: "sync::stages::hashing_account",
225 progress = %format_args!("{:.2}%", (index as f64 / total_hashes as f64) * 100.0),
226 "Inserting hashes"
227 );
228 }
229
230 let (key, value) = item?;
231 hashed_account_cursor
232 .append(RawKey::<B256>::from_vec(key), &RawValue::<Account>::from_vec(value))?;
233 }
234
235 let checkpoint = StageCheckpoint::new(input.target())
236 .with_account_hashing_stage_checkpoint(AccountHashingCheckpoint {
237 progress: stage_checkpoint_progress(provider)?,
238 ..Default::default()
239 });
240
241 Ok(ExecOutput::done(checkpoint))
242 } else {
243 let BlockRangeOutput { block_range, is_final_range } =
246 input.next_block_range_with_threshold(self.commit_threshold);
247 let (from_block, to_block) = block_range.into_inner();
248
249 let tx = provider.tx_ref();
250 let mut changeset_cursor = tx.cursor_read::<tables::AccountChangeSets>()?;
251 let mut changed = BTreeSet::new();
252 let mut total_entries = 0u64;
253 let mut last_block = from_block;
254
255 for entry in changeset_cursor.walk_range(from_block..=to_block)? {
256 let (block_number, account_before) = entry?;
257
258 if block_number != last_block && total_entries >= self.commit_entries {
262 break;
263 }
264
265 last_block = block_number;
266 changed.insert(account_before.address);
267 total_entries += 1;
268 }
269
270 let accounts = provider.basic_accounts(changed)?;
271 provider.insert_account_for_hashing(accounts)?;
272
273 let exhausted = total_entries < self.commit_entries;
274 let done = exhausted && is_final_range;
275 let progress_block = if exhausted { to_block } else { last_block };
276
277 let checkpoint = StageCheckpoint::new(progress_block)
278 .with_account_hashing_stage_checkpoint(AccountHashingCheckpoint {
279 progress: stage_checkpoint_progress(provider)?,
280 ..Default::default()
281 });
282
283 Ok(ExecOutput { checkpoint, done })
284 }
285 }
286
287 fn unwind(
289 &mut self,
290 provider: &Provider,
291 input: UnwindInput,
292 ) -> Result<UnwindOutput, StageError> {
293 let (range, unwind_progress, _) =
299 input.unwind_block_range_with_threshold(self.commit_threshold);
300
301 provider.unwind_account_hashing_range(range)?;
302
303 let mut stage_checkpoint =
304 input.checkpoint.account_hashing_stage_checkpoint().unwrap_or_default();
305
306 stage_checkpoint.progress = stage_checkpoint_progress(provider)?;
307
308 Ok(UnwindOutput {
309 checkpoint: StageCheckpoint::new(unwind_progress)
310 .with_account_hashing_stage_checkpoint(stage_checkpoint),
311 })
312 }
313}
314
315fn collect(
317 channels: &mut Vec<Receiver<(RawKey<B256>, RawValue<Account>)>>,
318 collector: &mut Collector<RawKey<B256>, RawValue<Account>>,
319) -> Result<(), StageError> {
320 for channel in channels.iter_mut() {
321 while let Ok((key, v)) = channel.recv() {
322 collector.insert(key, v)?;
323 }
324 }
325 info!(target: "sync::stages::hashing_account", "Hashed {} entries", collector.len());
326 channels.clear();
327 Ok(())
328}
329
330#[derive(Clone, Debug)]
342pub struct SeedOpts {
343 pub blocks: RangeInclusive<u64>,
345 pub accounts: usize,
347 pub txs: Range<u8>,
349}
350
351fn stage_checkpoint_progress(provider: &impl StatsReader) -> ProviderResult<EntitiesCheckpoint> {
352 Ok(EntitiesCheckpoint {
353 processed: provider.count_entries::<tables::HashedAccounts>()? as u64,
354 total: provider.count_entries::<tables::PlainAccountState>()? as u64,
355 })
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use crate::test_utils::{
362 stage_test_suite_ext, ExecuteStageTestRunner, StageTestRunner, TestRunnerError,
363 UnwindStageTestRunner,
364 };
365 use alloy_primitives::U256;
366 use assert_matches::assert_matches;
367 use reth_primitives_traits::Account;
368 use reth_provider::providers::StaticFileWriter;
369 use reth_stages_api::StageUnitCheckpoint;
370 use test_utils::*;
371
372 stage_test_suite_ext!(AccountHashingTestRunner, account_hashing);
373
374 #[tokio::test]
375 async fn execute_clean_account_hashing() {
376 let (previous_stage, stage_progress) = (20, 10);
377 let mut runner = AccountHashingTestRunner::default();
379 runner.set_clean_threshold(1);
380
381 let input = ExecInput {
382 target: Some(previous_stage),
383 checkpoint: Some(StageCheckpoint::new(stage_progress)),
384 };
385
386 runner.seed_execution(input).expect("failed to seed execution");
387
388 let rx = runner.execute(input);
389 let result = rx.await.unwrap();
390
391 assert_matches!(
392 result,
393 Ok(ExecOutput {
394 checkpoint: StageCheckpoint {
395 block_number,
396 stage_checkpoint: Some(StageUnitCheckpoint::Account(AccountHashingCheckpoint {
397 progress: EntitiesCheckpoint {
398 processed,
399 total,
400 },
401 ..
402 })),
403 },
404 done: true,
405 }) if block_number == previous_stage &&
406 processed == total &&
407 total == runner.db.count_entries::<tables::PlainAccountState>().unwrap() as u64
408 );
409
410 assert!(runner.validate_execution(input, result.ok()).is_ok(), "execution validation");
412 }
413
414 mod test_utils {
415 use super::*;
416 use crate::test_utils::TestStageDB;
417 use alloy_primitives::Address;
418 use reth_provider::DatabaseProviderFactory;
419
420 pub(crate) struct AccountHashingTestRunner {
421 pub(crate) db: TestStageDB,
422 commit_threshold: u64,
423 clean_threshold: u64,
424 commit_entries: u64,
425 etl_config: EtlConfig,
426 }
427
428 impl AccountHashingTestRunner {
429 pub(crate) fn set_clean_threshold(&mut self, threshold: u64) {
430 self.clean_threshold = threshold;
431 }
432
433 #[expect(dead_code)]
434 pub(crate) fn set_commit_threshold(&mut self, threshold: u64) {
435 self.commit_threshold = threshold;
436 }
437
438 pub(crate) fn check_hashed_accounts(&self) -> Result<(), TestRunnerError> {
441 self.db.query(|tx| {
442 let mut acc_cursor = tx.cursor_read::<tables::PlainAccountState>()?;
443 let mut hashed_acc_cursor = tx.cursor_read::<tables::HashedAccounts>()?;
444
445 while let Some((address, account)) = acc_cursor.next()? {
446 let hashed_addr = keccak256(address);
447 if let Some((_, acc)) = hashed_acc_cursor.seek_exact(hashed_addr)? {
448 assert_eq!(acc, account)
449 }
450 }
451 Ok(())
452 })?;
453
454 Ok(())
455 }
456
457 pub(crate) fn check_old_hashed_accounts(&self) -> Result<(), TestRunnerError> {
460 self.db.query(|tx| {
461 let mut acc_cursor = tx.cursor_read::<tables::PlainAccountState>()?;
462 let mut hashed_acc_cursor = tx.cursor_read::<tables::HashedAccounts>()?;
463
464 while let Some((address, account)) = acc_cursor.next()? {
465 let Account { nonce, balance, .. } = account;
466 let old_acc = Account {
467 nonce: nonce - 1,
468 balance: balance - U256::ONE,
469 ..Default::default()
470 };
471 let hashed_addr = keccak256(address);
472 if let Some((_, acc)) = hashed_acc_cursor.seek_exact(hashed_addr)? {
473 assert_eq!(acc, old_acc)
474 }
475 }
476 Ok(())
477 })?;
478
479 Ok(())
480 }
481 }
482
483 impl Default for AccountHashingTestRunner {
484 fn default() -> Self {
485 Self {
486 db: TestStageDB::default(),
487 commit_threshold: 1000,
488 clean_threshold: 1000,
489 commit_entries: u64::MAX,
490 etl_config: EtlConfig::default(),
491 }
492 }
493 }
494
495 impl StageTestRunner for AccountHashingTestRunner {
496 type S = AccountHashingStage;
497
498 fn db(&self) -> &TestStageDB {
499 &self.db
500 }
501
502 fn stage(&self) -> Self::S {
503 Self::S {
504 commit_threshold: self.commit_threshold,
505 clean_threshold: self.clean_threshold,
506 commit_entries: self.commit_entries,
507 etl_config: self.etl_config.clone(),
508 }
509 }
510 }
511
512 impl ExecuteStageTestRunner for AccountHashingTestRunner {
513 type Seed = Vec<(Address, Account)>;
514
515 fn seed_execution(&mut self, input: ExecInput) -> Result<Self::Seed, TestRunnerError> {
516 let provider = self.db.factory.database_provider_rw()?;
517 let res = Ok(AccountHashingStage::seed(
518 &provider,
519 SeedOpts { blocks: 0..=input.target(), accounts: 10, txs: 0..3 },
520 )
521 .unwrap());
522 provider.commit().expect("failed to commit");
523 res
524 }
525
526 fn validate_execution(
527 &self,
528 input: ExecInput,
529 output: Option<ExecOutput>,
530 ) -> Result<(), TestRunnerError> {
531 if let Some(output) = output {
532 let start_block = input.next_block();
533 let end_block = output.checkpoint.block_number;
534 if start_block > end_block {
535 return Ok(())
536 }
537 }
538 self.check_hashed_accounts()
539 }
540 }
541
542 impl UnwindStageTestRunner for AccountHashingTestRunner {
543 fn validate_unwind(&self, _input: UnwindInput) -> Result<(), TestRunnerError> {
544 self.check_old_hashed_accounts()
545 }
546 }
547 }
548}