Skip to main content

reth_trie/proof/
mod.rs

1use crate::{
2    hashed_cursor::{
3        HashedCursorFactory, HashedCursorMetricsCache, HashedStorageCursor,
4        InstrumentedHashedCursor,
5    },
6    node_iter::{TrieElement, TrieNodeIter},
7    prefix_set::{PrefixSetMut, TriePrefixSetsMut},
8    proof_v2::{self, SyncAccountValueEncoder},
9    trie_cursor::{InstrumentedTrieCursor, TrieCursorFactory, TrieCursorMetricsCache},
10    walker::TrieWalker,
11    HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,
12};
13use alloy_primitives::{
14    keccak256,
15    map::{B256Map, B256Set, HashSet},
16    Address, B256,
17};
18use alloy_rlp::{BufMut, Encodable};
19use alloy_trie::proof::AddedRemovedKeys;
20use reth_execution_errors::trie::StateProofError;
21use reth_trie_common::{
22    proof::ProofRetainer, AccountProof, BranchNodeMasks, BranchNodeMasksMap, DecodedMultiProofV2,
23    MultiProof, MultiProofTargets, MultiProofTargetsV2, StorageMultiProof,
24};
25
26mod trie_node;
27pub use trie_node::*;
28
29/// A struct for generating merkle proofs.
30///
31/// Proof generator adds the target address and slots to the prefix set, enables the proof retainer
32/// on the hash builder and follows the same algorithm as the state root calculator.
33/// See `StateRoot::root` for more info.
34#[derive(Debug)]
35pub struct Proof<T, H, K = AddedRemovedKeys> {
36    /// The factory for traversing trie nodes.
37    trie_cursor_factory: T,
38    /// The factory for hashed cursors.
39    hashed_cursor_factory: H,
40    /// A set of prefix sets that have changes.
41    prefix_sets: TriePrefixSetsMut,
42    /// Flag indicating whether to include branch node masks in the proof.
43    collect_branch_node_masks: bool,
44    /// Added and removed keys for proof retention.
45    added_removed_keys: Option<K>,
46}
47
48impl<T, H> Proof<T, H> {
49    /// Create a new [`Proof`] instance.
50    pub fn new(t: T, h: H) -> Self {
51        Self {
52            trie_cursor_factory: t,
53            hashed_cursor_factory: h,
54            prefix_sets: TriePrefixSetsMut::default(),
55            collect_branch_node_masks: false,
56            added_removed_keys: None,
57        }
58    }
59}
60
61impl<T, H, K> Proof<T, H, K> {
62    /// Set the trie cursor factory.
63    pub fn with_trie_cursor_factory<TF>(self, trie_cursor_factory: TF) -> Proof<TF, H, K> {
64        Proof {
65            trie_cursor_factory,
66            hashed_cursor_factory: self.hashed_cursor_factory,
67            prefix_sets: self.prefix_sets,
68            collect_branch_node_masks: self.collect_branch_node_masks,
69            added_removed_keys: self.added_removed_keys,
70        }
71    }
72
73    /// Set the hashed cursor factory.
74    pub fn with_hashed_cursor_factory<HF>(self, hashed_cursor_factory: HF) -> Proof<T, HF, K> {
75        Proof {
76            trie_cursor_factory: self.trie_cursor_factory,
77            hashed_cursor_factory,
78            prefix_sets: self.prefix_sets,
79            collect_branch_node_masks: self.collect_branch_node_masks,
80            added_removed_keys: self.added_removed_keys,
81        }
82    }
83
84    /// Set the prefix sets. They have to be mutable in order to allow extension with proof target.
85    pub fn with_prefix_sets_mut(mut self, prefix_sets: TriePrefixSetsMut) -> Self {
86        self.prefix_sets = prefix_sets;
87        self
88    }
89
90    /// Set the flag indicating whether to include branch node masks in the proof.
91    pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self {
92        self.collect_branch_node_masks = branch_node_masks;
93        self
94    }
95
96    /// Configures the proof to retain certain nodes which would otherwise fall outside the target
97    /// set, when those nodes might be required to calculate the state root when keys have been
98    /// added or removed to the trie.
99    ///
100    /// If None is given then retention of extra proofs is disabled.
101    pub fn with_added_removed_keys<K2>(self, added_removed_keys: Option<K2>) -> Proof<T, H, K2> {
102        Proof {
103            trie_cursor_factory: self.trie_cursor_factory,
104            hashed_cursor_factory: self.hashed_cursor_factory,
105            prefix_sets: self.prefix_sets,
106            collect_branch_node_masks: self.collect_branch_node_masks,
107            added_removed_keys,
108        }
109    }
110
111    /// Get a reference to the trie cursor factory.
112    pub const fn trie_cursor_factory(&self) -> &T {
113        &self.trie_cursor_factory
114    }
115
116    /// Get a reference to the hashed cursor factory.
117    pub const fn hashed_cursor_factory(&self) -> &H {
118        &self.hashed_cursor_factory
119    }
120}
121
122impl<T, H, K> Proof<T, H, K>
123where
124    T: TrieCursorFactory + Clone,
125    H: HashedCursorFactory + Clone,
126    K: AsRef<AddedRemovedKeys>,
127{
128    /// Generate an account proof from intermediate nodes.
129    pub fn account_proof(
130        self,
131        address: Address,
132        slots: &[B256],
133    ) -> Result<AccountProof, StateProofError> {
134        Ok(self
135            .multiproof(MultiProofTargets::from_iter([(
136                keccak256(address),
137                slots.iter().map(keccak256).collect(),
138            )]))?
139            .account_proof(address, slots)?)
140    }
141
142    /// Generate a state multiproof using the V2 proof calculator.
143    ///
144    /// This method uses `ProofCalculator` with `SyncAccountValueEncoder` for account proofs
145    /// and `StorageProofCalculator` for storage proofs.
146    pub fn multiproof_v2(
147        self,
148        targets: MultiProofTargetsV2,
149    ) -> Result<DecodedMultiProofV2, StateProofError> {
150        let MultiProofTargetsV2 { mut account_targets, storage_targets } = targets;
151
152        // Compute account proofs using the V2 proof calculator with sync account encoding.
153        let account_trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;
154        let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;
155        let mut account_value_encoder = SyncAccountValueEncoder::new(
156            self.trie_cursor_factory.clone(),
157            self.hashed_cursor_factory.clone(),
158        );
159        let mut account_calculator =
160            proof_v2::ProofCalculator::new(account_trie_cursor, hashed_account_cursor);
161        let account_proofs =
162            account_calculator.proof(&mut account_value_encoder, &mut account_targets)?;
163
164        // Compute storage proofs for each targeted account.
165        let mut storage_proofs =
166            B256Map::with_capacity_and_hasher(storage_targets.len(), Default::default());
167        for (hashed_address, mut targets) in storage_targets {
168            let storage_trie_cursor =
169                self.trie_cursor_factory.storage_trie_cursor(hashed_address)?;
170            let hashed_storage_cursor =
171                self.hashed_cursor_factory.hashed_storage_cursor(hashed_address)?;
172            let mut storage_calculator = proof_v2::StorageProofCalculator::new_storage(
173                storage_trie_cursor,
174                hashed_storage_cursor,
175            );
176            let proofs = storage_calculator.storage_proof(hashed_address, &mut targets)?;
177            storage_proofs.insert(hashed_address, proofs);
178        }
179
180        Ok(DecodedMultiProofV2 { account_proofs, storage_proofs })
181    }
182
183    /// Generate a state multiproof according to specified targets.
184    pub fn multiproof(
185        mut self,
186        mut targets: MultiProofTargets,
187    ) -> Result<MultiProof, StateProofError> {
188        let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;
189        let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;
190
191        // Create the walker.
192        let mut prefix_set = self.prefix_sets.account_prefix_set.clone();
193        prefix_set.extend_keys(targets.keys().map(Nibbles::unpack));
194        let walker =
195            TrieWalker::<_, AddedRemovedKeys>::state_trie(trie_cursor, prefix_set.freeze())
196                .with_added_removed_keys(self.added_removed_keys.as_ref());
197
198        // Create a hash builder to rebuild the root node since it is not available in the database.
199        let retainer: ProofRetainer = targets.keys().map(Nibbles::unpack).collect();
200        let retainer = retainer.with_added_removed_keys(self.added_removed_keys.as_ref());
201        let mut hash_builder = HashBuilder::default()
202            .with_proof_retainer(retainer)
203            .with_updates(self.collect_branch_node_masks);
204
205        // Initialize all storage multiproofs as empty.
206        // Storage multiproofs for non-empty tries will be overwritten if necessary.
207        let mut storages: B256Map<_> =
208            targets.keys().map(|key| (*key, StorageMultiProof::empty())).collect();
209        let mut account_rlp = Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE);
210        let mut account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);
211        while let Some(account_node) = account_node_iter.try_next()? {
212            match account_node {
213                TrieElement::Branch(node) => {
214                    hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);
215                }
216                TrieElement::Leaf(hashed_address, account) => {
217                    let proof_targets = targets.remove(&hashed_address);
218                    let leaf_is_proof_target = proof_targets.is_some();
219                    let collect_storage_masks =
220                        self.collect_branch_node_masks && leaf_is_proof_target;
221                    let storage_prefix_set = self
222                        .prefix_sets
223                        .storage_prefix_sets
224                        .remove(&hashed_address)
225                        .unwrap_or_default();
226                    let storage_multiproof = StorageProof::new_hashed(
227                        self.trie_cursor_factory.clone(),
228                        self.hashed_cursor_factory.clone(),
229                        hashed_address,
230                    )
231                    .with_prefix_set_mut(storage_prefix_set)
232                    .with_branch_node_masks(collect_storage_masks)
233                    .storage_multiproof(proof_targets.unwrap_or_default())?;
234
235                    // Encode account
236                    account_rlp.clear();
237                    let account = account.into_trie_account(storage_multiproof.root);
238                    account.encode(&mut account_rlp as &mut dyn BufMut);
239
240                    hash_builder.add_leaf(Nibbles::unpack(hashed_address), &account_rlp);
241
242                    // We might be adding leaves that are not necessarily our proof targets.
243                    if leaf_is_proof_target {
244                        // Overwrite storage multiproof.
245                        storages.insert(hashed_address, storage_multiproof);
246                    }
247                }
248            }
249        }
250        let _ = hash_builder.root();
251        let account_subtree = hash_builder.take_proof_nodes();
252        let branch_node_masks = if self.collect_branch_node_masks {
253            let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default();
254            updated_branch_nodes
255                .into_iter()
256                .map(|(path, node)| {
257                    (path, BranchNodeMasks { hash_mask: node.hash_mask, tree_mask: node.tree_mask })
258                })
259                .collect()
260        } else {
261            BranchNodeMasksMap::default()
262        };
263
264        Ok(MultiProof { account_subtree, branch_node_masks, storages })
265    }
266}
267
268/// Generates storage merkle proofs.
269#[derive(Debug)]
270pub struct StorageProof<'a, T, H, K = AddedRemovedKeys> {
271    /// The factory for traversing trie nodes.
272    trie_cursor_factory: T,
273    /// The factory for hashed cursors.
274    hashed_cursor_factory: H,
275    /// The hashed address of an account.
276    hashed_address: B256,
277    /// The set of storage slot prefixes that have changed.
278    prefix_set: PrefixSetMut,
279    /// Flag indicating whether to include branch node masks in the proof.
280    collect_branch_node_masks: bool,
281    /// Provided by the user to give the necessary context to retain extra proofs.
282    added_removed_keys: Option<K>,
283    /// Optional reference to accumulate trie cursor metrics.
284    trie_cursor_metrics: Option<&'a mut TrieCursorMetricsCache>,
285    /// Optional reference to accumulate hashed cursor metrics.
286    hashed_cursor_metrics: Option<&'a mut HashedCursorMetricsCache>,
287}
288
289impl<T, H> StorageProof<'static, T, H> {
290    /// Create a new [`StorageProof`] instance.
291    pub fn new(t: T, h: H, address: Address) -> Self {
292        Self::new_hashed(t, h, keccak256(address))
293    }
294
295    /// Create a new [`StorageProof`] instance with hashed address.
296    pub fn new_hashed(t: T, h: H, hashed_address: B256) -> Self {
297        Self {
298            trie_cursor_factory: t,
299            hashed_cursor_factory: h,
300            hashed_address,
301            prefix_set: PrefixSetMut::default(),
302            collect_branch_node_masks: false,
303            added_removed_keys: None,
304            trie_cursor_metrics: None,
305            hashed_cursor_metrics: None,
306        }
307    }
308}
309
310impl<'a, T, H, K> StorageProof<'a, T, H, K> {
311    /// Set the trie cursor factory.
312    pub fn with_trie_cursor_factory<TF>(
313        self,
314        trie_cursor_factory: TF,
315    ) -> StorageProof<'a, TF, H, K> {
316        StorageProof {
317            trie_cursor_factory,
318            hashed_cursor_factory: self.hashed_cursor_factory,
319            hashed_address: self.hashed_address,
320            prefix_set: self.prefix_set,
321            collect_branch_node_masks: self.collect_branch_node_masks,
322            added_removed_keys: self.added_removed_keys,
323            trie_cursor_metrics: self.trie_cursor_metrics,
324            hashed_cursor_metrics: self.hashed_cursor_metrics,
325        }
326    }
327
328    /// Set the hashed cursor factory.
329    pub fn with_hashed_cursor_factory<HF>(
330        self,
331        hashed_cursor_factory: HF,
332    ) -> StorageProof<'a, T, HF, K> {
333        StorageProof {
334            trie_cursor_factory: self.trie_cursor_factory,
335            hashed_cursor_factory,
336            hashed_address: self.hashed_address,
337            prefix_set: self.prefix_set,
338            collect_branch_node_masks: self.collect_branch_node_masks,
339            added_removed_keys: self.added_removed_keys,
340            trie_cursor_metrics: self.trie_cursor_metrics,
341            hashed_cursor_metrics: self.hashed_cursor_metrics,
342        }
343    }
344
345    /// Set the changed prefixes.
346    pub fn with_prefix_set_mut(mut self, prefix_set: PrefixSetMut) -> Self {
347        self.prefix_set = prefix_set;
348        self
349    }
350
351    /// Set the flag indicating whether to include branch node masks in the proof.
352    pub const fn with_branch_node_masks(mut self, branch_node_masks: bool) -> Self {
353        self.collect_branch_node_masks = branch_node_masks;
354        self
355    }
356
357    /// Set the trie cursor metrics cache to accumulate metrics into.
358    pub const fn with_trie_cursor_metrics(
359        mut self,
360        metrics: &'a mut TrieCursorMetricsCache,
361    ) -> Self {
362        self.trie_cursor_metrics = Some(metrics);
363        self
364    }
365
366    /// Set the hashed cursor metrics cache to accumulate metrics into.
367    pub const fn with_hashed_cursor_metrics(
368        mut self,
369        metrics: &'a mut HashedCursorMetricsCache,
370    ) -> Self {
371        self.hashed_cursor_metrics = Some(metrics);
372        self
373    }
374
375    /// Configures the retainer to retain proofs for certain nodes which would otherwise fall
376    /// outside the target set, when those nodes might be required to calculate the state root when
377    /// keys have been added or removed to the trie.
378    ///
379    /// If None is given then retention of extra proofs is disabled.
380    pub fn with_added_removed_keys<K2>(
381        self,
382        added_removed_keys: Option<K2>,
383    ) -> StorageProof<'a, T, H, K2> {
384        StorageProof {
385            trie_cursor_factory: self.trie_cursor_factory,
386            hashed_cursor_factory: self.hashed_cursor_factory,
387            hashed_address: self.hashed_address,
388            prefix_set: self.prefix_set,
389            collect_branch_node_masks: self.collect_branch_node_masks,
390            added_removed_keys,
391            trie_cursor_metrics: self.trie_cursor_metrics,
392            hashed_cursor_metrics: self.hashed_cursor_metrics,
393        }
394    }
395}
396
397impl<'a, T, H, K> StorageProof<'a, T, H, K>
398where
399    T: TrieCursorFactory,
400    H: HashedCursorFactory,
401    K: AsRef<AddedRemovedKeys>,
402{
403    /// Generate an account proof from intermediate nodes.
404    pub fn storage_proof(
405        self,
406        slot: B256,
407    ) -> Result<reth_trie_common::StorageProof, StateProofError> {
408        let targets = HashSet::from_iter([keccak256(slot)]);
409        Ok(self.storage_multiproof(targets)?.storage_proof(slot)?)
410    }
411
412    /// Generate storage proof.
413    pub fn storage_multiproof(
414        self,
415        targets: B256Set,
416    ) -> Result<StorageMultiProof, StateProofError> {
417        let mut discard_hashed_cursor_metrics = HashedCursorMetricsCache::default();
418        let hashed_cursor_metrics =
419            self.hashed_cursor_metrics.unwrap_or(&mut discard_hashed_cursor_metrics);
420
421        let hashed_storage_cursor =
422            self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;
423
424        let mut hashed_storage_cursor =
425            InstrumentedHashedCursor::new(hashed_storage_cursor, hashed_cursor_metrics);
426
427        // short circuit on empty storage
428        if hashed_storage_cursor.is_storage_empty()? {
429            return Ok(StorageMultiProof::empty())
430        }
431
432        let mut discard_trie_cursor_metrics = TrieCursorMetricsCache::default();
433        let trie_cursor_metrics =
434            self.trie_cursor_metrics.unwrap_or(&mut discard_trie_cursor_metrics);
435
436        let target_nibbles = targets.into_iter().map(Nibbles::unpack).collect::<Vec<_>>();
437        let mut prefix_set = self.prefix_set;
438        prefix_set.extend_keys(target_nibbles.iter().copied());
439
440        let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;
441
442        let trie_cursor = InstrumentedTrieCursor::new(trie_cursor, trie_cursor_metrics);
443
444        let walker = TrieWalker::<_>::storage_trie(trie_cursor, prefix_set.freeze())
445            .with_added_removed_keys(self.added_removed_keys.as_ref());
446
447        let retainer = ProofRetainer::from_iter(target_nibbles)
448            .with_added_removed_keys(self.added_removed_keys.as_ref());
449        let mut hash_builder = HashBuilder::default()
450            .with_proof_retainer(retainer)
451            .with_updates(self.collect_branch_node_masks);
452        let mut storage_node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);
453        while let Some(node) = storage_node_iter.try_next()? {
454            match node {
455                TrieElement::Branch(node) => {
456                    hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);
457                }
458                TrieElement::Leaf(hashed_slot, value) => {
459                    hash_builder.add_leaf(
460                        Nibbles::unpack(hashed_slot),
461                        alloy_rlp::encode_fixed_size(&value).as_ref(),
462                    );
463                }
464            }
465        }
466
467        let root = hash_builder.root();
468        let subtree = hash_builder.take_proof_nodes();
469        let branch_node_masks = if self.collect_branch_node_masks {
470            let updated_branch_nodes = hash_builder.updated_branch_nodes.unwrap_or_default();
471            updated_branch_nodes
472                .into_iter()
473                .map(|(path, node)| {
474                    (path, BranchNodeMasks { hash_mask: node.hash_mask, tree_mask: node.tree_mask })
475                })
476                .collect()
477        } else {
478            BranchNodeMasksMap::default()
479        };
480
481        Ok(StorageMultiProof { root, subtree, branch_node_masks })
482    }
483}