reth_storage_api/trie.rs
1use alloc::{boxed::Box, vec::Vec};
2use alloy_primitives::{Address, Bytes, B256, U256};
3use reth_primitives_traits::Account;
4use reth_storage_errors::provider::ProviderResult;
5use reth_trie_common::{
6 updates::{StorageTrieUpdatesSorted, TrieUpdates, TrieUpdatesSorted},
7 AccountProof, DecodedMultiProofV2, ExecutionWitnessMode, HashedPostState, HashedStorage,
8 MultiProofTargetsV2, StorageMultiProof, StorageProof,
9};
10
11/// A type that can compute the state root of a given post state.
12#[auto_impl::auto_impl(&, Box, Arc)]
13pub trait StateRootProvider {
14 /// Returns the state root of the execution state on top of the current state.
15 ///
16 /// # Note
17 ///
18 /// It is recommended to provide a different implementation from
19 /// `state_root_with_updates` since it affects the memory usage during state root
20 /// computation.
21 fn state_root(&self, hashed_state: HashedPostState) -> ProviderResult<B256>;
22
23 /// Returns the state root of the `HashedPostState` on top of the current state with trie
24 /// updates to be committed to the database.
25 fn state_root_with_updates(
26 &self,
27 hashed_state: HashedPostState,
28 ) -> ProviderResult<(B256, TrieUpdates)>;
29}
30
31/// A type that can compute the storage root for a given account.
32#[auto_impl::auto_impl(&, Box, Arc)]
33pub trait StorageRootProvider {
34 /// Returns the storage root of the `HashedStorage` for target address on top of the current
35 /// state.
36 fn storage_root(&self, address: Address, hashed_storage: HashedStorage)
37 -> ProviderResult<B256>;
38
39 /// Returns the storage proof of the `HashedStorage` for target slot on top of the current
40 /// state.
41 fn storage_proof(
42 &self,
43 address: Address,
44 slot: B256,
45 hashed_storage: HashedStorage,
46 ) -> ProviderResult<StorageProof>;
47
48 /// Returns the storage multiproof for target slots.
49 fn storage_multiproof(
50 &self,
51 address: Address,
52 slots: &[B256],
53 hashed_storage: HashedStorage,
54 ) -> ProviderResult<StorageMultiProof>;
55}
56
57/// A type that can iterate over consecutive hashed accounts and storage slots, and generate
58/// boundary proofs for them, for serving `snap/2` (EIP-8189) `GetAccountRange`/`GetStorageRanges`
59/// requests. Hash-native throughout, unlike [`StorageRootProvider`].
60#[auto_impl::auto_impl(&, Box, Arc)]
61pub trait StateRangeProvider {
62 /// Returns accounts (hash, account) in `[start, limit]`, bounded by `response_bytes`.
63 fn account_range(
64 &self,
65 start: B256,
66 limit: B256,
67 response_bytes: usize,
68 ) -> RangeResult<(B256, Account)>;
69
70 /// Returns the storage root for `hashed_address` without needing its address preimage.
71 fn storage_root_by_hash(&self, hashed_address: B256) -> ProviderResult<B256>;
72
73 /// Same as [`Self::account_range`], but for the storage slots of `hashed_address`.
74 ///
75 /// Returns `None` if `hashed_address` isn't present in the account trie at the pinned state
76 /// root, distinct from an account that is present but has no storage.
77 fn storage_range(
78 &self,
79 hashed_address: B256,
80 start: B256,
81 limit: B256,
82 response_bytes: usize,
83 ) -> StorageRangeResult;
84
85 /// Returns an account-trie boundary proof for the already-hashed `keys`.
86 fn account_range_proof(&self, keys: &[B256]) -> ProviderResult<Vec<Bytes>>;
87
88 /// Same as [`Self::account_range_proof`], but for the storage trie of `hashed_address`.
89 fn storage_range_proof(
90 &self,
91 hashed_address: B256,
92 keys: &[B256],
93 ) -> ProviderResult<Vec<Bytes>>;
94}
95
96/// A type that resolves retained state roots into reusable state range views.
97#[auto_impl::auto_impl(&, Arc)]
98pub trait StateRangeProviderFactory {
99 /// Returns a view pinned to `state_root`, or `None` if that root is not retained.
100 fn state_range_provider(&self, state_root: B256) -> ProviderResult<Option<StateRangeView>>;
101}
102
103/// A range query's items and why the range ended where it did.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct RangeResponse<T> {
106 /// The items found within the requested range, in ascending key order.
107 pub items: Vec<T>,
108 /// Why `items` doesn't necessarily continue past its last entry.
109 pub end: RangeEnd,
110}
111
112/// Why a range query stopped before the caller-requested `limit`.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum RangeEnd {
115 /// The cursor ran out of entries: `items` covers everything from `start` onward.
116 Exhausted,
117 /// The last returned item's key reached or passed the requested `limit`.
118 HashLimit,
119 /// `response_bytes` was exceeded before `limit` was reached.
120 ByteLimit,
121}
122
123/// Result of a [`StateRangeProvider`] range query.
124pub type RangeResult<T> = ProviderResult<RangeResponse<T>>;
125
126/// Result of a [`StateRangeProvider::storage_range`] query: `None` if the account itself isn't
127/// present in the trie at the pinned state root.
128pub type StorageRangeResult = ProviderResult<Option<RangeResponse<(B256, U256)>>>;
129
130/// A reusable state range view resolved for a specific state root.
131pub type StateRangeView = Box<dyn StateRangeProvider + Send + 'static>;
132
133/// A type that can generate state proofs and execution witnesses.
134#[auto_impl::auto_impl(&, Box, Arc)]
135pub trait StateProofProvider {
136 /// Get account and storage proofs for the target keys against the provider's state.
137 fn proof(&self, address: Address, slots: &[B256]) -> ProviderResult<AccountProof>;
138
139 /// Generate a V2 decoded multiproof for target hashed accounts and storage slots against the
140 /// provider's state.
141 ///
142 /// A storage address with no slot targets requests its storage root node. Empty targets return
143 /// an empty proof.
144 ///
145 /// Set `requires_masks` when the hash and tree masks of returned branch nodes must match the
146 /// stored trie, as required to produce trie updates from them. Otherwise node hashes are still
147 /// exact, but masks are not guaranteed to match.
148 fn multiproof_v2(
149 &self,
150 targets: MultiProofTargetsV2,
151 requires_masks: bool,
152 ) -> ProviderResult<DecodedMultiProofV2>;
153
154 /// Get a trie witness for applying the target state on top of the provider's state.
155 fn witness(
156 &self,
157 target: HashedPostState,
158 mode: ExecutionWitnessMode,
159 ) -> ProviderResult<Vec<Bytes>>;
160}
161
162/// Trie Writer
163#[auto_impl::auto_impl(&, Arc, Box)]
164pub trait TrieWriter: Send {
165 /// Writes trie updates to the database.
166 ///
167 /// Returns the number of entries modified.
168 fn write_trie_updates(&self, trie_updates: TrieUpdates) -> ProviderResult<usize> {
169 self.write_trie_updates_sorted(&trie_updates.into_sorted())
170 }
171
172 /// Writes trie updates to the database with already sorted updates.
173 ///
174 /// Returns the number of entries modified.
175 fn write_trie_updates_sorted(&self, trie_updates: &TrieUpdatesSorted) -> ProviderResult<usize>;
176}
177
178/// Storage Trie Writer
179#[auto_impl::auto_impl(&, Arc, Box)]
180pub trait StorageTrieWriter: Send {
181 /// Writes storage trie updates from the given storage trie map with already sorted updates.
182 ///
183 /// Expects the storage trie updates to already be sorted by the hashed address key.
184 ///
185 /// Returns the number of entries modified.
186 fn write_storage_trie_updates_sorted<'a>(
187 &self,
188 storage_tries: impl Iterator<Item = (&'a B256, &'a StorageTrieUpdatesSorted)>,
189 ) -> ProviderResult<usize>;
190}