|
| 1 | +"""Merkle proofs for SSZ.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Dict, List, Sequence, Set |
| 6 | + |
| 7 | +from pydantic import Field, model_validator |
| 8 | + |
| 9 | +from lean_spec.types.base import StrictBaseModel |
| 10 | +from lean_spec.types.hash import Bytes32 |
| 11 | + |
| 12 | +from ..constants import ZERO_HASH |
| 13 | +from ..gindex import GeneralizedIndex |
| 14 | +from ..utils import hash_nodes |
| 15 | + |
| 16 | +Root = bytes |
| 17 | +"""The type of a Merkle tree root.""" |
| 18 | +Proof = Sequence[Bytes32] |
| 19 | +"""The type of a Merkle proof.""" |
| 20 | +ProofHashes = Sequence[Bytes32] |
| 21 | +"""The type of a Merkle proof's helper nodes.""" |
| 22 | + |
| 23 | + |
| 24 | +class MerkleProof(StrictBaseModel): |
| 25 | + """ |
| 26 | + Represents a Merkle multiproof, encapsulating its data and verification logic. |
| 27 | +
|
| 28 | + This object is immutable; once created, its contents cannot be changed. |
| 29 | + """ |
| 30 | + |
| 31 | + leaves: Sequence[Bytes32] = Field(..., description="The leaf data being proven.") |
| 32 | + |
| 33 | + indices: Sequence[GeneralizedIndex] = Field( |
| 34 | + ..., description="The generalized indices of the leaves." |
| 35 | + ) |
| 36 | + |
| 37 | + proof_hashes: ProofHashes = Field(..., description="The helper nodes required for the proof.") |
| 38 | + |
| 39 | + @model_validator(mode="after") |
| 40 | + def check_leaves_and_indices_length(self) -> MerkleProof: |
| 41 | + """Ensures the number of leaves matches the number of indices.""" |
| 42 | + if len(self.leaves) != len(self.indices): |
| 43 | + raise ValueError("The number of leaves must match the number of indices.") |
| 44 | + return self |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def from_single_leaf( |
| 48 | + cls, leaf: Bytes32, proof_hashes: ProofHashes, index: GeneralizedIndex |
| 49 | + ) -> MerkleProof: |
| 50 | + """Creates a MerkleProof object from a traditional single-item proof.""" |
| 51 | + return cls(leaves=[leaf], proof_hashes=proof_hashes, indices=[index]) |
| 52 | + |
| 53 | + def _get_helper_indices(self) -> List[GeneralizedIndex]: |
| 54 | + """ |
| 55 | + Calculates the generalized indices of all "helper" nodes needed to prove the leaves. |
| 56 | +
|
| 57 | + This is an internal helper method. |
| 58 | + """ |
| 59 | + all_helper_indices: Set[GeneralizedIndex] = set() |
| 60 | + all_path_indices: Set[GeneralizedIndex] = set() |
| 61 | + |
| 62 | + for index in self.indices: |
| 63 | + all_helper_indices.update(index.get_branch_indices()) |
| 64 | + all_path_indices.update(index.get_path_indices()) |
| 65 | + |
| 66 | + return sorted(all_helper_indices - all_path_indices, key=lambda g: g.value, reverse=True) |
| 67 | + |
| 68 | + def calculate_root(self) -> Root: |
| 69 | + """ |
| 70 | + Calculates the Merkle root from the proof's leaves and helper nodes. |
| 71 | +
|
| 72 | + Handles both single and multi-leaf proofs seamlessly. |
| 73 | + """ |
| 74 | + # For a single leaf proof, use the more direct calculation. |
| 75 | + if len(self.indices) == 1: |
| 76 | + index = self.indices[0] |
| 77 | + leaf = self.leaves[0] |
| 78 | + if len(self.proof_hashes) != index.depth: |
| 79 | + raise ValueError("Proof length must match the depth of the index.") |
| 80 | + |
| 81 | + root = leaf |
| 82 | + for i, branch_node in enumerate(self.proof_hashes): |
| 83 | + if index.get_bit(i): |
| 84 | + root = hash_nodes(branch_node, root) |
| 85 | + else: |
| 86 | + root = hash_nodes(root, branch_node) |
| 87 | + return root |
| 88 | + |
| 89 | + # For multi-leaf proofs, perform tree reconstruction. |
| 90 | + helper_indices = self._get_helper_indices() |
| 91 | + if len(self.proof_hashes) != len(helper_indices): |
| 92 | + raise ValueError("Proof length does not match the required number of helper nodes.") |
| 93 | + |
| 94 | + # 1. Start with the known nodes (leaves and proof hashes). |
| 95 | + tree: Dict[int, Bytes32] = { |
| 96 | + **{index.value: node for index, node in zip(self.indices, self.leaves, strict=False)}, |
| 97 | + **{ |
| 98 | + index.value: node |
| 99 | + for index, node in zip(helper_indices, self.proof_hashes, strict=False) |
| 100 | + }, |
| 101 | + } |
| 102 | + |
| 103 | + # 2. Process nodes from deepest to shallowest. |
| 104 | + # The list of keys will grow as we create new parent nodes. |
| 105 | + keys = sorted(tree.keys(), reverse=True) |
| 106 | + pos = 0 |
| 107 | + while pos < len(keys): |
| 108 | + key = keys[pos] |
| 109 | + sibling_key = key ^ 1 |
| 110 | + |
| 111 | + # 3. If a node's sibling is also in the tree, we can create their parent. |
| 112 | + if sibling_key in tree: |
| 113 | + parent_key = key // 2 |
| 114 | + |
| 115 | + # Ensure we don't re-calculate a parent we already have. |
| 116 | + if parent_key not in tree: |
| 117 | + # The order of hashing depends on which key is smaller. |
| 118 | + if key < sibling_key: |
| 119 | + tree[parent_key] = hash_nodes(tree[key], tree[sibling_key]) |
| 120 | + else: |
| 121 | + tree[parent_key] = hash_nodes(tree[sibling_key], tree[key]) |
| 122 | + keys.append(parent_key) |
| 123 | + pos += 1 |
| 124 | + |
| 125 | + # 4. After processing all nodes, the root must be at index 1. |
| 126 | + if 1 not in tree: |
| 127 | + # This can happen if the proof is incomplete or for an empty leaf set. |
| 128 | + return ZERO_HASH |
| 129 | + |
| 130 | + return tree[1] |
| 131 | + |
| 132 | + def verify(self, root: Root) -> bool: |
| 133 | + """Verifies the Merkle proof against a known root.""" |
| 134 | + try: |
| 135 | + return self.calculate_root() == root |
| 136 | + except ValueError: |
| 137 | + return False |
0 commit comments