File size: 28,439 Bytes
0edf333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
"""Acquire and audit canonical signed EVM transaction envelopes.

The model sees the complete signed RLP envelope, including the type prefix, not
just calldata. Public RPC transaction objects are reconstructed and independently
checked against their advertised transaction hash and recovered sender. Blob
sidecars and Base's unsigned system deposits are deliberately outside this corpus.
"""

from __future__ import annotations

from collections import Counter
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import time
from typing import Any

from datasets import Dataset, DatasetDict, Features, Value, load_from_disk
from eth_account import Account
from eth_utils import keccak
import httpx
from omegaconf import DictConfig, OmegaConf
import pyarrow.parquet as pq
import rlp


_RECOVERY_ACCOUNT = Account()


class DataError(ValueError):
    """A transaction or local dataset failed an integrity check."""


class RpcError(RuntimeError):
    """All bounded RPC attempts failed."""


class RpcUnsupported(RpcError):
    """The optional raw-transaction RPC method is unavailable."""


def _integer(value: Any) -> int:
    if isinstance(value, bool):
        raise DataError("boolean is not an RPC quantity")
    number = int(value, 16) if isinstance(value, str) and value.startswith("0x") else int(value)
    if number < 0:
        raise DataError("negative RPC quantity")
    return number


def _bytes(value: str | None, size: int | None = None) -> bytes:
    if value is None:
        result = b""
    elif not isinstance(value, str) or not value.startswith("0x"):
        raise DataError("expected a 0x-prefixed byte string")
    else:
        text = value[2:]
        if len(text) % 2:
            raise DataError("odd-length hexadecimal byte string")
        try:
            result = bytes.fromhex(text)
        except ValueError as exc:
            raise DataError("invalid hexadecimal bytes") from exc
    if size is not None and len(result) != size:
        raise DataError(f"expected {size} bytes, got {len(result)}")
    return result


def _parity(tx: dict[str, Any]) -> int:
    parity = _integer(tx["yParity"] if "yParity" in tx else tx["v"])
    if parity not in (0, 1):
        raise DataError("typed transaction yParity must be 0 or 1")
    return parity


def reconstruct_raw(tx: dict[str, Any]) -> bytes:
    """Serialize an RPC transaction using the canonical EIP transaction schemas.

    Types 0, 1, 2, 3 and 4 follow EIP-155, 2930, 1559, 4844 and 7702.
    No signing or private keys are involved; the original signature is retained.
    """
    kind = _integer(tx.get("type", 0))
    if kind not in (0, 1, 2, 3, 4):
        raise DataError(f"unsupported transaction type {kind:#x} (system deposits excluded)")
    destination = _bytes(tx.get("to"))
    if len(destination) not in (0, 20) or (kind in (3, 4) and not destination):
        raise DataError("invalid transaction destination")
    payload = _bytes(tx.get("input", tx.get("data", "0x")))
    nonce, gas, value = (_integer(tx[key]) for key in ("nonce", "gas", "value"))
    signature = [_integer(tx["r"]), _integer(tx["s"])]
    if min(signature) <= 0:
        raise DataError("missing transaction signature")
    if kind == 0:
        fields = [nonce, _integer(tx["gasPrice"]), gas, destination, value, payload,
                  _integer(tx["v"]), *signature]
        return rlp.encode(fields)
    access_list = [
        [_bytes(entry["address"], 20), [_bytes(key, 32) for key in entry["storageKeys"]]]
        for entry in tx.get("accessList", [])
    ]
    fields = [_integer(tx["chainId"]), nonce]
    if kind == 1:
        fields.append(_integer(tx["gasPrice"]))
    else:
        fields.extend(_integer(tx[key]) for key in ("maxPriorityFeePerGas", "maxFeePerGas"))
    fields.extend([gas, destination, value, payload, access_list])
    if kind == 3:
        fields.extend([_integer(tx["maxFeePerBlobGas"]),
                       [_bytes(item, 32) for item in tx["blobVersionedHashes"]]])
    elif kind == 4:
        authorizations = [
            [_integer(auth["chainId"]), _bytes(auth["address"], 20), _integer(auth["nonce"]),
             _parity(auth), _integer(auth["r"]), _integer(auth["s"])]
            for auth in tx["authorizationList"]
        ]
        if not authorizations:
            raise DataError("type 4 authorization list is empty")
        fields.append(authorizations)
    fields.extend([_parity(tx), *signature])
    return bytes([kind]) + rlp.encode(fields)


def inspect_raw(raw: bytes, expected_chain_id: int) -> dict[str, Any]:
    """Recover the signer and chain binding from a signed canonical envelope."""
    if not raw:
        raise DataError("empty raw transaction")
    kind = raw[0] if raw[0] < 0x80 else 0
    if kind not in (0, 1, 2, 3, 4):
        raise DataError(f"unsupported transaction type {kind:#x}")
    decoded = rlp.decode(raw if kind == 0 else raw[1:], strict=True)
    lengths = {0: 9, 1: 11, 2: 12, 3: 14, 4: 13}
    if not isinstance(decoded, list) or len(decoded) != lengths[kind]:
        raise DataError("wrong RLP transaction field count; blob sidecars are excluded")
    if kind == 0:
        v = int.from_bytes(decoded[6])
        if v < 35:
            raise DataError("unprotected legacy signature has no chain binding")
        chain_id = (v - 35) // 2
        destination = decoded[3]
    else:
        chain_id = int.from_bytes(decoded[0])
        destination = decoded[4 if kind == 1 else 5]
    if chain_id != expected_chain_id:
        raise DataError(f"signed chain ID {chain_id} != expected {expected_chain_id}")
    try:
        sender = _RECOVERY_ACCOUNT.recover_transaction(raw).lower()
    except Exception as exc:
        raise DataError(f"invalid transaction signature: {exc}") from exc
    return {"tx_hash": "0x" + keccak(raw).hex(), "sender": sender,
            "to": "0x" + destination.hex() if destination else None,
            "tx_type": kind, "chain_id": chain_id, "raw_length": len(raw)}


def validate_transaction(tx: dict[str, Any], raw: bytes, chain_id: int) -> dict[str, Any]:
    details = inspect_raw(raw, chain_id)
    if details["tx_hash"] != tx["hash"].lower():
        raise DataError("keccak(raw) does not equal RPC transaction hash")
    if details["sender"] != tx["from"].lower():
        raise DataError("recovered signer does not equal RPC sender")
    destination = tx.get("to")
    if details["to"] != (destination.lower() if destination else None):
        raise DataError("raw destination does not equal RPC destination")
    if details["tx_type"] != _integer(tx.get("type", 0)):
        raise DataError("raw type does not equal RPC transaction type")
    if raw != reconstruct_raw(tx):
        raise DataError("raw envelope differs from reconstructed RPC transaction")
    return details


class RpcClient:
    """Small read-only JSON-RPC client with bounded retries and endpoint failover."""

    def __init__(self, endpoints: list[str], chain_id: int, timeout: float, retries: int):
        if not endpoints or retries < 1 or timeout <= 0:
            raise DataError("RPC endpoints, positive timeout and retries are required")
        self.endpoints = endpoints
        self.chain_id = chain_id
        self.retries = retries
        self.client = httpx.Client(timeout=timeout, headers={"User-Agent": "evm-bert-poc/0.1"})
        self.checked: set[str] = set()
        self.events: list[dict[str, Any]] = []
        self.last_endpoint: str | None = None
        self._id = 0

    def _request(self, endpoint: str, method: str, params: list[Any]) -> Any:
        self._id += 1
        response = self.client.post(endpoint, json={"jsonrpc": "2.0", "id": self._id,
                                                    "method": method, "params": params})
        response.raise_for_status()
        body = response.json()
        if body.get("id") != self._id:
            raise RpcError("RPC response ID mismatch")
        if body.get("error"):
            error = body["error"]
            message = str(error).lower()
            if error.get("code") in (-32601, -32004) or any(
                text in message for text in ("not supported", "not available", "does not exist")
            ):
                raise RpcUnsupported(str(error))
            raise RpcError(str(error))
        if "result" not in body or body["result"] is None:
            raise RpcError("RPC returned no result")
        return body["result"]

    def call(self, method: str, params: list[Any]) -> Any:
        errors: list[str] = []
        unsupported = 0
        for endpoint in self.endpoints:
            for attempt in range(self.retries):
                try:
                    if endpoint not in self.checked:
                        actual_chain = _integer(self._request(endpoint, "eth_chainId", []))
                        if actual_chain != self.chain_id:
                            raise RpcError(f"endpoint chain {actual_chain} != {self.chain_id}")
                        self.checked.add(endpoint)
                    result = self._request(endpoint, method, params)
                    self.last_endpoint = endpoint
                    return result
                except RpcUnsupported as exc:
                    unsupported += 1
                    errors.append(f"{endpoint}: {exc}")
                    break
                except (httpx.HTTPError, ValueError, RpcError) as exc:
                    errors.append(f"{endpoint}: {type(exc).__name__}: {exc}")
                    if attempt + 1 < self.retries:
                        time.sleep(min(0.25 * 2**attempt, 2))
            self.events.append({"endpoint": endpoint, "method": method, "error": errors[-1]})
        message = f"{method} failed: " + "; ".join(errors)
        if unsupported == len(self.endpoints):
            raise RpcUnsupported(message)
        raise RpcError(message)

    def close(self) -> None:
        self.client.close()


FEATURES = Features({
    "raw_hex": Value("string"), "tx_hash": Value("string"), "sender": Value("string"),
    "to": Value("string"), "block_number": Value("int64"), "block_hash": Value("string"),
    "transaction_index": Value("int64"), "tx_type": Value("int64"), "chain_id": Value("int64"),
    "chain": Value("string"), "raw_length": Value("int64"), "source_method": Value("string"),
    "split": Value("string"),
})


def _config(config: DictConfig | dict[str, Any]) -> dict[str, Any]:
    container = OmegaConf.to_container(config, resolve=True) if isinstance(config, DictConfig) else config
    return dict(container["data"] if "data" in container else container)


def _enable_fast_recovery() -> None:
    try:
        from eth_keys.backends import CoinCurveECCBackend
        _RECOVERY_ACCOUNT.set_key_backend(CoinCurveECCBackend())
    except ImportError:
        pass


def _split_rows(rows: list[dict[str, Any]], validation_fraction: float,
                test_fraction: float) -> dict[str, list[dict[str, Any]]]:
    if not (0 < validation_fraction < 1 and 0 < test_fraction < 1
            and validation_fraction + test_fraction < 1):
        raise DataError("validation/test fractions must be positive and sum to less than one")
    splits: dict[str, list[dict[str, Any]]] = {name: [] for name in ("train", "validation", "test")}
    for chain_id in sorted({row["chain_id"] for row in rows}):
        blocks = sorted({row["block_number"] for row in rows if row["chain_id"] == chain_id})
        if len(blocks) < 3:
            raise DataError(f"chain {chain_id} needs at least three nonempty signed-transaction blocks")
        n_validation = max(1, int(len(blocks) * validation_fraction))
        n_test = max(1, int(len(blocks) * test_fraction))
        if n_validation + n_test >= len(blocks):
            raise DataError("too few blocks for the requested split fractions")
        boundary_train, boundary_test = len(blocks) - n_validation - n_test, len(blocks) - n_test
        mapping = {block: "train" if index < boundary_train else
                   "validation" if index < boundary_test else "test"
                   for index, block in enumerate(blocks)}
        for row in rows:
            if row["chain_id"] == chain_id:
                row["split"] = mapping[row["block_number"]]
                splits[row["split"]].append(row)
    return splits


def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    with path.open("w") as stream:
        for row in rows:
            stream.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")


def _checksum(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _export(output: Path, rows: list[dict[str, Any]], source_blocks: list[dict[str, Any]],
            manifest: dict[str, Any], validation_fraction: float, test_fraction: float) -> None:
    splits = _split_rows(rows, validation_fraction, test_fraction)
    output.mkdir(parents=True, exist_ok=True)
    _write_jsonl(output / "transactions.jsonl", rows)
    _write_jsonl(output / "source_blocks.jsonl", source_blocks)
    dataset = DatasetDict({name: Dataset.from_list(items, features=FEATURES)
                           for name, items in splits.items()})
    dataset.save_to_disk(str(output / "dataset"))
    (output / "parquet").mkdir()
    for name, partition in dataset.items():
        partition.to_parquet(str(output / "parquet" / f"{name}.parquet"))
    manifest["rows"] = len(rows)
    manifest["splits"] = {name: len(items) for name, items in splits.items()}
    manifest["split_policy"] = "chronological whole blocks independently per chain; train < validation < test"
    manifest["sha256"] = {str(path.relative_to(output)): _checksum(path)
                          for path in sorted(output.rglob("*")) if path.is_file()}
    (output / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")


def collect(config: DictConfig | dict[str, Any]) -> dict[str, Any]:
    """Collect exactly the configured count per chain from recent finalized blocks.

    The oldest selected block may be capped; its newest eligible transactions are
    retained. Its entire RPC response is preserved for provenance. No transaction
    is submitted and no wallet or signing key is required.
    """
    settings = _config(config)
    output = Path(settings.get("output_dir", "data/transactions"))
    if output.exists() and any(output.iterdir()):
        raise DataError(f"refusing to overwrite nonempty corpus: {output}")
    chains = settings.get("chains") or [{"name": "ethereum", "chain_id": 1,
        "endpoints": settings.get("endpoints", ["https://ethereum-rpc.publicnode.com", "https://eth.llamarpc.com"]),
        "max_transactions": settings.get("max_transactions", 2000),
        "start_block": settings.get("start_block")}]
    chain_ids = [_integer(chain["chain_id"]) for chain in chains]
    if len(set(chain_ids)) != len(chain_ids):
        raise DataError("duplicate chain configurations")
    _enable_fast_recovery()
    rows: list[dict[str, Any]] = []
    sources: list[dict[str, Any]] = []
    seen: set[str] = set()
    chain_reports: list[dict[str, Any]] = []
    for chain in chains:
        chain_id = _integer(chain["chain_id"])
        target = int(chain.get("max_transactions", 20000))
        if target < 3:
            raise DataError("at least three transactions per chain are required")
        rpc = RpcClient(list(chain["endpoints"]), chain_id,
                        float(settings.get("timeout_seconds", 30)), int(settings.get("retries", 3)))
        selected: list[dict[str, Any]] = []
        skipped: list[dict[str, Any]] = []
        excluded_by_cap = 0
        probe: dict[str, Any] = {"status": "not_attempted"}
        block_summaries: list[dict[str, Any]] = []
        try:
            finalized = rpc.call("eth_getBlockByNumber", ["finalized", False])
            finalized_number = _integer(finalized["number"])
            start = chain.get("start_block", settings.get("start_block"))
            start = finalized_number if start is None else _integer(start)
            if start > finalized_number:
                raise DataError("start_block is newer than finalized anchor")
            previous: dict[str, Any] | None = None
            for offset in range(int(settings.get("max_blocks", 1000))):
                number = start - offset
                if number < 0:
                    break
                block = rpc.call("eth_getBlockByNumber", [hex(number), True])
                if _integer(block["number"]) != number:
                    raise DataError("RPC block number mismatch")
                if offset == 0 and number == finalized_number and block["hash"].lower() != finalized["hash"].lower():
                    raise DataError("finalized anchor changed during acquisition")
                if previous and previous["parentHash"].lower() != block["hash"].lower():
                    raise DataError("RPC blocks do not form a contiguous parent-linked chain")
                previous = block
                sources.append({"chain": chain["name"], "chain_id": chain_id,
                                "endpoint": rpc.last_endpoint, "block": block})
                added = 0
                transactions = block["transactions"]
                for tx in reversed(transactions):
                    if len(selected) >= target:
                        excluded_by_cap += 1
                        continue
                    try:
                        if _integer(tx["blockNumber"]) != number or tx["blockHash"].lower() != block["hash"].lower():
                            raise DataError("transaction block metadata disagrees with containing block")
                        raw = reconstruct_raw(tx)
                        details = validate_transaction(tx, raw, chain_id)
                        if details["tx_hash"] in seen:
                            raise DataError("duplicate transaction hash across the corpus")
                        if probe["status"] == "not_attempted":
                            try:
                                native = rpc.call("eth_getRawTransactionByHash", [tx["hash"]])
                                if _bytes(native) != raw:
                                    raise DataError("native raw RPC disagrees with canonical reconstruction")
                                probe = {"status": "matched", "tx_hash": tx["hash"], "endpoint": rpc.last_endpoint}
                            except RpcError as exc:
                                probe = {"status": "unavailable", "reason": str(exc), "tx_hash": tx["hash"]}
                        row = {**details, "raw_hex": "0x" + raw.hex(), "chain": chain["name"],
                               "block_number": number, "block_hash": block["hash"].lower(),
                               "transaction_index": _integer(tx["transactionIndex"]),
                               "source_method": "reconstructed_rlp", "split": ""}
                        selected.append(row)
                        seen.add(details["tx_hash"])
                        added += 1
                    except (DataError, KeyError, TypeError, ValueError) as exc:
                        skipped.append({"tx_hash": tx.get("hash"), "block_number": number,
                                        "tx_type": tx.get("type"), "reason": str(exc)})
                block_summaries.append({"number": number, "hash": block["hash"].lower(),
                                        "rpc_transactions": len(transactions), "selected": added})
                print(f"{chain['name']}: block {number}, {len(selected)}/{target} signed transactions, "
                      f"{len(skipped)} excluded", file=sys.stderr, flush=True)
                if len(selected) >= target:
                    break
            if len(selected) != target:
                raise DataError(f"{chain['name']}: collected {len(selected)}/{target} signed transactions "
                                f"within max_blocks; skipped {len(skipped)}")
            rows.extend(selected)
            chain_reports.append({"name": chain["name"], "chain_id": chain_id, "requested": target,
                "selected": len(selected), "finalized_anchor": {"number": finalized_number,
                    "hash": finalized["hash"].lower()}, "start_block": start,
                "oldest_block": min(row["block_number"] for row in selected),
                "blocks": block_summaries, "skipped": skipped, "excluded_by_cap": excluded_by_cap,
                "raw_rpc_probe": probe, "rpc_events": rpc.events,
                "transaction_types": dict(Counter(str(row["tx_type"]) for row in selected))})
        finally:
            rpc.close()
    rows.sort(key=lambda row: (row["chain_id"], row["block_number"], row["transaction_index"]))
    manifest = {"format_version": 1, "created_at": datetime.now(timezone.utc).isoformat(),
                "config": settings, "chains": chain_reports, "signature_verified": len(rows),
                "hash_verified": len(rows), "source_methods": {"reconstructed_rlp": len(rows)},
                "limitations": ["RPC provenance is not an independently verified consensus or Merkle proof",
                    "only signed chain-bound user transaction envelopes; unsigned system deposits excluded",
                    "blob sidecars excluded; envelope retains blob versioned hashes",
                    "recent finalized chronological sample; no claim of population representativeness"]}
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=f".{output.name}-", dir=output.parent) as temporary:
        stage = Path(temporary) / "corpus"
        _export(stage, rows, sources, manifest, float(settings.get("validation_fraction", .1)),
                float(settings.get("test_fraction", .1)))
        if output.exists():
            output.rmdir()
        stage.rename(output)
    return {"output_dir": str(output), "rows": len(rows), "splits": manifest["splits"],
            "chains": [{key: report[key] for key in ("name", "selected", "oldest_block", "transaction_types")}
                       for report in chain_reports], "manifest": str(output / "manifest.json")}


def load_rows(path: str | Path) -> list[dict[str, Any]]:
    """Load canonical JSONL rows or an exported Hugging Face dataset directory."""
    path = Path(path)
    if path.is_dir() and (path / "transactions.jsonl").exists():
        path = path / "transactions.jsonl"
    if path.is_file():
        return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
    dataset = load_from_disk(str(path))
    if isinstance(dataset, DatasetDict):
        return [dict(row) for partition in dataset.values() for row in partition]
    return [dict(row) for row in dataset]


def validate_dataset(config: DictConfig | dict[str, Any]) -> dict[str, Any]:
    """Recheck every envelope, source snapshot, split, local export and checksum."""
    _enable_fast_recovery()
    output = Path(_config(config).get("output_dir", "data/transactions"))
    manifest = json.loads((output / "manifest.json").read_text())
    for relative, expected in manifest["sha256"].items():
        path = output / relative
        if not path.is_relative_to(output) or not path.is_file() or _checksum(path) != expected:
            raise DataError(f"checksum mismatch or missing file: {relative}")
    rows = load_rows(output)
    if len(rows) != manifest["rows"]:
        raise DataError("manifest row count mismatch")
    source_lookup = {}
    source_chain_blocks: dict[int, list[dict[str, Any]]] = {}
    for source in load_rows(output / "source_blocks.jsonl"):
        block = source["block"]
        source_chain_blocks.setdefault(source["chain_id"], []).append(block)
        for index, tx in enumerate(block["transactions"]):
            if (_integer(tx["blockNumber"]) != _integer(block["number"])
                    or tx["blockHash"].lower() != block["hash"].lower()
                    or _integer(tx["transactionIndex"]) != index):
                raise DataError("source transaction metadata differs from containing block")
            key = (source["chain_id"], tx["hash"].lower())
            if key in source_lookup:
                raise DataError("duplicate transaction in source snapshots")
            source_lookup[key] = tx
    seen: set[str] = set()
    block_splits: dict[tuple[int, int], str] = {}
    for row in rows:
        if row["tx_hash"] in seen:
            raise DataError("duplicate transaction hash")
        seen.add(row["tx_hash"])
        raw = _bytes(row["raw_hex"])
        tx = source_lookup.get((row["chain_id"], row["tx_hash"]))
        if tx is None:
            raise DataError("row has no RPC provenance")
        details = validate_transaction(tx, raw, row["chain_id"])
        for key, expected in details.items():
            if row[key] != expected:
                raise DataError(f"stored {key} differs from signed envelope")
        if row["block_number"] != _integer(tx["blockNumber"]) or row["block_hash"] != tx["blockHash"].lower():
            raise DataError("stored block metadata differs from RPC provenance")
        if row["transaction_index"] != _integer(tx["transactionIndex"]):
            raise DataError("stored transaction index differs from RPC provenance")
        key = (row["chain_id"], row["block_number"])
        if key in block_splits and block_splits[key] != row["split"]:
            raise DataError("block leaks between splits")
        block_splits[key] = row["split"]
    for chain in manifest["chains"]:
        blocks = sorted(source_chain_blocks.get(chain["chain_id"], []),
                        key=lambda block: _integer(block["number"]))
        if not blocks or len(blocks) != len(chain["blocks"]):
            raise DataError("source block count differs from manifest")
        for older, newer in zip(blocks, blocks[1:]):
            if (_integer(newer["number"]) != _integer(older["number"]) + 1
                    or newer["parentHash"].lower() != older["hash"].lower()):
                raise DataError("source blocks do not form a contiguous parent-linked chain")
        if _integer(blocks[-1]["number"]) != chain["start_block"]:
            raise DataError("source newest block differs from acquisition start")
        if (chain["start_block"] == chain["finalized_anchor"]["number"]
                and blocks[-1]["hash"].lower() != chain["finalized_anchor"]["hash"]):
            raise DataError("source newest block differs from finalized anchor")
        selected = [row for row in rows if row["chain_id"] == chain["chain_id"]]
        if len(selected) != chain["requested"] or len(selected) != chain["selected"]:
            raise DataError("per-chain exact target count mismatch")
        partitions = [[row["block_number"] for row in selected if row["split"] == name]
                      for name in ("train", "validation", "test")]
        if not all(partitions) or not (max(partitions[0]) < min(partitions[1])
                                      and max(partitions[1]) < min(partitions[2])):
            raise DataError("splits are not strictly chronological per chain")
        if max(row["block_number"] for row in selected) > chain["finalized_anchor"]["number"]:
            raise DataError("rows newer than finalized anchor")
    dataset = load_from_disk(str(output / "dataset"))
    expected_splits = Counter(row["split"] for row in rows)
    if dict(expected_splits) != manifest["splits"]:
        raise DataError("manifest split counts mismatch")
    for name in ("train", "validation", "test"):
        expected = [row for row in rows if row["split"] == name]
        if [dict(row) for row in dataset[name]] != expected:
            raise DataError(f"HF {name} export differs from canonical JSONL")
        parquet = pq.read_table(output / "parquet" / f"{name}.parquet").to_pylist()
        if parquet != expected:
            raise DataError(f"Parquet {name} export differs from canonical JSONL")
    return {"valid": True, "rows": len(rows), "hashes_verified": len(rows),
            "signatures_verified": len(rows), "source_transactions_verified": len(rows),
            "splits": dict(expected_splits), "files_verified": len(manifest["sha256"])}