Web3-Dataset / scripts /preprocess.py
KurniaKadir's picture
Update scripts/preprocess.py
d37abcf verified
Raw History Blame Contribute Delete
14.4 kB
"""
Web3Coders Dataset Preprocessor – 2026 Edition (v2.0)
Preprocesses raw contract source files into the final dataset format:
- Compiles contracts to obtain bytecode and ABI (where applicable)
- Extracts security and gas metrics via Slither (Solidity) or equivalent
- Annotates with Halal compliance using HalalChain Compliance Checker
- Classifies contract type (DeFi, NFT, Token, etc.)
- Outputs JSONL files ready for Hugging Face dataset.
Usage:
python scripts/preprocess.py --input source_contracts/ --output data/
python scripts/preprocess.py --input source_contracts/ --output data/ --workers 8 --halal-api http://localhost:8000
Options:
--input Input directory containing contract source files
--output Output directory for JSONL shards (default: data/)
--workers Number of parallel workers (default: 4)
--shard-size Number of records per shard (default: 10000)
--halal-api Optional API endpoint for Halal compliance checking
--no-compile Skip compilation (only use existing ABIs/bytecode if provided)
"""
import os
import sys
import json
import hashlib
import subprocess
import argparse
import tempfile
import shutil
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from tqdm import tqdm
# ----------------------------------------------------------------------
# Language compilers/analyzers
# ----------------------------------------------------------------------
LANGUAGE_CONFIG = {
"solidity": {
"extensions": [".sol"],
"compile_cmd": ["solc", "--combined-json", "bin,abi,hashes", "--optimize"],
"analysis_module": "slither", # fallback to subprocess if slither not importable
},
"vyper": {
"extensions": [".vy"],
"compile_cmd": ["vyper", "-f", "bytecode", "abi"],
},
"rust": {
"extensions": [".rs"],
"compile_cmd": ["rustc", "--emit=llvm-bc"], # not directly usable for EVM
"note": "Rust contracts (e.g., Solana) require special handling; placeholder."
},
"move": {
"extensions": [".move"],
"compile_cmd": ["move", "build"], # Move CLI
"note": "Move contracts (Aptos/Sui) require separate tooling; placeholder."
},
}
# ----------------------------------------------------------------------
# Helper functions
# ----------------------------------------------------------------------
def compile_solidity(file_path: Path) -> Tuple[Optional[str], Optional[str]]:
"""Compile Solidity and return (bytecode, abi)."""
try:
# Use solc with combined-json output
cmd = ["solc", "--combined-json", "bin,abi", str(file_path)]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return None, None
output = json.loads(result.stdout)
# Expecting something like: {"contracts": {"file.sol:ContractName": {"bin": "...", "abi": "..."}}}
contracts = output.get("contracts", {})
if not contracts:
return None, None
# Take the first contract (usually the main one)
contract_key = next(iter(contracts))
contract_data = contracts[contract_key]
bytecode = contract_data.get("bin")
abi = contract_data.get("abi")
return bytecode, abi
except Exception as e:
print(f"Compilation error for {file_path}: {e}", file=sys.stderr)
return None, None
def compile_vyper(file_path: Path) -> Tuple[Optional[str], Optional[str]]:
"""Compile Vyper and return (bytecode, abi)."""
try:
# Vyper 0.3+ can output multiple formats
# We'll run separately for bytecode and abi
bytecode_cmd = ["vyper", "-f", "bytecode", str(file_path)]
bytecode_result = subprocess.run(bytecode_cmd, capture_output=True, text=True, timeout=30)
if bytecode_result.returncode != 0:
return None, None
bytecode = bytecode_result.stdout.strip()
abi_cmd = ["vyper", "-f", "abi", str(file_path)]
abi_result = subprocess.run(abi_cmd, capture_output=True, text=True, timeout=30)
if abi_result.returncode != 0:
return bytecode, None
abi = abi_result.stdout.strip()
return bytecode, abi
except Exception as e:
print(f"Compilation error for {file_path}: {e}", file=sys.stderr)
return None, None
def analyze_solidity_security(file_path: Path) -> Dict[str, Any]:
"""Use Slither to get security and gas info."""
try:
# Try importing slither
from slither import Slither
slither = Slither(str(file_path))
vulnerabilities = []
for detector in slither.detectors:
vulnerabilities.extend([v.name for v in detector.detect()])
# Gas estimates: approximate
gas_info = {}
for f in slither.functions:
if f.gas_estimated:
gas_info[f.name] = f.gas_estimated
# Quality score
score = slither.get_code_quality_score() if hasattr(slither, 'get_code_quality_score') else 0
return {
"vulnerabilities": vulnerabilities,
"gas_estimates": gas_info,
"slither_score": score,
}
except ImportError:
# Fallback: use slither CLI to get output
try:
cmd = ["slither", str(file_path), "--json", "-"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
return {"vulnerabilities": [], "gas_estimates": {}, "slither_score": 0}
data = json.loads(result.stdout)
# Parse detection results
vulns = []
for detection in data.get("detectors", []):
vulns.extend([issue["check"] for issue in detection.get("issues", [])])
# Gas not easily extracted via CLI; leave empty
return {"vulnerabilities": vulns, "gas_estimates": {}, "slither_score": 0}
except Exception:
return {"vulnerabilities": [], "gas_estimates": {}, "slither_score": 0}
except Exception as e:
print(f"Slither analysis error for {file_path}: {e}", file=sys.stderr)
return {"vulnerabilities": [], "gas_estimates": {}, "slither_score": 0}
def classify_contract_type(source_code: str) -> str:
"""Heuristic classification of contract type based on keywords and patterns."""
source = source_code.lower()
if "interface" in source and "erc20" in source:
return "Token"
elif "erc721" in source or "erc1155" in source:
return "NFT"
elif "dao" in source or "governance" in source or "proposal" in source:
return "DAO"
elif "lending" in source or "borrow" in source or "pool" in source:
return "DeFi"
elif "murabaha" in source or "mudarabah" in source or "islamic" in source:
return "Islamic Finance"
elif "staking" in source or "rewards" in source:
return "Staking"
else:
return "General"
def check_halal_compliance(source_code: str, api_endpoint: Optional[str] = None) -> Tuple[str, str]:
"""
Check Halal compliance using either local module or API.
Returns (status, fatwa_reference).
"""
# Default to pending if not determined
status = "pending"
fatwa_ref = ""
if api_endpoint:
try:
resp = requests.post(
f"{api_endpoint}/compliance",
json={"source": source_code},
timeout=30
)
if resp.status_code == 200:
data = resp.json()
status = data.get("status", "pending")
fatwa_ref = data.get("fatwa_reference", "")
except Exception as e:
print(f"Halal API error: {e}", file=sys.stderr)
else:
# Attempt to use local halalchain module if available
try:
from halalchain import ComplianceChecker
checker = ComplianceChecker()
result = checker.check_contract(source_code, rules=["no-riba", "no-gharar"])
status = result.get("status", "pending")
fatwa_ref = result.get("fatwa_reference", "")
except ImportError:
# Local fallback: simple keyword checks
if "riba" not in source_code.lower() and "interest" not in source_code.lower():
status = "compliant"
else:
status = "non-compliant"
return status, fatwa_ref
# ----------------------------------------------------------------------
# Main preprocessing worker
# ----------------------------------------------------------------------
def process_contract(file_path: Path, config: Dict) -> Optional[Dict[str, Any]]:
"""
Process a single contract file and return a record ready for dataset.
"""
lang = None
for l, cfg in LANGUAGE_CONFIG.items():
if file_path.suffix in cfg["extensions"]:
lang = l
break
if not lang:
return None
# Read source code
with open(file_path, "r", encoding="utf-8") as f:
source_code = f.read()
# Compile to get bytecode and ABI (if not disabled)
bytecode = None
abi = None
if not config.get("no_compile", False):
if lang == "solidity":
bytecode, abi = compile_solidity(file_path)
elif lang == "vyper":
bytecode, abi = compile_vyper(file_path)
else:
# For Rust/Move, we cannot easily get EVM bytecode; leave empty
pass
# Security & gas analysis (only for Solidity for now)
security_audit = {}
gas_estimates = []
if lang == "solidity":
sec = analyze_solidity_security(file_path)
security_audit = sec
# Convert gas dict to list of floats (average or max)
if sec.get("gas_estimates"):
gas_estimates = list(sec["gas_estimates"].values())
# Determine audit pass/fail based on vulnerabilities
audit_status = "pass" if len(sec.get("vulnerabilities", [])) == 0 else "fail"
# Halal compliance
status, fatwa_ref = check_halal_compliance(source_code, config.get("halal_api"))
# Contract type classification
contract_type = classify_contract_type(source_code)
# Build record
record = {
"source_code": source_code,
"bytecode": bytecode or "",
"abi": abi or "",
"gas_estimates": gas_estimates,
"security_audit": security_audit.get("vulnerabilities", []) if lang == "solidity" else "",
"halal_compliance": status,
"fatwa_reference": fatwa_ref,
"contract_type": contract_type,
}
return record
# ----------------------------------------------------------------------
# Directory processing with sharding
# ----------------------------------------------------------------------
def process_directory(input_dir: Path, output_dir: Path, config: Dict):
"""
Process all contract files in input_dir and write JSONL shards to output_dir.
"""
# Collect all files with known extensions
files = []
for lang, cfg in LANGUAGE_CONFIG.items():
for ext in cfg["extensions"]:
files.extend(input_dir.rglob(f"*{ext}"))
total = len(files)
print(f"Found {total} contract files to process.")
# Create output directory
output_dir.mkdir(parents=True, exist_ok=True)
# Determine shard size
shard_size = config.get("shard_size", 10000)
# Parallel processing
workers = config.get("workers", 4)
records = []
errors = []
with ThreadPoolExecutor(max_workers=workers) as executor:
futures = {executor.submit(process_contract, f, config): f for f in files}
with tqdm(total=total, desc="Processing contracts") as pbar:
for future in as_completed(futures):
file_path = futures[future]
try:
record = future.result()
if record:
records.append(record)
else:
errors.append(str(file_path))
except Exception as e:
errors.append(f"{file_path}: {e}")
pbar.update(1)
print(f"Processed {len(records)} contracts successfully, {len(errors)} errors.")
# Write shards
split_name = "train" # assume all go to train; could be split later
for i in range(0, len(records), shard_size):
shard_records = records[i:i+shard_size]
shard_num = i // shard_size
shard_file = output_dir / f"{split_name}-{shard_num:05d}-of-{ (len(records)//shard_size)+1 :05d}.jsonl"
with open(shard_file, "w", encoding="utf-8") as f:
for rec in shard_records:
f.write(json.dumps(rec) + "\n")
print(f"Written {shard_file} with {len(shard_records)} records.")
# Optionally create validation and test splits (e.g., random sampling)
# For simplicity, we skip here; user can split later.
# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="Preprocess Web3Coders dataset (2026)")
parser.add_argument("--input", required=True, help="Input directory with source contracts")
parser.add_argument("--output", default="data", help="Output directory for JSONL shards")
parser.add_argument("--workers", type=int, default=4, help="Number of parallel workers")
parser.add_argument("--shard-size", type=int, default=10000, help="Records per shard")
parser.add_argument("--halal-api", help="Halal compliance API endpoint (optional)")
parser.add_argument("--no-compile", action="store_true", help="Skip compilation (use existing ABI/bytecode if available?)")
args = parser.parse_args()
input_dir = Path(args.input)
if not input_dir.exists():
print(f"Error: Input directory {input_dir} does not exist.", file=sys.stderr)
sys.exit(1)
output_dir = Path(args.output)
config = {
"workers": args.workers,
"shard_size": args.shard_size,
"halal_api": args.halal_api,
"no_compile": args.no_compile,
}
process_directory(input_dir, output_dir, config)
if __name__ == "__main__":
main()