Skip to main content

reth_trie/proof/
mod.rs

1use crate::{
2    hashed_cursor::{HashedCursorFactory, HashedStorageCursor},
3    node_iter::{TrieElement, TrieNodeIter},
4    prefix_set::{PrefixSetMut, TriePrefixSetsMut},
5    trie_cursor::TrieCursorFactory,
6    walker::TrieWalker,
7    HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,
8};
9use alloy_primitives::{
10    keccak256,
11    map::{B256Map, B256Set, HashSet},
12    Address, B256,
13};
14use alloy_rlp::{BufMut, Encodable};
15use alloy_trie::proof::AddedRemovedKeys;
16use reth_execution_errors::trie::StateProofError;
17use reth_trie_common::{
18    proof::ProofRetainer, AccountProof, BranchNodeMasks, BranchNodeMasksMap, MultiProof,
19    MultiProofTargets, StorageMultiProof,
20};
21
22/// A struct for generating merkle proofs.
23///
24/// Proof generator adds the target address and slots to the prefix set, enables the proof retainer
25/// on the hash builder and follows the same algorithm as the state root calculator.
26/// See `StateRoot::root` for more info.
27#[derive(Debug)]
28pub struct Proof<T, H, K = AddedRemovedKeys> {
29    /// The factory for traversing trie nodes.
30    trie_cursor_factory: T,
31    /// The factory for hashed cursors.
32    hashed_cursor_factory: H,
33    /// A set of prefix sets that have changes.
34    prefix_sets: TriePrefixSetsMut,
35    /// Flag indicating whether to include branch node masks in the proof.
36    collect_branch_node_masks: bool,
37    /// Added and removed keys for proof retention.
38    added_removed_keys: Option<K>,
39}
40
41impl<T, H> Proof<T, H> {
42    /// Create a new [`Proof`] instance.
43    pub fn new(t: T, h: H) -> Self {
44        Self {
45            trie_cursor_factory: t,
46            hashed_cursor_factory: h,
47            prefix_sets: TriePrefixSetsMut::default(),
48            collect_branch_node_masks: false,
49            added_removed_keys: None,
50        }
51    }
52}
53
54impl<T, H, K> Proof<T, H, K> {
55    /// Set the prefix sets. They have to be mutable in order to allow extension with proof target.
56    pub fn with_prefix_sets_mut(mut self, prefix_sets: TriePrefixSetsMut) -> Self {
57        self.prefix_sets = prefix_sets;
58        self
59    }
60
61    /// Set the flag indicating whether to include branch node masks in the proof.
62    pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self {
63        self.collect_branch_node_masks = branch_node_masks;
64        self
65    }
66
67    /// Configures the proof to retain certain nodes which would otherwise fall outside the target
68    /// set, when those nodes might be required to calculate the state root when keys have been
69    /// added or removed to the trie.
70    ///
71    /// If None is given then retention of extra proofs is disabled.
72    pub fn with_added_removed_keys<K2>(self, added_removed_keys: Option<K2>) -> Proof<T, H, K2> {
73        Proof {
74            trie_cursor_factory: self.trie_cursor_factory,
75            hashed_cursor_factory: self.hashed_cursor_factory,
76            prefix_sets: self.prefix_sets,
77            collect_branch_node_masks: self.collect_branch_node_masks,
78            added_removed_keys,
79        }
80    }
81}
82
83impl<T, H, K> Proof<T, H, K>
84where
85    T: TrieCursorFactory + Clone,
86    H: HashedCursorFactory + Clone,
87    K: AsRef<AddedRemovedKeys>,
88{
89    /// Generate an account proof from intermediate nodes.
90    pub fn account_proof(
91        self,
92        address: Address,
93        slots: &[B256],
94    ) -> Result<AccountProof, StateProofError> {
95        Ok(self
96            .multiproof(MultiProofTargets::from_iter([(
97                keccak256(address),
98                slots.iter().map(keccak256).collect(),
99            )]))?
100            .account_proof(address, slots)?)
101    }
102
103    /// Generate a state multiproof according to specified targets.
104    pub fn multiproof(
105        mut self,
106        mut targets: MultiProofTargets,
107    ) -> Result<MultiProof, StateProofError> {
108        let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;
109        let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;
110
111        // Create the walker.
112        let mut prefix_set = self.prefix_sets.account_prefix_set.clone();
113        prefix_set.extend_keys(targets.keys().map(Nibbles::unpack));
114        let walker =
115            TrieWalker::<_, AddedRemovedKeys>::state_trie(trie_cursor, prefix_set.freeze())?
116                .with_added_removed_keys(self.added_removed_keys.as_ref());
117
118        // Create a hash builder to rebuild the root node since it is not available in the database.
119        let retainer: ProofRetainer = targets.keys().map(Nibbles::unpack).collect();
120        let retainer = retainer.with_added_removed_keys(self.added_removed_keys.as_ref());
121        let mut hash_builder = HashBuilder::default()
122            .with_proof_retainer(retainer)
123            .with_updates(self.collect_branch_node_masks);
124
125        // Initialize all storage multiproofs as empty.
126        // Storage multiproofs for non-empty tries will be overwritten if necessary.
127        let mut storages: B256Map<_> =
128            targets.keys().map(|key| (*key, StorageMultiProof::empty())).collect();
129        let mut account_rlp = Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE);
130        let mut account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);
131        while let Some(account_node) = account_node_iter.try_next()? {
132            match account_node {
133                TrieElement::Branch(node) => {
134                    hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);
135                }
136                TrieElement::Leaf(hashed_address, account) => {
137                    let proof_targets = targets.remove(&hashed_address);
138                    let leaf_is_proof_target = proof_targets.is_some();
139                    let collect_storage_masks =
140                        self.collect_branch_node_masks && leaf_is_proof_target;
141                    let storage_prefix_set = self
142                        .prefix_sets
143                        .storage_prefix_sets
144                        .remove(&hashed_address)
145                        .unwrap_or_default();
146                    let storage_multiproof = StorageProof::new_hashed(
147                        self.trie_cursor_factory.clone(),
148                        self.hashed_cursor_factory.clone(),
149                        hashed_address,
150                    )
151                    .with_prefix_set_mut(storage_prefix_set)
152                    .with_branch_node_masks(collect_storage_masks)
153                    .storage_multiproof(proof_targets.unwrap_or_default())?;
154
155                    // Encode account
156                    account_rlp.clear();
157                    let account = account.into_trie_account(storage_multiproof.root);
158                    account.encode(&mut account_rlp as &mut dyn BufMut);
159
160                    hash_builder.add_leaf(Nibbles::unpack(hashed_address), &account_rlp);
161
162                    // We might be adding leaves that are not necessarily our proof targets.
163                    if leaf_is_proof_target {
164                        // Overwrite storage multiproof.
165                        storages.insert(hashed_address, storage_multiproof);
166                    }
167                }
168            }
169        }
170        let _ = hash_builder.root();
171        let account_subtree = hash_builder.take_proof_nodes();
172        let branch_node_masks = if self.collect_branch_node_masks {
173            let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default();
174            updated_branch_nodes
175                .into_iter()
176                .map(|(path, node)| {
177                    (path, BranchNodeMasks { hash_mask: node.hash_mask, tree_mask: node.tree_mask })
178                })
179                .collect()
180        } else {
181            BranchNodeMasksMap::default()
182        };
183
184        Ok(MultiProof { account_subtree, branch_node_masks, storages })
185    }
186}
187
188/// Generates storage merkle proofs.
189#[derive(Debug)]
190pub struct StorageProof<T, H, K = AddedRemovedKeys> {
191    /// The factory for traversing trie nodes.
192    trie_cursor_factory: T,
193    /// The factory for hashed cursors.
194    hashed_cursor_factory: H,
195    /// The hashed address of an account.
196    hashed_address: B256,
197    /// The set of storage slot prefixes that have changed.
198    prefix_set: PrefixSetMut,
199    /// Flag indicating whether to include branch node masks in the proof.
200    collect_branch_node_masks: bool,
201    /// Provided by the user to give the necessary context to retain extra proofs.
202    added_removed_keys: Option<K>,
203}
204
205impl<T, H> StorageProof<T, H> {
206    /// Create a new [`StorageProof`] instance.
207    pub fn new(t: T, h: H, address: Address) -> Self {
208        Self::new_hashed(t, h, keccak256(address))
209    }
210
211    /// Create a new [`StorageProof`] instance with hashed address.
212    pub fn new_hashed(t: T, h: H, hashed_address: B256) -> Self {
213        Self {
214            trie_cursor_factory: t,
215            hashed_cursor_factory: h,
216            hashed_address,
217            prefix_set: PrefixSetMut::default(),
218            collect_branch_node_masks: false,
219            added_removed_keys: None,
220        }
221    }
222}
223
224impl<T, H, K> StorageProof<T, H, K> {
225    /// Set the changed prefixes.
226    pub fn with_prefix_set_mut(mut self, prefix_set: PrefixSetMut) -> Self {
227        self.prefix_set = prefix_set;
228        self
229    }
230
231    /// Set the flag indicating whether to include branch node masks in the proof.
232    pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self {
233        self.collect_branch_node_masks = branch_node_masks;
234        self
235    }
236
237    /// Configures the retainer to retain proofs for certain nodes which would otherwise fall
238    /// outside the target set, when those nodes might be required to calculate the state root when
239    /// keys have been added or removed to the trie.
240    ///
241    /// If None is given then retention of extra proofs is disabled.
242    pub fn with_added_removed_keys<K2>(
243        self,
244        added_removed_keys: Option<K2>,
245    ) -> StorageProof<T, H, K2> {
246        StorageProof {
247            trie_cursor_factory: self.trie_cursor_factory,
248            hashed_cursor_factory: self.hashed_cursor_factory,
249            hashed_address: self.hashed_address,
250            prefix_set: self.prefix_set,
251            collect_branch_node_masks: self.collect_branch_node_masks,
252            added_removed_keys,
253        }
254    }
255}
256
257impl<T, H, K> StorageProof<T, H, K>
258where
259    T: TrieCursorFactory,
260    H: HashedCursorFactory,
261    K: AsRef<AddedRemovedKeys>,
262{
263    /// Generate an account proof from intermediate nodes.
264    pub fn storage_proof(
265        self,
266        slot: B256,
267    ) -> Result<reth_trie_common::StorageProof, StateProofError> {
268        let targets = HashSet::from_iter([keccak256(slot)]);
269        Ok(self.storage_multiproof(targets)?.storage_proof(slot)?)
270    }
271
272    /// Generate storage proof.
273    pub fn storage_multiproof(
274        self,
275        targets: B256Set,
276    ) -> Result<StorageMultiProof, StateProofError> {
277        let mut hashed_storage_cursor =
278            self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;
279
280        // short circuit on empty storage
281        if hashed_storage_cursor.is_storage_empty()? {
282            return Ok(StorageMultiProof::empty())
283        }
284
285        let target_nibbles = targets.into_iter().map(Nibbles::unpack).collect::<Vec<_>>();
286        let mut prefix_set = self.prefix_set;
287        prefix_set.extend_keys(target_nibbles.iter().copied());
288
289        let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;
290
291        let walker = TrieWalker::<_>::storage_trie(trie_cursor, prefix_set.freeze())?
292            .with_added_removed_keys(self.added_removed_keys.as_ref());
293
294        let retainer = ProofRetainer::from_iter(target_nibbles)
295            .with_added_removed_keys(self.added_removed_keys.as_ref());
296        let mut hash_builder = HashBuilder::default()
297            .with_proof_retainer(retainer)
298            .with_updates(self.collect_branch_node_masks);
299        let mut storage_node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);
300        while let Some(node) = storage_node_iter.try_next()? {
301            match node {
302                TrieElement::Branch(node) => {
303                    hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);
304                }
305                TrieElement::Leaf(hashed_slot, value) => {
306                    hash_builder.add_leaf(
307                        Nibbles::unpack(hashed_slot),
308                        alloy_rlp::encode_fixed_size(&value).as_ref(),
309                    );
310                }
311            }
312        }
313
314        let root = hash_builder.root();
315        let subtree = hash_builder.take_proof_nodes();
316        let branch_node_masks = if self.collect_branch_node_masks {
317            let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default();
318            updated_branch_nodes
319                .into_iter()
320                .map(|(path, node)| {
321                    (path, BranchNodeMasks { hash_mask: node.hash_mask, tree_mask: node.tree_mask })
322                })
323                .collect()
324        } else {
325            BranchNodeMasksMap::default()
326        };
327
328        Ok(StorageMultiProof { root, subtree, branch_node_masks })
329    }
330}