Skip to content

Commit de31ae1

Browse files
authored
Merge pull request #10 from aniket866/Merkel-root-Proof
Add Merkle Proof Generation for Chunk-Level Dataset Verification
2 parents 99283f7 + faa4c98 commit de31ae1

2 files changed

Lines changed: 135 additions & 6 deletions

File tree

‎openverifiablellm/utils.py‎

Lines changed: 109 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,21 @@
1414
MERKLE_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB
1515

1616
# Merkle Tree Chunk-Level Hashing for Large Files
17-
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 1024) -> str:
17+
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = MERKLE_CHUNK_SIZE_BYTES) -> str:
18+
if chunk_size <= 0:
19+
raise ValueError("chunk_size must be a positive integer")
20+
1821
path = Path(file_path)
1922
leaves = []
2023

2124
with path.open("rb") as f:
2225
while chunk := f.read(chunk_size):
2326
# reuse compute_sha256
24-
leaf_hex = compute_sha256(chunk)
27+
leaf_hex = compute_sha256(data=chunk)
2528
leaves.append(bytes.fromhex(leaf_hex))
2629

2730
if not leaves:
28-
return compute_sha256(b"")
31+
return compute_sha256(data=b"")
2932

3033
while len(leaves) > 1:
3134
next_level = []
@@ -34,13 +37,113 @@ def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 10
3437
right = leaves[i + 1] if i + 1 < len(leaves) else left
3538

3639
combined = left + right
37-
parent_hex = compute_sha256(combined)
40+
parent_hex = compute_sha256(data=combined)
3841
next_level.append(bytes.fromhex(parent_hex))
3942

4043
leaves = next_level
4144

4245
return leaves[0].hex()
4346

47+
def generate_merkle_proof(
48+
file_path: Union[str, Path],
49+
chunk_index: int,
50+
chunk_size: int = MERKLE_CHUNK_SIZE_BYTES
51+
):
52+
"""
53+
Generate Merkle proof for a specific chunk index.
54+
55+
Returns:
56+
List of tuples (sibling_hash_hex, is_left)
57+
"""
58+
path = Path(file_path)
59+
60+
if chunk_size <= 0:
61+
raise ValueError("chunk_size must be a positive integer")
62+
63+
leaves = []
64+
65+
# Build leaf level
66+
with path.open("rb") as f:
67+
while chunk := f.read(chunk_size):
68+
leaf_hex = compute_sha256(data=chunk)
69+
leaves.append(bytes.fromhex(leaf_hex))
70+
71+
if not leaves:
72+
raise ValueError("Cannot generate proof for empty file")
73+
74+
if chunk_index < 0 or chunk_index >= len(leaves):
75+
raise IndexError("Chunk index out of range")
76+
77+
proof = []
78+
index = chunk_index
79+
80+
while len(leaves) > 1:
81+
# If odd number of nodes, duplicate last
82+
if len(leaves) % 2 == 1:
83+
leaves.append(leaves[-1])
84+
85+
sibling_index = index ^ 1
86+
sibling = leaves[sibling_index]
87+
88+
is_left = sibling_index < index
89+
proof.append((sibling.hex(), is_left))
90+
91+
# Build next level
92+
next_level = []
93+
for i in range(0, len(leaves), 2):
94+
combined = leaves[i] + leaves[i + 1]
95+
parent_hex = compute_sha256(data=combined)
96+
next_level.append(bytes.fromhex(parent_hex))
97+
98+
index //= 2
99+
leaves = next_level
100+
101+
return proof
102+
103+
def verify_merkle_proof(
104+
chunk_bytes: bytes,
105+
proof,
106+
merkle_root: str
107+
) -> bool:
108+
"""
109+
Verify a Merkle proof for given chunk bytes.
110+
"""
111+
try:
112+
current_hash = bytes.fromhex(compute_sha256(data=chunk_bytes))
113+
expected_root = bytes.fromhex(merkle_root)
114+
except (TypeError, ValueError):
115+
return False
116+
117+
if not isinstance(proof, (list, tuple)):
118+
return False
119+
120+
for step in proof:
121+
if not isinstance(step, (tuple, list)) or len(step) != 2:
122+
return False
123+
124+
sibling_hex, is_left = step
125+
126+
if not isinstance(sibling_hex, str) or not isinstance(is_left, bool):
127+
return False
128+
129+
try:
130+
sibling = bytes.fromhex(sibling_hex)
131+
except (TypeError, ValueError):
132+
return False
133+
134+
# Ensure correct hash length
135+
if len(sibling) != hashlib.sha256().digest_size:
136+
return False
137+
138+
if is_left:
139+
combined = sibling + current_hash
140+
else:
141+
combined = current_hash + sibling
142+
143+
parent_hex = compute_sha256(data=combined)
144+
current_hash = bytes.fromhex(parent_hex)
145+
146+
return current_hash == expected_root
44147

45148
# extract clean wikipage from actual wikipage
46149
def extract_text_from_xml(input_path):
@@ -103,8 +206,8 @@ def generate_manifest(raw_path, processed_path):
103206
manifest = {
104207
"wikipedia_dump": raw_path.name,
105208
"dump_date": extract_dump_date(raw_path.name),
106-
"raw_sha256": compute_sha256(str(raw_path)),
107-
"processed_sha256": compute_sha256(str(processed_path)),
209+
"raw_sha256": compute_sha256(file_path=raw_path),
210+
"processed_sha256": compute_sha256(file_path=processed_path),
108211

109212
# ---------------- ADDED FIELDS ----------------
110213
"raw_merkle_root": compute_merkle_root(raw_path, chunk_size=MERKLE_CHUNK_SIZE_BYTES),

‎tests/test_util.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,29 @@ def test_merkle_root_empty_file(tmp_path):
194194
expected = hashlib.sha256(b"").hexdigest()
195195

196196
assert root == expected
197+
198+
# --------------- Merkle proof generation ------------------------------------
199+
200+
def test_merkle_proof_verification(tmp_path):
201+
file = tmp_path / "data.txt"
202+
content = b"hello world this is merkle proof test"
203+
file.write_bytes(content)
204+
205+
root = utils.compute_merkle_root(file, chunk_size=8)
206+
proof = utils.generate_merkle_proof(file, chunk_index=1, chunk_size=8)
207+
208+
with file.open("rb") as f:
209+
f.seek(8)
210+
chunk = f.read(8)
211+
# Positive case
212+
assert utils.verify_merkle_proof(chunk, proof, root)
213+
214+
# Negative case: tampered chunk
215+
tampered_chunk = bytearray(chunk)
216+
tampered_chunk[0] ^= 1
217+
assert not utils.verify_merkle_proof(bytes(tampered_chunk), proof, root)
218+
219+
# Negative case: tampered proof
220+
bad_proof = proof.copy()
221+
bad_proof[0] = ("00" * 32, proof[0][1])
222+
assert not utils.verify_merkle_proof(chunk, bad_proof, root)

0 commit comments

Comments
 (0)