Skip to main content

reth_trie/proof_v2/
multiproof_calculator.rs

1//! Reusable multiproof generation over a fixed state snapshot.
2
3use super::{DeferredValueEncoder, LeafValueEncoder, ProofCalculator, StorageProofCalculator};
4use crate::{
5    hashed_cursor::{HashedCursorFactory, HashedStorageCursor},
6    prefix_set::{PrefixSet, TriePrefixSets},
7    trie_cursor::{TrieCursorFactory, TrieStorageCursor},
8    DecodedMultiProofV2, MultiProofTargetsV2,
9};
10use alloy_primitives::{map::B256Map, B256, U256};
11use alloy_rlp::Encodable;
12use reth_concurrency::sync::parking_lot::Mutex;
13use reth_execution_errors::StateProofError;
14use reth_primitives_traits::Account;
15use std::{fmt, marker::PhantomPinned, pin::Pin, sync::Arc};
16
17/// Generates account and storage multiproofs for one immutable state snapshot.
18///
19/// The calculator owns its cursor factories and may be reused for any number of requests. It stays
20/// usable after an error, but must be dropped after a panic during a request. The factories must
21/// keep describing the same state for the lifetime of the calculator. Cursor factories control
22/// whether their cursors are instrumented.
23///
24/// `'a` is the lifetime of the cursors opened from the owned factories. It is not tied to a
25/// caller-supplied borrow; it only needs to be satisfied by `T` and `H`.
26pub struct MultiProofCalculator<'a, T: TrieCursorFactory + 'a, H: HashedCursorFactory + 'a> {
27    account_calculator: Option<AccountCalculatorOf<'a, T, H>>,
28    storage_calculator: Option<Arc<Mutex<StorageCalculatorOf<'a, T, H>>>>,
29    prefix_sets: TriePrefixSets,
30    known_storage_roots: Arc<B256Map<B256>>,
31    // Cursors borrow these pinned factories. `Drop` releases them first.
32    factories: Pin<Box<MultiProofCalculatorFactories<T, H>>>,
33}
34
35impl<'a, T: TrieCursorFactory + 'a, H: HashedCursorFactory + 'a> MultiProofCalculator<'a, T, H> {
36    /// Creates a calculator for the supplied factories and frozen changed-key prefixes.
37    ///
38    /// Prefixes invalidate cached branch hashes for keys whose leaf values have changed, and apply
39    /// to every request served by this calculator.
40    ///
41    /// `known_storage_roots` supplies roots keyed by hashed account address. Each root must be
42    /// valid for the account leaf being encoded. Accounts absent from the map calculate their
43    /// storage roots from the cursors. Explicit storage proof requests always use the cursors.
44    pub fn new(
45        trie_cursor_factory: T,
46        hashed_cursor_factory: H,
47        prefix_sets: TriePrefixSets,
48        known_storage_roots: Arc<B256Map<B256>>,
49    ) -> Self {
50        Self {
51            account_calculator: None,
52            storage_calculator: None,
53            prefix_sets,
54            known_storage_roots,
55            factories: Box::pin(MultiProofCalculatorFactories {
56                trie_cursor_factory,
57                hashed_cursor_factory,
58                _pin: PhantomPinned,
59            }),
60        }
61    }
62
63    /// Generates account and storage proofs for `targets`.
64    ///
65    /// An explicit storage address with no slot targets requests its root and, for an extension
66    /// root, its child branch. Nodes are returned children before parents. Empty targets return an
67    /// empty proof.
68    pub fn multiproof(
69        &mut self,
70        targets: MultiProofTargetsV2,
71    ) -> Result<DecodedMultiProofV2, StateProofError> {
72        if targets.is_empty() {
73            return Ok(DecodedMultiProofV2::default())
74        }
75        let MultiProofTargetsV2 { mut account_targets, storage_targets } = targets;
76        let mut proof = DecodedMultiProofV2::default();
77
78        // Open the storage calculator, which account proofs also use for storage roots.
79        let storage_calculator = match &mut self.storage_calculator {
80            Some(storage_calculator) => storage_calculator,
81            slot @ None => {
82                // SAFETY: Cursors are private to this calculator and released before factories.
83                let factories = unsafe { Self::borrow_factories(self.factories.as_ref()) };
84                // Storage cursors are retargeted to each requested account before use.
85                let trie_cursor = factories.trie_cursor_factory.storage_trie_cursor(B256::ZERO)?;
86                let hashed_cursor =
87                    factories.hashed_cursor_factory.hashed_storage_cursor(B256::ZERO)?;
88                // Prefixes are taken only after the fallible cursor opens, so a failed
89                // initialization can be retried.
90                let prefix_sets = std::mem::take(&mut self.prefix_sets.storage_prefix_sets);
91                slot.insert(Arc::new(Mutex::new(PrefixSetStorageCalculator {
92                    calculator: StorageProofCalculator::new_storage(trie_cursor, hashed_cursor),
93                    prefix_sets,
94                    hashed_address: None,
95                })))
96            }
97        };
98
99        // Calculate account proofs, reusing known storage roots or computing missing roots inline.
100        if !account_targets.is_empty() {
101            let account_calculator = match &mut self.account_calculator {
102                Some(account_calculator) => account_calculator,
103                slot @ None => {
104                    // SAFETY: As above, cursors are released before factories.
105                    let factories = unsafe { Self::borrow_factories(self.factories.as_ref()) };
106                    let trie_cursor = factories.trie_cursor_factory.account_trie_cursor()?;
107                    let hashed_cursor = factories.hashed_cursor_factory.hashed_account_cursor()?;
108                    let prefix_set = std::mem::take(&mut self.prefix_sets.account_prefix_set);
109                    slot.insert(
110                        ProofCalculator::new(trie_cursor, hashed_cursor)
111                            .with_prefix_set(prefix_set),
112                    )
113                }
114            };
115            let mut encoder = AccountValueEncoder {
116                storage_calculator: storage_calculator.clone(),
117                known_storage_roots: self.known_storage_roots.clone(),
118            };
119            proof.account_proofs = account_calculator.proof(&mut encoder, &mut account_targets)?;
120        }
121
122        // Calculate storage proofs, or root nodes for accounts without slot targets.
123        if !storage_targets.is_empty() {
124            let mut storage_calculator = storage_calculator.lock();
125            for (hashed_address, mut targets) in storage_targets {
126                let calculator = storage_calculator.calculator_for(hashed_address);
127                let nodes = if targets.is_empty() {
128                    calculator.storage_root_nodes(hashed_address)?
129                } else {
130                    calculator.storage_proof(hashed_address, &mut targets)?
131                };
132                proof.storage_proofs.insert(hashed_address, nodes);
133            }
134        }
135        Ok(proof)
136    }
137
138    /// Extends the borrow of the pinned factories to the cursor lifetime `'a`.
139    ///
140    /// # Safety
141    ///
142    /// Every reference, cursor and encoder derived from the result must be dropped before the
143    /// factories, and none may escape this calculator.
144    const unsafe fn borrow_factories(
145        factories: Pin<&MultiProofCalculatorFactories<T, H>>,
146    ) -> &'a MultiProofCalculatorFactories<T, H> {
147        // SAFETY: The factories are pinned and immutable, and the caller keeps every borrower
148        // inside this calculator, which releases them before the factories.
149        unsafe { &*(factories.get_ref() as *const MultiProofCalculatorFactories<T, H>) }
150    }
151}
152
153impl<'a, T: TrieCursorFactory + 'a, H: HashedCursorFactory + 'a> Drop
154    for MultiProofCalculator<'a, T, H>
155{
156    fn drop(&mut self) {
157        // Cursors borrow `factories`, so release them before the fields drop.
158        self.account_calculator = None;
159        self.storage_calculator = None;
160    }
161}
162
163impl<T: TrieCursorFactory, H: HashedCursorFactory> fmt::Debug for MultiProofCalculator<'_, T, H> {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.debug_struct("MultiProofCalculator")
166            .field("account_initialized", &self.account_calculator.is_some())
167            .field("storage_initialized", &self.storage_calculator.is_some())
168            .finish_non_exhaustive()
169    }
170}
171
172/// Account calculator opened from the cursor factories of a [`MultiProofCalculator`].
173type AccountCalculatorOf<'a, T, H> = ProofCalculator<
174    <T as TrieCursorFactory>::AccountTrieCursor<'a>,
175    <H as HashedCursorFactory>::AccountCursor<'a>,
176    AccountValueEncoder<
177        <T as TrieCursorFactory>::StorageTrieCursor<'a>,
178        <H as HashedCursorFactory>::StorageCursor<'a>,
179    >,
180>;
181
182/// Storage calculator opened from the cursor factories of a [`MultiProofCalculator`].
183type StorageCalculatorOf<'a, T, H> = PrefixSetStorageCalculator<
184    <T as TrieCursorFactory>::StorageTrieCursor<'a>,
185    <H as HashedCursorFactory>::StorageCursor<'a>,
186>;
187
188/// Cursor factories owned by a [`MultiProofCalculator`] at a stable address.
189struct MultiProofCalculatorFactories<T, H> {
190    trie_cursor_factory: T,
191    hashed_cursor_factory: H,
192    _pin: PhantomPinned,
193}
194
195/// Storage proof calculator that applies each account's changed-slot prefixes.
196///
197/// All storage calculations go through this type so the prefixes always match the account being
198/// calculated.
199struct PrefixSetStorageCalculator<TC, HC> {
200    calculator: StorageProofCalculator<TC, HC>,
201    /// Changed-slot prefixes keyed by hashed address.
202    prefix_sets: B256Map<PrefixSet>,
203    /// Account whose prefixes are currently applied to `calculator`.
204    hashed_address: Option<B256>,
205}
206
207impl<TC: TrieStorageCursor, HC: HashedStorageCursor<Value = U256>>
208    PrefixSetStorageCalculator<TC, HC>
209{
210    fn calculator_for(&mut self, hashed_address: B256) -> &mut StorageProofCalculator<TC, HC> {
211        if self.hashed_address != Some(hashed_address) {
212            self.calculator
213                .set_prefix_set(self.prefix_sets.get(&hashed_address).cloned().unwrap_or_default());
214            self.hashed_address = Some(hashed_address);
215        }
216        &mut self.calculator
217    }
218}
219
220/// Account value encoder that reuses known storage roots or computes them on demand.
221struct AccountValueEncoder<TC, HC> {
222    // Arc<Mutex<_>> keeps the calculator Send whenever its cursors are. The mutex never poisons,
223    // which is why the calculator must not be reused after a panic.
224    storage_calculator: Arc<Mutex<PrefixSetStorageCalculator<TC, HC>>>,
225    known_storage_roots: Arc<B256Map<B256>>,
226}
227
228impl<TC: TrieStorageCursor, HC: HashedStorageCursor<Value = U256>> LeafValueEncoder
229    for AccountValueEncoder<TC, HC>
230{
231    type Value = Account;
232    type DeferredEncoder = AccountDeferredValueEncoder<TC, HC>;
233
234    fn deferred_encoder(
235        &mut self,
236        hashed_address: B256,
237        account: Account,
238    ) -> Self::DeferredEncoder {
239        if let Some(root) = self.known_storage_roots.get(&hashed_address) {
240            AccountDeferredValueEncoder::Known { storage_root: *root, account }
241        } else {
242            AccountDeferredValueEncoder::Calculate {
243                storage_calculator: self.storage_calculator.clone(),
244                hashed_address,
245                account,
246            }
247        }
248    }
249}
250
251/// Deferred account encoder using a known storage root or synchronous root calculation.
252enum AccountDeferredValueEncoder<TC, HC> {
253    Known {
254        storage_root: B256,
255        account: Account,
256    },
257    Calculate {
258        storage_calculator: Arc<Mutex<PrefixSetStorageCalculator<TC, HC>>>,
259        hashed_address: B256,
260        account: Account,
261    },
262}
263
264impl<TC: TrieStorageCursor, HC: HashedStorageCursor<Value = U256>> DeferredValueEncoder
265    for AccountDeferredValueEncoder<TC, HC>
266{
267    fn encode(self, buf: &mut Vec<u8>) -> Result<(), StateProofError> {
268        let (account, root) = match self {
269            Self::Known { storage_root, account } => (account, storage_root),
270            Self::Calculate { storage_calculator, hashed_address, account } => {
271                let root = storage_calculator
272                    .lock()
273                    .calculator_for(hashed_address)
274                    .storage_root(hashed_address)?;
275                (account, root)
276            }
277        };
278        account.into_trie_account(root).encode(buf);
279        Ok(())
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use crate::test_utils::TrieTestHarness;
287    use reth_trie_common::{Nibbles, TrieNode};
288    use reth_trie_sparse::{RevealableSparseTrie, SparseTrie, TrieNodeEpoch};
289    use std::collections::BTreeMap;
290
291    #[test]
292    fn empty_storage_targets_retain_extension_branch() {
293        let harness = TrieTestHarness::new(BTreeMap::from([
294            (B256::right_padding_from(&[0x34, 0x30]), U256::ONE),
295            (B256::right_padding_from(&[0x34, 0x31]), U256::from(2)),
296        ]));
297        let hashed_address = harness.hashed_address();
298        let mut calculator = MultiProofCalculator::new(
299            harness.trie_cursor_factory(),
300            harness.hashed_cursor_factory(),
301            TriePrefixSets::default(),
302            Arc::default(),
303        );
304        // Repeated root-only requests must preserve the branch and its persistence masks.
305        for _ in 0..2 {
306            let mut proof = calculator
307                .multiproof(MultiProofTargetsV2 {
308                    storage_targets: std::iter::once((hashed_address, Vec::new())).collect(),
309                    ..Default::default()
310                })
311                .unwrap();
312            let nodes = proof.storage_proofs.get_mut(&hashed_address).unwrap();
313            assert_eq!(nodes, &harness.root_nodes());
314            assert_eq!(nodes.len(), 2);
315            assert_eq!(nodes[0].path, Nibbles::from_nibbles([3, 4, 3]));
316            assert!(matches!(nodes[0].node, TrieNode::Branch(_)));
317            assert!(nodes[1].path.is_empty());
318            assert!(matches!(nodes[1].node, TrieNode::Extension(_)));
319
320            let mut trie = <RevealableSparseTrie>::default();
321            trie.reveal_v2_proof_nodes(nodes, true).unwrap();
322            assert_eq!(
323                trie.as_revealed_mut().unwrap().root(TrieNodeEpoch::UNMODIFIED),
324                harness.original_root()
325            );
326        }
327    }
328
329    #[test]
330    fn empty_storage_targets_non_extension_roots() {
331        for storage in [
332            BTreeMap::new(),
333            BTreeMap::from([(B256::ZERO, U256::ONE)]),
334            BTreeMap::from([
335                (B256::ZERO, U256::ONE),
336                (B256::right_padding_from(&[0x10]), U256::from(2)),
337            ]),
338        ] {
339            let harness = TrieTestHarness::new(storage);
340            let hashed_address = harness.hashed_address();
341            let mut calculator = MultiProofCalculator::new(
342                harness.trie_cursor_factory(),
343                harness.hashed_cursor_factory(),
344                TriePrefixSets::default(),
345                Arc::default(),
346            );
347            let mut proof = calculator
348                .multiproof(MultiProofTargetsV2 {
349                    storage_targets: std::iter::once((hashed_address, Vec::new())).collect(),
350                    ..Default::default()
351                })
352                .unwrap();
353            let nodes = proof.storage_proofs.get_mut(&hashed_address).unwrap();
354            assert_eq!(nodes, &harness.root_nodes());
355            assert_eq!(nodes.len(), 1);
356
357            let mut trie = <RevealableSparseTrie>::default();
358            trie.reveal_v2_proof_nodes(nodes, true).unwrap();
359            assert_eq!(
360                trie.as_revealed_mut().unwrap().root(TrieNodeEpoch::UNMODIFIED),
361                harness.original_root()
362            );
363        }
364    }
365}