alloy_trie/proof/
verify.rs

1//! Proof verification logic.
2
3use crate::{
4    EMPTY_ROOT_HASH,
5    nodes::{BranchNode, CHILD_INDEX_RANGE, RlpNode, TrieNode},
6    proof::ProofVerificationError,
7};
8use alloc::vec::Vec;
9use alloy_primitives::{B256, Bytes};
10use alloy_rlp::{Decodable, EMPTY_STRING_CODE};
11use core::ops::Deref;
12use nybbles::Nibbles;
13
14/// Verify the proof for given key value pair against the provided state root.
15///
16/// The expected node value can be either [Some] if it's expected to be present
17/// in the tree or [None] if this is an exclusion proof.
18pub fn verify_proof<'a, I>(
19    root: B256,
20    key: Nibbles,
21    expected_value: Option<Vec<u8>>,
22    proof: I,
23) -> Result<(), ProofVerificationError>
24where
25    I: IntoIterator<Item = &'a Bytes>,
26{
27    let mut proof = proof.into_iter().peekable();
28
29    // If the proof is empty or contains only an empty node, the expected value must be None.
30    if proof.peek().is_none_or(|node| node.as_ref() == [EMPTY_STRING_CODE]) {
31        return if root == EMPTY_ROOT_HASH {
32            if expected_value.is_none() {
33                Ok(())
34            } else {
35                Err(ProofVerificationError::ValueMismatch {
36                    path: key,
37                    got: None,
38                    expected: expected_value.map(Bytes::from),
39                })
40            }
41        } else {
42            Err(ProofVerificationError::RootMismatch { got: EMPTY_ROOT_HASH, expected: root })
43        };
44    }
45
46    let mut walked_path = Nibbles::new();
47    let mut last_decoded_node = Some(NodeDecodingResult::Node(RlpNode::word_rlp(&root)));
48    for node in proof {
49        // Check if the node that we just decoded (or root node, if we just started) matches
50        // the expected node from the proof.
51        if Some(RlpNode::from_rlp(node).as_slice()) != last_decoded_node.as_deref() {
52            let got = Some(Bytes::copy_from_slice(node));
53            let expected = last_decoded_node.as_deref().map(Bytes::copy_from_slice);
54            return Err(ProofVerificationError::ValueMismatch { path: walked_path, got, expected });
55        }
56
57        // Decode the next node from the proof.
58        last_decoded_node =
59            process_trie_node(TrieNode::decode(&mut &node[..])?, &mut walked_path, &key)?;
60    }
61
62    // Last decoded node should have the key that we are looking for.
63    last_decoded_node = last_decoded_node.filter(|_| walked_path == key);
64    if last_decoded_node.as_deref() == expected_value.as_deref() {
65        Ok(())
66    } else {
67        Err(ProofVerificationError::ValueMismatch {
68            path: key,
69            got: last_decoded_node.as_deref().map(Bytes::copy_from_slice),
70            expected: expected_value.map(Bytes::from),
71        })
72    }
73}
74
75/// The result of decoding a node from the proof.
76///
77/// - [`TrieNode::Branch`] is decoded into a [`NodeDecodingResult::Value`] if the node at the
78///   specified nibble was decoded into an in-place encoded [`TrieNode::Leaf`], or into a
79///   [`NodeDecodingResult::Node`] otherwise.
80/// - [`TrieNode::Extension`] is always decoded into a [`NodeDecodingResult::Node`].
81/// - [`TrieNode::Leaf`] is always decoded into a [`NodeDecodingResult::Value`].
82#[derive(Debug, PartialEq, Eq)]
83enum NodeDecodingResult {
84    Node(RlpNode),
85    Value(Vec<u8>),
86}
87
88impl Deref for NodeDecodingResult {
89    type Target = [u8];
90
91    fn deref(&self) -> &Self::Target {
92        match self {
93            Self::Node(node) => node.as_slice(),
94            Self::Value(value) => value,
95        }
96    }
97}
98
99#[inline]
100fn process_trie_node(
101    node: TrieNode,
102    walked_path: &mut Nibbles,
103    key: &Nibbles,
104) -> Result<Option<NodeDecodingResult>, ProofVerificationError> {
105    let node = match node {
106        TrieNode::Branch(branch) => process_branch(branch, walked_path, key)?,
107        TrieNode::Extension(extension) => {
108            walked_path.extend(&extension.key);
109            if extension.child.is_hash() {
110                Some(NodeDecodingResult::Node(extension.child))
111            } else {
112                process_trie_node(TrieNode::decode(&mut &extension.child[..])?, walked_path, key)?
113            }
114        }
115        TrieNode::Leaf(leaf) => {
116            walked_path.extend(&leaf.key);
117            Some(NodeDecodingResult::Value(leaf.value))
118        }
119        TrieNode::EmptyRoot => return Err(ProofVerificationError::UnexpectedEmptyRoot),
120    };
121    Ok(node)
122}
123
124#[inline]
125fn process_branch(
126    mut branch: BranchNode,
127    walked_path: &mut Nibbles,
128    key: &Nibbles,
129) -> Result<Option<NodeDecodingResult>, ProofVerificationError> {
130    if let Some(next) = key.get(walked_path.len()) {
131        let mut stack_ptr = branch.as_ref().first_child_index();
132        for index in CHILD_INDEX_RANGE {
133            if branch.state_mask.is_bit_set(index) {
134                if index == next {
135                    walked_path.push(next);
136
137                    let child = branch.stack.remove(stack_ptr);
138                    if child.len() == B256::len_bytes() + 1 {
139                        return Ok(Some(NodeDecodingResult::Node(child)));
140                    } else {
141                        // This node is encoded in-place.
142                        match TrieNode::decode(&mut &child[..])? {
143                            TrieNode::Branch(child_branch) => {
144                                // An in-place branch node can only have direct, also in-place
145                                // encoded, leaf children, as anything else overflows this branch
146                                // node, making it impossible to be encoded in-place in the first
147                                // place.
148                                return process_branch(child_branch, walked_path, key);
149                            }
150                            TrieNode::Extension(child_extension) => {
151                                walked_path.extend(&child_extension.key);
152
153                                // If the extension node's child is a hash, the encoded extension
154                                // node itself wouldn't fit for encoding in-place. So this extension
155                                // node must have a child that is also encoded in-place.
156                                //
157                                // Since the child cannot be a leaf node (otherwise this node itself
158                                // would be a leaf node, not an extension node), the child must be a
159                                // branch node encoded in-place.
160                                match TrieNode::decode(&mut &child_extension.child[..])? {
161                                    TrieNode::Branch(extension_child_branch) => {
162                                        return process_branch(
163                                            extension_child_branch,
164                                            walked_path,
165                                            key,
166                                        );
167                                    }
168                                    node @ (TrieNode::EmptyRoot
169                                    | TrieNode::Extension(_)
170                                    | TrieNode::Leaf(_)) => {
171                                        unreachable!("unexpected extension node child: {node:?}")
172                                    }
173                                }
174                            }
175                            TrieNode::Leaf(child_leaf) => {
176                                walked_path.extend(&child_leaf.key);
177                                return Ok(Some(NodeDecodingResult::Value(child_leaf.value)));
178                            }
179                            TrieNode::EmptyRoot => {
180                                return Err(ProofVerificationError::UnexpectedEmptyRoot);
181                            }
182                        }
183                    };
184                }
185                stack_ptr += 1;
186            }
187        }
188    }
189
190    Ok(None)
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::{
197        HashBuilder, TrieMask,
198        nodes::{BranchNode, ExtensionNode, LeafNode},
199        proof::{ProofNodes, ProofRetainer},
200        triehash_trie_root,
201    };
202    use alloy_primitives::hex;
203    use alloy_rlp::{EMPTY_STRING_CODE, Encodable};
204    use core::str::FromStr;
205
206    #[test]
207    fn empty_trie() {
208        let key = Nibbles::unpack(B256::repeat_byte(42));
209        let mut hash_builder = HashBuilder::default().with_proof_retainer(ProofRetainer::default());
210        let root = hash_builder.root();
211        let proof = hash_builder.take_proof_nodes();
212        assert_eq!(
213            proof,
214            ProofNodes::from_iter([(Nibbles::default(), Bytes::from([EMPTY_STRING_CODE]))])
215        );
216        assert_eq!(
217            verify_proof(root, key, None, proof.into_nodes_sorted().iter().map(|(_, node)| node)),
218            Ok(())
219        );
220
221        let mut dummy_proof = vec![];
222        BranchNode::default().encode(&mut dummy_proof);
223        assert_eq!(
224            verify_proof(root, key, None, [&Bytes::from(dummy_proof.clone())]),
225            Err(ProofVerificationError::ValueMismatch {
226                path: Nibbles::default(),
227                got: Some(Bytes::from(dummy_proof)),
228                expected: Some(Bytes::from(RlpNode::word_rlp(&EMPTY_ROOT_HASH)[..].to_vec()))
229            })
230        );
231    }
232
233    #[test]
234    fn inlined_trie_leaves() {
235        // root: ext(a7)
236        // a7: branch(children: 1, 7, f)
237        // a77: ext(d3)
238        // a77d3: branch(children: 3 (key: 70, value: 0x31), 9 (key: 70, value: 0x312e32))
239        let root =
240            B256::from_str("8523a13fdb0aa86480a61e34443a951e85e618b5c9b23b9e74cf2754941ce061")
241                .unwrap();
242        let proof = [
243            Bytes::from_str("e48200a7a080389e2b58154f1b8756223ec9ac277b6a166417b4279f016cb86582afb5ae6c").unwrap(),
244            Bytes::from_str("f84080c7833135508234358080808080a0d03438e4f6601da47dab30f52e4325509012ebc1a1c8901fd10d37e05db48bf180808080808080c88339365083312e3180").unwrap(),
245            Bytes::from_str("e08200d3dc808080c4822070318080808080c782207083312e3280808080808080").unwrap()
246        ];
247
248        let first_key = Nibbles::unpack(hex!("a77d3370"));
249        let first_value = vec![0x31];
250        let second_key = Nibbles::unpack(hex!("a77d3970"));
251        let second_value = hex!("0x312e32").to_vec();
252
253        assert_eq!(verify_proof(root, first_key, Some(first_value.clone()), &proof), Ok(()));
254        assert_eq!(
255            verify_proof(root, first_key, None, &proof),
256            Err(ProofVerificationError::ValueMismatch {
257                path: first_key,
258                got: Some(first_value.into()),
259                expected: None,
260            })
261        );
262
263        assert_eq!(verify_proof(root, second_key, Some(second_value.clone()), &proof), Ok(()));
264        assert_eq!(
265            verify_proof(root, second_key, None, &proof),
266            Err(ProofVerificationError::ValueMismatch {
267                path: second_key,
268                got: Some(second_value.into()),
269                expected: None,
270            })
271        );
272    }
273
274    #[test]
275    fn single_leaf_trie_proof_verification() {
276        let target = Nibbles::unpack(B256::with_last_byte(0x2));
277        let target_value = B256::with_last_byte(0x2);
278        let non_existent_target = Nibbles::unpack(B256::with_last_byte(0x3));
279
280        let retainer = ProofRetainer::from_iter([target, non_existent_target]);
281        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
282        hash_builder.add_leaf(target, &target_value[..]);
283        let root = hash_builder.root();
284        assert_eq!(root, triehash_trie_root([(target.pack(), target.pack())]));
285
286        let proof = hash_builder.take_proof_nodes().into_nodes_sorted();
287        assert_eq!(
288            verify_proof(
289                root,
290                target,
291                Some(target_value.to_vec()),
292                proof.iter().map(|(_, node)| node)
293            ),
294            Ok(())
295        );
296    }
297
298    #[test]
299    fn non_existent_proof_verification() {
300        let range = 0..=0xf;
301        let target = Nibbles::unpack(B256::with_last_byte(0xff));
302
303        let retainer = ProofRetainer::from_iter([target]);
304        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
305        for key in range.clone() {
306            let hash = B256::with_last_byte(key);
307            hash_builder.add_leaf(Nibbles::unpack(hash), &hash[..]);
308        }
309        let root = hash_builder.root();
310        assert_eq!(
311            root,
312            triehash_trie_root(range.map(|b| (B256::with_last_byte(b), B256::with_last_byte(b))))
313        );
314
315        let proof = hash_builder.take_proof_nodes().into_nodes_sorted();
316        assert_eq!(verify_proof(root, target, None, proof.iter().map(|(_, node)| node)), Ok(()));
317    }
318
319    #[test]
320    fn proof_verification_with_divergent_node() {
321        let existing_keys = [
322            hex!("0000000000000000000000000000000000000000000000000000000000000000"),
323            hex!("3a00000000000000000000000000000000000000000000000000000000000000"),
324            hex!("3c15000000000000000000000000000000000000000000000000000000000000"),
325        ];
326        let target = Nibbles::unpack(
327            B256::from_str("0x3c19000000000000000000000000000000000000000000000000000000000000")
328                .unwrap()
329                .as_slice(),
330        );
331        let value = B256::with_last_byte(1);
332
333        // Build trie without a target and retain proof first.
334        let retainer = ProofRetainer::from_iter([target]);
335        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
336        for key in &existing_keys {
337            hash_builder.add_leaf(Nibbles::unpack(B256::from_slice(key)), &value[..]);
338        }
339        let root = hash_builder.root();
340        assert_eq!(
341            root,
342            triehash_trie_root(existing_keys.map(|key| (B256::from_slice(&key), value)))
343        );
344        let proof = hash_builder.take_proof_nodes();
345        assert_eq!(proof, ProofNodes::from_iter([
346            (Nibbles::default(), Bytes::from_str("f851a0c530c099d779362b6bd0be05039b51ccd0a8ed39e0b2abacab8fe0e3441251878080a07d4ee4f073ae7ce32a6cbcdb015eb73dd2616f33ed2e9fb6ba51c1f9ad5b697b80808080808080808080808080").unwrap()),
347            (Nibbles::from_iter_unchecked(vec![0x3]), Bytes::from_str("f85180808080808080808080a057fcbd3f97b1093cd39d0f58dafd5058e2d9f79a419e88c2498ff3952cb11a8480a07520d69a83a2bdad373a68b2c9c8c0e1e1c99b6ec80b4b933084da76d644081980808080").unwrap()),
348            (Nibbles::from_iter_unchecked(vec![0x3, 0xc]), Bytes::from_str("f842a02015000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001").unwrap())
349        ]));
350        assert_eq!(
351            verify_proof(
352                root,
353                target,
354                None,
355                proof.into_nodes_sorted().iter().map(|(_, node)| node)
356            ),
357            Ok(())
358        );
359
360        let retainer = ProofRetainer::from_iter([target]);
361        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
362        for key in &existing_keys {
363            hash_builder.add_leaf(Nibbles::unpack(B256::from_slice(key)), &value[..]);
364        }
365        hash_builder.add_leaf(target, &value[..]);
366        let root = hash_builder.root();
367        assert_eq!(
368            root,
369            triehash_trie_root(
370                existing_keys
371                    .into_iter()
372                    .map(|key| (B256::from_slice(&key), value))
373                    .chain([(B256::from_slice(&target.pack()), value)])
374            )
375        );
376        let proof = hash_builder.take_proof_nodes();
377        assert_eq!(proof, ProofNodes::from_iter([
378            (Nibbles::default(), Bytes::from_str("f851a0c530c099d779362b6bd0be05039b51ccd0a8ed39e0b2abacab8fe0e3441251878080a0abd80d939392f6d222f8becc15f8c6f0dbbc6833dd7e54bfbbee0c589b7fd40380808080808080808080808080").unwrap()),
379            (Nibbles::from_iter_unchecked(vec![0x3]), Bytes::from_str("f85180808080808080808080a057fcbd3f97b1093cd39d0f58dafd5058e2d9f79a419e88c2498ff3952cb11a8480a09e7b3788773773f15e26ad07b72a2c25a6374bce256d9aab6cea48fbc77d698180808080").unwrap()),
380            (Nibbles::from_iter_unchecked(vec![0x3, 0xc]), Bytes::from_str("e211a0338ac0a453edb0e40a23a70aee59e02a6c11597c34d79a5ba94da8eb20dd4d52").unwrap()),
381            (Nibbles::from_iter_unchecked(vec![0x3, 0xc, 0x1]), Bytes::from_str("f8518080808080a020dc5b33292bfad9013bf123f7faf1efcc5c8e00c894177fc0bfb447daef522f808080a020dc5b33292bfad9013bf123f7faf1efcc5c8e00c894177fc0bfb447daef522f80808080808080").unwrap()),
382            (Nibbles::from_iter_unchecked(vec![0x3, 0xc, 0x1, 0x9]), Bytes::from_str("f8419f20000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001").unwrap()),
383        ]));
384        assert_eq!(
385            verify_proof(
386                root,
387                target,
388                Some(value.to_vec()),
389                proof.into_nodes_sorted().iter().map(|(_, node)| node)
390            ),
391            Ok(())
392        );
393    }
394
395    #[test]
396    fn extension_root_trie_proof_verification() {
397        let range = 0..=0xff;
398        let target = Nibbles::unpack(B256::with_last_byte(0x42));
399        let target_value = B256::with_last_byte(0x42);
400
401        let retainer = ProofRetainer::from_iter([target]);
402        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
403        for key in range.clone() {
404            let hash = B256::with_last_byte(key);
405            hash_builder.add_leaf(Nibbles::unpack(hash), &hash[..]);
406        }
407        let root = hash_builder.root();
408        assert_eq!(
409            root,
410            triehash_trie_root(range.map(|b| (B256::with_last_byte(b), B256::with_last_byte(b))))
411        );
412
413        let proof = hash_builder.take_proof_nodes().into_nodes_sorted();
414        assert_eq!(
415            verify_proof(
416                root,
417                target,
418                Some(target_value.to_vec()),
419                proof.iter().map(|(_, node)| node)
420            ),
421            Ok(())
422        );
423    }
424
425    #[test]
426    fn wide_trie_proof_verification() {
427        let range = 0..=0xff;
428        let target1 = Nibbles::unpack(B256::repeat_byte(0x42));
429        let target1_value = B256::repeat_byte(0x42);
430        let target2 = Nibbles::unpack(B256::repeat_byte(0xff));
431        let target2_value = B256::repeat_byte(0xff);
432
433        let retainer = ProofRetainer::from_iter([target1, target2]);
434        let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
435        for key in range.clone() {
436            let hash = B256::repeat_byte(key);
437            hash_builder.add_leaf(Nibbles::unpack(hash), &hash[..]);
438        }
439        let root = hash_builder.root();
440        assert_eq!(
441            root,
442            triehash_trie_root(range.map(|b| (B256::repeat_byte(b), B256::repeat_byte(b))))
443        );
444
445        let proof = hash_builder.take_proof_nodes();
446
447        assert_eq!(
448            verify_proof(
449                root,
450                target1,
451                Some(target1_value.to_vec()),
452                proof.matching_nodes_sorted(&target1).iter().map(|(_, node)| node)
453            ),
454            Ok(())
455        );
456
457        assert_eq!(
458            verify_proof(
459                root,
460                target2,
461                Some(target2_value.to_vec()),
462                proof.matching_nodes_sorted(&target2).iter().map(|(_, node)| node)
463            ),
464            Ok(())
465        );
466    }
467
468    #[test]
469    fn proof_verification_with_node_encoded_in_place() {
470        // Building a trie with a leaf, branch, and extension encoded in place:
471        //
472        // - node `2a`: 0x64
473        // - node `32a`: 0x64
474        // - node `33b`: 0x64
475        // - node `412a`: 0x64
476        // - node `413b`: 0x64
477        //
478        // This trie looks like:
479        //
480        // f83f => list len = 63
481        //    80
482        //    80
483        //    c2 => list len = 2 (leaf encoded in-place)
484        //       3a => odd leaf
485        //       64 => leaf node value
486        //    d5 => list len = 21 (branch encoded in-place)
487        //       80
488        //       80
489        //       c2 => list len = 2 (leaf node encoded in-place)
490        //          3a => odd leaf
491        //          64 leaf node value
492        //       c2 => list len = 2 (leaf node encoded in-place)
493        //          3b => odd leaf
494        //          64 leaf node value
495        //       80
496        //       80
497        //       80
498        //       80
499        //       80
500        //       80
501        //       80
502        //       80
503        //       80
504        //       80
505        //       80
506        //       80
507        //       80
508        //    d7 => list len = 23 (extension encoded in-place)
509        //       11 => odd extension
510        //       d5 => list len = 21 (branch encoded in-place)
511        //          80
512        //          80
513        //          c2 => list len = 2 (leaf node encoded in-place)
514        //             3a => odd leaf
515        //             64 leaf node value
516        //          c2 => list len = 2 (leaf node encoded in-place)
517        //             3b => odd leaf
518        //             64 leaf node value
519        //          80
520        //          80
521        //          80
522        //          80
523        //          80
524        //          80
525        //          80
526        //          80
527        //          80
528        //          80
529        //          80
530        //          80
531        //          80
532        //    80
533        //    80
534        //    80
535        //    80
536        //    80
537        //    80
538        //    80
539        //    80
540        //    80
541        //    80
542        //    80
543        //    80
544        //
545        // Flattened:
546        // f83f8080c23a64d58080c23a64c23b6480808080808080808080808080d711d58080c23a64c23b6480808080808080808080808080808080808080808080808080
547        //
548        // Root hash:
549        // 67dbae3a9cc1f4292b0739fa1bcb7f9e6603a6a138444656ec674e273417c918
550
551        let mut buffer = vec![];
552
553        let value = vec![0x64];
554        let child_leaf = TrieNode::Leaf(LeafNode::new(Nibbles::from_nibbles([0xa]), value.clone()));
555
556        let child_branch = TrieNode::Branch(BranchNode::new(
557            vec![
558                {
559                    buffer.clear();
560                    TrieNode::Leaf(LeafNode::new(Nibbles::from_nibbles([0xa]), value.clone()))
561                        .rlp(&mut buffer)
562                },
563                {
564                    buffer.clear();
565                    TrieNode::Leaf(LeafNode::new(Nibbles::from_nibbles([0xb]), value))
566                        .rlp(&mut buffer)
567                },
568            ],
569            TrieMask::new(0b0000000000001100_u16),
570        ));
571
572        let child_extension =
573            TrieNode::Extension(ExtensionNode::new(Nibbles::from_nibbles([0x1]), {
574                buffer.clear();
575                child_branch.rlp(&mut buffer)
576            }));
577
578        let root_branch = TrieNode::Branch(BranchNode::new(
579            vec![
580                {
581                    buffer.clear();
582                    child_leaf.rlp(&mut buffer)
583                },
584                {
585                    buffer.clear();
586                    child_branch.rlp(&mut buffer)
587                },
588                {
589                    buffer.clear();
590                    child_extension.rlp(&mut buffer)
591                },
592            ],
593            TrieMask::new(0b0000000000011100_u16),
594        ));
595
596        let mut root_encoded = vec![];
597        root_branch.encode(&mut root_encoded);
598
599        // Just to make sure our manual encoding above is correct
600        assert_eq!(
601            root_encoded,
602            hex!(
603                "f83f8080c23a64d58080c23a64c23b6480808080808080808080808080d711d58080c23a64c23b6480808080808080808080808080808080808080808080808080"
604            )
605        );
606
607        let root_hash = B256::from_slice(&hex!(
608            "67dbae3a9cc1f4292b0739fa1bcb7f9e6603a6a138444656ec674e273417c918"
609        ));
610        let root_encoded = Bytes::from(root_encoded);
611        let proof = vec![&root_encoded];
612
613        // Node `2a`: 0x64
614        verify_proof(root_hash, Nibbles::from_nibbles([0x2, 0xa]), Some(vec![0x64]), proof.clone())
615            .unwrap();
616
617        // Node `32a`: 0x64
618        verify_proof(
619            root_hash,
620            Nibbles::from_nibbles([0x3, 0x2, 0xa]),
621            Some(vec![0x64]),
622            proof.clone(),
623        )
624        .unwrap();
625
626        // Node `33b`: 0x64
627        verify_proof(
628            root_hash,
629            Nibbles::from_nibbles([0x3, 0x3, 0xb]),
630            Some(vec![0x64]),
631            proof.clone(),
632        )
633        .unwrap();
634
635        // Node `412a`: 0x64
636        verify_proof(
637            root_hash,
638            Nibbles::from_nibbles([0x4, 0x1, 0x2, 0xa]),
639            Some(vec![0x64]),
640            proof.clone(),
641        )
642        .unwrap();
643
644        // Node `413b`: 0x64
645        verify_proof(
646            root_hash,
647            Nibbles::from_nibbles([0x4, 0x1, 0x3, 0xb]),
648            Some(vec![0x64]),
649            proof.clone(),
650        )
651        .unwrap();
652    }
653
654    #[test]
655    #[cfg(feature = "arbitrary")]
656    #[cfg_attr(miri, ignore = "no proptest")]
657    fn arbitrary_proof_verification() {
658        use proptest::prelude::*;
659
660        proptest!(|(state: std::collections::BTreeMap<B256, alloy_primitives::U256>)| {
661            let hashed = state.into_iter()
662                .map(|(k, v)| (k, alloy_rlp::encode(v).to_vec()))
663                // Collect into a btree map to sort the data
664                .collect::<std::collections::BTreeMap<_, _>>();
665
666            let retainer = ProofRetainer::from_iter(hashed.clone().into_keys().map(Nibbles::unpack));
667            let mut hash_builder = HashBuilder::default().with_proof_retainer(retainer);
668            for (key, value) in hashed.clone() {
669                hash_builder.add_leaf(Nibbles::unpack(key), &value);
670            }
671
672            let root = hash_builder.root();
673            assert_eq!(root, triehash_trie_root(&hashed));
674
675            let proofs = hash_builder.take_proof_nodes();
676            for (key, value) in hashed {
677                let nibbles = Nibbles::unpack(key);
678                assert_eq!(verify_proof(root, nibbles, Some(value), proofs.matching_nodes_sorted(&nibbles).iter().map(|(_, node)| node)), Ok(()));
679            }
680        });
681    }
682}