Repository navigation
Extend the Merkle proof system by adding portable proof export and standalone - #11
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds portable Merkle-proof functionality and manifest metadata: compute_sha256 accepts data or file_path, new helpers to generate/export/load/verify Merkle proofs, and manifests now record raw/processed merkle roots and chunk size. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant FS as FileSystem
participant Utils
participant Verifier
User->>FS: provide file (raw/processed)
User->>Utils: compute_merkle_root(file_path, chunk_size)
Utils->>FS: read file in chunks
Utils-->>Utils: hash chunks and build Merkle tree
Utils-->>User: return merkle_root
User->>Utils: generate_merkle_proof(file_path, chunk_index, chunk_size)
Utils->>FS: read file chunks
Utils-->>Utils: assemble proof steps
Utils-->>User: return proof
User->>Utils: export_merkle_proof(proof, chunk_index, chunk_size, output_path)
Utils->>FS: write JSON proof
Verifier->>FS: read proof JSON
Verifier->>Utils: verify_merkle_proof_from_file(proof_file_path, chunk_data, expected_root)
Utils-->>Verifier: return boolean result
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.gitignore:
- Line 336: Replace the current gitignore pattern "*.venv" with the
directory-specific pattern ".venv/" (or add ".venv/" alongside "*.venv" if you
need to support both styles); update the line that currently contains "*.venv"
to ".venv/" so Git ignores the virtualenv directory conventionally.
In `@openverifiablellm/utils.py`:
- Around line 251-265: verify_merkle_proof_from_file currently lets exceptions
from load_merkle_proof propagate; wrap the call to load_merkle_proof in a
try/except that catches file/IO/JSON errors (e.g., FileNotFoundError, OSError,
json.JSONDecodeError, ValueError or a general Exception as a fallback), log a
warning via the module logger (e.g., logging.getLogger(__name__)) with context,
and return False on any exception; then proceed to check data.get("proof") and
call verify_merkle_proof as before.
- Around line 102-106: The verify_merkle_proof function is missing a type
annotation for the proof parameter; change its signature to annotate proof as
List[Tuple[str, bool]] (or the appropriate tuple element types used in the
function) and add the necessary typing imports (from typing import List, Tuple)
at the top of the file so the function reads something like def
verify_merkle_proof(chunk_bytes: bytes, proof: List[Tuple[str, bool]],
merkle_root: str) -> bool; ensure any references to proof inside the function
align with the annotated structure.
- Around line 46-50: The function generate_merkle_proof is missing a return type
annotation; update its signature to include the correct type (e.g., change to
def generate_merkle_proof(... ) -> List[bytes]: if it returns a list of hash
bytes) and add the corresponding import (from typing import List) or the
appropriate type (e.g., Tuple[bytes, ...], bytes, etc.) that matches the
implementation's actual returned value so the signature accurately reflects what
generate_merkle_proof returns.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
|
hi @Archit381 do checkout this, whenever you get free time |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 259-267: The code assumes load_merkle_proof returned a dict and
calls data.get("proof"), which will raise if data is a non-object JSON (e.g.,
list or string); change the logic to validate the payload type after loading by
checking that data is an instance of dict (or mapping) and if not log a warning
and return False, then proceed to read proof = data.get("proof") and handle
proof is None as before; reference the variables/functions data,
load_merkle_proof, proof, and the logger to locate and implement this guard.
- Around line 116-133: The proof verification loop currently accepts any
iterable pair; update the loop in verify logic to strictly validate each step:
check that sibling_hex is a str and is_left is a bool before attempting
bytes.fromhex, then after decoding ensure sibling has length 32 bytes (digest
size) and return False on any violation; retain the existing concatenation logic
that sets combined and uses compute_sha256 and current_hash but only after these
strict type/size checks.
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openverifiablellm/utils.py (1)
6-11: 🧹 Nitpick | 🔵 TrivialRemove duplicate
Unionimport.
Unionis imported twice (lines 6 and 11). Consolidate into a single import statement.📝 Proposed fix
-from typing import Union import hashlib import logging import json import platform -from typing import Union, Optional +from typing import Union, Optional🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openverifiablellm/utils.py` around lines 6 - 11, Remove the duplicate typing import: consolidate the two "from typing import Union" lines into a single import that includes both Union and Optional (e.g., "from typing import Union, Optional") so only one import from typing remains and the redundant import is removed; update the import statement near the top where "Union" and "Optional" currently appear.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 205-214: The function load_merkle_proof lacks a return type
annotation; update its signature to include an explicit return type (e.g., ->
Dict[str, Any] or -> Any) to reflect the JSON-typed proof, and add the required
typing imports (from typing import Dict, Any) at the top of the module if not
already present; keep the implementation the same but ensure the function
signature and imports reference load_merkle_proof so static checkers and callers
get proper type information.
- Around line 185-203: The export_merkle_proof function lacks type annotations
for proof and a return type and does not validate inputs; update its signature
to type-annotate proof (e.g., List[str] or the same type used by
generate_merkle_proof) and a return type of None, add input validation checks
(raise ValueError) to ensure chunk_size > 0 and chunk_index is within valid
range (0 <= chunk_index < number_of_chunks or as used in generate_merkle_proof),
and keep output_path typed as Union[str, Path]; perform these checks at the
start of export_merkle_proof and then proceed to write the JSON as before so
behavior matches generate_merkle_proof expectations.
- Around line 66-69: Calls to compute_sha256 currently pass positional arguments
(e.g., compute_sha256(chunk)), but compute_sha256 enforces keyword-only params;
update every call (including the call inside the file-read loop that builds
leaves) to use the appropriate keyword (use data=chunk when hashing an in-memory
bytes chunk, or file_path=<path> when hashing a file path). Search for
compute_sha256 usages (including in tests) and replace positional args with
data=<value> or file_path=<value> so the signature requirements are satisfied.
- Around line 260-262: Add an implementation of verify_merkle_proof_from_file in
utils.py that reads the stored proof file, computes the leaf hash for the
provided chunk (supporting bytes input via compute_sha256), reconstructs the
merkle root using the proof entries (respecting sibling order/direction stored
in the file or by reusing any existing verify_merkle_proof helper), and returns
True if the reconstructed root equals expected_root (False otherwise); ensure
the function accepts the same argument names used in tests (e.g.,
verify_merkle_proof_from_file(proof_file_path, chunk_data, expected_root)),
performs JSON parsing of the proof file, validates required keys, and raises a
clear exception on malformed proof data.
---
Outside diff comments:
In `@openverifiablellm/utils.py`:
- Around line 6-11: Remove the duplicate typing import: consolidate the two
"from typing import Union" lines into a single import that includes both Union
and Optional (e.g., "from typing import Union, Optional") so only one import
from typing remains and the redundant import is removed; update the import
statement near the top where "Union" and "Optional" currently appear.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
openverifiablellm/utils.py (1)
271-296:⚠️ Potential issue | 🟠 MajorReturn
Falsefor malformed/unreadable proof files instead of raising.This boolean verifier currently raises
FileNotFoundError/ValueErrorfor malformed input. That makes standalone verification brittle and regresses earlier robustness handling for invalid proof files.Suggested fix
def verify_merkle_proof_from_file( proof_file_path: Union[str, Path], chunk_data: bytes, expected_root: str ) -> bool: - proof_file_path = Path(proof_file_path) - - if not proof_file_path.exists(): - raise FileNotFoundError(f"Proof file not found: {proof_file_path}") - - with proof_file_path.open("r", encoding="utf-8") as f: - data = json.load(f) - - if not isinstance(data, dict): - raise ValueError("Malformed proof file: expected JSON object") - - required_keys = {"chunk_index", "chunk_size", "proof"} - if not required_keys.issubset(data.keys()): - raise ValueError("Malformed proof file: missing required keys") - - proof = data["proof"] - - if not isinstance(proof, list): - raise ValueError("Malformed proof: proof must be a list") - - return verify_merkle_proof(chunk_data, proof, expected_root) + try: + data = load_merkle_proof(proof_file_path) + except (OSError, json.JSONDecodeError, TypeError, ValueError) as e: + logger.warning("Failed to load proof file %s: %s", proof_file_path, e) + return False + + if not isinstance(data, dict): + logger.warning("Malformed proof file: expected JSON object") + return False + + required_keys = {"chunk_index", "chunk_size", "proof"} + if not required_keys.issubset(data): + logger.warning("Malformed proof file: missing required keys") + return False + + proof = data.get("proof") + if not isinstance(proof, list): + logger.warning("Malformed proof: proof must be a list") + return False + + return verify_merkle_proof(chunk_data, proof, expected_root)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openverifiablellm/utils.py` around lines 271 - 296, In verify_merkle_proof_from_file, don't raise on unreadable or malformed proof files—catch errors (FileNotFoundError, json.JSONDecodeError, ValueError and other I/O errors) around Path.exists(), file open/read and json.load(), and return False when any of these occur or when the structure checks fail; keep existing checks for required_keys, proof type and finally call verify_merkle_proof(chunk_data, proof, expected_root) and return its boolean result.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openverifiablellm/utils.py`:
- Line 11: Remove the duplicate "Union" import from the typing imports in this
module: ensure only one "from typing import ..." line contains Union (e.g.,
consolidate into a single import that includes Union, Optional, Dict, Any, List,
Tuple) so the redundant re-import is deleted and the F811 lint error is
resolved.
---
Duplicate comments:
In `@openverifiablellm/utils.py`:
- Around line 271-296: In verify_merkle_proof_from_file, don't raise on
unreadable or malformed proof files—catch errors (FileNotFoundError,
json.JSONDecodeError, ValueError and other I/O errors) around Path.exists(),
file open/read and json.load(), and return False when any of these occur or when
the structure checks fail; keep existing checks for required_keys, proof type
and finally call verify_merkle_proof(chunk_data, proof, expected_root) and
return its boolean result.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
openverifiablellm/utils.py (1)
315-340:⚠️ Potential issue | 🟠 Major
verify_merkle_proof_from_fileshould reject malformed input withFalseinstead of raising.Current behavior raises on missing/malformed files, which makes standalone verification brittle and inconsistent with
verify_merkle_proof’s boolean rejection contract.🛡️ Proposed fix
def verify_merkle_proof_from_file( proof_file_path: Union[str, Path], chunk_data: bytes, expected_root: str ) -> bool: - proof_file_path = Path(proof_file_path) - - if not proof_file_path.exists(): - raise FileNotFoundError(f"Proof file not found: {proof_file_path}") - - with proof_file_path.open("r", encoding="utf-8") as f: - data = json.load(f) - - if not isinstance(data, dict): - raise ValueError("Malformed proof file: expected JSON object") - - required_keys = {"chunk_index", "chunk_size", "proof"} - if not required_keys.issubset(data.keys()): - raise ValueError("Malformed proof file: missing required keys") - - proof = data["proof"] - - if not isinstance(proof, list): - raise ValueError("Malformed proof: proof must be a list") - - return verify_merkle_proof(chunk_data, proof, expected_root) + try: + data = load_merkle_proof(proof_file_path) + except (OSError, json.JSONDecodeError, ValueError, TypeError) as e: + logger.warning("Failed to load proof file %s: %s", proof_file_path, e) + return False + + if not isinstance(data, dict): + return False + + required_keys = {"chunk_index", "chunk_size", "proof"} + if not required_keys.issubset(data): + return False + + proof = data.get("proof") + if not isinstance(proof, list): + return False + + return verify_merkle_proof(chunk_data, proof, expected_root)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openverifiablellm/utils.py` around lines 315 - 340, The function verify_merkle_proof_from_file currently raises on missing file and malformed JSON; change it to return False instead of raising so it matches verify_merkle_proof’s boolean contract: in verify_merkle_proof_from_file, after converting proof_file_path to Path, if the file does not exist return False (do not raise); when loading JSON, catch json.JSONDecodeError and return False; validate that the loaded data is a dict, that required_keys ("chunk_index","chunk_size","proof") are present, and that proof is a list—if any check fails return False; finally call and return verify_merkle_proof(chunk_data, proof, expected_root) as before.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 270-314: There is a duplicate implementation of the function
verify_merkle_proof causing a redefinition error (Ruff F811); find the duplicate
verify_merkle_proof definition in the file and remove the redundant copy so only
a single canonical implementation remains, or if the two versions differ,
reconcile/merge their intended behavior into one function (preserve the correct
validation logic for chunk_bytes, proof, merkle_root, the hex decoding, sibling
length check against hashlib.sha256().digest_size, and the left/right
concatenation logic) and delete the other duplicate.
In `@tests/test_util.py`:
- Line 245: The test currently calls verify_merkle_proof_from_file positionally
and passes chunk as the first argument (which maps to the path parameter);
change the call to use explicit keyword arguments so the chunk variable is
passed to the chunk parameter and not to path — e.g. call
verify_merkle_proof_from_file(path=<correct_path_var>, chunk=chunk,
proof_file=proof_file, root=root) (use the actual path variable in scope) so the
mapping is unambiguous.
---
Duplicate comments:
In `@openverifiablellm/utils.py`:
- Around line 315-340: The function verify_merkle_proof_from_file currently
raises on missing file and malformed JSON; change it to return False instead of
raising so it matches verify_merkle_proof’s boolean contract: in
verify_merkle_proof_from_file, after converting proof_file_path to Path, if the
file does not exist return False (do not raise); when loading JSON, catch
json.JSONDecodeError and return False; validate that the loaded data is a dict,
that required_keys ("chunk_index","chunk_size","proof") are present, and that
proof is a list—if any check fails return False; finally call and return
verify_merkle_proof(chunk_data, proof, expected_root) as before.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Addressed Issues:
Closes #12
Real-Life Analogy
Imagine a university issues degree certificates.
Before this PR:
After this PR:
Earlier → Internal verification only.
Now → Portable, shareable, independently verifiable proof.
Summary
This PR extends the Merkle proof system by adding portable proof export and standalone verification.
Previously, the project supported:
However, proofs only existed inside the running Python process. They could not be saved, shared, or verified later.
With this update, Merkle proofs can now be:
This makes the verification process portable and shareable.
Problem
Before this change:
For real-world dataset distribution, this limits usability.
Solution
This PR introduces three new functions:
1.
export_merkle_proof()Exports a generated Merkle proof to a JSON file.
2.
load_merkle_proof()Loads a saved proof from a JSON file.
3.
verify_merkle_proof_from_file()Verifies a chunk using a stored proof file and the Merkle root.
Example proof file structure:
{ "chunk_index": 1, "chunk_size": 8, "proof": [ ["hash1...", false], ["hash2...", true] ] }What This Enables
This enhancement allows:
This moves the project from:
In-memory verification
→ Portable cryptographic verification system
Security Improvements
The verifier:
Negative test cases were added to validate these behaviors.
Testing
New tests were added to ensure:
All tests pass successfully.
Conclusion
This PR transforms the Merkle proof system from an internal mechanism into a portable verification framework.
It enables scalable, independent, and secure dataset verification, aligning the project closer to production-grade verifiable data infrastructure.
Checklist
We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact.
Summary by CodeRabbit
New Features
Tests