File size: 10,645 Bytes
d10146c 7d4212e d10146c 7d4212e d10146c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | """
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() |