File size: 14,433 Bytes
d37abcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c3cd
d37abcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c3cd
d37abcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c3cd
d37abcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c3cd
d37abcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542c3cd
d37abcf
 
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""
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()