Download scripts/validate.py from KurniaKadir/Web3-Dataset: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/KurniaKadir/Web3-Dataset/resolve/main/scripts/validate.py
- Command line
-
hf download hf://datasets/KurniaKadir/Web3-Dataset/scripts/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/KurniaKadir/Web3-Dataset/resolve/main/scripts/validate.py
10.6 kB
| """ | |
| Web3Coders Dataset Validation Script – 2026 Edition (v2.0) | |
| Validates all source contracts (Solidity, Vyper, Rust, Move) against: | |
| - Compilation/parsing (correctness) | |
| - Duplicate detection (MD5-based) | |
| - Metadata completeness (halal_compliance, fatwa_reference, etc.) | |
| - Optional integration with Halal compliance checker | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import hashlib | |
| import subprocess | |
| import argparse | |
| from pathlib import Path | |
| from typing import List, Dict, Set, Optional | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| # ---------------------------------------------------------------------- | |
| # Language compiler/checker configurations | |
| # ---------------------------------------------------------------------- | |
| LANGUAGE_CONFIG = { | |
| "solidity": { | |
| "extensions": [".sol"], | |
| "check_cmd": ["solc", "--validate"], | |
| "success_patterns": ["Compiler run successful"], | |
| "error_keywords": ["Error", "Exception"], | |
| }, | |
| "vyper": { | |
| "extensions": [".vy"], | |
| "check_cmd": ["vyper", "-f", "bytecode"], | |
| "success_patterns": ["0x"], | |
| "error_keywords": ["Error", "Exception", "SyntaxError"], | |
| }, | |
| "rust": { | |
| "extensions": [".rs"], | |
| "check_cmd": ["rustc", "--emit=mir", "-Z", "no-codegen"], # Only parse & type-check | |
| "success_patterns": [], | |
| "error_keywords": ["error", "abort"], | |
| }, | |
| "move": { | |
| "extensions": [".move"], | |
| "check_cmd": ["move", "build"], # Requires move-cli installed | |
| "success_patterns": ["SUCCESS"], | |
| "error_keywords": ["error", "abort", "failed"], | |
| }, | |
| } | |
| # ---------------------------------------------------------------------- | |
| # Validation functions | |
| # ---------------------------------------------------------------------- | |
| def find_contracts(root_dir: Path) -> Dict[str, List[Path]]: | |
| """Discover all contract files per language.""" | |
| contracts = {} | |
| for lang, config in LANGUAGE_CONFIG.items(): | |
| files = [] | |
| for ext in config["extensions"]: | |
| files.extend(root_dir.rglob(f"*{ext}")) | |
| contracts[lang] = files | |
| return contracts | |
| def compute_md5(file_path: Path) -> str: | |
| """Compute MD5 hash of file contents (excluding BOM and whitespace normalization?).""" | |
| hasher = hashlib.md5() | |
| with open(file_path, "rb") as f: | |
| for chunk in iter(lambda: f.read(65536), b""): | |
| hasher.update(chunk) | |
| return hasher.hexdigest() | |
| def check_duplicates(contracts_by_lang: Dict[str, List[Path]]) -> List[Dict]: | |
| """Identify duplicate files based on MD5 hash.""" | |
| seen: Dict[str, List[Path]] = {} | |
| duplicates = [] | |
| for lang, files in contracts_by_lang.items(): | |
| for f in files: | |
| md5 = compute_md5(f) | |
| if md5 in seen: | |
| # Duplicate found | |
| duplicates.append({ | |
| "original": seen[md5][0], | |
| "duplicate": f, | |
| "lang": lang, | |
| "md5": md5 | |
| }) | |
| seen[md5].append(f) | |
| else: | |
| seen[md5] = [f] | |
| return duplicates | |
| def validate_file(file_path: Path, lang: str) -> Dict: | |
| """Validate a single contract file using appropriate compiler.""" | |
| config = LANGUAGE_CONFIG.get(lang) | |
| if not config: | |
| return {"path": str(file_path), "lang": lang, "valid": False, "error": "Unknown language"} | |
| cmd = config["check_cmd"] + [str(file_path)] | |
| try: | |
| result = subprocess.run( | |
| cmd, | |
| capture_output=True, | |
| text=True, | |
| timeout=30 # prevent hanging | |
| ) | |
| stdout = result.stdout + result.stderr | |
| # Check for errors | |
| has_error = any(kw in stdout for kw in config["error_keywords"]) | |
| success = not has_error | |
| # For languages with explicit success patterns, also check | |
| if config["success_patterns"]: | |
| success = success and any(p in stdout for p in config["success_patterns"]) | |
| return { | |
| "path": str(file_path), | |
| "lang": lang, | |
| "valid": success, | |
| "stdout": stdout[:500] + ("..." if len(stdout) > 500 else ""), | |
| "returncode": result.returncode, | |
| } | |
| except subprocess.TimeoutExpired: | |
| return {"path": str(file_path), "lang": lang, "valid": False, "error": "Timeout"} | |
| except Exception as e: | |
| return {"path": str(file_path), "lang": lang, "valid": False, "error": str(e)} | |
| def validate_all_contracts(contracts_by_lang: Dict[str, List[Path]], workers: int = 4) -> List[Dict]: | |
| """Parallel validation of all contracts.""" | |
| results = [] | |
| tasks = [] | |
| with ThreadPoolExecutor(max_workers=workers) as executor: | |
| for lang, files in contracts_by_lang.items(): | |
| for f in files: | |
| tasks.append(executor.submit(validate_file, f, lang)) | |
| for future in as_completed(tasks): | |
| results.append(future.result()) | |
| return results | |
| def check_metadata_completeness(data_dir: Path) -> Dict: | |
| """ | |
| Check that each contract in the dataset has all required metadata fields. | |
| Assumes data/ directory contains JSONL files with the dataset. | |
| """ | |
| required_fields = {"source_code", "bytecode", "abi", "gas_estimates", | |
| "security_audit", "halal_compliance", "contract_type"} | |
| # fatwa_reference is optional but recommended | |
| issues = {} | |
| for split in ["train", "validation", "test"]: | |
| # Check all shards | |
| shard_files = list(data_dir.glob(f"{split}-*.jsonl")) | |
| if not shard_files: | |
| # fallback to single file | |
| single = data_dir / f"{split}.jsonl" | |
| if single.exists(): | |
| shard_files = [single] | |
| missing_fields = [] | |
| for shard in shard_files: | |
| with open(shard, "r", encoding="utf-8") as f: | |
| for line_num, line in enumerate(f, 1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| record = json.loads(line) | |
| missing = [field for field in required_fields if field not in record] | |
| if missing: | |
| missing_fields.append({ | |
| "shard": str(shard), | |
| "line": line_num, | |
| "missing": missing, | |
| "contract_type": record.get("contract_type", "unknown") | |
| }) | |
| except json.JSONDecodeError as e: | |
| missing_fields.append({ | |
| "shard": str(shard), | |
| "line": line_num, | |
| "error": f"JSON parse error: {e}" | |
| }) | |
| issues[split] = missing_fields | |
| return issues | |
| # ---------------------------------------------------------------------- | |
| # Main entry point | |
| # ---------------------------------------------------------------------- | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Web3Coders Dataset Validator (2026)") | |
| parser.add_argument("--source-root", default="source_contracts", | |
| help="Root directory of contract source files") | |
| parser.add_argument("--data-root", default="data", | |
| help="Root directory of JSONL data files") | |
| parser.add_argument("--workers", type=int, default=4, | |
| help="Number of parallel workers for validation") | |
| parser.add_argument("--no-compile", action="store_true", | |
| help="Skip compilation validation (only metadata/duplicate checks)") | |
| parser.add_argument("--check-duplicates", action="store_true", | |
| help="Check for duplicate files via MD5") | |
| parser.add_argument("--check-metadata", action="store_true", | |
| help="Check metadata completeness in JSONL files") | |
| args = parser.parse_args() | |
| source_root = Path(args.source_root) | |
| data_root = Path(args.data_root) | |
| if not source_root.exists(): | |
| print(f"Error: source root '{source_root}' does not exist.", file=sys.stderr) | |
| sys.exit(1) | |
| # 1. Find contracts | |
| contracts_by_lang = find_contracts(source_root) | |
| print(f"Found contracts: {sum(len(files) for files in contracts_by_lang.values())} total") | |
| for lang, files in contracts_by_lang.items(): | |
| print(f" {lang}: {len(files)} files") | |
| # 2. Duplicate detection | |
| if args.check_duplicates: | |
| duplicates = check_duplicates(contracts_by_lang) | |
| if duplicates: | |
| print("\n⚠️ Duplicate files found:") | |
| for dup in duplicates: | |
| print(f" {dup['duplicate']} (MD5: {dup['md5']}) is a duplicate of {dup['original']}") | |
| else: | |
| print("✅ No duplicate files found.") | |
| # 3. Compilation validation | |
| if not args.no_compile: | |
| print("\n🔍 Validating contracts...") | |
| results = validate_all_contracts(contracts_by_lang, workers=args.workers) | |
| errors = [r for r in results if not r["valid"]] | |
| if errors: | |
| print(f"❌ {len(errors)} contracts failed validation:") | |
| for err in errors: | |
| print(f" {err['path']} ({err['lang']}) - {err.get('error', 'compilation error')}") | |
| if "stdout" in err: | |
| print(f" Output: {err['stdout']}") | |
| else: | |
| print("✅ All contracts compiled successfully!") | |
| else: | |
| print("⏭️ Skipping compilation validation (--no-compile set)") | |
| # 4. Metadata completeness | |
| if args.check_metadata: | |
| if data_root.exists(): | |
| print("\n📋 Checking metadata completeness...") | |
| issues = check_metadata_completeness(data_root) | |
| total_issues = sum(len(v) for v in issues.values()) | |
| if total_issues > 0: | |
| print(f"❌ {total_issues} metadata issues found:") | |
| for split, split_issues in issues.items(): | |
| if split_issues: | |
| print(f" {split}: {len(split_issues)} issues") | |
| for issue in split_issues[:5]: # show first 5 per split | |
| print(f" {issue}") | |
| if len(split_issues) > 5: | |
| print(f" ... and {len(split_issues)-5} more") | |
| else: | |
| print("✅ All metadata fields are present!") | |
| else: | |
| print("⚠️ Data directory not found; skipping metadata check") | |
| print("\n✅ Validation complete.") | |
| if __name__ == "__main__": | |
| main() |