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#[derive(Debug)]
35pub struct Proof<T, H, K = AddedRemovedKeys> {
36 trie_cursor_factory: T,
38 hashed_cursor_factory: H,
40 prefix_sets: TriePrefixSetsMut,
42 collect_branch_node_masks: bool,
44 added_removed_keys: Option<K>,
46}
47
48impl<T, H> Proof<T, H> {
49 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 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 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 pub fn with_prefix_sets_mut(mut self, prefix_sets: TriePrefixSetsMut) -> Self {
86 self.prefix_sets = prefix_sets;
87 self
88 }
89
90 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 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 pub const fn trie_cursor_factory(&self) -> &T {
113 &self.trie_cursor_factory
114 }
115
116 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 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 pub fn multiproof_v2(
147 self,
148 targets: MultiProofTargetsV2,
149 ) -> Result<DecodedMultiProofV2, StateProofError> {
150 let MultiProofTargetsV2 { mut account_targets, storage_targets } = targets;
151
152 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 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 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 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 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 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 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 if leaf_is_proof_target {
244 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#[derive(Debug)]
270pub struct StorageProof<'a, T, H, K = AddedRemovedKeys> {
271 trie_cursor_factory: T,
273 hashed_cursor_factory: H,
275 hashed_address: B256,
277 prefix_set: PrefixSetMut,
279 collect_branch_node_masks: bool,
281 added_removed_keys: Option<K>,
283 trie_cursor_metrics: Option<&'a mut TrieCursorMetricsCache>,
285 hashed_cursor_metrics: Option<&'a mut HashedCursorMetricsCache>,
287}
288
289impl<T, H> StorageProof<'static, T, H> {
290 pub fn new(t: T, h: H, address: Address) -> Self {
292 Self::new_hashed(t, h, keccak256(address))
293 }
294
295 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 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 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 pub fn with_prefix_set_mut(mut self, prefix_set: PrefixSetMut) -> Self {
347 self.prefix_set = prefix_set;
348 self
349 }
350
351 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 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 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 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 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 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 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}