Skip to main content

reth_trie_common/
proofs.rs

1//! Merkle trie proofs.
2
3use crate::{BranchNodeMasksMap, Nibbles, ProofTrieNode, TrieAccount};
4use alloc::{borrow::Cow, collections::VecDeque, vec::Vec};
5use alloy_primitives::{
6    keccak256,
7    map::{hash_map, B256Map, B256Set},
8    Address, Bytes, B256, U256,
9};
10use alloy_rlp::{encode_fixed_size, Decodable, Encodable, EMPTY_STRING_CODE};
11use alloy_trie::{
12    nodes::TrieNode,
13    proof::{verify_proof, DecodedProofNodes, ProofNodes, ProofVerificationError},
14    EMPTY_ROOT_HASH,
15};
16use derive_more::{Deref, DerefMut, IntoIterator};
17use itertools::Itertools;
18use reth_primitives_traits::Account;
19
20/// Proof targets map.
21#[derive(Deref, DerefMut, IntoIterator, Clone, PartialEq, Eq, Default, Debug)]
22pub struct MultiProofTargets(B256Map<B256Set>);
23
24impl FromIterator<(B256, B256Set)> for MultiProofTargets {
25    fn from_iter<T: IntoIterator<Item = (B256, B256Set)>>(iter: T) -> Self {
26        Self(B256Map::from_iter(iter))
27    }
28}
29
30impl MultiProofTargets {
31    /// Creates an empty `MultiProofTargets` with at least the specified capacity.
32    pub fn with_capacity(capacity: usize) -> Self {
33        Self(B256Map::with_capacity_and_hasher(capacity, Default::default()))
34    }
35
36    /// Create `MultiProofTargets` with a single account as a target.
37    pub fn account(hashed_address: B256) -> Self {
38        Self::accounts([hashed_address])
39    }
40
41    /// Create `MultiProofTargets` with a single account and slots as targets.
42    pub fn account_with_slots<I: IntoIterator<Item = B256>>(
43        hashed_address: B256,
44        slots_iter: I,
45    ) -> Self {
46        Self(B256Map::from_iter([(hashed_address, slots_iter.into_iter().collect())]))
47    }
48
49    /// Create `MultiProofTargets` only from accounts.
50    pub fn accounts<I: IntoIterator<Item = B256>>(iter: I) -> Self {
51        Self(iter.into_iter().map(|hashed_address| (hashed_address, Default::default())).collect())
52    }
53
54    /// Retains the targets representing the difference,
55    /// i.e., the values that are in `self` but not in `other`.
56    pub fn retain_difference(&mut self, other: &Self) {
57        self.0.retain(|hashed_address, hashed_slots| {
58            other.get(hashed_address).is_none_or(|other_hashed_slots| {
59                hashed_slots.retain(|hashed_slot| !other_hashed_slots.contains(hashed_slot));
60                !hashed_slots.is_empty()
61            })
62        });
63    }
64
65    /// Extend multi proof targets with contents of other.
66    pub fn extend(&mut self, other: Self) {
67        self.extend_inner(Cow::Owned(other));
68    }
69
70    /// Extend multi proof targets with contents of other.
71    ///
72    /// Slightly less efficient than [`Self::extend`], but preferred to `extend(other.clone())`.
73    pub fn extend_ref(&mut self, other: &Self) {
74        self.extend_inner(Cow::Borrowed(other));
75    }
76
77    fn extend_inner(&mut self, other: Cow<'_, Self>) {
78        for (hashed_address, hashed_slots) in other.iter() {
79            match self.entry(*hashed_address) {
80                hash_map::Entry::Vacant(entry) => {
81                    entry.insert(hashed_slots.clone());
82                }
83                hash_map::Entry::Occupied(mut entry) => {
84                    entry.get_mut().extend(hashed_slots);
85                }
86            }
87        }
88    }
89
90    /// Returns an iterator that yields chunks of the specified size.
91    ///
92    /// See [`ChunkedMultiProofTargets`] for more information.
93    ///
94    /// # Panics
95    ///
96    /// Panics if the chunk size is zero.
97    pub fn chunks(self, size: usize) -> ChunkedMultiProofTargets {
98        ChunkedMultiProofTargets::new(self, size)
99    }
100
101    /// Returns the number of items that will be considered during chunking in `[Self::chunks]`.
102    pub fn chunking_length(&self) -> usize {
103        self.values().map(|slots| 1 + slots.len().saturating_sub(1)).sum::<usize>()
104    }
105}
106
107/// An iterator that yields chunks of the proof targets of at most `size` account and storage
108/// targets.
109///
110/// For example, for the following proof targets:
111/// ```text
112/// - 0x1: [0x10, 0x20, 0x30]
113/// - 0x2: [0x40]
114/// - 0x3: []
115/// ```
116///
117/// and `size = 2`, the iterator will yield the following chunks:
118/// ```text
119/// - { 0x1: [0x10, 0x20] }
120/// - { 0x1: [0x30], 0x2: [0x40] }
121/// - { 0x3: [] }
122/// ```
123///
124/// It follows two rules:
125/// - If account has associated storage slots, each storage slot is counted towards the chunk size.
126/// - If account has no associated storage slots, the account is counted towards the chunk size.
127#[derive(Debug)]
128pub struct ChunkedMultiProofTargets {
129    flattened_targets: alloc::vec::IntoIter<(B256, Option<B256>)>,
130    size: usize,
131}
132
133impl ChunkedMultiProofTargets {
134    fn new(targets: MultiProofTargets, size: usize) -> Self {
135        assert!(size > 0, "chunk size must be non-zero");
136        let flattened_targets = targets
137            .into_iter()
138            .flat_map(|(address, slots)| {
139                if slots.is_empty() {
140                    // If the account has no storage slots, we still need to yield the account
141                    // address with empty storage slots. `None` here means that
142                    // there's no storage slot to fetch.
143                    itertools::Either::Left(core::iter::once((address, None)))
144                } else {
145                    itertools::Either::Right(
146                        slots.into_iter().map(move |slot| (address, Some(slot))),
147                    )
148                }
149            })
150            .sorted_unstable();
151        Self { flattened_targets, size }
152    }
153}
154
155impl Iterator for ChunkedMultiProofTargets {
156    type Item = MultiProofTargets;
157
158    fn next(&mut self) -> Option<Self::Item> {
159        let chunk = self.flattened_targets.by_ref().take(self.size).fold(
160            MultiProofTargets::default(),
161            |mut acc, (address, slot)| {
162                let entry = acc.entry(address).or_default();
163                if let Some(slot) = slot {
164                    entry.insert(slot);
165                }
166                acc
167            },
168        );
169
170        if chunk.is_empty() {
171            None
172        } else {
173            Some(chunk)
174        }
175    }
176}
177
178/// The state multiproof of target accounts and multiproofs of their storage tries.
179/// Multiproof is effectively a state subtrie that only contains the nodes
180/// in the paths of target accounts.
181#[derive(Clone, Default, Debug, PartialEq, Eq)]
182pub struct MultiProof {
183    /// State trie multiproof for requested accounts.
184    pub account_subtree: ProofNodes,
185    /// Consolidated branch node masks (`hash_mask`, `tree_mask`) for each path in the account
186    /// proof.
187    pub branch_node_masks: BranchNodeMasksMap,
188    /// Storage trie multiproofs.
189    pub storages: B256Map<StorageMultiProof>,
190}
191
192impl MultiProof {
193    /// Returns true if the multiproof is empty.
194    pub fn is_empty(&self) -> bool {
195        self.account_subtree.is_empty() &&
196            self.branch_node_masks.is_empty() &&
197            self.storages.is_empty()
198    }
199
200    /// Return the account proof nodes for the given account path.
201    pub fn account_proof_nodes(&self, path: &Nibbles) -> Vec<(Nibbles, Bytes)> {
202        self.account_subtree.matching_nodes_sorted(path)
203    }
204
205    /// Return the storage proof nodes for the given storage slots of the account path.
206    pub fn storage_proof_nodes(
207        &self,
208        hashed_address: B256,
209        slots: impl IntoIterator<Item = B256>,
210    ) -> Vec<(B256, Vec<(Nibbles, Bytes)>)> {
211        self.storages
212            .get(&hashed_address)
213            .map(|storage_mp| {
214                slots
215                    .into_iter()
216                    .map(|slot| {
217                        let nibbles = Nibbles::unpack(slot);
218                        (slot, storage_mp.subtree.matching_nodes_sorted(&nibbles))
219                    })
220                    .collect()
221            })
222            .unwrap_or_default()
223    }
224
225    /// Construct the account proof from the multiproof.
226    pub fn account_proof(
227        &self,
228        address: Address,
229        slots: &[B256],
230    ) -> Result<AccountProof, alloy_rlp::Error> {
231        let hashed_address = keccak256(address);
232        let nibbles = Nibbles::unpack(hashed_address);
233
234        // Retrieve the account proof.
235        let proof = self
236            .account_proof_nodes(&nibbles)
237            .into_iter()
238            .map(|(_, node)| node)
239            .collect::<Vec<_>>();
240
241        // Inspect the last node in the proof. If it's a leaf node with matching suffix,
242        // then the node contains the encoded trie account.
243        let info = 'info: {
244            if let Some(last) = proof.last() &&
245                let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? &&
246                nibbles.ends_with(&leaf.key)
247            {
248                let account = TrieAccount::decode(&mut &leaf.value[..])?;
249                break 'info Some(Account::from(account))
250            }
251            None
252        };
253
254        // Retrieve proofs for requested storage slots.
255        let storage_multiproof = self.storages.get(&hashed_address);
256        let storage_root = storage_multiproof.map(|m| m.root).unwrap_or(EMPTY_ROOT_HASH);
257        let mut storage_proofs = Vec::with_capacity(slots.len());
258        for slot in slots {
259            let proof = if let Some(multiproof) = &storage_multiproof {
260                multiproof.storage_proof(*slot)?
261            } else {
262                StorageProof::new(*slot)
263            };
264            storage_proofs.push(proof);
265        }
266        Ok(AccountProof { address, info, proof, storage_root, storage_proofs })
267    }
268
269    /// Extends this multiproof with another one, merging both account and storage
270    /// proofs.
271    pub fn extend(&mut self, other: Self) {
272        self.account_subtree.extend_from(other.account_subtree);
273        self.branch_node_masks.extend(other.branch_node_masks);
274
275        let reserve = if self.storages.is_empty() {
276            other.storages.len()
277        } else {
278            other.storages.len().div_ceil(2)
279        };
280        self.storages.reserve(reserve);
281        for (hashed_address, storage) in other.storages {
282            match self.storages.entry(hashed_address) {
283                hash_map::Entry::Occupied(mut entry) => {
284                    debug_assert_eq!(entry.get().root, storage.root);
285                    let entry = entry.get_mut();
286                    entry.subtree.extend_from(storage.subtree);
287                    entry.branch_node_masks.extend(storage.branch_node_masks);
288                }
289                hash_map::Entry::Vacant(entry) => {
290                    entry.insert(storage);
291                }
292            }
293        }
294    }
295
296    /// Create a [`MultiProof`] from a [`StorageMultiProof`].
297    pub fn from_storage_proof(hashed_address: B256, storage_proof: StorageMultiProof) -> Self {
298        Self {
299            storages: B256Map::from_iter([(hashed_address, storage_proof)]),
300            ..Default::default()
301        }
302    }
303}
304
305/// This is a type of [`MultiProof`] that uses decoded proofs, meaning these proofs are stored as a
306/// collection of [`TrieNode`]s instead of RLP-encoded bytes.
307#[derive(Clone, Default, Debug, PartialEq, Eq)]
308pub struct DecodedMultiProof {
309    /// State trie multiproof for requested accounts.
310    pub account_subtree: DecodedProofNodes,
311    /// Consolidated branch node masks (`hash_mask`, `tree_mask`) for each path in the account
312    /// proof.
313    pub branch_node_masks: BranchNodeMasksMap,
314    /// Storage trie multiproofs.
315    pub storages: B256Map<DecodedStorageMultiProof>,
316}
317
318impl DecodedMultiProof {
319    /// Returns true if the multiproof is empty.
320    pub fn is_empty(&self) -> bool {
321        self.account_subtree.is_empty() &&
322            self.branch_node_masks.is_empty() &&
323            self.storages.is_empty()
324    }
325
326    /// Return the account proof nodes for the given account path.
327    pub fn account_proof_nodes(&self, path: &Nibbles) -> Vec<(Nibbles, TrieNode)> {
328        self.account_subtree.matching_nodes_sorted(path)
329    }
330
331    /// Return the storage proof nodes for the given storage slots of the account path.
332    pub fn storage_proof_nodes(
333        &self,
334        hashed_address: B256,
335        slots: impl IntoIterator<Item = B256>,
336    ) -> Vec<(B256, Vec<(Nibbles, TrieNode)>)> {
337        self.storages
338            .get(&hashed_address)
339            .map(|storage_mp| {
340                slots
341                    .into_iter()
342                    .map(|slot| {
343                        let nibbles = Nibbles::unpack(slot);
344                        (slot, storage_mp.subtree.matching_nodes_sorted(&nibbles))
345                    })
346                    .collect()
347            })
348            .unwrap_or_default()
349    }
350
351    /// Construct the account proof from the multiproof.
352    pub fn account_proof(
353        &self,
354        address: Address,
355        slots: &[B256],
356    ) -> Result<DecodedAccountProof, alloy_rlp::Error> {
357        let hashed_address = keccak256(address);
358        let nibbles = Nibbles::unpack(hashed_address);
359
360        // Retrieve the account proof.
361        let proof = self
362            .account_proof_nodes(&nibbles)
363            .into_iter()
364            .map(|(_, node)| node)
365            .collect::<Vec<_>>();
366
367        // Inspect the last node in the proof. If it's a leaf node with matching suffix,
368        // then the node contains the encoded trie account.
369        let info = 'info: {
370            if let Some(TrieNode::Leaf(leaf)) = proof.last() &&
371                nibbles.ends_with(&leaf.key)
372            {
373                let account = TrieAccount::decode(&mut &leaf.value[..])?;
374                break 'info Some(Account::from(account))
375            }
376            None
377        };
378
379        // Retrieve proofs for requested storage slots.
380        let storage_multiproof = self.storages.get(&hashed_address);
381        let storage_root = storage_multiproof.map(|m| m.root).unwrap_or(EMPTY_ROOT_HASH);
382        let mut storage_proofs = Vec::with_capacity(slots.len());
383        for slot in slots {
384            let proof = if let Some(multiproof) = &storage_multiproof {
385                multiproof.storage_proof(*slot)?
386            } else {
387                DecodedStorageProof::new(*slot)
388            };
389            storage_proofs.push(proof);
390        }
391        Ok(DecodedAccountProof { address, info, proof, storage_root, storage_proofs })
392    }
393
394    /// Extends this multiproof with another one, merging both account and storage
395    /// proofs.
396    pub fn extend(&mut self, other: Self) {
397        self.account_subtree.extend_from(other.account_subtree);
398        self.branch_node_masks.extend(other.branch_node_masks);
399
400        let reserve = if self.storages.is_empty() {
401            other.storages.len()
402        } else {
403            other.storages.len().div_ceil(2)
404        };
405        self.storages.reserve(reserve);
406        for (hashed_address, storage) in other.storages {
407            match self.storages.entry(hashed_address) {
408                hash_map::Entry::Occupied(mut entry) => {
409                    debug_assert_eq!(entry.get().root, storage.root);
410                    let entry = entry.get_mut();
411                    entry.subtree.extend_from(storage.subtree);
412                    entry.branch_node_masks.extend(storage.branch_node_masks);
413                }
414                hash_map::Entry::Vacant(entry) => {
415                    entry.insert(storage);
416                }
417            }
418        }
419    }
420
421    /// Create a [`DecodedMultiProof`] from a [`DecodedStorageMultiProof`].
422    pub fn from_storage_proof(
423        hashed_address: B256,
424        storage_proof: DecodedStorageMultiProof,
425    ) -> Self {
426        Self {
427            storages: B256Map::from_iter([(hashed_address, storage_proof)]),
428            ..Default::default()
429        }
430    }
431}
432
433impl TryFrom<MultiProof> for DecodedMultiProof {
434    type Error = alloy_rlp::Error;
435
436    fn try_from(multi_proof: MultiProof) -> Result<Self, Self::Error> {
437        let account_subtree = DecodedProofNodes::try_from(multi_proof.account_subtree)?;
438        let storages = multi_proof
439            .storages
440            .into_iter()
441            .map(|(address, storage)| Ok((address, storage.try_into()?)))
442            .collect::<Result<B256Map<_>, alloy_rlp::Error>>()?;
443        Ok(Self { account_subtree, branch_node_masks: multi_proof.branch_node_masks, storages })
444    }
445}
446
447/// V2 decoded multiproof which contains the results of both account and storage V2 proof
448/// calculations. Nodes use the standard MPT representation, with extensions separate from branches.
449#[derive(Clone, Debug, PartialEq, Eq, Default)]
450pub struct DecodedMultiProofV2 {
451    /// Account trie proof nodes.
452    pub account_proofs: Vec<ProofTrieNode>,
453    /// Storage trie proof nodes indexed by account.
454    pub storage_proofs: B256Map<Vec<ProofTrieNode>>,
455}
456
457impl DecodedMultiProofV2 {
458    /// Returns true if there are no proofs
459    pub fn is_empty(&self) -> bool {
460        self.account_proofs.is_empty() && self.storage_proofs.is_empty()
461    }
462
463    /// Construct an account proof from the V2 multiproof.
464    ///
465    /// An extension on a requested path is followed by its child branch, if the multiproof holds
466    /// it, even when the path diverges within the extension key.
467    pub fn account_proof(
468        &self,
469        address: Address,
470        slots: &[B256],
471    ) -> Result<AccountProof, alloy_rlp::Error> {
472        let hashed_address = keccak256(address);
473        let nibbles = Nibbles::unpack(hashed_address);
474        let account_nodes = matching_v2_proof_nodes(&self.account_proofs, &nibbles);
475
476        let (info, storage_root) = 'account: {
477            if let Some(ProofTrieNode { node: TrieNode::Leaf(leaf), .. }) =
478                account_nodes.clone().last() &&
479                nibbles.ends_with(&leaf.key)
480            {
481                let account = TrieAccount::decode(&mut &leaf.value[..])?;
482                let storage_root = account.storage_root;
483                break 'account (Some(Account::from(account)), storage_root)
484            }
485            (None, EMPTY_ROOT_HASH)
486        };
487
488        let proof = encode_path_proof_nodes(&self.account_proofs, &nibbles);
489        let storage_nodes = self.storage_proofs.get(&hashed_address);
490        let mut storage_proofs = Vec::with_capacity(slots.len());
491        for slot in slots {
492            let nibbles = Nibbles::unpack(keccak256(slot));
493            let nodes =
494                storage_nodes.iter().flat_map(|nodes| matching_v2_proof_nodes(nodes, &nibbles));
495            let value = 'value: {
496                if let Some(ProofTrieNode { node: TrieNode::Leaf(leaf), .. }) = nodes.clone().last() &&
497                    nibbles.ends_with(&leaf.key)
498                {
499                    break 'value U256::decode(&mut &leaf.value[..])?
500                }
501                U256::ZERO
502            };
503            storage_proofs.push(StorageProof {
504                key: *slot,
505                nibbles,
506                value,
507                proof: storage_nodes
508                    .map(|nodes| encode_path_proof_nodes(nodes, &nibbles))
509                    .unwrap_or_default(),
510            });
511        }
512
513        Ok(AccountProof { address, info, proof, storage_root, storage_proofs })
514    }
515
516    /// Builds a `DecodedMultiProofV2` from a flat witness map (hash → RLP-encoded trie node).
517    ///
518    /// This performs a BFS traversal starting from `state_root`, following hashed and inline
519    /// children and organizing decoded nodes into account and storage proof vectors. This is the
520    /// inverse of witness generation — it reconstructs the structured multiproof from the flat
521    /// format used in `ExecutionWitness`.
522    pub fn from_witness(
523        state_root: B256,
524        witness: &B256Map<impl AsRef<[u8]>>,
525    ) -> Result<Self, alloy_rlp::Error> {
526        Self::from_witness_with(state_root, |hash| {
527            witness.get(hash).map(|bytes| TrieNode::decode(&mut bytes.as_ref())).transpose()
528        })
529    }
530
531    /// Builds a `DecodedMultiProofV2` from a witness map of already decoded trie nodes, keyed by
532    /// node hash.
533    ///
534    /// Same traversal as [`Self::from_witness`], for callers that build multiproofs at several
535    /// roots over one witness and decode each node once. Inline children are still decoded from
536    /// their parent.
537    pub fn from_witness_decoded(
538        state_root: B256,
539        witness: &B256Map<TrieNode>,
540    ) -> Result<Self, alloy_rlp::Error> {
541        Self::from_witness_with(state_root, |hash| Ok(witness.get(hash).cloned()))
542    }
543
544    /// Builds a `DecodedMultiProofV2` by BFS from `state_root`, resolving hashed nodes with
545    /// `node_by_hash`.
546    ///
547    /// `node_by_hash` returns the decoded node for a hash, `None` to leave that node blinded, or
548    /// an error that aborts the traversal. Inline children are decoded from their parent.
549    pub fn from_witness_with(
550        state_root: B256,
551        mut node_by_hash: impl FnMut(&B256) -> Result<Option<TrieNode>, alloy_rlp::Error>,
552    ) -> Result<Self, alloy_rlp::Error> {
553        let mut account_proofs = Vec::new();
554        let mut storage_proofs = B256Map::<Vec<ProofTrieNode>>::default();
555
556        let Some(root) = node_by_hash(&state_root)? else { return Ok(Self::default()) };
557        let mut queue = VecDeque::from([(root, Nibbles::default(), None)]);
558
559        while let Some((trie_node, path, maybe_account)) = queue.pop_front() {
560            match &trie_node {
561                TrieNode::Branch(branch) => {
562                    if path.len() >= 64 {
563                        return Err(alloy_rlp::Error::Custom("branch path exceeds 64 nibbles"));
564                    }
565                    for (idx, maybe_child) in branch.as_ref().children() {
566                        if let Some(child) = maybe_child {
567                            let mut child_path = path;
568                            child_path.push_unchecked(idx);
569                            let child = if let Some(hash) = child.as_hash() {
570                                let Some(node) = node_by_hash(&hash)? else { continue };
571                                node
572                            } else {
573                                TrieNode::decode(&mut child.as_slice())?
574                            };
575                            queue.push_back((child, child_path, maybe_account));
576                        }
577                    }
578                }
579                TrieNode::Extension(ext) => {
580                    if path.len() + ext.key.len() > 64 {
581                        return Err(alloy_rlp::Error::Custom("extension path exceeds 64 nibbles"));
582                    }
583                    let mut child_path = path;
584                    child_path.extend(&ext.key);
585                    let child = if let Some(hash) = ext.child.as_hash() {
586                        node_by_hash(&hash)?
587                    } else {
588                        Some(TrieNode::decode(&mut ext.child.as_slice())?)
589                    };
590                    if let Some(child) = child {
591                        queue.push_back((child, child_path, maybe_account));
592                    }
593                }
594                TrieNode::Leaf(leaf) => {
595                    if path.len() + leaf.key.len() != 64 {
596                        return Err(alloy_rlp::Error::Custom("leaf path must contain 64 nibbles"));
597                    }
598                    if maybe_account.is_none() {
599                        let mut full_path = path;
600                        full_path.extend(&leaf.key);
601                        let hashed_address = B256::from_slice(&full_path.pack());
602                        let account = TrieAccount::decode(&mut &leaf.value[..])?;
603                        if account.storage_root != EMPTY_ROOT_HASH &&
604                            let Some(node) = node_by_hash(&account.storage_root)?
605                        {
606                            queue.push_back((node, Nibbles::default(), Some(hashed_address)));
607                        }
608                    }
609                }
610                TrieNode::EmptyRoot => {}
611            }
612
613            let node = ProofTrieNode { path, node: trie_node, masks: None };
614            if let Some(account) = maybe_account {
615                storage_proofs.entry(account).or_default().push(node);
616            } else {
617                account_proofs.push(node);
618            }
619        }
620
621        account_proofs.sort_by(|a, b| crate::depth_first_cmp(&a.path, &b.path));
622        for nodes in storage_proofs.values_mut() {
623            nodes.sort_by(|a, b| crate::depth_first_cmp(&a.path, &b.path));
624        }
625
626        Ok(Self { account_proofs, storage_proofs })
627    }
628
629    /// Appends the given multiproof's data to this one.
630    ///
631    /// This implementation does not deduplicate redundant proofs.
632    pub fn extend(&mut self, other: Self) {
633        self.account_proofs.extend(other.account_proofs);
634        for (hashed_address, other_storage_proofs) in other.storage_proofs {
635            match self.storage_proofs.entry(hashed_address) {
636                hash_map::Entry::Vacant(entry) => {
637                    entry.insert(other_storage_proofs);
638                }
639                hash_map::Entry::Occupied(mut entry) => {
640                    entry.get_mut().extend(other_storage_proofs);
641                }
642            }
643        }
644    }
645}
646
647/// Returns proof nodes matching `path` in root-to-leaf order.
648fn matching_v2_proof_nodes<'a>(
649    nodes: &'a [ProofTrieNode],
650    path: &'a Nibbles,
651) -> impl Iterator<Item = &'a ProofTrieNode> + Clone {
652    nodes.iter().rev().filter(move |node| path.starts_with(&node.path))
653}
654
655/// Encodes the proof nodes matching `path` in root-to-leaf order.
656///
657/// A matching extension is followed by its child branch even when `path` diverges within the
658/// extension key, which some proof consumers need to verify absence.
659fn encode_path_proof_nodes(proof_nodes: &[ProofTrieNode], path: &Nibbles) -> Vec<Bytes> {
660    let mut nodes = Vec::new();
661    for (index, node) in proof_nodes.iter().enumerate().rev() {
662        if !path.starts_with(&node.path) {
663            continue
664        }
665        nodes.push(node);
666        // Nodes are in depth-first post-order and an extension has a single child, so its child
667        // branch, if present, is the node right before it.
668        if let TrieNode::Extension(extension) = &node.node &&
669            !path.slice(node.path.len()..).starts_with(&extension.key) &&
670            let Some(branch) = index.checked_sub(1).map(|index| &proof_nodes[index]) &&
671            branch.path.starts_with(&node.path) &&
672            branch.path.slice(node.path.len()..) == extension.key
673        {
674            nodes.push(branch);
675        }
676    }
677    encode_v2_proof_nodes(nodes.into_iter())
678}
679
680/// Encodes V2 proof nodes as standard MPT proof nodes.
681///
682/// Inline children are already encoded in their parent and must not be emitted separately.
683fn encode_v2_proof_nodes<'a>(nodes: impl Iterator<Item = &'a ProofTrieNode>) -> Vec<Bytes> {
684    let mut proof = Vec::new();
685    for proof_node in nodes {
686        let mut encoded = Vec::new();
687        proof_node.node.encode(&mut encoded);
688        if proof_node.path.is_empty() || encoded.len() >= B256::len_bytes() {
689            proof.push(Bytes::from(encoded));
690        }
691    }
692    proof
693}
694
695impl From<DecodedMultiProof> for DecodedMultiProofV2 {
696    fn from(proof: DecodedMultiProof) -> Self {
697        let account_proofs =
698            decoded_proof_nodes_to_v2(proof.account_subtree, &proof.branch_node_masks);
699        let storage_proofs = proof
700            .storages
701            .into_iter()
702            .map(|(address, storage)| {
703                (address, decoded_proof_nodes_to_v2(storage.subtree, &storage.branch_node_masks))
704            })
705            .collect();
706        Self { account_proofs, storage_proofs }
707    }
708}
709
710/// Converts a [`DecodedProofNodes`] (path → [`TrieNode`] map) into a `Vec<ProofTrieNode>`,
711/// preserving separate extension and branch nodes.
712fn decoded_proof_nodes_to_v2(
713    nodes: DecodedProofNodes,
714    masks: &BranchNodeMasksMap,
715) -> Vec<ProofTrieNode> {
716    let mut sorted: Vec<_> = nodes.into_inner().into_iter().collect();
717    sorted.sort_unstable_by(|a, b| crate::depth_first_cmp(&a.0, &b.0));
718    sorted
719        .into_iter()
720        .map(|(path, node)| ProofTrieNode { path, node, masks: masks.get(&path).copied() })
721        .collect()
722}
723
724/// The merkle multiproof of storage trie.
725#[derive(Clone, Debug, PartialEq, Eq)]
726pub struct StorageMultiProof {
727    /// Storage trie root.
728    pub root: B256,
729    /// Storage multiproof for requested slots.
730    pub subtree: ProofNodes,
731    /// Consolidated branch node masks (`hash_mask`, `tree_mask`) for each path in the storage
732    /// proof.
733    pub branch_node_masks: BranchNodeMasksMap,
734}
735
736impl StorageMultiProof {
737    /// Create new storage multiproof for empty trie.
738    pub fn empty() -> Self {
739        Self {
740            root: EMPTY_ROOT_HASH,
741            subtree: ProofNodes::from_iter([(
742                Nibbles::default(),
743                Bytes::from([EMPTY_STRING_CODE]),
744            )]),
745            branch_node_masks: BranchNodeMasksMap::default(),
746        }
747    }
748
749    /// Return storage proofs for the target storage slot (unhashed).
750    pub fn storage_proof(&self, slot: B256) -> Result<StorageProof, alloy_rlp::Error> {
751        let nibbles = Nibbles::unpack(keccak256(slot));
752
753        // Retrieve the storage proof.
754        let proof = self
755            .subtree
756            .matching_nodes_iter(&nibbles)
757            .sorted_by(|a, b| a.0.cmp(b.0))
758            .map(|(_, node)| node.clone())
759            .collect::<Vec<_>>();
760
761        // Inspect the last node in the proof. If it's a leaf node with matching suffix,
762        // then the node contains the encoded slot value.
763        let value = 'value: {
764            if let Some(last) = proof.last() &&
765                let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? &&
766                nibbles.ends_with(&leaf.key)
767            {
768                break 'value U256::decode(&mut &leaf.value[..])?
769            }
770            U256::ZERO
771        };
772
773        Ok(StorageProof { key: slot, nibbles, value, proof })
774    }
775}
776
777/// The decoded merkle multiproof for a storage trie.
778#[derive(Clone, Debug, PartialEq, Eq)]
779pub struct DecodedStorageMultiProof {
780    /// Storage trie root.
781    pub root: B256,
782    /// Storage multiproof for requested slots.
783    pub subtree: DecodedProofNodes,
784    /// Consolidated branch node masks (`hash_mask`, `tree_mask`) for each path in the storage
785    /// proof.
786    pub branch_node_masks: BranchNodeMasksMap,
787}
788
789impl DecodedStorageMultiProof {
790    /// Create new storage multiproof for empty trie.
791    pub fn empty() -> Self {
792        Self {
793            root: EMPTY_ROOT_HASH,
794            subtree: DecodedProofNodes::from_iter([(Nibbles::default(), TrieNode::EmptyRoot)]),
795            branch_node_masks: BranchNodeMasksMap::default(),
796        }
797    }
798
799    /// Return storage proofs for the target storage slot (unhashed).
800    pub fn storage_proof(&self, slot: B256) -> Result<DecodedStorageProof, alloy_rlp::Error> {
801        let nibbles = Nibbles::unpack(keccak256(slot));
802
803        // Retrieve the storage proof.
804        let proof = self
805            .subtree
806            .matching_nodes_iter(&nibbles)
807            .sorted_by(|a, b| a.0.cmp(b.0))
808            .map(|(_, node)| node.clone())
809            .collect::<Vec<_>>();
810
811        // Inspect the last node in the proof. If it's a leaf node with matching suffix,
812        // then the node contains the encoded slot value.
813        let value = 'value: {
814            if let Some(TrieNode::Leaf(leaf)) = proof.last() &&
815                nibbles.ends_with(&leaf.key)
816            {
817                break 'value U256::decode(&mut &leaf.value[..])?
818            }
819            U256::ZERO
820        };
821
822        Ok(DecodedStorageProof { key: slot, nibbles, value, proof })
823    }
824}
825
826impl TryFrom<StorageMultiProof> for DecodedStorageMultiProof {
827    type Error = alloy_rlp::Error;
828
829    fn try_from(multi_proof: StorageMultiProof) -> Result<Self, Self::Error> {
830        let subtree = DecodedProofNodes::try_from(multi_proof.subtree)?;
831        Ok(Self {
832            root: multi_proof.root,
833            subtree,
834            branch_node_masks: multi_proof.branch_node_masks,
835        })
836    }
837}
838
839/// The merkle proof with the relevant account info.
840#[derive(Clone, PartialEq, Eq, Debug)]
841#[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))]
842#[cfg_attr(any(test, feature = "serde"), serde(rename_all = "camelCase"))]
843pub struct AccountProof {
844    /// The address associated with the account.
845    pub address: Address,
846    /// Account info, if any.
847    pub info: Option<Account>,
848    /// Array of rlp-serialized merkle trie nodes which starting from the root node and
849    /// following the path of the hashed address as key.
850    pub proof: Vec<Bytes>,
851    /// The storage trie root.
852    pub storage_root: B256,
853    /// Array of storage proofs as requested.
854    pub storage_proofs: Vec<StorageProof>,
855}
856
857/// Normalize an empty-trie proof for the EIP-1186 (`eth_getProof`) response.
858///
859/// An empty trie is internally represented by a single empty-root sentinel node (`0x80`, the
860/// RLP empty string whose hash is `EMPTY_ROOT_HASH`). EIP-1186 defines the proof field as the
861/// array of trie nodes along the key path; an empty trie has none, and geth returns `[]`. This
862/// strips that lone sentinel so the response matches geth and the spec. It is applied only at
863/// the response boundary, leaving the underlying proof construction unchanged.
864#[cfg(feature = "eip1186")]
865fn normalize_eip1186_empty_trie_proof(proof: Vec<Bytes>) -> Vec<Bytes> {
866    if proof.len() == 1 && proof[0].as_ref() == [EMPTY_STRING_CODE] {
867        Vec::new()
868    } else {
869        proof
870    }
871}
872
873#[cfg(feature = "eip1186")]
874impl AccountProof {
875    /// Convert into an EIP-1186 account proof response.
876    ///
877    /// For non-existent accounts, this returns `KECCAK_EMPTY` for `codeHash` and
878    /// `EMPTY_ROOT_HASH` for `storageHash`, matching reth's default behavior.
879    ///
880    /// Use [`Self::into_eip1186_response_with`] to customize the behavior for
881    /// non-existent accounts (e.g. returning `B256::ZERO` for geth compatibility).
882    pub fn into_eip1186_response(
883        self,
884        slots: Vec<alloy_serde::JsonStorageKey>,
885    ) -> alloy_rpc_types_eth::EIP1186AccountProofResponse {
886        self.into_eip1186_response_with(slots, false)
887    }
888
889    /// Convert into an EIP-1186 account proof response, with optional geth-compatible
890    /// zero hashes for non-existent accounts.
891    ///
892    /// When `zero_empty_account` is `true`, non-existent accounts return `B256::ZERO`
893    /// for both `codeHash` and `storageHash`, matching geth's behavior since v1.13.4
894    /// ([go-ethereum#28357](https://github.com/ethereum/go-ethereum/pull/28357)).
895    ///
896    /// When `false`, returns `KECCAK_EMPTY` / `EMPTY_ROOT_HASH` (reth default).
897    ///
898    /// See: <https://github.com/ethereum/go-ethereum/issues/28441>
899    pub fn into_eip1186_response_with(
900        self,
901        slots: Vec<alloy_serde::JsonStorageKey>,
902        zero_empty_account: bool,
903    ) -> alloy_rpc_types_eth::EIP1186AccountProofResponse {
904        // The proof nodes carry the complete account RLP, including any account extension.
905        let is_non_existent = self.info.is_none();
906        let info = self.info.unwrap_or_default();
907        let (code_hash, storage_hash) = if is_non_existent && zero_empty_account {
908            (B256::ZERO, B256::ZERO)
909        } else {
910            (info.get_bytecode_hash(), self.storage_root)
911        };
912        alloy_rpc_types_eth::EIP1186AccountProofResponse {
913            address: self.address,
914            balance: info.balance,
915            code_hash,
916            nonce: info.nonce,
917            storage_hash,
918            account_proof: normalize_eip1186_empty_trie_proof(self.proof),
919            storage_proof: self
920                .storage_proofs
921                .into_iter()
922                .zip(slots)
923                .map(|(proof, slot)| proof.into_eip1186_proof(slot))
924                .collect(),
925        }
926    }
927
928    /// Converts an
929    /// [`EIP1186AccountProofResponse`](alloy_rpc_types_eth::EIP1186AccountProofResponse) to an
930    /// [`AccountProof`].
931    ///
932    /// This is the inverse of [`Self::into_eip1186_response`]
933    #[allow(clippy::needless_update)]
934    pub fn from_eip1186_proof(proof: alloy_rpc_types_eth::EIP1186AccountProofResponse) -> Self {
935        let alloy_rpc_types_eth::EIP1186AccountProofResponse {
936            nonce,
937            address,
938            balance,
939            code_hash,
940            storage_hash,
941            account_proof,
942            storage_proof,
943            ..
944        } = proof;
945        let storage_proofs = storage_proof.into_iter().map(Into::into).collect();
946
947        // EIP-1186's summary fields omit the account extension, so take it from the account leaf
948        // of an inclusion proof.
949        let leaf_account = Account::EXTENSIONS_ENABLED
950            .then(|| inclusion_proof_account(address, &account_proof))
951            .flatten();
952
953        let (storage_root, info) = if nonce == 0 &&
954            balance.is_zero() &&
955            (storage_hash.is_zero() || storage_hash == EMPTY_ROOT_HASH) &&
956            (code_hash == alloy_consensus::constants::KECCAK_EMPTY || code_hash.is_zero()) &&
957            !leaf_account.as_ref().is_some_and(Account::has_extension)
958        {
959            // Account does not exist in state. Return `None` here to prevent proof
960            // verification.
961            //
962            // Note: geth (since v1.13.4, go-ethereum#28357) returns `B256::ZERO` for
963            // both `codeHash` and `storageHash` in exclusion proofs, while reth
964            // returns `KECCAK_EMPTY` / `EMPTY_ROOT_HASH`. We accept both formats here
965            // so that proofs obtained from any client can be deserialized correctly.
966            // See: https://github.com/ethereum/go-ethereum/issues/28441
967            (EMPTY_ROOT_HASH, None)
968        } else {
969            (
970                storage_hash,
971                Some(Account {
972                    nonce,
973                    balance,
974                    bytecode_hash: code_hash.into(),
975                    ..leaf_account.unwrap_or_default()
976                }),
977            )
978        };
979
980        Self { address, info, proof: account_proof, storage_root, storage_proofs }
981    }
982}
983
984#[cfg(feature = "eip1186")]
985impl From<alloy_rpc_types_eth::EIP1186AccountProofResponse> for AccountProof {
986    fn from(proof: alloy_rpc_types_eth::EIP1186AccountProofResponse) -> Self {
987        Self::from_eip1186_proof(proof)
988    }
989}
990
991/// Returns the account committed by the leaf of an inclusion proof for `address`.
992///
993/// The leaf has to lie on the full path of `address`, so an exclusion proof cannot supply another
994/// account. This does not authenticate the proof root; callers still have to verify the proof
995/// against a trusted state root.
996#[cfg(feature = "eip1186")]
997fn inclusion_proof_account(address: Address, proof: &[Bytes]) -> Option<Account> {
998    let root = keccak256(proof.first()?);
999    let TrieNode::Leaf(leaf) = alloy_rlp::decode_exact::<TrieNode>(proof.last()?).ok()? else {
1000        return None
1001    };
1002    verify_proof(root, Nibbles::unpack(keccak256(address)), Some(leaf.value.clone()), proof)
1003        .ok()?;
1004    alloy_rlp::decode_exact::<TrieAccount>(&leaf.value).ok().map(Account::from)
1005}
1006
1007impl Default for AccountProof {
1008    fn default() -> Self {
1009        Self::new(Address::default())
1010    }
1011}
1012
1013impl AccountProof {
1014    /// Create new account proof entity.
1015    pub const fn new(address: Address) -> Self {
1016        Self {
1017            address,
1018            info: None,
1019            proof: Vec::new(),
1020            storage_root: EMPTY_ROOT_HASH,
1021            storage_proofs: Vec::new(),
1022        }
1023    }
1024
1025    /// Verify the storage proofs and account proof against the provided state root.
1026    #[allow(clippy::clone_on_copy)]
1027    pub fn verify(&self, root: B256) -> Result<(), ProofVerificationError> {
1028        // Verify storage proofs.
1029        for storage_proof in &self.storage_proofs {
1030            storage_proof.verify(self.storage_root)?;
1031        }
1032
1033        // Verify the account proof.
1034        let expected = if self.info.is_none() && self.storage_root == EMPTY_ROOT_HASH {
1035            None
1036        } else {
1037            Some(alloy_rlp::encode(
1038                self.info.clone().unwrap_or_default().into_trie_account(self.storage_root),
1039            ))
1040        };
1041        let nibbles = Nibbles::unpack(keccak256(self.address));
1042        verify_proof(root, nibbles, expected, &self.proof)
1043    }
1044}
1045
1046/// The merkle proof with the relevant account info.
1047#[derive(Clone, PartialEq, Eq, Debug)]
1048pub struct DecodedAccountProof {
1049    /// The address associated with the account.
1050    pub address: Address,
1051    /// Account info.
1052    pub info: Option<Account>,
1053    /// Array of merkle trie nodes which starting from the root node and following the path of the
1054    /// hashed address as key.
1055    pub proof: Vec<TrieNode>,
1056    /// The storage trie root.
1057    pub storage_root: B256,
1058    /// Array of storage proofs as requested.
1059    pub storage_proofs: Vec<DecodedStorageProof>,
1060}
1061
1062impl Default for DecodedAccountProof {
1063    fn default() -> Self {
1064        Self::new(Address::default())
1065    }
1066}
1067
1068impl DecodedAccountProof {
1069    /// Create new account proof entity.
1070    pub const fn new(address: Address) -> Self {
1071        Self {
1072            address,
1073            info: None,
1074            proof: Vec::new(),
1075            storage_root: EMPTY_ROOT_HASH,
1076            storage_proofs: Vec::new(),
1077        }
1078    }
1079}
1080
1081/// The merkle proof of the storage entry.
1082#[derive(Clone, PartialEq, Eq, Default, Debug)]
1083#[cfg_attr(any(test, feature = "serde"), derive(serde::Serialize, serde::Deserialize))]
1084pub struct StorageProof {
1085    /// The raw storage key.
1086    pub key: B256,
1087    /// The hashed storage key nibbles.
1088    pub nibbles: Nibbles,
1089    /// The storage value.
1090    pub value: U256,
1091    /// Array of rlp-serialized merkle trie nodes which starting from the storage root node and
1092    /// following the path of the hashed storage slot as key.
1093    pub proof: Vec<Bytes>,
1094}
1095
1096impl StorageProof {
1097    /// Create new storage proof from the storage slot.
1098    pub fn new(key: B256) -> Self {
1099        let nibbles = Nibbles::unpack(keccak256(key));
1100        Self { key, nibbles, ..Default::default() }
1101    }
1102
1103    /// Create new storage proof from the storage slot and its pre-hashed image.
1104    pub fn new_with_hashed(key: B256, hashed_key: B256) -> Self {
1105        Self { key, nibbles: Nibbles::unpack(hashed_key), ..Default::default() }
1106    }
1107
1108    /// Create new storage proof from the storage slot and its pre-hashed image.
1109    pub fn new_with_nibbles(key: B256, nibbles: Nibbles) -> Self {
1110        Self { key, nibbles, ..Default::default() }
1111    }
1112
1113    /// Set proof nodes on storage proof.
1114    pub fn with_proof(mut self, proof: Vec<Bytes>) -> Self {
1115        self.proof = proof;
1116        self
1117    }
1118
1119    /// Verify the proof against the provided storage root.
1120    pub fn verify(&self, root: B256) -> Result<(), ProofVerificationError> {
1121        let expected =
1122            if self.value.is_zero() { None } else { Some(encode_fixed_size(&self.value).to_vec()) };
1123        verify_proof(root, self.nibbles, expected, &self.proof)
1124    }
1125}
1126
1127#[cfg(feature = "eip1186")]
1128impl StorageProof {
1129    /// Convert into an EIP-1186 storage proof
1130    pub fn into_eip1186_proof(
1131        self,
1132        slot: alloy_serde::JsonStorageKey,
1133    ) -> alloy_rpc_types_eth::EIP1186StorageProof {
1134        alloy_rpc_types_eth::EIP1186StorageProof {
1135            key: slot,
1136            value: self.value,
1137            proof: normalize_eip1186_empty_trie_proof(self.proof),
1138        }
1139    }
1140
1141    /// Convert from an
1142    /// [`EIP1186StorageProof`](alloy_rpc_types_eth::EIP1186StorageProof)
1143    ///
1144    /// This is the inverse of [`Self::into_eip1186_proof`].
1145    pub fn from_eip1186_proof(storage_proof: alloy_rpc_types_eth::EIP1186StorageProof) -> Self {
1146        Self {
1147            value: storage_proof.value,
1148            proof: storage_proof.proof,
1149            ..Self::new(storage_proof.key.as_b256())
1150        }
1151    }
1152}
1153
1154#[cfg(feature = "eip1186")]
1155impl From<alloy_rpc_types_eth::EIP1186StorageProof> for StorageProof {
1156    fn from(proof: alloy_rpc_types_eth::EIP1186StorageProof) -> Self {
1157        Self::from_eip1186_proof(proof)
1158    }
1159}
1160
1161/// The merkle proof of the storage entry, using decoded proofs.
1162#[derive(Clone, PartialEq, Eq, Default, Debug)]
1163pub struct DecodedStorageProof {
1164    /// The raw storage key.
1165    pub key: B256,
1166    /// The hashed storage key nibbles.
1167    pub nibbles: Nibbles,
1168    /// The storage value.
1169    pub value: U256,
1170    /// Array of merkle trie nodes which starting from the storage root node and following the path
1171    /// of the hashed storage slot as key.
1172    pub proof: Vec<TrieNode>,
1173}
1174
1175impl DecodedStorageProof {
1176    /// Create new storage proof from the storage slot.
1177    pub fn new(key: B256) -> Self {
1178        let nibbles = Nibbles::unpack(keccak256(key));
1179        Self { key, nibbles, ..Default::default() }
1180    }
1181
1182    /// Create new storage proof from the storage slot and its pre-hashed image.
1183    pub fn new_with_hashed(key: B256, hashed_key: B256) -> Self {
1184        Self { key, nibbles: Nibbles::unpack(hashed_key), ..Default::default() }
1185    }
1186
1187    /// Create new storage proof from the storage slot and its pre-hashed image.
1188    pub fn new_with_nibbles(key: B256, nibbles: Nibbles) -> Self {
1189        Self { key, nibbles, ..Default::default() }
1190    }
1191
1192    /// Set proof nodes on storage proof.
1193    pub fn with_proof(mut self, proof: Vec<TrieNode>) -> Self {
1194        self.proof = proof;
1195        self
1196    }
1197}
1198
1199/// Implementation of hasher using our keccak256 hashing function
1200/// for compatibility with `triehash` crate.
1201#[cfg(any(test, feature = "test-utils"))]
1202pub mod triehash {
1203    use alloy_primitives::{keccak256, B256};
1204    use alloy_rlp::RlpEncodable;
1205    use hash_db::Hasher;
1206    use plain_hasher::PlainHasher;
1207
1208    /// A [Hasher] that calculates a keccak256 hash of the given data.
1209    #[derive(Default, Debug, Clone, PartialEq, Eq, RlpEncodable)]
1210    #[non_exhaustive]
1211    pub struct KeccakHasher;
1212
1213    #[cfg(any(test, feature = "test-utils"))]
1214    impl Hasher for KeccakHasher {
1215        type Out = B256;
1216        type StdHasher = PlainHasher;
1217
1218        const LENGTH: usize = 32;
1219
1220        fn hash(x: &[u8]) -> Self::Out {
1221            keccak256(x)
1222        }
1223    }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228    use super::*;
1229    use crate::BranchNodeMasks;
1230    use alloy_trie::{
1231        nodes::{BranchNode, ExtensionNode, LeafNode, RlpNode},
1232        TrieMask,
1233    };
1234
1235    #[cfg(feature = "eip1186")]
1236    use alloy_consensus::constants::KECCAK_EMPTY;
1237
1238    #[test]
1239    fn v2_account_proof_preserves_extension_branch() {
1240        let branch =
1241            BranchNode::new(vec![RlpNode::word_rlp(&B256::repeat_byte(0x11))], TrieMask::from(1));
1242        let branch_rlp = alloy_rlp::encode(&branch);
1243        let key = Nibbles::unpack(keccak256(Address::ZERO)).slice(0..2);
1244        let extension =
1245            TrieNode::Extension(ExtensionNode::new(key, RlpNode::from_rlp(&branch_rlp)));
1246        let extension_rlp = alloy_rlp::encode(&extension);
1247        let multiproof = DecodedMultiProofV2 {
1248            account_proofs: vec![
1249                ProofTrieNode { path: key, node: TrieNode::Branch(branch), masks: None },
1250                ProofTrieNode { path: Nibbles::default(), node: extension, masks: None },
1251            ],
1252            ..Default::default()
1253        };
1254
1255        let proof = multiproof.account_proof(Address::ZERO, &[]).unwrap();
1256
1257        assert_eq!(proof.proof, vec![Bytes::from(extension_rlp), Bytes::from(branch_rlp)]);
1258        assert!(proof.info.is_none());
1259    }
1260
1261    #[test]
1262    fn v2_proof_keeps_excluded_extension_branch() {
1263        // Returns proof nodes for an extension whose key diverges from `path` at its second
1264        // nibble, with the extension and child branch encodings.
1265        fn diverging_extension(path: &Nibbles) -> (Vec<ProofTrieNode>, Bytes, Bytes) {
1266            let branch = BranchNode::new(
1267                vec![RlpNode::word_rlp(&B256::repeat_byte(0x11))],
1268                TrieMask::from(1),
1269            );
1270            let branch_rlp = alloy_rlp::encode(&branch);
1271            let key = Nibbles::from_nibbles([path.get(0).unwrap(), path.get(1).unwrap() ^ 1]);
1272            let extension =
1273                TrieNode::Extension(ExtensionNode::new(key, RlpNode::from_rlp(&branch_rlp)));
1274            let extension_rlp = alloy_rlp::encode(&extension);
1275            let nodes = vec![
1276                ProofTrieNode { path: key, node: TrieNode::Branch(branch), masks: None },
1277                ProofTrieNode { path: Nibbles::default(), node: extension, masks: None },
1278            ];
1279            (nodes, Bytes::from(extension_rlp), Bytes::from(branch_rlp))
1280        }
1281
1282        let hashed_address = keccak256(Address::ZERO);
1283        let (account_proofs, account_extension, account_branch) =
1284            diverging_extension(&Nibbles::unpack(hashed_address));
1285        let (storage_nodes, storage_extension, storage_branch) =
1286            diverging_extension(&Nibbles::unpack(keccak256(B256::ZERO)));
1287        let multiproof = DecodedMultiProofV2 {
1288            account_proofs,
1289            storage_proofs: B256Map::from_iter([(hashed_address, storage_nodes)]),
1290        };
1291
1292        let proof = multiproof.account_proof(Address::ZERO, &[B256::ZERO]).unwrap();
1293        assert_eq!(proof.proof, vec![account_extension, account_branch]);
1294        assert_eq!(proof.storage_proofs[0].proof, vec![storage_extension, storage_branch]);
1295    }
1296
1297    #[test]
1298    fn v2_proof_ignores_overlong_extension() {
1299        let path = Nibbles::unpack(keccak256(Address::ZERO));
1300        let branch =
1301            BranchNode::new(vec![RlpNode::word_rlp(&B256::repeat_byte(0x11))], TrieMask::from(1));
1302        let branch_rlp = alloy_rlp::encode(&branch);
1303        // The key diverges from `path` and would take the branch path past 64 nibbles.
1304        let extension_path = path.slice(..63);
1305        let key = Nibbles::from_nibbles([path.get(63).unwrap() ^ 1, 0]);
1306        let extension =
1307            TrieNode::Extension(ExtensionNode::new(key, RlpNode::from_rlp(&branch_rlp)));
1308        let extension_rlp = alloy_rlp::encode(&extension);
1309        let multiproof = DecodedMultiProofV2 {
1310            account_proofs: vec![
1311                ProofTrieNode {
1312                    path: Nibbles::from_nibbles([path.get(0).unwrap() ^ 1]),
1313                    node: TrieNode::Branch(branch),
1314                    masks: None,
1315                },
1316                ProofTrieNode { path: extension_path, node: extension, masks: None },
1317            ],
1318            ..Default::default()
1319        };
1320
1321        let proof = multiproof.account_proof(Address::ZERO, &[]).unwrap();
1322
1323        assert_eq!(proof.proof, vec![Bytes::from(extension_rlp)]);
1324    }
1325
1326    fn decode_witness(witness: &B256Map<impl AsRef<[u8]>>) -> B256Map<TrieNode> {
1327        witness
1328            .iter()
1329            .map(|(hash, bytes)| (*hash, TrieNode::decode(&mut bytes.as_ref()).unwrap()))
1330            .collect()
1331    }
1332
1333    #[test]
1334    fn decoded_multiproof_preserves_extensions_and_branch_masks() {
1335        let branch = TrieNode::Branch(BranchNode::new(
1336            vec![RlpNode::word_rlp(&B256::repeat_byte(0x11)); 2],
1337            TrieMask::new(0b11),
1338        ));
1339        let branch_path = Nibbles::from_nibbles([1, 2]);
1340        let extension = TrieNode::Extension(ExtensionNode::new(
1341            branch_path,
1342            RlpNode::from_rlp(&alloy_rlp::encode(&branch)),
1343        ));
1344        let masks = BranchNodeMasks { hash_mask: TrieMask::new(0b11), tree_mask: TrieMask::new(1) };
1345        let decoded = DecodedMultiProof {
1346            account_subtree: DecodedProofNodes::from_iter([
1347                (Nibbles::default(), extension.clone()),
1348                (branch_path, branch.clone()),
1349            ]),
1350            branch_node_masks: BranchNodeMasksMap::from_iter([(branch_path, masks)]),
1351            ..Default::default()
1352        };
1353
1354        let proof = DecodedMultiProofV2::from(decoded);
1355
1356        assert_eq!(
1357            proof.account_proofs,
1358            vec![
1359                ProofTrieNode { path: branch_path, node: branch, masks: Some(masks) },
1360                ProofTrieNode { path: Nibbles::default(), node: extension, masks: None },
1361            ]
1362        );
1363    }
1364
1365    #[test]
1366    fn witness_preserves_extension_with_unrevealed_child() {
1367        let extension = TrieNode::Extension(ExtensionNode::new(
1368            Nibbles::from_nibbles([1, 2]),
1369            RlpNode::word_rlp(&B256::repeat_byte(0x11)),
1370        ));
1371        let encoded = alloy_rlp::encode(&extension);
1372        let state_root = keccak256(&encoded);
1373        let witness = B256Map::from_iter([(state_root, Bytes::from(encoded))]);
1374
1375        let proof = DecodedMultiProofV2::from_witness(state_root, &witness).unwrap();
1376
1377        assert_eq!(
1378            DecodedMultiProofV2::from_witness_decoded(state_root, &decode_witness(&witness)),
1379            Ok(proof.clone())
1380        );
1381
1382        assert_eq!(
1383            proof.account_proofs,
1384            vec![ProofTrieNode { path: Nibbles::default(), node: extension, masks: None }]
1385        );
1386    }
1387
1388    #[test]
1389    fn witness_nodes_are_depth_first_ordered() {
1390        fn insert_node(witness: &mut B256Map<Bytes>, node: impl alloy_rlp::Encodable) -> RlpNode {
1391            let encoded = alloy_rlp::encode(node);
1392            witness.insert(keccak256(&encoded), encoded.clone().into());
1393            RlpNode::from_rlp(&encoded)
1394        }
1395
1396        let mut witness = B256Map::default();
1397        let leaf_key = Nibbles::from_nibbles([0; 63]);
1398
1399        let storage_leaf_0 = insert_node(
1400            &mut witness,
1401            LeafNode::new(leaf_key, encode_fixed_size(&U256::ONE).to_vec()),
1402        );
1403        let storage_leaf_1 = insert_node(
1404            &mut witness,
1405            LeafNode::new(leaf_key, encode_fixed_size(&U256::from(2)).to_vec()),
1406        );
1407        let storage_root = insert_node(
1408            &mut witness,
1409            BranchNode::new(vec![storage_leaf_0, storage_leaf_1], TrieMask::new(0b11)),
1410        );
1411
1412        let account_leaf_0 = insert_node(
1413            &mut witness,
1414            LeafNode::new(
1415                leaf_key,
1416                alloy_rlp::encode(TrieAccount {
1417                    storage_root: storage_root.as_hash().expect("storage root is hashed"),
1418                    ..Default::default()
1419                }),
1420            ),
1421        );
1422        let account_leaf_1 = insert_node(
1423            &mut witness,
1424            LeafNode::new(leaf_key, alloy_rlp::encode(TrieAccount::default())),
1425        );
1426        let state_root = insert_node(
1427            &mut witness,
1428            BranchNode::new(vec![account_leaf_0, account_leaf_1], TrieMask::new(0b11)),
1429        )
1430        .as_hash()
1431        .expect("state root is hashed");
1432
1433        let proof = DecodedMultiProofV2::from_witness(state_root, &witness).unwrap();
1434        assert_eq!(
1435            DecodedMultiProofV2::from_witness_decoded(state_root, &decode_witness(&witness)),
1436            Ok(proof.clone())
1437        );
1438        let expected_paths =
1439            [Nibbles::from_nibbles([0]), Nibbles::from_nibbles([1]), Nibbles::default()];
1440
1441        assert_eq!(
1442            proof.account_proofs.iter().map(|node| node.path).collect::<Vec<_>>(),
1443            expected_paths
1444        );
1445        assert_eq!(
1446            proof.storage_proofs[&B256::ZERO].iter().map(|node| node.path).collect::<Vec<_>>(),
1447            expected_paths
1448        );
1449    }
1450
1451    #[test]
1452    fn witness_nodes_follow_inline_children() {
1453        let leaf_key = Nibbles::from_nibbles([0]);
1454        let leaf_0 =
1455            alloy_rlp::encode(LeafNode::new(leaf_key, encode_fixed_size(&U256::ONE).to_vec()));
1456        let leaf_1 =
1457            alloy_rlp::encode(LeafNode::new(leaf_key, encode_fixed_size(&U256::from(2)).to_vec()));
1458        assert!(leaf_0.len() < B256::len_bytes());
1459        assert!(leaf_1.len() < B256::len_bytes());
1460
1461        let branch = alloy_rlp::encode(BranchNode::new(
1462            vec![RlpNode::from_rlp(&leaf_0), RlpNode::from_rlp(&leaf_1)],
1463            TrieMask::new(0b11),
1464        ));
1465        assert!(branch.len() < B256::len_bytes());
1466
1467        let extension_key = Nibbles::from_nibbles([0; 62]);
1468        let storage_root_node =
1469            alloy_rlp::encode(ExtensionNode::new(extension_key, RlpNode::from_rlp(&branch)));
1470        let storage_root = keccak256(&storage_root_node);
1471
1472        let account_root_node = alloy_rlp::encode(LeafNode::new(
1473            Nibbles::from_nibbles([0; 64]),
1474            alloy_rlp::encode(TrieAccount { storage_root, ..Default::default() }),
1475        ));
1476        let state_root = keccak256(&account_root_node);
1477        let witness = B256Map::from_iter([
1478            (state_root, Bytes::from(account_root_node)),
1479            (storage_root, Bytes::from(storage_root_node)),
1480        ]);
1481
1482        let proof = DecodedMultiProofV2::from_witness(state_root, &witness).unwrap();
1483        assert_eq!(
1484            DecodedMultiProofV2::from_witness_decoded(state_root, &decode_witness(&witness)),
1485            Ok(proof.clone())
1486        );
1487        let mut leaf_0_path = extension_key;
1488        leaf_0_path.push_unchecked(0);
1489        let mut leaf_1_path = extension_key;
1490        leaf_1_path.push_unchecked(1);
1491
1492        assert_eq!(
1493            proof.storage_proofs[&B256::ZERO].iter().map(|node| node.path).collect::<Vec<_>>(),
1494            [leaf_0_path, leaf_1_path, extension_key, Nibbles::default()]
1495        );
1496
1497        let nodes = &proof.storage_proofs[&B256::ZERO];
1498        for (path, value) in [(leaf_0_path, 1), (leaf_1_path, 2)] {
1499            let key = path.join(&leaf_key);
1500            let encoded = encode_v2_proof_nodes(matching_v2_proof_nodes(nodes, &key));
1501            assert_eq!(encoded, vec![witness[&storage_root].clone()]);
1502            verify_proof(storage_root, key, Some(alloy_rlp::encode(U256::from(value))), &encoded)
1503                .unwrap();
1504        }
1505    }
1506
1507    #[test]
1508    fn v2_proof_encoding_keeps_short_root() {
1509        let leaf = LeafNode::new(Nibbles::default(), vec![1]);
1510        let encoded = alloy_rlp::encode(&leaf);
1511        assert!(encoded.len() < 32);
1512        let nodes =
1513            [ProofTrieNode { path: Nibbles::default(), node: TrieNode::Leaf(leaf), masks: None }];
1514        assert_eq!(encode_v2_proof_nodes(nodes.iter()), vec![Bytes::from(encoded)]);
1515    }
1516
1517    #[test]
1518    fn witness_rejects_invalid_path_lengths() {
1519        let leaf = alloy_rlp::encode(LeafNode::new(Nibbles::default(), vec![1]));
1520        let branch = alloy_rlp::encode(BranchNode::new(
1521            vec![RlpNode::from_rlp(&leaf), RlpNode::from_rlp(&leaf)],
1522            TrieMask::new(0b11),
1523        ));
1524        let extension = alloy_rlp::encode(ExtensionNode::new(
1525            Nibbles::from_nibbles([0]),
1526            RlpNode::from_rlp(&branch),
1527        ));
1528
1529        let long_leaf = alloy_rlp::encode(LeafNode::new(Nibbles::from_nibbles([0]), vec![1]));
1530        for (child, depth, expected) in [
1531            (&branch, 64, "branch path exceeds 64 nibbles"),
1532            (&extension, 64, "extension path exceeds 64 nibbles"),
1533            (&leaf, 63, "leaf path must contain 64 nibbles"),
1534            (&long_leaf, 64, "leaf path must contain 64 nibbles"),
1535        ] {
1536            let storage = alloy_rlp::encode(ExtensionNode::new(
1537                Nibbles::from_nibbles(vec![0; depth]),
1538                RlpNode::from_rlp(child),
1539            ));
1540            let storage_root = keccak256(&storage);
1541            let account = alloy_rlp::encode(LeafNode::new(
1542                Nibbles::from_nibbles([0; 64]),
1543                alloy_rlp::encode(TrieAccount { storage_root, ..Default::default() }),
1544            ));
1545            let state_root = keccak256(&account);
1546            let witness = B256Map::from_iter([(state_root, account), (storage_root, storage)]);
1547            assert_eq!(
1548                DecodedMultiProofV2::from_witness(state_root, &witness),
1549                Err(alloy_rlp::Error::Custom(expected)),
1550            );
1551            assert_eq!(
1552                DecodedMultiProofV2::from_witness_decoded(state_root, &decode_witness(&witness)),
1553                Err(alloy_rlp::Error::Custom(expected)),
1554            );
1555        }
1556
1557        for length in [63, 65] {
1558            // A branch adds one nibble to the account leaf's path.
1559            let account = alloy_rlp::encode(LeafNode::new(
1560                Nibbles::from_nibbles(vec![0; length - 1]),
1561                alloy_rlp::encode(TrieAccount::default()),
1562            ));
1563            let hash = keccak256(&account);
1564            let root = alloy_rlp::encode(BranchNode::new(
1565                vec![RlpNode::word_rlp(&hash), RlpNode::word_rlp(&hash)],
1566                TrieMask::new(0b11),
1567            ));
1568            let state_root = keccak256(&root);
1569            let witness = B256Map::from_iter([(state_root, root), (hash, account)]);
1570            assert_eq!(
1571                DecodedMultiProofV2::from_witness(state_root, &witness),
1572                Err(alloy_rlp::Error::Custom("leaf path must contain 64 nibbles")),
1573            );
1574            assert_eq!(
1575                DecodedMultiProofV2::from_witness_decoded(state_root, &decode_witness(&witness)),
1576                Err(alloy_rlp::Error::Custom("leaf path must contain 64 nibbles")),
1577            );
1578        }
1579    }
1580
1581    #[test]
1582    fn test_multiproof_extend_account_proofs() {
1583        let mut proof1 = MultiProof::default();
1584        let mut proof2 = MultiProof::default();
1585
1586        let addr1 = B256::random();
1587        let addr2 = B256::random();
1588
1589        proof1.account_subtree.insert(
1590            Nibbles::unpack(addr1),
1591            alloy_rlp::encode_fixed_size(&U256::from(42)).to_vec().into(),
1592        );
1593        proof2.account_subtree.insert(
1594            Nibbles::unpack(addr2),
1595            alloy_rlp::encode_fixed_size(&U256::from(43)).to_vec().into(),
1596        );
1597
1598        proof1.extend(proof2);
1599
1600        assert!(proof1.account_subtree.contains_key(&Nibbles::unpack(addr1)));
1601        assert!(proof1.account_subtree.contains_key(&Nibbles::unpack(addr2)));
1602    }
1603
1604    #[test]
1605    fn test_multiproof_extend_storage_proofs() {
1606        let mut proof1 = MultiProof::default();
1607        let mut proof2 = MultiProof::default();
1608
1609        let addr = B256::random();
1610        let root = B256::random();
1611
1612        let mut subtree1 = ProofNodes::default();
1613        subtree1.insert(
1614            Nibbles::from_nibbles(vec![0]),
1615            alloy_rlp::encode_fixed_size(&U256::from(42)).to_vec().into(),
1616        );
1617        proof1.storages.insert(
1618            addr,
1619            StorageMultiProof {
1620                root,
1621                subtree: subtree1,
1622                branch_node_masks: BranchNodeMasksMap::default(),
1623            },
1624        );
1625
1626        let mut subtree2 = ProofNodes::default();
1627        subtree2.insert(
1628            Nibbles::from_nibbles(vec![1]),
1629            alloy_rlp::encode_fixed_size(&U256::from(43)).to_vec().into(),
1630        );
1631        proof2.storages.insert(
1632            addr,
1633            StorageMultiProof {
1634                root,
1635                subtree: subtree2,
1636                branch_node_masks: BranchNodeMasksMap::default(),
1637            },
1638        );
1639
1640        proof1.extend(proof2);
1641
1642        let storage = proof1.storages.get(&addr).unwrap();
1643        assert_eq!(storage.root, root);
1644        assert!(storage.subtree.contains_key(&Nibbles::from_nibbles(vec![0])));
1645        assert!(storage.subtree.contains_key(&Nibbles::from_nibbles(vec![1])));
1646    }
1647
1648    #[test]
1649    fn test_multi_proof_retain_difference() {
1650        let mut empty = MultiProofTargets::default();
1651        empty.retain_difference(&Default::default());
1652        assert!(empty.is_empty());
1653
1654        let targets = MultiProofTargets::accounts((0..10).map(B256::with_last_byte));
1655
1656        let mut diffed = targets.clone();
1657        diffed.retain_difference(&MultiProofTargets::account(B256::with_last_byte(11)));
1658        assert_eq!(diffed, targets);
1659
1660        diffed.retain_difference(&MultiProofTargets::accounts((0..5).map(B256::with_last_byte)));
1661        assert_eq!(diffed, MultiProofTargets::accounts((5..10).map(B256::with_last_byte)));
1662
1663        diffed.retain_difference(&targets);
1664        assert!(diffed.is_empty());
1665
1666        let mut targets = MultiProofTargets::default();
1667        let (account1, account2, account3) =
1668            (1..=3).map(B256::with_last_byte).collect_tuple().unwrap();
1669        let account2_slots = (1..5).map(B256::with_last_byte).collect::<B256Set>();
1670        targets.insert(account1, B256Set::from_iter([B256::with_last_byte(1)]));
1671        targets.insert(account2, account2_slots.clone());
1672        targets.insert(account3, B256Set::from_iter([B256::with_last_byte(1)]));
1673
1674        let mut diffed = targets.clone();
1675        diffed.retain_difference(&MultiProofTargets::accounts((1..=3).map(B256::with_last_byte)));
1676        assert_eq!(diffed, targets);
1677
1678        // remove last 3 slots for account 2
1679        let mut account2_slots_expected_len = account2_slots.len();
1680        for slot in account2_slots.iter().skip(1) {
1681            diffed.retain_difference(&MultiProofTargets::account_with_slots(account2, [*slot]));
1682            account2_slots_expected_len -= 1;
1683            assert_eq!(
1684                diffed.get(&account2).map(|slots| slots.len()),
1685                Some(account2_slots_expected_len)
1686            );
1687        }
1688
1689        diffed.retain_difference(&targets);
1690        assert!(diffed.is_empty());
1691    }
1692
1693    #[test]
1694    fn test_multi_proof_retain_difference_no_overlap() {
1695        let mut targets = MultiProofTargets::default();
1696
1697        // populate some targets
1698        let (addr1, addr2) = (B256::random(), B256::random());
1699        let (slot1, slot2) = (B256::random(), B256::random());
1700        targets.insert(addr1, std::iter::once(slot1).collect());
1701        targets.insert(addr2, std::iter::once(slot2).collect());
1702
1703        let mut retained = targets.clone();
1704        retained.retain_difference(&Default::default());
1705        assert_eq!(retained, targets);
1706
1707        // add a different addr and slot to fetched proof targets
1708        let mut other_targets = MultiProofTargets::default();
1709        let addr3 = B256::random();
1710        let slot3 = B256::random();
1711        other_targets.insert(addr3, B256Set::from_iter([slot3]));
1712
1713        // check that the prefetch proof targets are the same because the fetched proof targets
1714        // don't overlap with the prefetch targets
1715        let mut retained = targets.clone();
1716        retained.retain_difference(&other_targets);
1717        assert_eq!(retained, targets);
1718    }
1719
1720    #[test]
1721    fn test_get_prefetch_proof_targets_remove_subset() {
1722        // populate some targets
1723        let mut targets = MultiProofTargets::default();
1724        let (addr1, addr2) = (B256::random(), B256::random());
1725        let (slot1, slot2) = (B256::random(), B256::random());
1726        targets.insert(addr1, B256Set::from_iter([slot1]));
1727        targets.insert(addr2, B256Set::from_iter([slot2]));
1728
1729        // add a subset of the first target to other proof targets
1730        let other_targets = MultiProofTargets::account_with_slots(addr1, [slot1]);
1731
1732        let mut retained = targets.clone();
1733        retained.retain_difference(&other_targets);
1734
1735        // check that the prefetch proof targets do not include the subset
1736        assert_eq!(retained.len(), 1);
1737        assert!(!retained.contains_key(&addr1));
1738        assert!(retained.contains_key(&addr2));
1739
1740        // now add one more slot to the prefetch targets
1741        let slot3 = B256::random();
1742        targets.get_mut(&addr1).unwrap().insert(slot3);
1743
1744        let mut retained = targets.clone();
1745        retained.retain_difference(&other_targets);
1746
1747        // check that the prefetch proof targets do not include the subset
1748        // but include the new slot
1749        assert_eq!(retained.len(), 2);
1750        assert!(retained.contains_key(&addr1));
1751        assert_eq!(retained.get(&addr1), Some(&B256Set::from_iter([slot3])));
1752        assert!(retained.contains_key(&addr2));
1753        assert_eq!(retained.get(&addr2), Some(&B256Set::from_iter([slot2])));
1754    }
1755
1756    #[test]
1757    #[cfg(feature = "eip1186")]
1758    fn eip_1186_roundtrip() {
1759        let mut acc = AccountProof {
1760            address: Address::random(),
1761            info: Some(
1762                // non-empty account
1763                Account { nonce: 100, bytecode_hash: Some(KECCAK_EMPTY), ..Default::default() },
1764            ),
1765            proof: vec![],
1766            storage_root: B256::ZERO,
1767            storage_proofs: vec![],
1768        };
1769
1770        let rpc_proof = acc.clone().into_eip1186_response(Vec::new());
1771        let inverse: AccountProof = rpc_proof.into();
1772        assert_eq!(acc, inverse);
1773
1774        // make account empty
1775        acc.info.as_mut().unwrap().nonce = 0;
1776        let rpc_proof = acc.clone().into_eip1186_response(Vec::new());
1777        let inverse: AccountProof = rpc_proof.into();
1778        acc.info.take();
1779        acc.storage_root = EMPTY_ROOT_HASH;
1780        assert_eq!(acc, inverse);
1781    }
1782
1783    #[test]
1784    #[cfg(feature = "eip1186")]
1785    fn from_eip1186_proof_accepts_geth_zero_hashes() {
1786        // geth (since v1.13.4) returns B256::ZERO for codeHash and storageHash
1787        // in exclusion proofs for non-existent accounts, instead of
1788        // KECCAK_EMPTY / EMPTY_ROOT_HASH. Verify that from_eip1186_proof
1789        // correctly recognizes this format as a non-existent account.
1790        let geth_proof = alloy_rpc_types_eth::EIP1186AccountProofResponse {
1791            address: Address::random(),
1792            balance: U256::ZERO,
1793            code_hash: B256::ZERO,
1794            nonce: 0,
1795            storage_hash: B256::ZERO,
1796            account_proof: vec![],
1797            storage_proof: vec![],
1798        };
1799
1800        let acc: AccountProof = geth_proof.into();
1801        // Should be interpreted as a non-existent account (info = None)
1802        assert!(acc.info.is_none());
1803        assert_eq!(acc.storage_root, EMPTY_ROOT_HASH);
1804    }
1805
1806    #[test]
1807    #[cfg(feature = "eip1186")]
1808    fn from_eip1186_proof_recovers_account_extension() {
1809        if !Account::EXTENSIONS_ENABLED {
1810            return;
1811        }
1812
1813        // An account that only has an extension, encoded as the fifth field of the trie account.
1814        let extension = [0x82, 0xaa];
1815        let payload_length = 0u64.length() +
1816            U256::ZERO.length() +
1817            EMPTY_ROOT_HASH.length() +
1818            KECCAK_EMPTY.length() +
1819            extension[..].length();
1820        let mut value = Vec::new();
1821        alloy_rlp::Header { list: true, payload_length }.encode(&mut value);
1822        0u64.encode(&mut value);
1823        U256::ZERO.encode(&mut value);
1824        EMPTY_ROOT_HASH.encode(&mut value);
1825        KECCAK_EMPTY.encode(&mut value);
1826        extension[..].encode(&mut value);
1827
1828        // A trie holding only this account, so its leaf is the root.
1829        let address = Address::with_last_byte(1);
1830        let leaf = alloy_rlp::encode(LeafNode::new(Nibbles::unpack(keccak256(address)), value));
1831        let root = keccak256(&leaf);
1832        let response = alloy_rpc_types_eth::EIP1186AccountProofResponse {
1833            address,
1834            balance: U256::ZERO,
1835            code_hash: KECCAK_EMPTY,
1836            nonce: 0,
1837            storage_hash: EMPTY_ROOT_HASH,
1838            account_proof: vec![leaf.into()],
1839            storage_proof: vec![],
1840        };
1841
1842        let proof = AccountProof::from_eip1186_proof(response.clone());
1843        assert!(proof.info.as_ref().is_some_and(Account::has_extension));
1844        assert_eq!(proof.verify(root), Ok(()));
1845
1846        // An exclusion proof for another address ends in the same leaf, which is not its account.
1847        let other =
1848            AccountProof::from_eip1186_proof(alloy_rpc_types_eth::EIP1186AccountProofResponse {
1849                address: Address::with_last_byte(2),
1850                ..response
1851            });
1852        assert_eq!(other.info, None);
1853        assert_eq!(other.verify(root), Ok(()));
1854    }
1855
1856    #[test]
1857    #[cfg(feature = "eip1186")]
1858    fn from_eip1186_proof_accepts_empty_hashes() {
1859        let proof = alloy_rpc_types_eth::EIP1186AccountProofResponse {
1860            address: Address::random(),
1861            balance: U256::ZERO,
1862            code_hash: KECCAK_EMPTY,
1863            nonce: 0,
1864            storage_hash: EMPTY_ROOT_HASH,
1865            account_proof: vec![],
1866            storage_proof: vec![],
1867        };
1868
1869        let acc: AccountProof = proof.into();
1870        assert!(acc.info.is_none());
1871        assert_eq!(acc.storage_root, EMPTY_ROOT_HASH);
1872    }
1873
1874    #[test]
1875    #[cfg(feature = "eip1186")]
1876    #[allow(clippy::needless_update)]
1877    fn into_eip1186_response_zero_empty_account() {
1878        // Non-existent account (info = None)
1879        let acc = AccountProof {
1880            address: Address::random(),
1881            info: None,
1882            proof: vec![],
1883            storage_root: EMPTY_ROOT_HASH,
1884            storage_proofs: vec![],
1885        };
1886
1887        // Default behavior: KECCAK_EMPTY / EMPTY_ROOT_HASH
1888        let rpc_default = acc.clone().into_eip1186_response(Vec::new());
1889        assert_eq!(rpc_default.code_hash, KECCAK_EMPTY);
1890        assert_eq!(rpc_default.storage_hash, EMPTY_ROOT_HASH);
1891
1892        // zero_empty_account = false: same as default
1893        let rpc_compat_off = acc.clone().into_eip1186_response_with(Vec::new(), false);
1894        assert_eq!(rpc_compat_off.code_hash, KECCAK_EMPTY);
1895        assert_eq!(rpc_compat_off.storage_hash, EMPTY_ROOT_HASH);
1896
1897        // zero_empty_account = true: B256::ZERO (geth-compat)
1898        let rpc_compat_on = acc.into_eip1186_response_with(Vec::new(), true);
1899        assert_eq!(rpc_compat_on.code_hash, B256::ZERO);
1900        assert_eq!(rpc_compat_on.storage_hash, B256::ZERO);
1901
1902        // Existing account should NOT be affected by zero_empty_account
1903        let existing_acc = AccountProof {
1904            address: Address::random(),
1905            info: Some(Account {
1906                nonce: 42,
1907                balance: U256::from(100),
1908                bytecode_hash: Some(KECCAK_EMPTY),
1909                ..Default::default()
1910            }),
1911            proof: vec![],
1912            storage_root: B256::random(),
1913            storage_proofs: vec![],
1914        };
1915        let rpc_existing = existing_acc.clone().into_eip1186_response_with(Vec::new(), true);
1916        assert_eq!(rpc_existing.code_hash, KECCAK_EMPTY);
1917        assert_eq!(rpc_existing.storage_hash, existing_acc.storage_root);
1918    }
1919
1920    #[test]
1921    fn test_multiproof_targets_chunking_length() {
1922        let mut targets = MultiProofTargets::default();
1923        targets.insert(B256::with_last_byte(1), B256Set::default());
1924        targets.insert(
1925            B256::with_last_byte(2),
1926            B256Set::from_iter([B256::with_last_byte(10), B256::with_last_byte(20)]),
1927        );
1928        targets.insert(
1929            B256::with_last_byte(3),
1930            B256Set::from_iter([
1931                B256::with_last_byte(30),
1932                B256::with_last_byte(31),
1933                B256::with_last_byte(32),
1934            ]),
1935        );
1936
1937        let chunking_length = targets.chunking_length();
1938        for size in 1..=targets.clone().chunks(1).count() {
1939            let chunk_count = targets.clone().chunks(size).count();
1940            let expected_count = chunking_length.div_ceil(size);
1941            assert_eq!(
1942                chunk_count, expected_count,
1943                "chunking_length: {}, size: {}",
1944                chunking_length, size
1945            );
1946        }
1947    }
1948
1949    #[test]
1950    fn test_nonempty_storage_trie_returns_nonempty_proof() {
1951        let slot = B256::with_last_byte(1);
1952        let nibbles = Nibbles::unpack(keccak256(slot));
1953        let value = U256::from(999);
1954        let leaf = alloy_trie::nodes::LeafNode::new(nibbles, encode_fixed_size(&value).to_vec());
1955        let mut encoded = vec![];
1956        alloy_rlp::Encodable::encode(&leaf, &mut encoded);
1957
1958        let mut subtree = ProofNodes::default();
1959        subtree.insert(nibbles, encoded.into());
1960
1961        let multiproof = StorageMultiProof {
1962            root: B256::with_last_byte(0xFF),
1963            subtree,
1964            branch_node_masks: BranchNodeMasksMap::default(),
1965        };
1966
1967        let proof = multiproof.storage_proof(slot).unwrap();
1968        assert!(!proof.proof.is_empty(), "non-empty trie must return non-empty proof");
1969        assert_eq!(proof.value, value);
1970    }
1971
1972    #[cfg(feature = "eip1186")]
1973    #[test]
1974    fn eip1186_response_normalizes_empty_trie_proof() {
1975        let slot = B256::with_last_byte(1);
1976        let sentinel = || vec![Bytes::from([EMPTY_STRING_CODE])];
1977
1978        // Empty account trie + empty storage trie: both proofs are the lone `0x80` sentinel.
1979        let account = AccountProof {
1980            address: Address::ZERO,
1981            info: None,
1982            proof: sentinel(),
1983            storage_root: EMPTY_ROOT_HASH,
1984            storage_proofs: vec![StorageProof::new(slot).with_proof(sentinel())],
1985        };
1986
1987        let resp = account.into_eip1186_response(vec![alloy_serde::JsonStorageKey::from(slot)]);
1988
1989        assert!(
1990            resp.account_proof.is_empty(),
1991            "empty account trie must yield empty account_proof, got {:?}",
1992            resp.account_proof
1993        );
1994        assert_eq!(resp.storage_proof.len(), 1);
1995        assert!(
1996            resp.storage_proof[0].proof.is_empty(),
1997            "empty storage trie must yield empty storage proof, got {:?}",
1998            resp.storage_proof[0].proof
1999        );
2000    }
2001
2002    #[cfg(feature = "eip1186")]
2003    #[test]
2004    fn eip1186_response_keeps_nonempty_proof() {
2005        // A real (non-empty) proof must pass through unchanged: multiple nodes, and a single
2006        // node that is not the `0x80` sentinel.
2007        let multi = vec![Bytes::from([0x01, 0x02]), Bytes::from([0x03])];
2008        let single_non_sentinel = vec![Bytes::from([0xf8, 0x44])];
2009
2010        let account = AccountProof {
2011            address: Address::ZERO,
2012            info: None,
2013            proof: multi.clone(),
2014            storage_root: EMPTY_ROOT_HASH,
2015            storage_proofs: vec![
2016                StorageProof::new(B256::with_last_byte(1)).with_proof(single_non_sentinel.clone())
2017            ],
2018        };
2019
2020        let resp = account.into_eip1186_response(vec![alloy_serde::JsonStorageKey::from(
2021            B256::with_last_byte(1),
2022        )]);
2023
2024        assert_eq!(resp.account_proof, multi);
2025        assert_eq!(resp.storage_proof[0].proof, single_non_sentinel);
2026    }
2027
2028    #[cfg(feature = "eip1186")]
2029    #[test]
2030    fn eip1186_response_keeps_key_of_each_requested_slot() {
2031        let slot = B256::with_last_byte(1);
2032        let keys = vec![
2033            alloy_serde::JsonStorageKey::Number(U256::from(1)),
2034            alloy_serde::JsonStorageKey::Hash(slot),
2035        ];
2036        let mut account = AccountProof::new(Address::ZERO);
2037        account.storage_proofs = vec![StorageProof::new(slot); 2];
2038
2039        let resp = account.into_eip1186_response(keys.clone());
2040
2041        assert_eq!(resp.storage_proof.iter().map(|p| p.key).collect::<Vec<_>>(), keys);
2042    }
2043}