Skip to main content

reth_trie_db/
prefix_set.rs

1use alloy_primitives::{
2    keccak256,
3    map::{AddressMap, AddressSet, B256Set},
4    BlockNumber,
5};
6use core::ops::RangeInclusive;
7use reth_db_api::{
8    cursor::DbCursorRO,
9    models::{AccountBeforeTx, BlockNumberAddress},
10    tables,
11    transaction::DbTx,
12};
13use reth_storage_api::{ChangeSetReader, DBProvider, StorageChangeSetReader};
14use reth_storage_errors::provider::ProviderError;
15use reth_trie::{
16    prefix_set::{PrefixSetMut, TriePrefixSets, TriePrefixSetsMut},
17    Nibbles,
18};
19
20/// Load prefix sets using a provider that implements [`ChangeSetReader`]. This function can read
21/// changesets from both static files and database.
22///
23/// The provider streams the changesets of the range. Addresses and storage slots are deduplicated
24/// across blocks before they are hashed.
25pub fn load_prefix_sets_with_provider<Provider>(
26    provider: &Provider,
27    range: RangeInclusive<BlockNumber>,
28) -> Result<TriePrefixSets, ProviderError>
29where
30    Provider: ChangeSetReader + StorageChangeSetReader + DBProvider,
31{
32    let mut account_addresses = AddressSet::default();
33    provider.for_each_account_changeset(range.clone(), |_, AccountBeforeTx { address, .. }| {
34        account_addresses.insert(address);
35    })?;
36
37    let mut prefix_sets = TriePrefixSetsMut::default();
38
39    // Sorted hashed addresses make the `HashedAccounts` cursor seek forward only.
40    let mut hashed_addresses = account_addresses.into_iter().map(keccak256).collect::<Vec<_>>();
41    hashed_addresses.sort_unstable();
42    let mut account_hashed_state_cursor =
43        provider.tx_ref().cursor_read::<tables::HashedAccounts>()?;
44    for hashed_address in hashed_addresses {
45        prefix_sets.account_prefix_set.insert(Nibbles::unpack(hashed_address));
46        if account_hashed_state_cursor.seek_exact(hashed_address)?.is_none() {
47            prefix_sets.destroyed_accounts.insert(hashed_address);
48        }
49    }
50
51    // Storage is scanned after the account loop, so the hashed addresses are already dropped.
52    let mut storage_slots = AddressMap::<B256Set>::default();
53    provider.for_each_storage_changeset(range, |BlockNumberAddress((_, address)), entry| {
54        storage_slots.entry(address).or_default().insert(entry.key);
55    })?;
56
57    // An address can also be in the account changesets. `PrefixSetMut::freeze` removes the
58    // duplicate account prefix.
59    for (address, slots) in storage_slots {
60        let hashed_address = keccak256(address);
61        prefix_sets.account_prefix_set.insert(Nibbles::unpack(hashed_address));
62        prefix_sets.storage_prefix_sets.insert(
63            hashed_address,
64            PrefixSetMut::from(slots.into_iter().map(|slot| Nibbles::unpack(keccak256(slot)))),
65        );
66    }
67
68    Ok(prefix_sets.freeze())
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use alloy_primitives::{Address, B256, U256};
75    use proptest::{collection::btree_set, prelude::*};
76    use reth_db_api::{
77        models::{StorageBeforeTx, StorageSettings},
78        transaction::DbTxMut,
79    };
80    use reth_primitives_traits::{Account, StorageEntry};
81    use reth_provider::{
82        test_utils::create_test_provider_factory, StaticFileProviderFactory, StaticFileSegment,
83        StaticFileWriter,
84    };
85    use reth_storage_api::StorageSettingsCache;
86    use std::collections::BTreeSet;
87
88    /// Changed addresses of each block, as indices.
89    type AccountBlocks = Vec<BTreeSet<u8>>;
90
91    /// Changed `(address, slot)` pairs of each block, as indices.
92    type StorageBlocks = Vec<BTreeSet<(u8, u8)>>;
93
94    fn assert_prefix_sets_eq(actual: &TriePrefixSets, expected: &TriePrefixSets) {
95        assert_eq!(actual.account_prefix_set.slice(), expected.account_prefix_set.slice());
96        assert_eq!(actual.destroyed_accounts, expected.destroyed_accounts);
97        assert_eq!(actual.storage_prefix_sets.len(), expected.storage_prefix_sets.len());
98        for (hashed_address, expected_set) in &expected.storage_prefix_sets {
99            assert_eq!(actual.storage_prefix_sets[hashed_address].slice(), expected_set.slice());
100        }
101    }
102
103    /// Writes the blocks as v1 or v2 changesets plus `HashedAccounts` rows for `existing`, then
104    /// compares the loaded prefix sets with sets built straight from the fixture over the full
105    /// range, over a range without the first block, and over a range that ends past both tips.
106    /// The two tables can end at different blocks, so on v2 the segments have different tips.
107    fn check_against_fixture(
108        account_blocks: &AccountBlocks,
109        storage_blocks: &StorageBlocks,
110        existing: &BTreeSet<u8>,
111        v2: bool,
112    ) {
113        let address = |index: u8| Address::with_last_byte(index);
114        let slot = |index: u8| B256::with_last_byte(index);
115
116        let factory = create_test_provider_factory();
117        factory.set_storage_settings_cache(if v2 {
118            StorageSettings::v2()
119        } else {
120            StorageSettings::v1()
121        });
122
123        let provider = factory.provider_rw().unwrap();
124        for &index in existing {
125            provider
126                .tx_ref()
127                .put::<tables::HashedAccounts>(keccak256(address(index)), Account::default())
128                .unwrap();
129        }
130        if v2 {
131            let static_file_provider = factory.static_file_provider();
132            let mut account_writer =
133                static_file_provider.latest_writer(StaticFileSegment::AccountChangeSets).unwrap();
134            let mut storage_writer =
135                static_file_provider.latest_writer(StaticFileSegment::StorageChangeSets).unwrap();
136            for (block_number, accounts) in account_blocks.iter().enumerate() {
137                account_writer
138                    .append_account_changeset(
139                        accounts
140                            .iter()
141                            .map(|&a| AccountBeforeTx { address: address(a), info: None })
142                            .collect(),
143                        block_number as BlockNumber,
144                    )
145                    .unwrap();
146            }
147            for (block_number, slots) in storage_blocks.iter().enumerate() {
148                storage_writer
149                    .append_storage_changeset(
150                        slots
151                            .iter()
152                            .map(|&(a, s)| StorageBeforeTx {
153                                address: address(a),
154                                key: slot(s),
155                                value: U256::ZERO,
156                            })
157                            .collect(),
158                        block_number as BlockNumber,
159                    )
160                    .unwrap();
161            }
162            account_writer.commit().unwrap();
163            storage_writer.commit().unwrap();
164        } else {
165            for (block_number, accounts) in account_blocks.iter().enumerate() {
166                for &a in accounts {
167                    provider
168                        .tx_ref()
169                        .put::<tables::AccountChangeSets>(
170                            block_number as BlockNumber,
171                            AccountBeforeTx { address: address(a), info: None },
172                        )
173                        .unwrap();
174                }
175            }
176            for (block_number, slots) in storage_blocks.iter().enumerate() {
177                for &(a, s) in slots {
178                    provider
179                        .tx_ref()
180                        .put::<tables::StorageChangeSets>(
181                            BlockNumberAddress((block_number as BlockNumber, address(a))),
182                            StorageEntry { key: slot(s), value: U256::ZERO },
183                        )
184                        .unwrap();
185                }
186            }
187        }
188        provider.commit().unwrap();
189
190        let provider = factory.provider().unwrap();
191        let last_block = account_blocks.len().max(storage_blocks.len()) as BlockNumber - 1;
192        for range in [0..=last_block, 1.min(last_block)..=last_block, 0..=last_block + 2] {
193            let in_range = |block_number: usize| range.contains(&(block_number as BlockNumber));
194            let mut expected = TriePrefixSetsMut::default();
195            for (_, accounts) in account_blocks.iter().enumerate().filter(|(n, _)| in_range(*n)) {
196                for &a in accounts {
197                    let hashed_address = keccak256(address(a));
198                    expected.account_prefix_set.insert(Nibbles::unpack(hashed_address));
199                    if !existing.contains(&a) {
200                        expected.destroyed_accounts.insert(hashed_address);
201                    }
202                }
203            }
204            for (_, slots) in storage_blocks.iter().enumerate().filter(|(n, _)| in_range(*n)) {
205                for &(a, s) in slots {
206                    let hashed_address = keccak256(address(a));
207                    expected.account_prefix_set.insert(Nibbles::unpack(hashed_address));
208                    expected
209                        .storage_prefix_sets
210                        .entry(hashed_address)
211                        .or_default()
212                        .insert(Nibbles::unpack(keccak256(slot(s))));
213                }
214            }
215
216            let actual = load_prefix_sets_with_provider(&provider, range).unwrap();
217            assert_prefix_sets_eq(&actual, &expected.freeze());
218        }
219    }
220
221    // Few distinct indices, so addresses and slots repeat across blocks.
222    fn account_blocks_strategy() -> impl Strategy<Value = AccountBlocks> {
223        prop::collection::vec(btree_set(0u8..12, 0..6), 1..12)
224    }
225
226    fn storage_blocks_strategy() -> impl Strategy<Value = StorageBlocks> {
227        prop::collection::vec(btree_set((0u8..12, 0u8..6), 0..10), 1..12)
228    }
229
230    proptest! {
231        #![proptest_config(ProptestConfig::with_cases(32))]
232
233        #[test]
234        fn matches_fixture_v1(
235            account_blocks in account_blocks_strategy(),
236            storage_blocks in storage_blocks_strategy(),
237            existing in btree_set(0u8..12, 0..12),
238        ) {
239            check_against_fixture(&account_blocks, &storage_blocks, &existing, false);
240        }
241
242        #[test]
243        fn matches_fixture_v2(
244            account_blocks in account_blocks_strategy(),
245            storage_blocks in storage_blocks_strategy(),
246            existing in btree_set(0u8..12, 0..12),
247        ) {
248            check_against_fixture(&account_blocks, &storage_blocks, &existing, true);
249        }
250    }
251}