From aee2bf4622c4ad515d56da9baaca26e92e6d03c3 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Thu, 29 Oct 2026 08:13:53 +0300 Subject: [PATCH 01/92] feat(ml): data pipeline for phishing-transaction classification Experimental, optional 'ml' extra (scikit-learn, LightGBM, pandas, pandera, openpyxl); core install unchanged. - sources: three public label sets pinned to commits with SHA-256 (PTXPhish NDSS'25, Poison-Hunter CCS'24, Forta). The two without a license are fetched locally on request, never redistributed. - labels: PTXPhish's wide sheet parsed into one pandera-validated row per transaction; address lists parsed for the data card only. - collect: deterministic stratified sample; budgeted, resumable chain collection (tx, receipt, sender nonce and target code at the previous block) with a hard cap on total RPC attempts, recorded after every transaction. - features: point-in-time transaction features; block number and raw identifiers never used as features. - dataset/splits: validated table with input-hash manifest; study window where both classes occur; time-ordered splits; per-account purge with hubs from training rows only. - train/report: trivial, rule and learned baselines (LR, RF, LightGBM), selection on validation log loss, test scored once, bootstrap CIs, promotion gate, run ledger, hash-pinned model card, ML_EVALUATION.md. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 15 +- src/cryptoguard/cli.py | 8 + src/cryptoguard/ml/__init__.py | 24 ++ src/cryptoguard/ml/cli.py | 156 ++++++++++++ src/cryptoguard/ml/collect.py | 228 ++++++++++++++++++ src/cryptoguard/ml/dataset.py | 174 ++++++++++++++ src/cryptoguard/ml/features.py | 205 ++++++++++++++++ src/cryptoguard/ml/labels.py | 142 +++++++++++ src/cryptoguard/ml/report.py | 174 ++++++++++++++ src/cryptoguard/ml/sources.py | 177 ++++++++++++++ src/cryptoguard/ml/splits.py | 97 ++++++++ src/cryptoguard/ml/train.py | 428 +++++++++++++++++++++++++++++++++ uv.lock | 312 +++++++++++++++++++++++- 13 files changed, 2136 insertions(+), 4 deletions(-) create mode 100644 src/cryptoguard/ml/__init__.py create mode 100644 src/cryptoguard/ml/cli.py create mode 100644 src/cryptoguard/ml/collect.py create mode 100644 src/cryptoguard/ml/dataset.py create mode 100644 src/cryptoguard/ml/features.py create mode 100644 src/cryptoguard/ml/labels.py create mode 100644 src/cryptoguard/ml/report.py create mode 100644 src/cryptoguard/ml/sources.py create mode 100644 src/cryptoguard/ml/splits.py create mode 100644 src/cryptoguard/ml/train.py diff --git a/pyproject.toml b/pyproject.toml index 7a5b0cd..1120b15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,13 @@ analytics = [ "numpy>=2.5.4", "scipy>=1.18.1", ] +ml = [ + "lightgbm>=4.7.0", + "openpyxl>=3.1.5", + "pandas>=3.1.0", + "pandera>=0.35.0", + "scikit-learn>=1.9.1", +] [dependency-groups] dev = [ @@ -33,6 +40,12 @@ dev = [ "numpy>=2.5.4", "scipy>=1.18.1", "scipy-stubs>=1.18.1.1", + "scikit-learn>=1.9.1", + "lightgbm>=4.7.0", + "pandas>=3.1.0", + "pandera>=0.35.0", + "openpyxl>=3.1.5", + "pandas-stubs>=3.0.5.260914", ] [build-system] @@ -84,5 +97,5 @@ plugins = ["pydantic.mypy"] mypy_path = "src" [[tool.mypy.overrides]] -module = ["Crypto.*"] +module = ["Crypto.*", "sklearn.*", "joblib.*", "lightgbm.*"] ignore_missing_imports = true diff --git a/src/cryptoguard/cli.py b/src/cryptoguard/cli.py index 18179c8..aa296f3 100644 --- a/src/cryptoguard/cli.py +++ b/src/cryptoguard/cli.py @@ -825,6 +825,10 @@ def main(argv: Sequence[str] | None = None) -> int: p_purge.add_argument("--address", help="only this address") p_purge.add_argument("--yes", action="store_true", help="confirm deletion") + from cryptoguard.ml.cli import add_parser as add_ml_parser + + add_ml_parser(sub) + args = parser.parse_args(argv) try: @@ -922,6 +926,10 @@ def main(argv: Sequence[str] | None = None) -> int: return _replay_command(args, settings) if args.command == "campaigns": return _campaign_command(args, settings) + if args.command == "ml": + from cryptoguard.ml.cli import run as run_ml + + return run_ml(args) if args.command == "ack": from cryptoguard.database.repository import open_repository diff --git a/src/cryptoguard/ml/__init__.py b/src/cryptoguard/ml/__init__.py new file mode 100644 index 0000000..bb76697 --- /dev/null +++ b/src/cryptoguard/ml/__init__.py @@ -0,0 +1,24 @@ +"""Experimental machine-learning subsystem (needs the ``ml`` extra). + +Phishing-transaction classification trained on independently labelled public data +(PTXPhish, NDSS 2025), with point-in-time features read from the chain. Shadow mode only: +scores are context for a human reviewer and never create, change or resolve findings. +See ML.md for data, method, results and limitations. + +Heavy libraries (pandas, scikit-learn, LightGBM) are imported inside the functions that +need them, never at module import. +""" + +from __future__ import annotations + +ML_VERSION = "cg-ml/0.1.0" +FEATURE_SET_VERSION = "ptx-features/1" + + +def ml_available() -> bool: + import importlib.util + + return all( + importlib.util.find_spec(name) is not None + for name in ("pandas", "pandera", "sklearn", "lightgbm", "openpyxl") + ) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py new file mode 100644 index 0000000..fc5c13e --- /dev/null +++ b/src/cryptoguard/ml/cli.py @@ -0,0 +1,156 @@ +"""``cryptoguard ml ...`` commands (experimental; need the ``ml`` extra).""" + +from __future__ import annotations + +import argparse +import asyncio +from pathlib import Path + +from cryptoguard.ml.sources import DEFAULT_DATA_DIR + +ML_DIR = Path("data") / "ml" +SAMPLE = ML_DIR / "sample.csv" +CHAIN = ML_DIR / "chain" / "ptxphish.jsonl" +TOTAL_REQUEST_CAP = 12_000 # approved budget for the whole collection, over all runs + + +def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: + p = sub.add_parser("ml", help="experimental ML pipeline (needs the ml extra)") + ml = p.add_subparsers(dest="ml_command", required=True) + f = ml.add_parser("fetch-sources", help="download pinned label sources (hash-verified)") + f.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + s = ml.add_parser("sample", help="draw the deterministic collection sample") + s.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + s.add_argument("--out", type=Path, default=SAMPLE) + c = ml.add_parser("collect", help="budgeted, resumable chain data collection") + c.add_argument("--rpc-url", required=True) + c.add_argument("--sample", type=Path, default=SAMPLE) + c.add_argument("--out", type=Path, default=CHAIN) + c.add_argument("--max-requests", type=int, default=TOTAL_REQUEST_CAP) + c.add_argument("--limit", type=int, default=None, help="collect at most this many txs") + b = ml.add_parser("build", help="validated feature table, splits and manifest") + b.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + t = ml.add_parser("train", help="train, select on validation, test once, record the run") + t.add_argument("--report", type=Path, default=Path("ML_EVALUATION.md")) + + +def run(args: argparse.Namespace) -> int: + from cryptoguard.ml import ml_available + + if not ml_available(): + print("error [ml_unavailable]: install the ml extra (uv sync --extra ml)") + return 1 + if args.ml_command == "fetch-sources": + from cryptoguard.ml.sources import SOURCES, fetch_sources + + for name, path, status in fetch_sources(args.data_dir): + license_ = SOURCES[name].license or "no license (local use only)" + print(f"{status:10} {name}/{path} [{license_}]") + return 0 + if args.ml_command == "sample": + from cryptoguard.ml.collect import draw_sample + from cryptoguard.ml.labels import load_ptxphish + + sample = draw_sample(load_ptxphish(args.data_dir)) + args.out.parent.mkdir(parents=True, exist_ok=True) + sample.to_csv(args.out, index=False, lineterminator="\n") + print(sample.groupby(["family", "subtype"]).size().to_string()) + print(f"Wrote {len(sample)} rows to {args.out}") + return 0 + if args.ml_command == "collect": + import pandas as pd + + from cryptoguard.ml.collect import collect, requests_used + + sample = pd.read_csv(args.sample, dtype={"tx_hash": str}) + if args.limit is not None: + sample = sample.head(args.limit) + remaining = min(args.max_requests, TOTAL_REQUEST_CAP) - requests_used(args.out) + if remaining <= 0: + print(f"Request budget exhausted ({requests_used(args.out)} used).") + return 1 + stats = asyncio.run(collect(sample, args.out, rpc_url=args.rpc_url, max_requests=remaining)) + # The collector records its attempts in the ledger itself, after every transaction. + print({**stats, "requests_total": requests_used(args.out), "cap": TOTAL_REQUEST_CAP}) + return 0 + if args.ml_command == "build": + return _build(args) + if args.ml_command == "train": + return _train(args) + raise AssertionError(args.ml_command) + + +TABLE = ML_DIR / "dataset.csv" +SPLITS = ML_DIR / "splits.csv" +RUNS = ML_DIR / "runs" + + +def _build(args: argparse.Namespace) -> int: + import json + + import pandas as pd + + from cryptoguard.ml.collect import load_collected, requests_used + from cryptoguard.ml.dataset import build_table, write_table + from cryptoguard.ml.labels import load_ptxphish + from cryptoguard.ml.sources import SOURCES, local_path + from cryptoguard.ml.splits import make_splits + + records = load_collected(CHAIN) + table, facts = build_table(load_ptxphish(args.data_dir), records) + split, summary = make_splits(table, records) + facts["sample_rows"] = len(pd.read_csv(SAMPLE)) + facts["rpc_requests_used"] = requests_used(CHAIN) + src = SOURCES["ptxphish"] + manifest = write_table( + table, + {**facts, "splits": summary}, + TABLE, + { + "labels": local_path(args.data_dir, src, src.files[0]), + "sample": SAMPLE, + "chain": CHAIN, + }, + ) + table.assign(split=split)[["tx_hash", "split"]].to_csv(SPLITS, index=False, lineterminator="\n") + print( + json.dumps({k: manifest[k] for k in ("rows", "block_range", "groups", "splits")}, indent=1) + ) + return 0 + + +def _train(args: argparse.Namespace) -> int: + import hashlib + import json + from datetime import UTC, datetime + + import pandas as pd + + from cryptoguard.ml.report import render_report + from cryptoguard.ml.train import ledger_entry, promotion_gate, run_training, save_run + + table = pd.read_csv(TABLE, dtype={"tx_hash": str, "group": str}) + split = pd.read_csv(SPLITS, dtype=str).set_index("tx_hash").loc[table["tx_hash"], "split"] + split.index = table.index + manifest_path = TABLE.with_suffix(".manifest.json") + manifest_sha = hashlib.sha256(manifest_path.read_bytes()).hexdigest() + out = run_training(table, split) + gate = promotion_gate(out["results"], out["selected"]) + run_id = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + manifest_sha[:8] + config = { + "table_sha256": json.loads(manifest_path.read_text())["table"]["sha256"], + "splits": json.loads(manifest_path.read_text())["splits"], + } + entry = ledger_entry(run_id, config, out, gate, manifest_sha) + run_dir = save_run(RUNS / run_id, entry, out) + with (RUNS / "ledger.jsonl").open("a", encoding="utf-8") as fh: + fh.write(json.dumps({k: entry[k] for k in entry if k != "results"}, default=str) + "\n") + report = render_report(entry, out, json.loads(manifest_path.read_text())) + args.report.write_text(report, encoding="utf-8") + sel = entry["selected"] + print( + f"run {run_id}: selected {sel['name']} ({sel['feature_set']}), " + f"test AP {entry['test']['average_precision']:.3f}, gate {gate['validated_for_shadow']}, " + f"{out['seconds']} s -> {run_dir}; wrote {args.report}" + ) + return 0 diff --git a/src/cryptoguard/ml/collect.py b/src/cryptoguard/ml/collect.py new file mode 100644 index 0000000..d8b2388 --- /dev/null +++ b/src/cryptoguard/ml/collect.py @@ -0,0 +1,228 @@ +"""Budgeted, resumable collection of point-in-time chain data for labelled transactions. + +For each sampled transaction the collector reads, from one RPC endpoint: + +1. the transaction (``eth_getTransactionByHash``), +2. its receipt (``eth_getTransactionReceipt``: status, gas used, logs), +3. the sender's nonce at the block *before* the transaction's block + (``eth_getTransactionCount``), and +4. the target's code at that same earlier block (``eth_getCode``; skipped for contract + creations). + +Nothing after the transaction's own block is read, so features describe what was knowable +when the transaction executed. Labels are never sent anywhere: the sample order is fixed by +a seed before collection starts. Every HTTP attempt counts against ``max_requests`` +(retries included); the run stops cleanly before exceeding it and resumes from its JSONL +checkpoint, skipping transactions already collected. +""" + +from __future__ import annotations + +import asyncio +import json +import random +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy +from cryptoguard.core.errors import RpcError + +if TYPE_CHECKING: + import pandas as pd + +REQUESTS_PER_TX = 4 +SAMPLE_SEED = 20261029 + + +@dataclass(frozen=True) +class SamplePlan: + phishing: int = 1_350 # all address-poisoning rows, the rest stratified by subtype + benign: int = 1_350 # stratified by subtype + seed: int = SAMPLE_SEED + + +DEFAULT_PLAN = SamplePlan() + + +def draw_sample(labels: pd.DataFrame, plan: SamplePlan = DEFAULT_PLAN) -> pd.DataFrame: + """Deterministic stratified sample, returned in collection order (shuffled, so a + partial collection stays stratified).""" + import pandas as pd + + rng = random.Random(plan.seed) # noqa: S311 - reproducible sampling, not cryptography + chosen: list[pd.DataFrame] = [] + + def stratified(frame: pd.DataFrame, n: int) -> pd.DataFrame: + counts = frame["subtype"].value_counts().sort_index() + quotas = (counts / counts.sum() * n).round().astype(int).clip(upper=counts) + parts = [] + for subtype, quota in quotas.items(): + rows = frame[frame["subtype"] == subtype].sort_values("tx_hash") + idx = sorted(rng.sample(range(len(rows)), int(quota))) + parts.append(rows.iloc[idx]) + return pd.concat(parts) + + poisoning = labels[labels["family"] == "address_poisoning"] + chosen.append(poisoning) + other = labels[(labels["label"] == 1) & (labels["family"] != "address_poisoning")] + chosen.append(stratified(other, max(plan.phishing - len(poisoning), 0))) + chosen.append(stratified(labels[labels["label"] == 0], plan.benign)) + sample = pd.concat(chosen).sort_values("tx_hash").reset_index(drop=True) + order = list(range(len(sample))) + rng.shuffle(order) + sample = sample.iloc[order].reset_index(drop=True) + sample.insert(0, "order", range(len(sample))) + return sample + + +def _done(path: Path) -> set[str]: + if not path.exists(): + return set() + done = set() + for line in path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + row = json.loads(line) + if row["status"] in ("ok", "not_found"): + done.add(row["tx_hash"]) + return done + + +async def _collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: + tx = await client.call("eth_getTransactionByHash", [tx_hash]) + if tx is None or tx.get("blockNumber") is None: + return {"tx_hash": tx_hash, "status": "not_found"} + receipt = await client.call("eth_getTransactionReceipt", [tx_hash]) + before = hex(int(tx["blockNumber"], 16) - 1) + nonce = await client.call("eth_getTransactionCount", [tx["from"], before]) + code = "0x" + if tx.get("to"): + code = await client.call("eth_getCode", [tx["to"], before]) + logs = receipt.get("logs", []) if receipt else [] + return { + "tx_hash": tx_hash, + "status": "ok", + "tx": { + k: tx.get(k) + for k in ( + "blockNumber", + "from", + "to", + "value", + "gas", + "gasPrice", + "maxFeePerGas", + "maxPriorityFeePerGas", + "nonce", + "type", + "input", + ) + }, + "receipt": None + if receipt is None + else { + "status": receipt.get("status"), + "gasUsed": receipt.get("gasUsed"), + "contractAddress": receipt.get("contractAddress"), + "logs": [ + {"address": log["address"], "topics": log["topics"], "data": log["data"]} + for log in logs + ], + }, + "from_nonce_before": nonce, + "to_code_before": {"size": (len(code) - 2) // 2, "prefix": code[:8]}, + } + + +async def collect( + sample: pd.DataFrame, + out: Path, + *, + rpc_url: str, + max_requests: int, + concurrency: int = 3, + client: JsonRpcClient | None = None, +) -> dict[str, int]: + """Collect chain data for the sample in order until done or the budget is spent.""" + out.parent.mkdir(parents=True, exist_ok=True) + done = _done(out) + todo = [h for h in sample["tx_hash"] if h not in done] + retry = RetryPolicy(max_retries=4) + rpc = client or JsonRpcClient(rpc_url, timeout=20, retry=retry, max_concurrency=concurrency) + # Worst case still in flight when a worker checks: every worker's transaction with every + # call retried to the limit. Stopping this far below the cap makes it a hard cap. + margin = concurrency * REQUESTS_PER_TX * (retry.max_retries + 1) + stats = {"already": len(done), "ok": 0, "not_found": 0, "error": 0, "skipped_budget": 0} + lock = asyncio.Lock() + queue: asyncio.Queue[str] = asyncio.Queue() + for h in todo: + queue.put_nowait(h) + recorded = 0 + + def flush_budget() -> None: + # Written after every transaction, so an interrupted run never loses its count. + nonlocal recorded + delta = rpc.metrics.requests - recorded + if delta: + record_requests(out, delta) + recorded += delta + + async def worker() -> None: + while not queue.empty(): + tx_hash = queue.get_nowait() + if rpc.metrics.requests + margin > max_requests: + stats["skipped_budget"] += 1 + continue + try: + row = await _collect_one(rpc, tx_hash) + except RpcError as exc: + row = {"tx_hash": tx_hash, "status": "error", "error": exc.code} + async with lock: + stats[row["status"]] += 1 + with out.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(row, separators=(",", ":")) + "\n") + flush_budget() + + try: + await asyncio.gather(*(worker() for _ in range(concurrency))) + finally: + flush_budget() + stats["requests"] = rpc.metrics.requests + stats["retries"] = rpc.metrics.retries + if client is None: + await rpc.aclose() + return stats + + +def budget_path(out: Path) -> Path: + return out.with_name(out.name + ".budget.json") + + +def requests_used(out: Path) -> int: + """Cumulative RPC attempts over every run that wrote ``out`` (the cap is a total).""" + path = budget_path(out) + return int(json.loads(path.read_text(encoding="utf-8"))["requests"]) if path.exists() else 0 + + +def record_requests(out: Path, requests: int, note: str | None = None) -> int: + path = budget_path(out) + state: dict[str, Any] = ( + json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"requests": 0} + ) + state["requests"] = int(state["requests"]) + requests + if note: + notes: list[str] = state.setdefault("notes", []) + notes.append(note) + path.write_text(json.dumps(state, indent=1), encoding="utf-8") + return int(state["requests"]) + + +def load_collected(path: Path) -> dict[str, dict[str, Any]]: + """Latest successful record per transaction.""" + rows: dict[str, dict[str, Any]] = {} + for line in path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + row = json.loads(line) + if row["status"] in ("ok", "not_found"): + rows[row["tx_hash"]] = row + return rows diff --git a/src/cryptoguard/ml/dataset.py b/src/cryptoguard/ml/dataset.py new file mode 100644 index 0000000..d6df417 --- /dev/null +++ b/src/cryptoguard/ml/dataset.py @@ -0,0 +1,174 @@ +"""Build the validated modelling table and its manifest from labels plus collected chain data. + +Rows are grouped by the accounts they tie together (``features.parties``), joined by +union-find. Accounts used by many distinct senders (tokens, routers, marketplaces) are +public infrastructure: they do not join rows, or every row would collapse into one group. +The rule is label-free; ``group_report`` states how much it cuts. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from cryptoguard.ml import FEATURE_SET_VERSION +from cryptoguard.ml.features import FEATURES, extract, parties + +if TYPE_CHECKING: + import pandas as pd + +# Public infrastructure (label-free): an account used by at least HUB_MIN_SENDERS distinct +# senders (routers, Permit2), or a log-emitting contract (token, marketplace) touched by +# at least EMITTER_MIN_SENDERS distinct senders. Phishing contracts that victims call +# directly emit no logs and stay linking accounts unless they reach HUB_MIN_SENDERS. +HUB_MIN_SENDERS = 10 +EMITTER_MIN_SENDERS = 2 + + +def table_schema() -> Any: + import pandera.pandas as pa + + finite = pa.Check(lambda s: s.notna() & (s.abs() < 1e12), element_wise=False) + return pa.DataFrameSchema( + { + "tx_hash": pa.Column(str, pa.Check.str_matches(r"^0x[0-9a-f]{64}$"), unique=True), + "block_number": pa.Column(int, pa.Check.gt(0)), + "label": pa.Column(int, pa.Check.isin([0, 1])), + "family": pa.Column(str), + "subtype": pa.Column(str), + "group": pa.Column(str), + **{name: pa.Column(float, finite) for name in FEATURES}, + }, + strict=True, + ordered=True, + ) + + +class _UnionFind: + def __init__(self) -> None: + self.parent: dict[str, str] = {} + + def find(self, x: str) -> str: + self.parent.setdefault(x, x) + while self.parent[x] != x: + self.parent[x] = self.parent[self.parent[x]] + x = self.parent[x] + return x + + def union(self, a: str, b: str) -> None: + ra, rb = self.find(a), self.find(b) + if ra != rb: + self.parent[max(ra, rb)] = min(ra, rb) # deterministic representative + + +def hubs(records: dict[str, dict[str, Any]]) -> set[str]: + senders: dict[str, set[str]] = defaultdict(set) + emitter_senders: dict[str, set[str]] = defaultdict(set) + for rec in records.values(): + sender = (rec["tx"].get("from") or "").lower() + for account in parties(rec): + senders[account].add(sender) + for log in (rec.get("receipt") or {}).get("logs") or []: + emitter_senders[log["address"].lower()].add(sender) + return {a for a, s in senders.items() if len(s) >= HUB_MIN_SENDERS} | { + a for a, s in emitter_senders.items() if len(s) >= EMITTER_MIN_SENDERS + } + + +def assign_groups(records: dict[str, dict[str, Any]], hub_set: set[str]) -> dict[str, str]: + uf = _UnionFind() + for tx_hash in sorted(records): + uf.find(tx_hash) + for account in sorted(parties(records[tx_hash]) - hub_set): + uf.union(tx_hash, "acct:" + account) + return {h: "g" + hashlib.sha256(uf.find(h).encode()).hexdigest()[:12] for h in records} + + +def build_table( + labels: pd.DataFrame, records: dict[str, dict[str, Any]] +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Validated table (one row per collected, labelled transaction) and build facts.""" + import pandas as pd + + ok = {h: r for h, r in records.items() if r["status"] == "ok"} + hub_set = hubs(ok) + groups = assign_groups(ok, hub_set) + by_hash: dict[str, dict[str, Any]] = { + str(r["tx_hash"]): {str(k): v for k, v in r.items()} for r in labels.to_dict("records") + } + rows = [] + for tx_hash in sorted(ok): + if tx_hash not in by_hash: + continue + lab = by_hash[tx_hash] + rows.append( + { + "tx_hash": tx_hash, + "block_number": int(ok[tx_hash]["tx"]["blockNumber"], 16), + "label": int(lab["label"]), + "family": str(lab["family"]), + "subtype": str(lab["subtype"]), + "group": groups[tx_hash], + **extract(ok[tx_hash]), + } + ) + table = table_schema().validate(pd.DataFrame(rows)) + facts = { + "feature_set": FEATURE_SET_VERSION, + "rows": len(table), + "not_found": sum(r["status"] == "not_found" for r in records.values()), + "hub_accounts": len(hub_set), + "hub_rule": {"min_senders": HUB_MIN_SENDERS, "emitter_min_senders": EMITTER_MIN_SENDERS}, + } + return table, facts + + +def group_report(table: pd.DataFrame) -> dict[str, Any]: + """Diagnostics only (labels are read here, never when grouping).""" + g = table.groupby("group")["label"].agg(["size", "mean"]) + mixed = g[(g["mean"] > 0) & (g["mean"] < 1)] + return { + "groups": len(g), + "largest_group_rows": int(g["size"].max()), + "singleton_groups": int((g["size"] == 1).sum()), + "mixed_label_groups": len(mixed), + "rows_in_mixed_groups": int(mixed["size"].sum()), + "phishing_rows_sharing_a_group": int( + table[table["label"] == 1].groupby("group").size().loc[lambda s: s > 1].sum() + ), + } + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def write_table( + table: pd.DataFrame, facts: dict[str, Any], out: Path, inputs: dict[str, Path] +) -> dict[str, Any]: + """Write the table as CSV (stable formatting) plus a manifest of every input's hash.""" + out.parent.mkdir(parents=True, exist_ok=True) + data = table.to_csv(index=False, lineterminator="\n", float_format="%.10g").encode() + out.write_bytes(data) + manifest = { + **facts, + "table": {"path": out.as_posix(), "sha256": sha256_bytes(data)}, + "inputs": { + k: {"path": p.as_posix(), "sha256": sha256_bytes(p.read_bytes())} + for k, p in inputs.items() + }, + "label_counts": { + f"{r['family']}/{r['subtype']}": int(r["n"]) + for r in table.groupby(["family", "subtype"]) + .size() + .reset_index(name="n") + .to_dict("records") + }, + "block_range": [int(table["block_number"].min()), int(table["block_number"].max())], + "groups": group_report(table), + } + out.with_suffix(".manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8") + return manifest diff --git a/src/cryptoguard/ml/features.py b/src/cryptoguard/ml/features.py new file mode 100644 index 0000000..eab3ccb --- /dev/null +++ b/src/cryptoguard/ml/features.py @@ -0,0 +1,205 @@ +"""Point-in-time transaction features (pure Python: shared by training and shadow scoring). + +Inputs are one collected record (``collect.py``): the transaction, its receipt, the sender's +nonce and the target's code at the block *before* the transaction. Nothing later is used. + +Deliberately excluded: + +- ``block_number`` and timestamps: used to split data in time, never as features, so a model + cannot learn when the dataset authors happened to collect each class; +- raw addresses, hashes and selectors as identifiers: only coarse, generalizable properties + (code size, vanity zero runs, known function families, log structure) are encoded. +""" + +from __future__ import annotations + +import math +from itertools import combinations +from typing import Any + +TRANSFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" +APPROVAL = "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925" +APPROVAL_FOR_ALL = "0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31" +UNLIMITED = 2**255 # allowance at or above this is "effectively unlimited" + +# Function families by 4-byte selector (public, well-known signatures). +SELECTORS = { + "approve": {"0x095ea7b3", "0x39509351"}, # approve, increaseAllowance + "permit": {"0xd505accf", "0x8fcbaf0c", "0x2b67b570", "0x2a2d80d1"}, # EIP-2612, DAI, Permit2 + "set_approval_for_all": {"0xa22cb465"}, + "transfer": {"0xa9059cbb"}, + "transfer_from": {"0x23b872dd", "0x42842e0e", "0xb88d4fde", "0xf242432a"}, + "multicall": {"0xac9650d8", "0x5ae401dc", "0x1f0464d1", "0x252dba42", "0x82ad56cb"}, + "seaport": {"0xfb0f3ee1", "0x87201b41", "0xe7acab24", "0xb3a34c4c", "0xed98a574"}, + "upgrade": {"0x3659cfe6", "0x4f1ef286"}, # upgradeTo, upgradeToAndCall +} + +FEATURES: tuple[str, ...] = ( + "value_eth_log", + "is_zero_value", + "gas_limit_log", + "gas_price_gwei_log", + "is_typed_fee", + "input_bytes_log", + "input_is_bare_selector", + *(f"fn_{name}" for name in SELECTORS), + "fn_other", + "is_contract_creation", + "to_is_contract", + "to_code_size_log", + "to_is_delegated_eoa", + "to_vanity_zero_nibbles", + "from_vanity_zero_nibbles", + "sender_prior_txs_log", + "status_success", + "gas_used_ratio", + "n_logs", + "n_log_emitters", + "n_transfers", + "n_zero_value_transfers", + "n_transfers_not_from_sender", + "n_transfers_from_sender", + "n_transfers_to_sender", + "n_transfer_recipients", + "n_approvals", + "n_unlimited_approvals", + "n_approval_for_all_granted", + "max_party_affix_match", +) + + +def _int(value: str | None) -> int: + return int(value, 16) if value else 0 + + +def _log1p(x: float) -> float: + return math.log1p(max(x, 0.0)) + + +def _topic_address(topic: str) -> str: + return "0x" + topic[-40:].lower() + + +def _vanity_zeros(address: str | None) -> int: + """Leading plus trailing zero nibbles, e.g. 0x0000553f…0000 -> 8 (vanity-mined).""" + if not address: + return 0 + body = address.lower()[2:] + return (len(body) - len(body.lstrip("0"))) + (len(body) - len(body.rstrip("0"))) + + +def affix_match(a: str, b: str) -> int: + """Common leading plus trailing hex characters of two distinct addresses.""" + x, y = a.lower()[2:], b.lower()[2:] + if x == y: + return 0 + prefix = next((i for i, (p, q) in enumerate(zip(x, y, strict=True)) if p != q), len(x)) + suffix = next( + (i for i, (p, q) in enumerate(zip(reversed(x), reversed(y), strict=True)) if p != q), + len(x), + ) + return prefix + suffix + + +def extract(record: dict[str, Any]) -> dict[str, float]: + """Feature vector for one collected record (status "ok").""" + tx = record["tx"] + receipt = record.get("receipt") or {} + sender = (tx.get("from") or "").lower() + target = (tx.get("to") or "").lower() or None + data = tx.get("input") or "0x" + selector = data[:10].lower() if len(data) >= 10 else None + value = _int(tx.get("value")) + gas = _int(tx.get("gas")) + fee = _int(tx.get("maxFeePerGas")) or _int(tx.get("gasPrice")) + code = record.get("to_code_before") or {"size": 0, "prefix": "0x"} + + f: dict[str, float] = { + "value_eth_log": _log1p(value / 1e18), + "is_zero_value": float(value == 0), + "gas_limit_log": _log1p(gas), + "gas_price_gwei_log": _log1p(fee / 1e9), + "is_typed_fee": float(tx.get("maxFeePerGas") is not None), + "input_bytes_log": _log1p((len(data) - 2) / 2), + "input_is_bare_selector": float(len(data) == 10), + } + family = next((name for name, sels in SELECTORS.items() if selector in sels), None) + for name in SELECTORS: + f[f"fn_{name}"] = float(family == name) + f["fn_other"] = float(family is None and selector is not None) + + f["is_contract_creation"] = float(target is None) + f["to_is_contract"] = float(code["size"] > 0 and not code["prefix"].startswith("0xef0100")) + f["to_code_size_log"] = _log1p(code["size"]) + f["to_is_delegated_eoa"] = float(code["prefix"].startswith("0xef0100")) + f["to_vanity_zero_nibbles"] = float(_vanity_zeros(target)) + f["from_vanity_zero_nibbles"] = float(_vanity_zeros(sender)) + f["sender_prior_txs_log"] = _log1p(_int(record.get("from_nonce_before"))) + + f["status_success"] = float(_int(receipt.get("status")) == 1) + f["gas_used_ratio"] = _int(receipt.get("gasUsed")) / gas if gas else 0.0 + logs = receipt.get("logs") or [] + f["n_logs"] = float(len(logs)) + f["n_log_emitters"] = float(len({log["address"].lower() for log in logs})) + + transfers = [lg for lg in logs if lg["topics"] and lg["topics"][0].lower() == TRANSFER] + parties: set[str] = {sender} | ({target} if target else set()) + recipients: set[str] = set() + zero = not_sender = from_sender = to_sender = 0 + for log in transfers: + if len(log["topics"]) < 3: + continue + src, dst = _topic_address(log["topics"][1]), _topic_address(log["topics"][2]) + parties |= {src, dst} + recipients.add(dst) + amount = _int(log["data"]) if len(log["topics"]) == 3 and log["data"] != "0x" else None + zero += amount == 0 + not_sender += src != sender + from_sender += src == sender + to_sender += dst == sender + f["n_transfers"] = float(len(transfers)) + f["n_zero_value_transfers"] = float(zero) + f["n_transfers_not_from_sender"] = float(not_sender) + f["n_transfers_from_sender"] = float(from_sender) + f["n_transfers_to_sender"] = float(to_sender) + f["n_transfer_recipients"] = float(len(recipients)) + + approvals = unlimited = for_all = 0 + for log in logs: + topic0 = log["topics"][0].lower() if log["topics"] else "" + if topic0 == APPROVAL: + approvals += 1 + if len(log["topics"]) == 3 and log["data"] != "0x" and _int(log["data"]) >= UNLIMITED: + unlimited += 1 + if len(log["topics"]) >= 3: + parties.add(_topic_address(log["topics"][2])) + elif topic0 == APPROVAL_FOR_ALL: + for_all += _int(log["data"]) == 1 + if len(log["topics"]) >= 3: + parties.add(_topic_address(log["topics"][2])) + f["n_approvals"] = float(approvals) + f["n_unlimited_approvals"] = float(unlimited) + f["n_approval_for_all_granted"] = float(for_all) + # Lookalike pairs among the parties of one transaction (bounded: logs can be long). + pool = sorted(p for p in parties if p and p != "0x" + "0" * 40)[:40] + f["max_party_affix_match"] = float( + max((affix_match(a, b) for a, b in combinations(pool, 2)), default=0) + ) + assert tuple(f) == FEATURES, "feature order drifted" + return f + + +def parties(record: dict[str, Any]) -> set[str]: + """Accounts a transaction ties together: sender, target, approved spenders and + operators, transfer recipients. Used only to group rows for leakage-safe splits (an + attacker's or a user's repeated addresses must not straddle train and test).""" + tx = record["tx"] + sender = (tx.get("from") or "").lower() + out = {sender, (tx.get("to") or "").lower()} + for log in (record.get("receipt") or {}).get("logs") or []: + topics = log["topics"] + if not topics or len(topics) < 3: + continue + if topics[0].lower() in (APPROVAL, APPROVAL_FOR_ALL) or topics[0].lower() == TRANSFER: + out.add(_topic_address(topics[2])) + return {a for a in out if a and a != "0x" + "0" * 40} diff --git a/src/cryptoguard/ml/labels.py b/src/cryptoguard/ml/labels.py new file mode 100644 index 0000000..f91af47 --- /dev/null +++ b/src/cryptoguard/ml/labels.py @@ -0,0 +1,142 @@ +"""Parse the external label sources into validated long-format tables. + +PTXPhish (the training labels) is a wide spreadsheet: one column of transaction hashes per +attack subtype plus two benign columns ("KOL" and "Developer" transactions), with a +"Source" column next to some subtypes. It contains no addresses, values or timestamps: +every feature must come from the chain (``collect.py``). + +Poison-Hunter and Forta give address-level labels only. They are parsed for the data card +(overlaps, duplicates) and never used as training labels: Poison-Hunter's benign class is +1,154 *popular* addresses (separable from phishing addresses by popularity alone), and both +draw on Etherscan's labels, which are not independent of each other. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from cryptoguard.ml.sources import SOURCES, local_path, verify + +if TYPE_CHECKING: + import pandas as pd + +TX_HASH = re.compile(r"^0x[0-9a-f]{64}$") +ADDRESS = re.compile(r"^0x[0-9a-f]{40}$") + +# PTXPhish sheet layout (row 3 holds the subtype headers; data starts at row 4). +_PTX_HEADER_ROW = 3 +_PTX_FAMILIES = { + "Approve": "ice_phishing", + "Permit": "ice_phishing", + "SetApproveForAll": "ice_phishing", + "Bulk transfer": "nft_order", + "Proxy upgrade": "nft_order", + "Free buy order": "nft_order", + "Zero value transfer": "address_poisoning", + "Fake token transfer": "address_poisoning", + "Dust value transfer": "address_poisoning", + "Airdrop function": "payable_function", + "Wallet function": "payable_function", + "Benign KOL": "benign", + "Benign Developer": "benign", +} +FAMILIES = ( + "ice_phishing", + "nft_order", + "address_poisoning", + "payable_function", + "benign", +) + + +def _snake(name: str) -> str: + return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_") + + +def ptx_schema() -> Any: + import pandera.pandas as pa + + return pa.DataFrameSchema( + { + "tx_hash": pa.Column(str, pa.Check.str_matches(TX_HASH.pattern), unique=True), + "family": pa.Column(str, pa.Check.isin(FAMILIES)), + "subtype": pa.Column(str, pa.Check.isin([_snake(k) for k in _PTX_FAMILIES])), + "label": pa.Column(int, pa.Check.isin([0, 1])), + }, + checks=pa.Check( + lambda df: (df["label"] == (df["family"] != "benign").astype(int)).all(), + error="label must be 1 exactly for the attack families", + ), + strict=True, + coerce=False, + ) + + +def load_ptxphish(data_dir: Path) -> pd.DataFrame: + """One validated row per labelled transaction (lower-case hash).""" + import pandas as pd + + source = SOURCES["ptxphish"] + verify(data_dir, source) + path = local_path(data_dir, source, source.files[0]) + sheet = pd.read_excel(path, header=None, dtype=str) + headers = sheet.iloc[_PTX_HEADER_ROW].tolist() + seen = {h for h in headers if isinstance(h, str)} - {"Source"} + if seen != set(_PTX_FAMILIES): + raise ValueError(f"unexpected PTXPhish layout: subtypes {sorted(seen)}") + rows = [] + for column, header in enumerate(headers): + if header not in _PTX_FAMILIES: + continue + for value in sheet.iloc[_PTX_HEADER_ROW + 1 :, column].dropna(): + tx_hash = str(value).strip().lower() + if not TX_HASH.match(tx_hash): + raise ValueError(f"PTXPhish column {header!r}: not a tx hash: {value!r}") + family = _PTX_FAMILIES[header] + rows.append((tx_hash, family, _snake(header), int(family != "benign"))) + frame = pd.DataFrame(rows, columns=["tx_hash", "family", "subtype", "label"]) + frame = frame.astype({"tx_hash": str, "family": str, "subtype": str, "label": int}) + return ptx_schema().validate(frame) # type: ignore[no-any-return] + + +def load_address_labels(data_dir: Path) -> pd.DataFrame: + """Address-level labels from Poison-Hunter and Forta (data card only, not training).""" + import pandas as pd + + rows: list[tuple[str, str, str]] = [] + ph = SOURCES["poison-hunter"] + verify(data_dir, ph) + for file, label in ( + ("phishing_address_groundtruth.txt", "phishing"), + ("benign_addresses_on_etherscan.txt", "benign_popular"), + ): + text = (data_dir / ph.name / file).read_text(encoding="utf-8") + rows += [(a.strip().lower(), label, f"poison-hunter:{file}") for a in text.split()] + forta = SOURCES["forta"] + verify(data_dir, forta) + for file, column in ( + ("labels/1/phishing_scams.csv", "address"), + ("labels/1/etherscan_malicious_labels.csv", "banned_address"), + ): + table = pd.read_csv(data_dir / forta.name / file, usecols=[column], dtype=str) + rows += [(a.lower(), "phishing", f"forta:{file}") for a in table[column].dropna()] + frame = pd.DataFrame(rows, columns=["address", "label", "source"]) + bad = frame[~frame["address"].str.match(ADDRESS.pattern)] + if len(bad): + raise ValueError(f"{len(bad)} malformed addresses, e.g. {bad.iloc[0].to_dict()}") + return frame + + +def poison_hunter_sample_is_shifted(data_dir: Path) -> bool: + """The 150-row transfer sample has two more fields per row than header names, so a + plain CSV read assigns values to the wrong columns. Detected, reported, never used.""" + import csv + + path = data_dir / "poison-hunter" / "phishing_transfers_sample.csv" + with path.open(encoding="utf-8", newline="") as fh: + reader = csv.reader(fh) + header = next(reader) + widths = {len(row) for row in reader if row} + return widths != {len(header)} diff --git a/src/cryptoguard/ml/report.py b/src/cryptoguard/ml/report.py new file mode 100644 index 0000000..51dd980 --- /dev/null +++ b/src/cryptoguard/ml/report.py @@ -0,0 +1,174 @@ +"""Render ML_EVALUATION.md from one training run (generated; never edit by hand).""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +from cryptoguard.ml.sources import SOURCES + + +def _f(x: float | None, digits: int = 3) -> str: + return "—" if x is None else f"{x:.{digits}f}" + + +def _ci(r: dict[str, Any], key: str) -> str: + ci = (r.get("ci95") or {}).get(key) + return f" [{ci[0]:.3f}, {ci[1]:.3f}]" if ci else "" + + +def render_report(entry: dict[str, Any], out: dict[str, Any], manifest: dict[str, Any]) -> str: + gate = entry["gate"] + sel = entry["selected"] + splits = manifest["splits"] + L: list[str] = [] + add = L.append + add("# ML evaluation (experimental, shadow mode only)\n") + add( + f"Generated by `cryptoguard ml train` on {datetime.now(UTC):%Y-%m-%d %H:%M} UTC; do not " + f"edit by hand. Run `{entry['run_id']}`, code `{entry['git']}`, {entry['ml_version']}, " + f"features `{entry['feature_set_version']}`. Training and evaluation took " + f"{entry['seconds']} s on CPU.\n" + ) + add("## Task\n") + add( + "Classify an Ethereum transaction as part of a phishing operation or not, from " + "information available when it executed: the transaction, its receipt, and the " + "sender's nonce and target's code at the previous block. Labels come from PTXPhish " + "(NDSS 2025), reviewed by two security experts and independent of CryptoGuard. " + "Many labelled phishing transactions are the *attacker's* (for ice phishing, the " + "`transferFrom` that drains the victim), so this is not a pre-signing warning for a " + "victim's own approval.\n" + ) + add("## Data\n") + add("| Source | Pinned commit | License | Use |") + add("|---|---|---|---|") + uses = { + "ptxphish": "training and evaluation labels", + "poison-hunter": "data card only", + "forta": "data card only", + } + for name, s in SOURCES.items(): + add( + f"| [{s.repository}](https://github.com/{s.repository}) | `{s.commit[:10]}` | " + f"{s.license or 'none published (not redistributed)'} | {uses[name]} |" + ) + add("") + add( + f"- Collected: {manifest['rows']} labelled transactions with chain data " + f"(sample of {manifest.get('sample_rows', '?')}; " + f"{manifest.get('rpc_requests_used', '?')} of 12,000 approved RPC requests used; " + f"not found on chain: {manifest['not_found']}). Blocks " + f"{manifest['block_range'][0]:,} to {manifest['block_range'][1]:,}." + ) + add( + "- Per subtype: " + ", ".join(f"{k} {v}" for k, v in manifest["label_counts"].items()) + "." + ) + g = manifest["groups"] + add( + f"- Account groups (diagnostic): {g['groups']} groups, largest {g['largest_group_rows']} " + f"rows, {g['mixed_label_groups']} mixed-label group(s) holding " + f"{g['rows_in_mixed_groups']} rows; {g['phishing_rows_sharing_a_group']} phishing rows " + "share infrastructure with another phishing row." + ) + add("") + add("## Splits\n") + lo, hi = splits["window"] + add( + f"Study window: blocks {lo:,} to {hi:,}, where both classes occur (benign transactions " + "outside it are excluded, or the era alone would separate the classes). Ordered by " + f"block: validation from block {splits['boundaries']['validation_from_block']:,}, test " + f"from {splits['boundaries']['test_from_block']:,}. Rows sharing a non-hub account with " + f"an earlier split are dropped; hubs come from training rows only " + f"({splits['hub_accounts_from_train']}).\n" + ) + add("| Split | Benign | Phishing |") + add("|---|---|---|") + for name, counts in sorted(splits["counts"].items()): + add(f"| {name} | {counts.get('0', 0)} | {counts.get('1', 0)} |") + add("") + add("## Results\n") + add( + "Hyperparameters, thresholds and the selected model were chosen on validation; test " + "was scored once. AP = average precision (PR-AUC); intervals are 95% bootstrap " + "intervals over test rows.\n" + ) + neg = entry["test"]["rows"] - entry["test"]["positives"] + add( + f"Test rows: {entry['test']['rows']} ({entry['test']['positives']} phishing, {neg} benign; " + f"phishing share {entry['test']['prevalence']:.2f}, so any ranking scores AP of at least " + "that much — compare AP lift and the false-positive rate, measured on only " + f"{neg} benign rows).\n" + ) + add( + "| Model | Features | Val log loss | Val AP | Test AP [95% CI] | Test AP lift " + "| Test ROC-AUC | Test bal. acc. | Test recall [95% CI] | Test FPR [95% CI] |" + ) + add("|---|---|---|---|---|---|---|---|---|---|") + for r in entry["results"]: + v, t = r["validation"], r["test"] + is_sel = r["name"] == sel["name"] and r["feature_set"] == sel["feature_set"] + loss = _f(v["log_loss"]) if r["kind"] != "rule" else "—" + add( + f"| {r['name']}{' (selected)' if is_sel else ''} | {r['feature_set'] or '—'} " + f"| {loss} | {_f(v['average_precision'])} " + f"| {_f(t['average_precision'])}{_ci(t, 'average_precision')} | {_f(t['ap_lift'])} " + f"| {_f(t['roc_auc'])} | {_f(t['balanced_accuracy'])} " + f"| {_f(t['recall'])}{_ci(t, 'recall')} " + f"| {_f(t['false_positive_rate'])}{_ci(t, 'false_positive_rate')} |" + ) + add("") + st = entry["test"] + add( + f"Selected: **{sel['name']}** on `{sel['feature_set']}` features, {sel['params']}, " + f"threshold {sel['threshold']:.3f}. Test confusion: {st['confusion']}.\n" + ) + if st.get("recall_by_family"): + add( + "Test recall by phishing family: " + + ", ".join(f"{k} {v:.2f}" for k, v in st["recall_by_family"].items()) + + ".\n" + ) + add("### Promotion gate (shadow mode)\n") + add( + f"- On validation, close at least {gate['required_gap_reduction']:.0%} of the AP gap " + f"between the best baseline ({gate['best_baseline_validation_ap']:.3f}) and 1.0 " + f"(closed: {gate['validation_gap_closed']:.0%}): **{gate['validation_beats_baselines']}**." + ) + add( + f"- Test AP interval must lie above the best baseline's test AP " + f"({gate['best_baseline_test_ap']:.3f}): **{gate['test_interval_above_best_baseline']}**." + ) + add(f"- Validated for shadow mode: **{gate['validated_for_shadow']}**.\n") + add("### What the selected model relies on\n") + add("Permutation importance on validation (increase in log loss when a feature is shuffled):\n") + for imp in out["importance"][:10]: + add(f"- `{imp['feature']}`: {imp['mean']:.3f} ± {imp['std']:.3f}") + add("") + add("### Errors on test\n") + fn, fp = out["errors"]["false_negatives"], out["errors"]["false_positives"] + add(f"Missed phishing (lowest scores first, up to 15 of {st['confusion']['fn']}):\n") + for e in fn: + add(f"- `{e['tx_hash']}` {e['family']}/{e['subtype']}, score {e['score']:.3f}") + add(f"\nBenign flagged (highest scores first, up to 15 of {st['confusion']['fp']}):\n") + for e in fp: + add(f"- `{e['tx_hash']}` {e['subtype']}, score {e['score']:.3f}") + add("") + add("## Limitations\n") + for item in ( + "One labelled source. PTXPhish's benign class is transactions of prominent accounts " + '("KOL") and developers, not a random sample of Ethereum users; precision on real ' + "traffic, where phishing is far rarer than here, will be much lower than measured.", + "The `no_identity` rows show how much depends on who sends a transaction (long " + "histories, vanity addresses) rather than what it does; those signals partly reflect " + "how the dataset was built.", + "Small test split after the time window and account purge; intervals are wide.", + "The CryptoGuard comparison is a transaction-level proxy of its signals, not its " + "wallet-centric detectors, which need wallet history this dataset lacks.", + "Features use the receipt (logs of the executed transaction). Scoring a transaction " + "before it is signed would need a simulation, which is not implemented.", + "Not independently reviewed. The model never creates findings (shadow mode only).", + ): + add(f"- {item}") + add("") + return "\n".join(L) diff --git a/src/cryptoguard/ml/sources.py b/src/cryptoguard/ml/sources.py new file mode 100644 index 0000000..74b56ee --- /dev/null +++ b/src/cryptoguard/ml/sources.py @@ -0,0 +1,177 @@ +"""Pinned external label sources: where each file comes from, its hash and its license. + +Two of the three sources publish no license, so their files are never redistributed with +CryptoGuard: ``fetch_sources`` downloads them on request into the local data directory +(git-ignored) and refuses any file whose SHA-256 differs from the pinned value. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from pathlib import Path + +import httpx + +DEFAULT_DATA_DIR = Path("data") / "external" + + +@dataclass(frozen=True) +class SourceFile: + path: str + sha256: str + size: int + + +@dataclass(frozen=True) +class Source: + name: str + repository: str + commit: str + license: str | None # SPDX id; None = no license published (all rights reserved) + citation: str + files: tuple[SourceFile, ...] + + @property + def redistributable(self) -> bool: + return self.license is not None + + def url(self, file: SourceFile) -> str: + return f"https://raw.githubusercontent.com/{self.repository}/{self.commit}/{file.path}" + + +SOURCES: dict[str, Source] = { + "ptxphish": Source( + name="ptxphish", + repository="HypoopyH/PTXPhish", + commit="18efed8f8e8eaa6abb36ef94bfec4c06dd744090", + license=None, + citation=( + "Chen, Hu, He, Luo, Wu, Zhou. Dissecting Payload-based Transaction Phishing on " + "Ethereum. NDSS 2025." + ), + files=( + SourceFile( + "dataset/PTXPHISH.xlsx", + "a5bdc03757963d22a58b755caf08f058530658c34b5b38af428af0ee35b38ce0", + 897_414, + ), + SourceFile( + "dataset/InitialAddress.xlsx", + "2b8a8cd6c9a9b70b16c14eb15310650ca07c8be0c09c0a3bba8ca39f0a84785a", + 28_127, + ), + ), + ), + "poison-hunter": Source( + name="poison-hunter", + repository="DS2L/Poison-Hunter", + commit="74ff6f7d14f196a7396d7aa0b88aecd9a3bd9ff0", + license=None, + citation="Guan, Li. Characterizing Ethereum Address Poisoning Attack. ACM CCS 2024.", + files=( + SourceFile( + "benign_addresses_on_etherscan.txt", + "301cd31f4280cef85a1075f0da1dd390d05cc2c7c90a2020a4cbb9bc982fc3a1", + 49_622, + ), + SourceFile( + "phishing_address_groundtruth.txt", + "d0e16888ccea93207ea6387815d0ab75076558524a9d2e7212f22a6855415cbd", + 253_270, + ), + SourceFile( + "phishing_address_we_detected_TP.txt", + "69fd916960998d3f3e87b517ad4a3e787e1789b7dbaa451cfc0d631cfe2c06c8", + 246_347, + ), + SourceFile( + "phishing_transfers_sample.csv", + "1de4bf2aa0bdc02e8347eeedf5d843f32e83a3f8e0c7fd864fea1997726fcc84", + 63_454, + ), + ), + ), + "forta": Source( + name="forta", + repository="forta-network/labelled-datasets", + commit="40a9c2f2bd7e9ddfdd0f3540db589f0288e1e88a", + license="MIT", + citation="Forta Network, labelled-datasets (Etherscan phish-hack/exploit/heist labels).", + files=( + SourceFile( + "labels/1/phishing_scams.csv", + "10fb332f7e79056862900692df3503ef26fa193445b4f2908cecdae2d0c0b3c9", + 525_163, + ), + SourceFile( + "labels/1/etherscan_malicious_labels.csv", + "9a787753c7caf64d506de755830ac85d05f21973939763251f54c38136505f42", + 678_922, + ), + SourceFile( + "labels/1/malicious_smart_contracts.csv", + "b2f680720f6dd56158c82ff141aecbea3d9f68e987193e9ea9314da13afdb81e", + 162_717, + ), + ), + ), +} + + +class SourceIntegrityError(RuntimeError): + """A downloaded or cached file does not match its pinned hash.""" + + +def local_path(data_dir: Path, source: Source, file: SourceFile) -> Path: + return data_dir / source.name / file.path + + +def sha256_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def verify(data_dir: Path, source: Source) -> list[Path]: + """Return the source's local files, raising if one is missing or altered.""" + paths = [] + for file in source.files: + path = local_path(data_dir, source, file) + if not path.exists(): + raise FileNotFoundError(f"{path} is missing; run `cryptoguard ml fetch-sources`.") + if (digest := sha256_file(path)) != file.sha256: + raise SourceIntegrityError(f"{path}: sha256 {digest} != pinned {file.sha256}") + paths.append(path) + return paths + + +def fetch_sources( + data_dir: Path = DEFAULT_DATA_DIR, + names: tuple[str, ...] | None = None, + *, + client: httpx.Client | None = None, +) -> list[tuple[str, str, str]]: + """Download missing files at their pinned commits; verify every file. Returns + (source, path, status) rows.""" + rows = [] + own = client is None + http = client or httpx.Client(timeout=60, follow_redirects=True) + try: + for name in names or tuple(SOURCES): + source = SOURCES[name] + for file in source.files: + path = local_path(data_dir, source, file) + if path.exists() and sha256_file(path) == file.sha256: + rows.append((name, file.path, "cached")) + continue + data = http.get(source.url(file)).raise_for_status().content + if (digest := hashlib.sha256(data).hexdigest()) != file.sha256: + raise SourceIntegrityError( + f"{source.url(file)}: sha256 {digest} != pinned {file.sha256}" + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + rows.append((name, file.path, "downloaded")) + finally: + if own: + http.close() + return rows diff --git a/src/cryptoguard/ml/splits.py b/src/cryptoguard/ml/splits.py new file mode 100644 index 0000000..520df96 --- /dev/null +++ b/src/cryptoguard/ml/splits.py @@ -0,0 +1,97 @@ +"""Leakage-safe train / validation / test splits. + +1. **Study window.** Only blocks where both classes occur are kept. PTXPhish's benign + transactions span 2017-2024 but its phishing ones 2022-2023; outside the overlap, the + era alone (gas-fee format, token mix) would separate the classes. +2. **Time.** Rows are ordered by block; train is the earliest part, then validation, then + test. No block is shared by two splits. +3. **Account purge.** A validation row sharing any non-hub account (sender, target, + spender, recipient: ``features.parties``) with a training row is dropped, and a test row + sharing one with a kept training or validation row is dropped. This stops repeated + users and reused attacker infrastructure from appearing on both sides. +4. **Point in time.** Hubs (public infrastructure, ``dataset.hubs``) are determined from the + training rows only, so later data never shapes the split. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from cryptoguard.ml.dataset import hubs +from cryptoguard.ml.features import parties + +if TYPE_CHECKING: + import pandas as pd + + +@dataclass(frozen=True) +class SplitPlan: + train: float = 0.6 + validation: float = 0.2 # test gets the rest + + +DEFAULT_SPLIT = SplitPlan() + + +def study_window(table: pd.DataFrame) -> tuple[int, int]: + """Block range in which both classes occur (a dataset definition, stated in reports).""" + by = table.groupby("label")["block_number"] + return int(by.min().max()), int(by.max().min()) + + +def _cut(blocks: list[int], fraction: float) -> int: + """First block of the part after ``fraction`` of rows (never splits a block).""" + index = min(int(len(blocks) * fraction), len(blocks) - 1) + return blocks[index] + + +def make_splits( + table: pd.DataFrame, + records: dict[str, dict[str, Any]], + plan: SplitPlan = DEFAULT_SPLIT, +) -> tuple[pd.Series, dict[str, Any]]: + """A split name per row ("train", "validation", "test", or "excluded:").""" + import pandas as pd + + lo, hi = study_window(table) + split = pd.Series("excluded:outside_window", index=table.index, dtype=object) + inside = table[(table["block_number"] >= lo) & (table["block_number"] <= hi)] + blocks = sorted(inside["block_number"]) + val_start = _cut(blocks, plan.train) + test_start = _cut(blocks, plan.train + plan.validation) + split[inside.index[inside["block_number"] < val_start]] = "train" + split[ + inside.index[(inside["block_number"] >= val_start) & (inside["block_number"] < test_start)] + ] = "validation" + split[inside.index[inside["block_number"] >= test_start]] = "test" + + train_records = {h: records[h] for h in table.loc[split == "train", "tx_hash"]} + hub_set = hubs(train_records) + + def accounts(tx_hash: str) -> set[str]: + return parties(records[tx_hash]) - hub_set + + seen: set[str] = set() + for tx_hash in table.loc[split == "train", "tx_hash"]: + seen |= accounts(tx_hash) + for name in ("validation", "test"): + keep: set[str] = set() + for index in table.index[split == name]: + acc = accounts(str(table.at[index, "tx_hash"])) + if acc & seen: + split[index] = f"excluded:shares_account_with_earlier_split({name})" + else: + keep |= acc + seen |= keep + + summary: dict[str, Any] = { + "window": [lo, hi], + "boundaries": {"validation_from_block": val_start, "test_from_block": test_start}, + "hub_accounts_from_train": len(hub_set), + "counts": { + str(name): {str(k): int(v) for k, v in grp["label"].value_counts().sort_index().items()} + for name, grp in table.groupby(split) + }, + } + return split, summary diff --git a/src/cryptoguard/ml/train.py b/src/cryptoguard/ml/train.py new file mode 100644 index 0000000..7f88fe4 --- /dev/null +++ b/src/cryptoguard/ml/train.py @@ -0,0 +1,428 @@ +"""Train, select and evaluate phishing-transaction classifiers (CPU, seconds). + +Protocol: every choice (hyperparameters, decision threshold, feature set, which model is +"selected") is made on the validation split. The test split is scored once, at the end, +for every model family, so baselines and models are compared on identical rows. + +Baselines: + +- ``majority`` and ``stratified``: trivial (sklearn ``DummyClassifier``); +- ``rule_phishing_shape``: a hand-written heuristic ("delegated transfer, permit, operator + grant, upgrade, bare-selector call with value, or zero-value transfer"); +- ``rule_cryptoguard_signals``: the transaction-level signals CryptoGuard's detectors use + (unlimited allowance, operator grant, zero-value transfer, lookalike affix >= 7). This is a + proxy: CryptoGuard's detectors are wallet-centric and need the wallet's history, which + this dataset does not contain, so the real detector cannot be run on it. +""" + +from __future__ import annotations + +import json +import platform +import subprocess +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from cryptoguard.ml import FEATURE_SET_VERSION, ML_VERSION +from cryptoguard.ml.features import FEATURES + +if TYPE_CHECKING: + import numpy as np + import pandas as pd + +SEED = 20261029 + +# Features that describe *who* rather than *what*: long sender histories (the benign class +# is "KOL" and developer accounts) and vanity-mined addresses. Real signals, but also the +# likeliest dataset-construction artefacts, so every model is also trained without them. +IDENTITY_FEATURES = ("sender_prior_txs_log", "from_vanity_zero_nibbles", "to_vanity_zero_nibbles") +FEATURE_SETS: dict[str, tuple[str, ...]] = { + "full": FEATURES, + "no_identity": tuple(f for f in FEATURES if f not in IDENTITY_FEATURES), +} + + +@dataclass +class ModelResult: + name: str + kind: str # "trivial" | "rule" | "learned" + feature_set: str | None + params: dict[str, Any] + validation: dict[str, Any] + test: dict[str, Any] = field(default_factory=dict) + threshold: float = 0.5 + + +def _git_sha() -> str: + try: + sha = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + ).stdout.strip() + dirty = subprocess.run( + ["git", "status", "--porcelain", "--untracked-files=no"], # noqa: S607 + capture_output=True, + text=True, + check=True, + ).stdout.strip() + return sha + ("+dirty" if dirty else "") + except (OSError, subprocess.CalledProcessError): + return "unknown" + + +def _versions() -> dict[str, str]: + import importlib.metadata as md + + out = {"python": platform.python_version()} + for pkg in ("cryptoguard", "numpy", "pandas", "scikit-learn", "lightgbm", "pandera"): + try: + out[pkg] = md.version(pkg) + except md.PackageNotFoundError: + out[pkg] = "missing" + return out + + +def rule_scores(frame: pd.DataFrame, rule: str) -> np.ndarray: + import numpy as np + + if rule == "rule_phishing_shape": + hit = ( + (frame["fn_transfer_from"] > 0) + | (frame["fn_permit"] > 0) + | (frame["fn_set_approval_for_all"] > 0) + | (frame["fn_upgrade"] > 0) + | ((frame["input_is_bare_selector"] > 0) & (frame["is_zero_value"] == 0)) + | (frame["n_zero_value_transfers"] > 0) + ) + elif rule == "rule_cryptoguard_signals": + hit = ( + (frame["n_unlimited_approvals"] > 0) + | (frame["n_approval_for_all_granted"] > 0) + | (frame["n_zero_value_transfers"] > 0) + | (frame["max_party_affix_match"] >= 7) + ) + else: + raise ValueError(rule) + return np.asarray(hit, dtype=float) + + +def metrics(y: np.ndarray, score: np.ndarray, threshold: float) -> dict[str, Any]: + import numpy as np + from sklearn.metrics import ( + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + confusion_matrix, + f1_score, + log_loss, + precision_score, + recall_score, + roc_auc_score, + ) + + pred = (score >= threshold).astype(int) + both = len(np.unique(y)) == 2 + tn, fp, fn, tp = confusion_matrix(y, pred, labels=[0, 1]).ravel() + prevalence = float(y.mean()) if len(y) else 0.0 + ap = float(average_precision_score(y, score)) if both else None + return { + "rows": len(y), + "positives": int(y.sum()), + "prevalence": prevalence, + "average_precision": ap, + # AP is at least the positive share; lift = share of the remaining room achieved. + "ap_lift": None if ap is None or prevalence >= 1 else (ap - prevalence) / (1 - prevalence), + "roc_auc": float(roc_auc_score(y, score)) if both else None, + "log_loss": float(log_loss(y, np.clip(score, 1e-6, 1 - 1e-6), labels=[0, 1])), + "balanced_accuracy": float(balanced_accuracy_score(y, pred)) if both else None, + "brier": float(brier_score_loss(y, np.clip(score, 0, 1))), + "precision": float(precision_score(y, pred, zero_division=0)), + "recall": float(recall_score(y, pred, zero_division=0)), + "f1": float(f1_score(y, pred, zero_division=0)), + "false_positive_rate": float(fp / (fp + tn)) if fp + tn else None, + "confusion": {"tn": int(tn), "fp": int(fp), "fn": int(fn), "tp": int(tp)}, + } + + +def best_threshold(y: np.ndarray, score: np.ndarray) -> float: + """Threshold maximising F1 on the given (validation) rows.""" + import numpy as np + from sklearn.metrics import f1_score + + candidates = np.unique(score) + if len(candidates) > 200: + candidates = np.quantile(score, np.linspace(0, 1, 201)) + f1s = [f1_score(y, (score >= t).astype(int), zero_division=0) for t in candidates] + return float(candidates[int(np.argmax(f1s))]) + + +def bootstrap_ci( + y: np.ndarray, score: np.ndarray, threshold: float, n: int = 1000 +) -> dict[str, list[float]]: + """95% percentile intervals for test AP, recall and false-positive rate (seeded + resamples of rows).""" + import numpy as np + from sklearn.metrics import average_precision_score, recall_score + + rng = np.random.default_rng(SEED) + ap, rec, fpr = [], [], [] + for _ in range(n): + idx = rng.integers(0, len(y), len(y)) + if len(np.unique(y[idx])) < 2: + continue + pred = (score[idx] >= threshold).astype(int) + ap.append(average_precision_score(y[idx], score[idx])) + rec.append(recall_score(y[idx], pred, zero_division=0)) + neg = y[idx] == 0 + fpr.append(float(pred[neg].mean())) + + def q(values: list[float]) -> list[float]: + return [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))] + + return {"average_precision": q(ap), "recall": q(rec), "false_positive_rate": q(fpr)} + + +def _candidates() -> list[tuple[str, dict[str, Any]]]: + out: list[tuple[str, dict[str, Any]]] = [] + out += [("logistic_regression", {"C": c}) for c in (0.01, 0.1, 1.0, 10.0)] + out += [("random_forest", {"min_samples_leaf": m}) for m in (1, 3, 10)] + out += [ + ("lightgbm", {"num_leaves": nl, "min_child_samples": mc}) + for nl in (7, 15) + for mc in (5, 20) + ] + return out + + +def make_model(name: str, params: dict[str, Any]): # type: ignore[no-untyped-def] + if name == "logistic_regression": + from sklearn.linear_model import LogisticRegression + from sklearn.pipeline import make_pipeline + from sklearn.preprocessing import StandardScaler + + return make_pipeline( + StandardScaler(), + LogisticRegression( + C=params["C"], class_weight="balanced", max_iter=2_000, random_state=SEED + ), + ) + if name == "random_forest": + from sklearn.ensemble import RandomForestClassifier + + return RandomForestClassifier( + n_estimators=300, + min_samples_leaf=params["min_samples_leaf"], + class_weight="balanced_subsample", + n_jobs=2, + random_state=SEED, + ) + if name == "lightgbm": + from lightgbm import LGBMClassifier + + return LGBMClassifier( + n_estimators=300, + learning_rate=0.05, + num_leaves=params["num_leaves"], + min_child_samples=params["min_child_samples"], + subsample=0.8, + subsample_freq=1, + colsample_bytree=0.8, + class_weight="balanced", + n_jobs=2, + random_state=SEED, + deterministic=True, + force_col_wise=True, + verbose=-1, + ) + raise ValueError(name) + + +def run_training(table: pd.DataFrame, split: pd.Series) -> dict[str, Any]: + """Fit everything, select on validation, score test once. Returns the full result.""" + import numpy as np + from sklearn.dummy import DummyClassifier + from sklearn.inspection import permutation_importance + + started = time.perf_counter() + train, val, test = (table[split == s] for s in ("train", "validation", "test")) + y_tr, y_va, y_te = (part["label"].to_numpy() for part in (train, val, test)) + results: list[ModelResult] = [] + fitted: dict[tuple[str, str], Any] = {} + + for strategy in ("most_frequent", "stratified"): + dummy = DummyClassifier(strategy=strategy, random_state=SEED).fit( + train[list(FEATURES)], y_tr + ) + s_va = dummy.predict_proba(val[list(FEATURES)])[:, 1] + res = ModelResult( + "majority" if strategy == "most_frequent" else "stratified", + "trivial", + None, + {"strategy": strategy}, + metrics(y_va, s_va, 0.5), + ) + res.test = metrics(y_te, dummy.predict_proba(test[list(FEATURES)])[:, 1], 0.5) + results.append(res) + for rule in ("rule_phishing_shape", "rule_cryptoguard_signals"): + res = ModelResult(rule, "rule", None, {}, metrics(y_va, rule_scores(val, rule), 0.5)) + res.test = metrics(y_te, rule_scores(test, rule), 0.5) + res.test["ci95"] = bootstrap_ci(y_te, rule_scores(test, rule), 0.5) + results.append(res) + + # Learned models: every candidate scored on validation; best per (family, feature set) by + # validation log loss (a proper scoring rule: AP saturates near 1 on this data). + best: dict[tuple[str, str], tuple[float, dict[str, Any], Any, np.ndarray]] = {} + for fs_name, fs_tuple in FEATURE_SETS.items(): + for name, params in _candidates(): + model = make_model(name, params).fit(train[list(fs_tuple)], y_tr) + s_va = model.predict_proba(val[list(fs_tuple)])[:, 1] + loss = metrics(y_va, s_va, 0.5)["log_loss"] + key = (name, fs_name) + if key not in best or loss < best[key][0]: + best[key] = (loss, params, model, s_va) + for (name, fs_name), (_, params, model, s_va) in sorted(best.items()): + fs_cols = list(FEATURE_SETS[fs_name]) + thr = best_threshold(y_va, s_va) + res = ModelResult(name, "learned", fs_name, params, metrics(y_va, s_va, thr), threshold=thr) + s_te = model.predict_proba(test[fs_cols])[:, 1] + res.test = metrics(y_te, s_te, thr) + res.test["ci95"] = bootstrap_ci(y_te, s_te, thr) + res.test["recall_by_family"] = { + fam: float( + ((s_te >= thr) & (test["family"] == fam).to_numpy()).sum() + / max((test["family"] == fam).sum(), 1) + ) + for fam in sorted(test.loc[test["label"] == 1, "family"].unique()) + } + fitted[(name, fs_name)] = model + results.append(res) + + learned = [r for r in results if r.kind == "learned"] + selected = min(learned, key=lambda r: r.validation["log_loss"]) + model = fitted[(selected.name, selected.feature_set or "full")] + cols = list(FEATURE_SETS[selected.feature_set or "full"]) + imp = permutation_importance( + model, val[cols], y_va, scoring="neg_log_loss", n_repeats=5, random_state=SEED, n_jobs=1 + ) + importance: list[dict[str, Any]] = sorted( + ( + {"feature": c, "mean": float(m), "std": float(s)} + for c, m, s in zip(cols, imp.importances_mean, imp.importances_std, strict=True) + ), + key=lambda d: -float(d["mean"]), + ) + s_te = model.predict_proba(test[cols])[:, 1] + errors = test.assign(score=s_te) + fn = errors[(errors["label"] == 1) & (errors["score"] < selected.threshold)] + fp = errors[(errors["label"] == 0) & (errors["score"] >= selected.threshold)] + return { + "results": results, + "selected": selected, + "model": model, + "feature_columns": cols, + "importance": importance, + "errors": { + "false_negatives": fn.sort_values("score")[["tx_hash", "family", "subtype", "score"]] + .head(15) + .to_dict("records"), + "false_positives": fp.sort_values("score", ascending=False)[ + ["tx_hash", "subtype", "score"] + ] + .head(15) + .to_dict("records"), + }, + "seconds": round(time.perf_counter() - started, 1), + "reference": { + c: [float(q) for q in np.quantile(train[c], np.linspace(0, 1, 11))] for c in cols + }, + } + + +GATE_GAP_REDUCTION = 0.5 + + +def promotion_gate(results: list[ModelResult], selected: ModelResult) -> dict[str, Any]: + """A model is validated for shadow mode only if (1) on validation it closes at least half + of the AP gap between the best non-learned baseline and a perfect ranking, and (2) its + test AP interval lies entirely above the best baseline's test AP. + + Revised before the final run: the first version demanded "+0.05 AP over the best + baseline", which cannot be met when that baseline already exceeds 0.95 (as on a + partial-data dry run). Documented in ML.md. + """ + baselines = [r for r in results if r.kind != "learned"] + base_val = max(r.validation["average_precision"] or 0.0 for r in baselines) + base_test = max(r.test["average_precision"] or 0.0 for r in baselines) + model_val = selected.validation["average_precision"] or 0.0 + gap_closed = (model_val - base_val) / (1 - base_val) if base_val < 1 else 0.0 + val_ok = gap_closed >= GATE_GAP_REDUCTION + test_ok = selected.test["ci95"]["average_precision"][0] > base_test + return { + "best_baseline_validation_ap": base_val, + "best_baseline_test_ap": base_test, + "validation_gap_closed": gap_closed, + "required_gap_reduction": GATE_GAP_REDUCTION, + "validation_beats_baselines": bool(val_ok), + "test_interval_above_best_baseline": bool(test_ok), + "validated_for_shadow": bool(val_ok and test_ok), + } + + +def ledger_entry( + run_id: str, + config: dict[str, Any], + out: dict[str, Any], + gate: dict[str, Any], + manifest_sha: str, +) -> dict[str, Any]: + sel: ModelResult = out["selected"] + return { + "run_id": run_id, + "ml_version": ML_VERSION, + "feature_set_version": FEATURE_SET_VERSION, + "git": _git_sha(), + "versions": _versions(), + "config": config, + "dataset_manifest_sha256": manifest_sha, + "selected": { + "name": sel.name, + "feature_set": sel.feature_set, + "params": sel.params, + "threshold": sel.threshold, + }, + "validation": sel.validation, + "test": sel.test, + "gate": gate, + "seconds": out["seconds"], + "results": [asdict(r) for r in out["results"]], + } + + +def save_run(run_dir: Path, entry: dict[str, Any], out: dict[str, Any]) -> Path: + """Persist the selected model with a hash-pinned card (``registry.load_model`` checks it).""" + import hashlib + + import joblib + + run_dir.mkdir(parents=True, exist_ok=True) + model_path = run_dir / "model.joblib" + joblib.dump(out["model"], model_path) + card = { + "run_id": entry["run_id"], + "ml_version": ML_VERSION, + "feature_set_version": FEATURE_SET_VERSION, + "feature_columns": out["feature_columns"], + "threshold": entry["selected"]["threshold"], + "selected": entry["selected"], + "gate": entry["gate"], + "model_sha256": hashlib.sha256(model_path.read_bytes()).hexdigest(), + "reference_quantiles": out["reference"], + "trained_on": entry["config"], + } + (run_dir / "model_card.json").write_text(json.dumps(card, indent=1), encoding="utf-8") + (run_dir / "run.json").write_text(json.dumps(entry, indent=1, default=str), encoding="utf-8") + return run_dir diff --git a/uv.lock b/uv.lock index f150683..1d600d7 100644 --- a/uv.lock +++ b/uv.lock @@ -2,8 +2,15 @@ version = 1 revision = 5 requires-python = ">=3.12" resolution-markers = [ - "python_full_version >= '3.15'", - "python_full_version < '3.15'", + "python_full_version >= '3.15' and sys_platform == 'win32'", + "python_full_version >= '3.15' and sys_platform == 'emscripten'", + "python_full_version >= '3.15' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'emscripten'", + "python_full_version == '3.14.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", + "python_full_version < '3.14' and sys_platform == 'win32'", + "python_full_version < '3.14' and sys_platform == 'emscripten'", + "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] [[package]] @@ -119,6 +126,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, ] +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + [[package]] name = "colorama" version = "0.4.6" @@ -147,14 +163,27 @@ analytics = [ { name = "numpy" }, { name = "scipy" }, ] +ml = [ + { name = "lightgbm" }, + { name = "openpyxl" }, + { name = "pandas" }, + { name = "pandera" }, + { name = "scikit-learn" }, +] [package.dev-dependencies] dev = [ + { name = "lightgbm" }, { name = "mypy" }, { name = "numpy" }, + { name = "openpyxl" }, + { name = "pandas" }, + { name = "pandas-stubs" }, + { name = "pandera" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "ruff" }, + { name = "scikit-learn" }, { name = "scipy" }, { name = "scipy-stubs" }, ] @@ -163,27 +192,47 @@ dev = [ requires-dist = [ { name = "fastapi", specifier = ">=0.115" }, { name = "httpx", specifier = ">=0.27" }, + { name = "lightgbm", marker = "extra == 'ml'", specifier = ">=4.7.0" }, { name = "numpy", marker = "extra == 'analytics'", specifier = ">=2.5.4" }, + { name = "openpyxl", marker = "extra == 'ml'", specifier = ">=3.1.5" }, + { name = "pandas", marker = "extra == 'ml'", specifier = ">=3.1.0" }, + { name = "pandera", marker = "extra == 'ml'", specifier = ">=0.35.0" }, { name = "pycryptodome", specifier = ">=3.20" }, { name = "pydantic", specifier = ">=2.9" }, { name = "pydantic-settings", specifier = ">=2.5" }, + { name = "scikit-learn", marker = "extra == 'ml'", specifier = ">=1.9.1" }, { name = "scipy", marker = "extra == 'analytics'", specifier = ">=1.18.1" }, { name = "sqlalchemy", specifier = ">=2.0.35" }, { name = "uvicorn", specifier = ">=0.30" }, ] -provides-extras = ["analytics"] +provides-extras = ["analytics", "ml"] [package.metadata.requires-dev] dev = [ + { name = "lightgbm", specifier = ">=4.7.0" }, { name = "mypy", specifier = ">=1.11" }, { name = "numpy", specifier = ">=2.5.4" }, + { name = "openpyxl", specifier = ">=3.1.5" }, + { name = "pandas", specifier = ">=3.1.0" }, + { name = "pandas-stubs", specifier = ">=3.0.5.260914" }, + { name = "pandera", specifier = ">=0.35.0" }, { name = "pytest", specifier = ">=8.3" }, { name = "pytest-asyncio", specifier = ">=0.24" }, { name = "ruff", specifier = ">=0.6" }, + { name = "scikit-learn", specifier = ">=1.9.1" }, { name = "scipy", specifier = ">=1.18.1" }, { name = "scipy-stubs", specifier = ">=1.18.1.1" }, ] +[[package]] +name = "et-xmlfile" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/38/af70d7ab1ae9d4da450eeec1fa3918940a5fafb9055e934af8d6eb0c2313/et_xmlfile-2.0.0.tar.gz", hash = "sha256:dab3f4764309081ce75662649be815c4c9081e88f0837825f90fd28317d4da54", size = 17234, upload-time = "2024-10-25T17:25:40.039Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" }, +] + [[package]] name = "fastapi" version = "0.161.1" @@ -256,6 +305,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, ] +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + [[package]] name = "librt" version = "0.16.0" @@ -357,6 +418,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/69/7a5d10ac409c4da0355e054a14371871da9b5557fcc42772cd00181c6cce/librt-0.16.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8ceafb70f2a4f0826f11031942e59c0728fd98da112dc346d4352bde1e486866", size = 116391, upload-time = "2026-09-29T00:55:07.484Z" }, ] +[[package]] +name = "lightgbm" +version = "4.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "narwhals" }, + { name = "numpy" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/63/8e/4db5e29290d7e619c307fdb8dab0a0514090af2ce3ec483050e024ec6126/lightgbm-4.7.0.tar.gz", hash = "sha256:f8e20f682c9aabd000bcf4a7ed8aa6f473c1adfecccae34ec24e823d156f4af0", size = 1792896, upload-time = "2026-07-18T21:00:56.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/05/7213965863cba1ed0150ad045bceed6276a1afaaaedbaeff4699ec4f0ccb/lightgbm-4.7.0-py3-none-macosx_10_15_x86_64.whl", hash = "sha256:dfc1cfe8e760387be1e7ba7a214688be21fdff96e4ed9749188f83e1877c2477", size = 1877851, upload-time = "2026-07-18T21:00:35.225Z" }, + { url = "https://files.pythonhosted.org/packages/b2/86/f4fe714f2e0bf3941705a20d7f6849dc476276d71236e82ea6b0d6539b86/lightgbm-4.7.0-py3-none-macosx_12_0_arm64.whl", hash = "sha256:129535462686f274df179133643118c5c5c5667167fe6c3a28d955f0b3c8e868", size = 1498914, upload-time = "2026-07-18T21:00:36.549Z" }, + { url = "https://files.pythonhosted.org/packages/c6/a3/b29580948b92e8c2f84dea70118ac702ff067dc52ec4ffb5d73c953536a5/lightgbm-4.7.0-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d4529acec5c6fefe4768302a529707d0ead90f6a6f42df694b856212e09695b8", size = 3349492, upload-time = "2026-07-18T21:00:37.943Z" }, + { url = "https://files.pythonhosted.org/packages/15/eb/837ea3b40cc36e22eeebb9785c01e42b2c255d033eea1d2d9ee8e2540e55/lightgbm-4.7.0-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d23e922acd891e77212e4d0fbcee9ba973c96dee479491341d05ba595357ebb7", size = 3476028, upload-time = "2026-07-18T21:00:39.331Z" }, + { url = "https://files.pythonhosted.org/packages/d5/0b/c5c17d862b12ce292f24cd85d40f2f8f8981668fbdbd43fdc2625eccbc79/lightgbm-4.7.0-py3-none-win_amd64.whl", hash = "sha256:f42d1e5b32b6f170e606d7c689c6165671da98d7bf37f1addec2623efc8740c9", size = 1360833, upload-time = "2026-07-18T21:00:40.865Z" }, +] + [[package]] name = "mypy" version = "2.4.0" @@ -420,6 +499,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, ] +[[package]] +name = "narwhals" +version = "2.28.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/67/43/e11d75a7fb635c6f63dd6e176cb3e050ec2fee35f2f2267b332a6ad351ec/narwhals-2.28.0.tar.gz", hash = "sha256:2d9860c80d6610820826e94c6e42ce4b1d92d89cdd479586e652a8d211dab345", size = 754977, upload-time = "2026-10-27T12:19:33.777Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cf/82/8ef9c7e0f50493307a49c09cfa7f00c5a778b6d1921f7b2dabe1d3a5809e/narwhals-2.28.0-py3-none-any.whl", hash = "sha256:1f69d6385ec30e2fa6e1fdeb37c562ecabd0f713f6f3e3b58a668c5c9df9567f", size = 490591, upload-time = "2026-10-27T12:19:31.649Z" }, +] + [[package]] name = "numpy" version = "2.5.4" @@ -505,6 +593,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b1/a4/9376b38b7387a0296b1f626b966e5503578625c9673777db1b45bf70acb0/numpy_typing_compat-20260602.2.5-py3-none-any.whl", hash = "sha256:21ba7757c8924d359a9ed3ab2163c282a70983ae64498fdba6d1892a6641c8b1", size = 5881, upload-time = "2026-06-02T15:52:34.167Z" }, ] +[[package]] +name = "openpyxl" +version = "3.1.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "et-xmlfile" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/f9/88d94a75de065ea32619465d2f77b29a0469500e99012523b91cc4141cd1/openpyxl-3.1.5.tar.gz", hash = "sha256:cf0e3cf56142039133628b5acffe8ef0c12bc902d2aadd3e0fe5878dc08d1050", size = 186464, upload-time = "2024-06-28T14:03:44.161Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" }, +] + [[package]] name = "opentelemetry-api" version = "1.45.1" @@ -544,6 +644,96 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] +[[package]] +name = "pandas" +version = "3.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/55/b1/a10c0d1a7e3ce44eb42635771004aa503e3b9ddde0bd39c524dda65f7eff/pandas-3.1.0.tar.gz", hash = "sha256:ecb9b2d8a817b1e1ba1fdb90c0abe9eab31b4fdf2562b7a56b86ac66ace17e49", size = 5933421, upload-time = "2026-10-22T11:57:03.087Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/12/b94c28870f351e9650c724e6daedf661455b348a9dca6d717c42c30fa216/pandas-3.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f4772320b7735d96dbbef437129f840dec4175f8a18a2391bd1222ed8943825c", size = 11587014, upload-time = "2026-10-22T11:55:07.208Z" }, + { url = "https://files.pythonhosted.org/packages/1b/4b/af8ca15261db52ab07f5d0c2d4c1bc28d822ea4c2a79756bc2606c012e7c/pandas-3.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cc5e4e12d287ea77bbf4c4d4bf47ed152d82a990d3a6794dee7c350f887532b5", size = 11167712, upload-time = "2026-10-22T11:55:09.523Z" }, + { url = "https://files.pythonhosted.org/packages/49/c4/cd5127751e2bef3d10f07e0d856e120916a3df0df6450f759ddb48c78b1c/pandas-3.1.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9b4e696ff70ed06e986feeec09356c491ce878d0df69a36c8e591b6a38afa29b", size = 11476964, upload-time = "2026-10-22T11:55:11.889Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a6/dc89cdd95e12093bc813e9b814a09f1a056be3e1304edaef9bf9dbee108a/pandas-3.1.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9433b5dc2f26ef9d9b56daaf4d41d078bf4372c5d88c42ed5b397a6eea80de16", size = 12019688, upload-time = "2026-10-22T11:55:14.246Z" }, + { url = "https://files.pythonhosted.org/packages/36/87/da14aa671da792612f15847451e731d5dc0f06f6747b76b15f197ffcce13/pandas-3.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3cba20fd269808e224d6212273008173978033a1dee0f3f217bfdbd58775a72c", size = 12490149, upload-time = "2026-10-22T11:55:16.675Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a0/1ce996c7354ad37983955571058ba0dde585663163ab067275197183868f/pandas-3.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:743554ed96755ad1963397ccadbe9965d92db8777ca2ae8c1fe58bd9549d7f28", size = 13090624, upload-time = "2026-10-22T11:55:18.854Z" }, + { url = "https://files.pythonhosted.org/packages/92/72/d235f82b51a22478938a3583b68e8dc05811937543adf410f34bab76004a/pandas-3.1.0-cp312-cp312-pyemscripten_2024_0_wasm32.whl", hash = "sha256:ac2f833557874a79fc0b5fac4c86e402ea6498beba8753dc29ca23d08481689a", size = 8091628, upload-time = "2026-10-22T11:55:21.285Z" }, + { url = "https://files.pythonhosted.org/packages/10/72/06aefff8fe5efc5e1ca8bfb2695b648a435358f6dc224d4e40159314181a/pandas-3.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:b8c75dbb27c7d170b25c13dd35515da4bb92d40fe8bb3bd2c69a95de2218889b", size = 10748836, upload-time = "2026-10-22T11:55:23.47Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/4c86f659f5b14790d14e17253becc93c4e3d1511b73f0ba2184f06b164f8/pandas-3.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:73b6cea22090b7123c78ee662a5108ff36616b0bec4fe47026f86fb04a49bce7", size = 10128898, upload-time = "2026-10-22T11:55:25.995Z" }, + { url = "https://files.pythonhosted.org/packages/01/54/eb85f8b2ce121c21286842cf81abaa670ec3570173c512298f91128927a5/pandas-3.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:849d5019dead65944875ce21fbf71a2ca18e982164cd7367623cbda8567c3122", size = 11609893, upload-time = "2026-10-22T11:55:28.592Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f2/b327e814327b7e7e61b5c5cceafd5c0c20f0d38e94f99ebf2dd6c1cec85b/pandas-3.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:c1e084760f3b275eed5863407d025b933d25f3247515fcc84bf664405e8bb3d2", size = 11182834, upload-time = "2026-10-22T11:55:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6d/2b918a45ad31d85f898567c948f11d0789ffe7fbadd6f487565e99d179b6/pandas-3.1.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c1009f5b6819b81319cf177b4f01a2823ed54c81db8bd11cdf2375f42d064c02", size = 11421478, upload-time = "2026-10-22T11:55:33.257Z" }, + { url = "https://files.pythonhosted.org/packages/4b/6f/b63e1d43eef5746014ae3f4786c72e0020e61b6b373a2abb6ebf1be3df49/pandas-3.1.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:de6d0fc96e8551b83f400bf212611a0b3a2b389594d20a2540dacc61b21e7bce", size = 11991052, upload-time = "2026-10-22T11:55:35.556Z" }, + { url = "https://files.pythonhosted.org/packages/fd/43/2cf85145d822957a3f8959fd0a850e6bf687dac2823c612b3912b8888dae/pandas-3.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5611344f9f0ed51619ac7acdbf72b86f5043801a66e3f8730c8971257082e8ad", size = 12455560, upload-time = "2026-10-22T11:55:37.656Z" }, + { url = "https://files.pythonhosted.org/packages/7f/72/0cb19cea2e6afbb0854cbde0ed1345b61600e0de84eb7b73583fde3e3b55/pandas-3.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:39c67ed9e56ad3ac0727dc2ae6a1eef766988c762d5ce2e2a162613d81c8990b", size = 13045764, upload-time = "2026-10-22T11:55:39.969Z" }, + { url = "https://files.pythonhosted.org/packages/e3/5c/ea5472e8444f5871427f3a6818725684fcdce74223ca1b22aa7ca345d490/pandas-3.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:07807035ad66de0d833d68f9bee05801dbf08b88d56a233b0e9fd189372c3261", size = 10729719, upload-time = "2026-10-22T11:55:42.008Z" }, + { url = "https://files.pythonhosted.org/packages/45/f7/8cdd350c67bc62865d1e30cd7add43dd631420223487ba42dfcfd0d0e052/pandas-3.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:54fed4a50b8321ff8d413b46b7e31a023cecefd06c7210c02aa980a9836428b2", size = 10116651, upload-time = "2026-10-22T11:55:44.367Z" }, + { url = "https://files.pythonhosted.org/packages/c3/a9/e82d44fe20dc61dd2e15bdd17c78aa0023d860d55620e4fe82f9e644a089/pandas-3.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a8c44d40cbb6d00128bf2d8f8bb66c8d561744b6d44686b5a1a01f3b3fd1245f", size = 11675868, upload-time = "2026-10-22T11:55:46.617Z" }, + { url = "https://files.pythonhosted.org/packages/83/38/6be618d98e2cbbb99a40349717532f0c2b6794ddc62f1199e3f83e45a40f/pandas-3.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:89b66823678cdd53cf97187e7cd6861402bdd147d11a383706093136a4e83f45", size = 11262553, upload-time = "2026-10-22T11:55:49.143Z" }, + { url = "https://files.pythonhosted.org/packages/06/5c/66e27fb0d691e835bd55b336bdf47312a541a66a17ba4d72a988d743bb79/pandas-3.1.0-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2a8dc7780720b9e2182799ee86279d4cc7d1fd30b230ea1b202da5b6f7e14c3a", size = 11548155, upload-time = "2026-10-22T11:55:51.674Z" }, + { url = "https://files.pythonhosted.org/packages/37/1e/42e81484c5a6791ab1b8c52c1ff1ef0483c119f710ed58ee603d241b8792/pandas-3.1.0-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4455cdcc03e42c17233184e8e4ea65c3ed2925d8b1d9d7dd8e6fced3f6e43c1", size = 12029136, upload-time = "2026-10-22T11:55:53.823Z" }, + { url = "https://files.pythonhosted.org/packages/cd/c9/a3b4fd156457f3eb2585838cd56427a113eeeba679204de435a3224b8cc3/pandas-3.1.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:224a9267e5fa70c16bf4f8a317435eef98387940ce6c8c611f1f68f2c3415e10", size = 12575350, upload-time = "2026-10-22T11:55:56.006Z" }, + { url = "https://files.pythonhosted.org/packages/4e/25/23a017003d792117b297bbd87e35a1bb5658509f610ecd5aeaebb84762aa/pandas-3.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c261c7a808982557c2917d40ffd27916769f26aacb4e6775c01e4467bcd34c3b", size = 13096142, upload-time = "2026-10-22T11:55:58.434Z" }, + { url = "https://files.pythonhosted.org/packages/1c/d2/f4074b7d1234d112aaa23a796be1574441a9fa873707eb98312a237a6185/pandas-3.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:e77112cfcabb3bef7281a72170670db9a5b31409a1cd3199939abb1fba67a7ad", size = 10885958, upload-time = "2026-10-22T11:56:00.895Z" }, + { url = "https://files.pythonhosted.org/packages/25/9f/bcfc9e0ea07f5c7583e129e62cd0529747317977ac1b85878b80235bb322/pandas-3.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:6c51273b89784c9d54020ed2f60e20524169aef349bddf6cba9f5e83b46077a7", size = 10281257, upload-time = "2026-10-22T11:56:03.478Z" }, + { url = "https://files.pythonhosted.org/packages/05/e4/b3bf0b702c0a886e4abcfc2ebdc681310498592a10d9ca0ce5db6df47b70/pandas-3.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:84377fa82d0b40165379a0058d8a1a267ceb09e65160de6fcc75475d4d595884", size = 12134028, upload-time = "2026-10-22T11:56:05.696Z" }, + { url = "https://files.pythonhosted.org/packages/3e/ff/9e08cf048d73f4dfdb10da859790cd1a4213465dec39ea367a606d580c4a/pandas-3.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:37f88576f3449bfd86c1052f6b42274b61d7250c8d9dcc55f9dc4de7fe9883ae", size = 11729164, upload-time = "2026-10-22T11:56:08.335Z" }, + { url = "https://files.pythonhosted.org/packages/1f/ff/a0df60d70fac10006841457c30d35647ae0c93af33e420e5e047b15e058d/pandas-3.1.0-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:756fd67995f3efb6b25f8eaea95c0e893f84e0068e2c53c5fdbb65275041d4db", size = 11413041, upload-time = "2026-10-22T11:56:11.38Z" }, + { url = "https://files.pythonhosted.org/packages/55/04/e6742d85ba7d166a1a8a99ff9f4aa9e585fb24028522daa187859ce50b5d/pandas-3.1.0-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c4d9252b57bded194d09cd5ebf18d9b4edac238b16f56984ea8281d2ecfe39cd", size = 11869427, upload-time = "2026-10-22T11:56:13.637Z" }, + { url = "https://files.pythonhosted.org/packages/0a/a1/c9f4915408ef10b541f31b7812ca038dd903572c163b7be7bdcece8a5110/pandas-3.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:461b79db058639e446ddf90dd7f4804fae385acf0669f6e31321333e14cb6bc5", size = 12430367, upload-time = "2026-10-22T11:56:15.829Z" }, + { url = "https://files.pythonhosted.org/packages/9f/ed/636b9cc8d30b3e2027b43036dd5a8e9e7cfdd5aa86f4454235c5ef7f96db/pandas-3.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bfac077874a396b7ae61a307b27aa6f0256cf31c143b7f96ac622765754cc300", size = 12945204, upload-time = "2026-10-22T11:56:18.419Z" }, + { url = "https://files.pythonhosted.org/packages/e6/5e/5c28942fa8c6cf2d8b4e941abee43a44ba0a123f9fef6411f0319aefddd5/pandas-3.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:1340f823a1d189fae8365de314c4d3c2ea0173c61bca66cc76a91385c64d9d3d", size = 11297553, upload-time = "2026-10-22T11:56:20.934Z" }, + { url = "https://files.pythonhosted.org/packages/cd/a4/5991dfb2cccd233ae754f2fb37a4b1474d90595d83f6790467dc5a7d8041/pandas-3.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2bb3f8cc42fae0c0de5186778f4a4957656b9b3955aca48383abfdac44a83598", size = 10626068, upload-time = "2026-10-22T11:56:23.187Z" }, + { url = "https://files.pythonhosted.org/packages/77/26/5cd42609d8e6cb3991242116a0e499d09f29f5bcf574f72f0a4aba13a87e/pandas-3.1.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:04ca88727dfa86837030c493d7512bb1c008aa4f5f14149c5f8d3ff446791340", size = 11666949, upload-time = "2026-10-22T11:56:25.842Z" }, + { url = "https://files.pythonhosted.org/packages/97/5f/ca1ac99da700c215c52fb0f5063a7fbf14878c6e100f687704c21985640e/pandas-3.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:c0bfec4d188fb0c05bba47b9f9def87624b8c545913aa3585a28f19f27ce847e", size = 11255062, upload-time = "2026-10-22T11:56:28.201Z" }, + { url = "https://files.pythonhosted.org/packages/d3/eb/8d7aef062e7d1f48869288e5c5ae5d109923f37ed3bbd0fdcaecc87784e9/pandas-3.1.0-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bbfb087db83eb79ca348047961d367bdd4bf9820d90a5945f3652c7060da7363", size = 11547558, upload-time = "2026-10-22T11:56:30.492Z" }, + { url = "https://files.pythonhosted.org/packages/06/c4/a041c786bc29935afe44806f72c0111f2643cbac5cab761007a227e12e97/pandas-3.1.0-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b5ce18612ca955e7a95d0bacc20120aedf97e2fbbebbe4de029fc24479e79b8", size = 12026259, upload-time = "2026-10-22T11:56:33.219Z" }, + { url = "https://files.pythonhosted.org/packages/d3/4a/ce6690c7e6081c96857ad7dcbe3b978394d8db682610755919e61863516f/pandas-3.1.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:a13199463b129363701a540c7b79586581b246b10b6a7ad682c41b268e7991d5", size = 12563821, upload-time = "2026-10-22T11:56:35.402Z" }, + { url = "https://files.pythonhosted.org/packages/75/ec/ae440ecbfa8f5ba0230541b4519c1fed0c4293ff362f18f7f353b12e2dca/pandas-3.1.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:8e4de3fe8017e3445f1174707cd977e4e1154a704af2c060a1f648862f81acb9", size = 13086426, upload-time = "2026-10-22T11:56:37.666Z" }, + { url = "https://files.pythonhosted.org/packages/e7/1e/6459d4b0ed9c3d72b9ab63387ec11e1e658579e702e0ef117be8b5d7d0d1/pandas-3.1.0-cp315-cp315-win_amd64.whl", hash = "sha256:eee72bba8a72f0bf9522132e5c87cd10fce9d77440b50f65326b093ec9fb8d43", size = 10877850, upload-time = "2026-10-22T11:56:39.994Z" }, + { url = "https://files.pythonhosted.org/packages/f5/22/e5fad1828e5f923e80a8d7ba9187f687159004a10f99f95dd5346b04c54e/pandas-3.1.0-cp315-cp315-win_arm64.whl", hash = "sha256:9ea2983fe096a3d997c8c4b9f26775fa51e7fb251b10634bd7f87e6fe3542d52", size = 10276384, upload-time = "2026-10-22T11:56:42.193Z" }, + { url = "https://files.pythonhosted.org/packages/59/76/89820c2e1950425f39d30695d2296a8c7d400c4c2d279e7618363a7289ac/pandas-3.1.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:84d73e0814a38711e4f2a24b272f748a0b4335169d2f9752407ae26bde22990f", size = 12107257, upload-time = "2026-10-22T11:56:44.498Z" }, + { url = "https://files.pythonhosted.org/packages/c8/2c/af4397e6e855d2c0dcb3392ab7788087be4ef53f6a3f166daad8b83c783e/pandas-3.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d3920d9b4de89fbef76ba6b863d58a330b5bfb720c9f8f58eb9b7da9b711d034", size = 11704430, upload-time = "2026-10-22T11:56:46.791Z" }, + { url = "https://files.pythonhosted.org/packages/fd/9e/7791cd269099f9fca7dc4718955cfe4bb94aedb6634b59eeffefb1ed6a74/pandas-3.1.0-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1d61e0eae5219cd024fcbc21304de759964b5642ddcdbb28d9a8ba442ab6901", size = 11378442, upload-time = "2026-10-22T11:56:49.113Z" }, + { url = "https://files.pythonhosted.org/packages/54/6c/da4013bd33c49a12eb3127771111caeed3222a985651e3465bc06f839ce7/pandas-3.1.0-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bbb121205af7bc5e587b94a07b5f67b5ba687a918665b9e8748f21388a88b044", size = 11850193, upload-time = "2026-10-22T11:56:51.558Z" }, + { url = "https://files.pythonhosted.org/packages/14/89/8c820bd6fb6ad8f0edb2877639bc7e164bfb4b8e4cdf7a2202f54959ea1b/pandas-3.1.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:684ef3add5a92abb99c1622f2bd04b54b8843075a266e8240106ca94ce1d1237", size = 12394022, upload-time = "2026-10-22T11:56:53.785Z" }, + { url = "https://files.pythonhosted.org/packages/92/f5/9d753d85c4ea85b6d1c3735496ae5b416d7ef6905f1845c70e9521d124d9/pandas-3.1.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:dde9a55ecd3c4f9100ac50ab15e852e4c54fcf372d800e4495e0b2159a0122ab", size = 12916085, upload-time = "2026-10-22T11:56:56.084Z" }, + { url = "https://files.pythonhosted.org/packages/e6/f9/4a6965677477dbbb19f8881befb01b67eb6009809db73f7f1b7a0132faf1/pandas-3.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:3fe234bfb9999552dc54c45851752e56e163218d7663897dca950b4a7c32af39", size = 11267097, upload-time = "2026-10-22T11:56:58.479Z" }, + { url = "https://files.pythonhosted.org/packages/99/35/e60fd8228db4eb848802988dbc6e3a0f1a81c57f06ad95ebe4cd534fa655/pandas-3.1.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f1a93c24175129bfc9922ef748ddae1d8137c743ed835e2615be329f606fed4d", size = 10597861, upload-time = "2026-10-22T11:57:00.776Z" }, +] + +[[package]] +name = "pandas-stubs" +version = "3.0.5.260914" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c1/93/8948ae6c1e1e3d6833596fd266f7be2d27c1451b8be094975ad42c5e842e/pandas_stubs-3.0.5.260914.tar.gz", hash = "sha256:3f6fc1f147f68fd89c007105e7c94a948acb4ecd7eb20dc1c02e153c4ed5c250", size = 117622, upload-time = "2026-09-14T16:42:35.065Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/cb/5ad79e02a556cc23fed5816de0109fa8af660c66cfa5f4af74c3e8d4cd26/pandas_stubs-3.0.5.260914-py3-none-any.whl", hash = "sha256:39a1300c5c5c55fdf609e3476805decce5d5015539a4dcb683449f8feaeee2fb", size = 177344, upload-time = "2026-09-14T16:42:33.771Z" }, +] + +[[package]] +name = "pandera" +version = "0.35.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, + { name = "pydantic" }, + { name = "typeguard" }, + { name = "typing-extensions" }, + { name = "typing-inspect" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ca/44/a996e575da4f1adec5a4ff16eb43d69d0125901315ca9ac9613ac3b61009/pandera-0.35.0.tar.gz", hash = "sha256:d2d11bbf9b4dd19c227caf31ac57ac28a679bbe18577f9496dcf809143232389", size = 1132618, upload-time = "2026-10-25T02:33:03.012Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/29/17/239d1e64d290c26f126582445649bc7c925a7a80f2472b8bd04d6ec22f8d/pandera-0.35.0-py3-none-any.whl", hash = "sha256:ce5cab5e882480d07575361899a4140585b80c489410cf97b7ef6e8aa90de3b6", size = 557083, upload-time = "2026-10-25T02:33:01.376Z" }, +] + [[package]] name = "pathspec" version = "1.1.1" @@ -762,6 +952,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" }, ] +[[package]] +name = "python-dateutil" +version = "3.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0e/df/f15f80383f152452d8985b36d95cb8751f901a3e0ff4cd27f7e118f168e2/python_dateutil-3.0.0.tar.gz", hash = "sha256:7ebcb3c29a92f3ceafe79a7a48a5c45677e9e004bbeec5742ac0bbb00560b7a2", size = 271066, upload-time = "2026-10-21T23:41:45.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5a/17/cebee01d1c0c1441174cf0456ddc91b280d79acb65340c05e41d77866ee8/python_dateutil-3.0.0-py2.py3-none-any.whl", hash = "sha256:3c79630202e4152c6add678446984236efe4f57e84d8e892aab0637bab82e9fd", size = 94659, upload-time = "2026-10-21T23:41:43.431Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.4" @@ -796,6 +999,57 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/60/a3604c79cb02777b6cb84da894104021986f06c4bc41375102cc95049a32/ruff-0.17.2-py3-none-win_arm64.whl", hash = "sha256:195ad918027f817c119310ca89a42d347887dfc28934aaa869325e9c5dc9d962", size = 9827036, upload-time = "2026-10-22T18:37:58.031Z" }, ] +[[package]] +name = "scikit-learn" +version = "1.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "narwhals" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d2/eb/eaf5e07fcc0da7149b0e084f24e54edd7441b9a89ce7e034032ae97fe3a0/scikit_learn-1.9.1.tar.gz", hash = "sha256:629cada3e33e2b9bf376cdc7614a47a4140b8aedc1d836579e359736fbd82977", size = 7786908, upload-time = "2026-09-10T18:34:04.679Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/a7/25f0a43d2fde306e8ef45f45121192f687b79beaf4bae8c21607c46c5e63/scikit_learn-1.9.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0c0f8b5d09b44101cea2767f300680bada1ea27f976fe4b48b83950a4f55a49a", size = 8775209, upload-time = "2026-09-10T18:32:42.804Z" }, + { url = "https://files.pythonhosted.org/packages/60/ea/57e57539ce175d774fc291ed091b0a6d756854b92cd92554c6bb4d0ae498/scikit_learn-1.9.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:8c14ce41d561f7749f990b41d6703fe02c4669fbc485e598e069e0a1967b488e", size = 8295541, upload-time = "2026-09-10T18:32:45.069Z" }, + { url = "https://files.pythonhosted.org/packages/78/2b/5721a174406bfba49bce20ae997b3b64cf355c3f623a2638284ab6a82156/scikit_learn-1.9.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e4c20a6c017d820faa7ac8c783e3d0c6a9a2e297bf9f55332ca17cdf7fd4d04d", size = 8871592, upload-time = "2026-09-10T18:32:46.999Z" }, + { url = "https://files.pythonhosted.org/packages/8e/57/a50162f3d29feb979ab6347c6debda506dfb525bcff3c50dd17606651c7e/scikit_learn-1.9.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e5d7b18a5b9dca241a74695f3275fa4c895a9dadc72b3d8df5fa9d1083c9b83e", size = 9166043, upload-time = "2026-09-10T18:32:49.343Z" }, + { url = "https://files.pythonhosted.org/packages/72/8d/27c054166bac671770d1ea0ef7716134fe8119c0df224a58c89fd735a61c/scikit_learn-1.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:4b59abb30618121cc46b45972d6bf53a7128b4df4cd346c6ca6f4d5f9031e49c", size = 8262238, upload-time = "2026-09-10T18:32:51.679Z" }, + { url = "https://files.pythonhosted.org/packages/9d/d6/493086006ea0c68ad62c40a8dece1961b61bf503f45400f133d47f56e5be/scikit_learn-1.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:d5945a2908be62350e2978344e62b56c1552c2ca4f844ebf6277c94944d647dd", size = 7902102, upload-time = "2026-09-10T18:32:53.67Z" }, + { url = "https://files.pythonhosted.org/packages/bb/8d/b60d5e7354ff0ff5cc9400e60273696589d87a30b8b2235886a76d80d062/scikit_learn-1.9.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c2b312fd8c02951a364fa120ea08c1cec10d863466bf1701b013152d7537835", size = 8739300, upload-time = "2026-09-10T18:32:55.483Z" }, + { url = "https://files.pythonhosted.org/packages/2f/81/3c6392c03665d2899457a76e535a9a6f597dddddf3220fd2e1d790da88c5/scikit_learn-1.9.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:61cd968ab831a76d0ecbaf0347ab2270268716da28f94fd022497e3d6f205f13", size = 8262364, upload-time = "2026-09-10T18:32:57.966Z" }, + { url = "https://files.pythonhosted.org/packages/0f/35/a15b8653499692879821301d48059376d6e68e8b65cd0f22d19b6ee83cd9/scikit_learn-1.9.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5990f9c69e431bfaddcde1a6d7c5355243e026bc9b9e560c13893b90dab53fb4", size = 8823698, upload-time = "2026-09-10T18:33:00.632Z" }, + { url = "https://files.pythonhosted.org/packages/23/e5/688703d357e5393f708d98eb189fd415ae69e39f6de03c6bd4005aef6118/scikit_learn-1.9.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:55e79d6e9b0923f1a978179822bd43d7f5543f45e970a00fe861f43486380aba", size = 9121732, upload-time = "2026-09-10T18:33:02.825Z" }, + { url = "https://files.pythonhosted.org/packages/96/45/a10add34c08184d373be9384660c75758128ca881ed27b503b6f6a742478/scikit_learn-1.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:2070f271e5375dc42c6bb93b461ab1c0aa5841d4009267e0cfd95a39dca94a43", size = 8237244, upload-time = "2026-09-10T18:33:05.26Z" }, + { url = "https://files.pythonhosted.org/packages/9e/08/7a89bcdadd1fff0d464d01056417b646c9abcbc54f7297a0a1203bba5ebb/scikit_learn-1.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:613f0a783ca05aa844a4e1ac42d48425058f2c52be73f40f8cd98b7cd111acd6", size = 7875398, upload-time = "2026-09-10T18:33:07.506Z" }, + { url = "https://files.pythonhosted.org/packages/64/e3/b58e45082dcf3dcf0eb1192ee03545ec43d8c98441dfe20e88afca8442ce/scikit_learn-1.9.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d5d117952769b563067656784e03c75a2d8235a7a05cf7fffa78a311e75aac08", size = 8747414, upload-time = "2026-09-10T18:33:10.698Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ed/d68115577c8b42b0442ebd8180945d4008880a33176094640e00b585128e/scikit_learn-1.9.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:8893bc6331f60f18d4ac75e12ed356e2dcf6a564bf767918b5b7ca54c8c8be49", size = 8279175, upload-time = "2026-09-10T18:33:12.846Z" }, + { url = "https://files.pythonhosted.org/packages/c4/6c/06c7eb61a438e389cbf3f7210897069bec5a883dbe03c189ae792781e11a/scikit_learn-1.9.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5492cf2df5226691c32611de8734bcf42148c6547ae53c7f4e6b847793addc0", size = 8881706, upload-time = "2026-09-10T18:33:14.741Z" }, + { url = "https://files.pythonhosted.org/packages/86/4e/0bab75490ca4b85fad8388739c7ebc71d9db553f8c69e39943ee8db0aaae/scikit_learn-1.9.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:993d332ff80e62efae9e39603b7e872297c418d780f01a01855269a3489c950f", size = 9152030, upload-time = "2026-09-10T18:33:17.436Z" }, + { url = "https://files.pythonhosted.org/packages/9a/13/31c6f8ba1b7eecef9dd9558576c752d2ec5785fd0e456bb9fc59305be23f/scikit_learn-1.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:ca9051447455dae341d4d591eece7deb2d8e3d1020298fc87a81fc51e4da8f53", size = 8377024, upload-time = "2026-09-10T18:33:19.941Z" }, + { url = "https://files.pythonhosted.org/packages/62/e6/6d3cb8a45f5228f915acd66b819dd6b8232ccbe24532f51d278e3991df31/scikit_learn-1.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:90de6573f733a9fb79476ff1371af52a397d41c8b35f9146e20923db010d67b6", size = 8014196, upload-time = "2026-09-10T18:33:22.126Z" }, + { url = "https://files.pythonhosted.org/packages/66/6e/6befb2d5961490d18d9dbc16a5df37aa121d08bc9893316a6a363977a903/scikit_learn-1.9.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b5cad1624de8b75e5b9ccb7b0ce1ff1d01306340a3efc56d5529c5ba92392eb", size = 9066066, upload-time = "2026-09-10T18:33:24.396Z" }, + { url = "https://files.pythonhosted.org/packages/cb/18/11271f2f7db337db01f598e358721b1e83989407131272e5dd64214c28a8/scikit_learn-1.9.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:d137ce8a6142029fb5c35bd82f470c40cd9e760e5e2f7694b362c497c4ab3fa2", size = 8647654, upload-time = "2026-09-10T18:33:26.649Z" }, + { url = "https://files.pythonhosted.org/packages/e7/04/9c15d201e1b6a2e81b8215865df7646c5a360f560831769c8dc92ac1ab9a/scikit_learn-1.9.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:66f852f7325b5070bc28329005aca76055a2def78faac039548ae889aeaa45a6", size = 8889070, upload-time = "2026-09-10T18:33:28.95Z" }, + { url = "https://files.pythonhosted.org/packages/1a/5a/4cb6c85160af4a639e87a3b7bf8b1c25cfc3b504c5af710ca416a6dcfc5f/scikit_learn-1.9.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:748bcb0a4cc04aec470652c9e5ec68450948e867387e7dfade647107ade68d25", size = 9131227, upload-time = "2026-09-10T18:33:31.008Z" }, + { url = "https://files.pythonhosted.org/packages/00/0e/361440972ae3d19b90ea88a84791138a51de0e8432a770ba741b2c8d9ced/scikit_learn-1.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:38cd925e893e5539be704d5edc64dbe081aacdab6b89d8c2977c1f6a7a453ce5", size = 8683001, upload-time = "2026-09-10T18:33:33.188Z" }, + { url = "https://files.pythonhosted.org/packages/e2/8f/a9f405c5c0e2df6f343a871b40c97fb32969e3ccc38e3033dd118f3c261e/scikit_learn-1.9.1-cp314-cp314t-win_arm64.whl", hash = "sha256:b01e5b01735d38474127ca3f49319b592506225a87793b27559816b5c75cea39", size = 8257996, upload-time = "2026-09-10T18:33:35.343Z" }, + { url = "https://files.pythonhosted.org/packages/e5/c5/74a83ea39cef7cd07f53e06cc1cf51e79f35df74f81db956835d59ec34b1/scikit_learn-1.9.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:8dec64f31a6e0ec826aca6c1b39a51e16d946e400d4c0904316f3ca72ccfb825", size = 8747991, upload-time = "2026-09-10T18:33:37.4Z" }, + { url = "https://files.pythonhosted.org/packages/64/c9/cc93e8a7fe204e43d70e96e5eb89871643be20025eea05eb4fdaf19afe39/scikit_learn-1.9.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:e1b468241f4a7a9a7a0d6479ad3cc47681cc151a4046c530f2777c3d68f08942", size = 8279340, upload-time = "2026-09-10T18:33:39.705Z" }, + { url = "https://files.pythonhosted.org/packages/a2/61/0c6080f0d356fb966053009e7f25e9bff6cf74b0b16195ccf0c3757d1ae8/scikit_learn-1.9.1-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ca869d0080a5723cde2d5a8b54a2da1ff7e68735a9e9adb3da1243183a0fa01", size = 8881917, upload-time = "2026-09-10T18:33:41.912Z" }, + { url = "https://files.pythonhosted.org/packages/47/bb/98a31f10fffbd39edcc2f8bf4119b29652248bb110b7d45c84e68aa293ab/scikit_learn-1.9.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6754b7cabfc3df0b1f7b38f7a344f559bbae9d82f0ac5e3d48cccbd19fdcefdf", size = 9152805, upload-time = "2026-09-10T18:33:44.23Z" }, + { url = "https://files.pythonhosted.org/packages/f6/48/858ceff52213cfd97c0a069362071756bcb70b9fac9771b38d87c4cf7f17/scikit_learn-1.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:52cfdb1fed3a34362dbc0bd96f2e761a66fd5724d6901629f5a558f1f3bd9849", size = 8376719, upload-time = "2026-09-10T18:33:46.492Z" }, + { url = "https://files.pythonhosted.org/packages/2a/1e/5337a871bdea53effbd154b61429df048f2665653251de74a3bd8a6dea9e/scikit_learn-1.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:ae6571a4828c6f5019bcd2b4125e5b18c0af3dbc9c99726c891f45f41335ec8e", size = 8014341, upload-time = "2026-09-10T18:33:48.762Z" }, + { url = "https://files.pythonhosted.org/packages/0e/35/150383a42d83ec4c7b39f9c50bd68408ecf04c19fc30ea5198fa42e67d9c/scikit_learn-1.9.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:48fefd8eb42bd4eec3e2d348149368ccd6d71987e20c30706a56a24eb86a6e73", size = 9059953, upload-time = "2026-09-10T18:33:50.951Z" }, + { url = "https://files.pythonhosted.org/packages/9f/dd/aa0d738808540f7eaacfab93e01982db8ef1c1c7473ef0ad38193e6aebd1/scikit_learn-1.9.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:09f4d73049cd63575157f6b1060e06a8c83a4bd3488dbfaeedf35ccba7aad712", size = 8646602, upload-time = "2026-09-10T18:33:53.23Z" }, + { url = "https://files.pythonhosted.org/packages/7e/cc/687ae4214c2f598906c3b9fa5f86fbaf834b35e20360625528ff1b713f06/scikit_learn-1.9.1-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b3da53831534214322d9cb240fa6f390b36cf69eba727a6d4bd3238677630d70", size = 8880366, upload-time = "2026-09-10T18:33:55.764Z" }, + { url = "https://files.pythonhosted.org/packages/c2/03/82215cb78ad1c513a4498777571fb28444621ad26ef636287551767b7732/scikit_learn-1.9.1-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:caae15634feceafa2612566b109a3082d3293167fac388eedaf77bff66b51983", size = 9129640, upload-time = "2026-09-10T18:33:58.186Z" }, + { url = "https://files.pythonhosted.org/packages/d4/90/4b7af4efd7909a4a0524a9f18457e4eb2eb60616eff2c7627eda8e3cdceb/scikit_learn-1.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:ffbcbbbb44202fbe9bc64bced25a145759adb9ef010b3d37a8064958ac13df2a", size = 8678083, upload-time = "2026-09-10T18:34:00.354Z" }, + { url = "https://files.pythonhosted.org/packages/31/27/068e484d4b83004302e0d9cfc1faca69bcc010d76fbb66a642446095af1b/scikit_learn-1.9.1-cp315-cp315t-win_arm64.whl", hash = "sha256:800dd22dd87fe97dcea484c24e85dd93cf1734d86bd74e668ad18f7967f4d1b5", size = 8259434, upload-time = "2026-09-10T18:34:02.678Z" }, +] + [[package]] name = "scipy" version = "1.18.1" @@ -879,6 +1133,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/27/53/9b6dff8225ef3dbc203b1c2329d9efb2b66dfd51d5c2bf048c0676f47731/scipy_stubs-1.18.1.1-py3-none-any.whl", hash = "sha256:1a48be1702cad1ae9aa850c62ed157c988d990305880511d0e38994d502664f4", size = 665244, upload-time = "2026-09-20T22:37:37.029Z" }, ] +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sqlalchemy" version = "2.1.6" @@ -964,6 +1227,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f3/93/181df62699d9b5aca1d87e5cfda131dac87e3cdaebf668662f7206ca3470/starlette-1.9.0-py3-none-any.whl", hash = "sha256:fd3f159936e882d06c1108f84688f7cda2cf85fc6a592a50edbd175e882c2ddc", size = 80335, upload-time = "2026-10-18T15:50:31.526Z" }, ] +[[package]] +name = "threadpoolctl" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/00/dc/6c58154c1c65f758ea979e7139cb76993a9cfc662d14e9be3c4a667cfb77/threadpoolctl-3.7.0.tar.gz", hash = "sha256:61348cfb77d53b9242e0017029244b559b810c142ced65b4e21eeca1843959a7", size = 31961, upload-time = "2026-09-15T15:46:20.263Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/3f/f88a53f60a472b46f4023f56d204dd7de33d34c5d2acbfa0d70a674e639e/threadpoolctl-3.7.0-py3-none-any.whl", hash = "sha256:cd8b60b5641b45c67bbf73c64c843235fc2d8a480c87389f52f5dbee893b86be", size = 26362, upload-time = "2026-09-15T15:46:19.168Z" }, +] + +[[package]] +name = "typeguard" +version = "4.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/de/4420db493fa8fc0856d5e5c1b159c63a323d2de2317babe36b01568928e8/typeguard-4.6.0.tar.gz", hash = "sha256:e7414f09111317de3e335de92cd397c5c0ca00b1cc1676de12e1d444a79b3f21", size = 82330, upload-time = "2026-07-26T08:40:23.207Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/eb/461d5f167b6f5c7d97696f397c82f82e3480e003fce3f0a1cd1dd26e2eb2/typeguard-4.6.0-py3-none-any.whl", hash = "sha256:79878165bb86f2cf5d41d159a0ff1792a796cf496882d2fe1b1c6c7049b9cdd7", size = 36884, upload-time = "2026-07-26T08:40:21.868Z" }, +] + [[package]] name = "typing-extensions" version = "4.16.0" @@ -973,6 +1257,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] +[[package]] +name = "typing-inspect" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mypy-extensions" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dc/74/1789779d91f1961fa9438e9a8710cdae6bd138c80d7303996933d117264a/typing_inspect-0.9.0.tar.gz", hash = "sha256:b23fc42ff6f6ef6954e4852c1fb512cdd18dbea03134f91f856a95ccc9461f78", size = 13825, upload-time = "2023-05-24T20:25:47.612Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/65/f3/107a22063bf27bdccf2024833d3445f4eea42b2e598abfbd46f6a63b6cb0/typing_inspect-0.9.0-py3-none-any.whl", hash = "sha256:9ee6fc59062311ef8547596ab6b955e1b8aa46242d854bfc78f4f6b0eff35f9f", size = 8827, upload-time = "2023-05-24T20:25:45.287Z" }, +] + [[package]] name = "typing-inspection" version = "0.4.4" @@ -985,6 +1282,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + [[package]] name = "uvicorn" version = "0.54.0" From e9b49f1795e45b3b4770758496f7256f67b9c46f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Thu, 29 Oct 2026 08:48:31 +0300 Subject: [PATCH 02/92] feat(ml): shadow-mode scoring, monitoring, registry and tests - Shadow scoring (CRYPTOGUARD_ML_SHADOW=shadow, off by default): POST /api/v1/ml/transactions/score and GET /api/v1/ml/status; 409 feature_disabled when off, 503 ml_unavailable without the extra or a promoted model; only a transaction hash is accepted; never findings. CLI: ml promote / score / monitor. - Registry: promotion only if the run's gate passed; the pickled model loads only when its SHA-256 matches its model card. - Monitoring: population stability index of shadow-scored features against per-bin training shares (ties handled). - Splits: hubs are now a curated public-infrastructure registry only. The degree-based rule let a scam contract with many victims count as public infrastructure, so its later victims reached the test split (caught by a new leakage regression test). Over-linking only costs evaluation rows; under-linking leaks. - Gate: requires closing half of the validation AP gap to 1.0 (the first version, +0.05 AP, was unsatisfiable above a 0.95 baseline); model and hyperparameter selection by validation log loss (AP saturates). - Collector: request ledger written after every transaction. - Tests: features (point in time), labels, source integrity, sampling, split leakage, collector cap/resume, deterministic training smoke run, registry refusals, PSI, API opt-in and findings isolation; CI installs the ml extra from the wheel. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 9 + src/cryptoguard/api/app.py | 2 + src/cryptoguard/api/ml_routes.py | 62 ++++++ src/cryptoguard/core/config.py | 7 + src/cryptoguard/core/errors.py | 7 + src/cryptoguard/ml/cli.py | 44 ++++ src/cryptoguard/ml/collect.py | 4 +- src/cryptoguard/ml/dataset.py | 50 +++-- src/cryptoguard/ml/inference.py | 108 ++++++++++ src/cryptoguard/ml/monitoring.py | 73 +++++++ src/cryptoguard/ml/registry.py | 72 +++++++ src/cryptoguard/ml/train.py | 53 +++-- tests/integration/test_ml_api.py | 138 ++++++++++++ tests/ml_synthetic.py | 137 ++++++++++++ tests/unit/test_ml_features.py | 144 +++++++++++++ tests/unit/test_ml_pipeline.py | 346 +++++++++++++++++++++++++++++++ 16 files changed, 1217 insertions(+), 39 deletions(-) create mode 100644 src/cryptoguard/api/ml_routes.py create mode 100644 src/cryptoguard/ml/inference.py create mode 100644 src/cryptoguard/ml/monitoring.py create mode 100644 src/cryptoguard/ml/registry.py create mode 100644 tests/integration/test_ml_api.py create mode 100644 tests/ml_synthetic.py create mode 100644 tests/unit/test_ml_features.py create mode 100644 tests/unit/test_ml_pipeline.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af9f5bc..d7f39e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -159,6 +159,15 @@ jobs: wheel=$(ls dist/*.whl) uv pip install --python "$RUNNER_TEMP/cg-analytics" "${wheel}[analytics]" uv run --no-project python scripts/smoke_install.py --venv "$RUNNER_TEMP/cg-analytics" --analytics + - name: Clean install with the experimental ml extra + run: | + uv venv --python 3.12 "$RUNNER_TEMP/cg-ml" + wheel=$(ls dist/*.whl) + uv pip install --python "$RUNNER_TEMP/cg-ml" "${wheel}[ml]" + cd "$RUNNER_TEMP" + if [ -x cg-ml/bin/python ]; then py=cg-ml/bin/python; else py=cg-ml/Scripts/python.exe; fi + "$py" -I -c "from cryptoguard.ml import ml_available; assert ml_available()" + "$py" -I -m cryptoguard.cli ml --help - name: Keep the distributions if: matrix.os == 'ubuntu-latest' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/src/cryptoguard/api/app.py b/src/cryptoguard/api/app.py index 0daaea2..1dcf41f 100644 --- a/src/cryptoguard/api/app.py +++ b/src/cryptoguard/api/app.py @@ -20,6 +20,7 @@ from cryptoguard import __version__ from cryptoguard.api.campaign_routes import router as campaign_router from cryptoguard.api.history_routes import router as history_router +from cryptoguard.api.ml_routes import router as ml_router from cryptoguard.api.ratelimit import TokenBucketLimiter from cryptoguard.api.replay_routes import router as replay_router from cryptoguard.api.schemas import ( @@ -338,6 +339,7 @@ async def _unexpected_error(request: Request, exc: Exception) -> JSONResponse: app.include_router(history_router) app.include_router(replay_router) app.include_router(campaign_router) + app.include_router(ml_router) return app diff --git a/src/cryptoguard/api/ml_routes.py b/src/cryptoguard/api/ml_routes.py new file mode 100644 index 0000000..b16c6f2 --- /dev/null +++ b/src/cryptoguard/api/ml_routes.py @@ -0,0 +1,62 @@ +"""Experimental ML endpoints (``CRYPTOGUARD_ML_SHADOW=shadow``). + +With the setting ``off`` (default) both endpoints answer 409 ``feature_disabled``. Scores are +returned for review and logged for drift monitoring only: nothing here writes findings, +severities or snapshots. The RPC endpoint is the operator's configured provider; requests +carry only a transaction hash. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from fastapi import APIRouter, Request +from pydantic import BaseModel, ConfigDict, Field + +from cryptoguard.api.state import get_state +from cryptoguard.blockchain.provider import RpcEthereumProvider +from cryptoguard.core.errors import MlUnavailableError +from cryptoguard.ml.inference import ShadowScore, loaded_model, score_transaction +from cryptoguard.services.providers import require_provider + +router = APIRouter(prefix="/api/v1") + + +class ScoreRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + tx_hash: str = Field(pattern=r"^0x[0-9a-fA-F]{64}$") + + +class MlStatus(BaseModel): + experimental: bool = True + run_id: str + selected: dict[str, Any] + gate: dict[str, Any] + drift: dict[str, Any] + + +@router.post("/ml/transactions/score", response_model=ShadowScore) +async def score(request: Request, body: ScoreRequest) -> ShadowScore: + """EXPERIMENTAL: shadow-mode phishing score for one transaction (never a finding).""" + state = get_state(request) + loaded_model(state.settings) # 409 / 503 before any RPC call + provider = require_provider(state.provider) + if not isinstance(provider, RpcEthereumProvider): + raise MlUnavailableError("ML scoring needs a real RPC provider (not demo fixtures).") + return await score_transaction(provider.client, body.tx_hash, state.settings) + + +@router.get("/ml/status", response_model=MlStatus) +async def status(request: Request) -> MlStatus: + """EXPERIMENTAL: the promoted shadow model, its promotion gate and feature drift.""" + from cryptoguard.ml.monitoring import drift_report + + settings = get_state(request).settings + model = loaded_model(settings) + return MlStatus( + run_id=model.run_id, + selected=model.card["selected"], + gate=model.card["gate"], + drift=drift_report(model.card, Path(settings.ml_score_log_path)), + ) diff --git a/src/cryptoguard/core/config.py b/src/cryptoguard/core/config.py index c3d57e4..58b67dc 100644 --- a/src/cryptoguard/core/config.py +++ b/src/cryptoguard/core/config.py @@ -102,6 +102,13 @@ class Settings(BaseSettings): campaign_runs_retained: int = Field(default=20, ge=1, le=1_000) campaign_expansion_max_requests: int = Field(default=600, ge=1, le=20_000) + # Experimental ML scoring of transactions (needs the ``ml`` extra and a promoted model, + # see ML.md). "off": endpoints refuse. "shadow": scores are returned for review and + # logged for drift monitoring; they never create findings or change severities. + ml_shadow: Literal["off", "shadow"] = "off" + ml_registry_path: str = "data/ml/registry.json" + ml_score_log_path: str = "data/ml/shadow_scores.jsonl" + database_url: str = "sqlite:///./data/cryptoguard.db" # Lifetime of the database lease that makes snapshots (per wallet) and campaign runs # single-flight across processes. Must exceed the longest expected run; an overrunning diff --git a/src/cryptoguard/core/errors.py b/src/cryptoguard/core/errors.py index 6f1a1cb..02c87d4 100644 --- a/src/cryptoguard/core/errors.py +++ b/src/cryptoguard/core/errors.py @@ -147,6 +147,13 @@ class FeatureDisabledError(CryptoGuardError): http_status = 409 +class MlUnavailableError(CryptoGuardError): + """The ml extra is not installed, or no validated shadow model is promoted.""" + + code = "ml_unavailable" + http_status = 503 + + class NoCampaignRunError(CryptoGuardError): code = "no_campaign_run" http_status = 404 diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index fc5c13e..0b9c618 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -32,6 +32,12 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None b.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) t = ml.add_parser("train", help="train, select on validation, test once, record the run") t.add_argument("--report", type=Path, default=Path("ML_EVALUATION.md")) + pr = ml.add_parser("promote", help="make a run the shadow model (only if its gate passed)") + pr.add_argument("run_dir", type=Path) + sc = ml.add_parser("score", help="shadow-mode score for one transaction (not a finding)") + sc.add_argument("tx_hash") + sc.add_argument("--rpc-url", required=True) + ml.add_parser("monitor", help="feature drift of shadow-scored transactions") def run(args: argparse.Namespace) -> int: @@ -77,9 +83,47 @@ def run(args: argparse.Namespace) -> int: return _build(args) if args.ml_command == "train": return _train(args) + if args.ml_command == "promote": + from cryptoguard.ml.registry import ModelRegistryError, promote + + try: + print(promote(args.run_dir)) + except ModelRegistryError as exc: + print(f"error [not_promoted]: {exc}") + return 1 + return 0 + if args.ml_command in ("score", "monitor"): + return _shadow(args) raise AssertionError(args.ml_command) +def _shadow(args: argparse.Namespace) -> int: + import json + + from cryptoguard.blockchain.rpc import JsonRpcClient + from cryptoguard.core.config import Settings + from cryptoguard.ml.inference import loaded_model, score_transaction + from cryptoguard.ml.monitoring import drift_report + + settings = Settings(ml_shadow="shadow") # the command itself is the opt-in + if args.ml_command == "monitor": + model = loaded_model(settings) + print(json.dumps(drift_report(model.card, Path(settings.ml_score_log_path)), indent=1)) + return 0 + + async def run() -> str: + client = JsonRpcClient(args.rpc_url, timeout=20) + try: + return (await score_transaction(client, args.tx_hash, settings)).model_dump_json( + indent=1 + ) + finally: + await client.aclose() + + print(asyncio.run(run())) + return 0 + + TABLE = ML_DIR / "dataset.csv" SPLITS = ML_DIR / "splits.csv" RUNS = ML_DIR / "runs" diff --git a/src/cryptoguard/ml/collect.py b/src/cryptoguard/ml/collect.py index d8b2388..94d976f 100644 --- a/src/cryptoguard/ml/collect.py +++ b/src/cryptoguard/ml/collect.py @@ -88,7 +88,7 @@ def _done(path: Path) -> set[str]: return done -async def _collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: +async def collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: tx = await client.call("eth_getTransactionByHash", [tx_hash]) if tx is None or tx.get("blockNumber") is None: return {"tx_hash": tx_hash, "status": "not_found"} @@ -174,7 +174,7 @@ async def worker() -> None: stats["skipped_budget"] += 1 continue try: - row = await _collect_one(rpc, tx_hash) + row = await collect_one(rpc, tx_hash) except RpcError as exc: row = {"tx_hash": tx_hash, "status": "error", "error": exc.code} async with lock: diff --git a/src/cryptoguard/ml/dataset.py b/src/cryptoguard/ml/dataset.py index d6df417..db0d529 100644 --- a/src/cryptoguard/ml/dataset.py +++ b/src/cryptoguard/ml/dataset.py @@ -1,16 +1,17 @@ """Build the validated modelling table and its manifest from labels plus collected chain data. Rows are grouped by the accounts they tie together (``features.parties``), joined by -union-find. Accounts used by many distinct senders (tokens, routers, marketplaces) are -public infrastructure: they do not join rows, or every row would collapse into one group. -The rule is label-free; ``group_report`` states how much it cuts. +union-find. Only a curated registry of public infrastructure (major tokens, DEX routers, +marketplaces, Permit2) does not join rows. Degree-based rules ("used by many senders") were +tried and rejected: a scam contract called by many victims looks exactly like a popular +router, and exempting it lets its later victims leak into the test split. Over-linking only +costs evaluation rows; under-linking leaks. ``group_report`` states the effect. """ from __future__ import annotations import hashlib import json -from collections import defaultdict from pathlib import Path from typing import TYPE_CHECKING, Any @@ -20,12 +21,25 @@ if TYPE_CHECKING: import pandas as pd -# Public infrastructure (label-free): an account used by at least HUB_MIN_SENDERS distinct -# senders (routers, Permit2), or a log-emitting contract (token, marketplace) touched by -# at least EMITTER_MIN_SENDERS distinct senders. Phishing contracts that victims call -# directly emit no logs and stay linking accounts unless they reach HUB_MIN_SENDERS. -HUB_MIN_SENDERS = 10 -EMITTER_MIN_SENDERS = 2 +# Public infrastructure on Ethereum mainnet, identified by name from the projects' own +# published deployments (independent of any label source). Lower-case. +PUBLIC_INFRASTRUCTURE: dict[str, str] = { + "0xdac17f958d2ee523a2206206994597c13d831ec7": "Tether USD (USDT)", + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": "USD Coin (USDC)", + "0x6b175474e89094c44da98b954eedeac495271d0f": "Dai (DAI)", + "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2": "Wrapped Ether (WETH)", + "0xae7ab96520de3a18e5e111b5eaab095312d7fe84": "Lido staked ETH (stETH)", + "0x7a250d5630b4cf539739df2c5dacb4c659f2488d": "Uniswap V2 Router 02", + "0xe592427a0aece92de3edee1f18e0157c05861564": "Uniswap V3 SwapRouter", + "0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45": "Uniswap V3 SwapRouter02", + "0x000000000022d473030f116ddee9f6b43ac78ba3": "Uniswap Permit2", + "0x1111111254eeb25477b68fb85ed929f73a960582": "1inch Aggregation Router v5", + "0xdef1c0ded9bec7f1a1670819833240f027b25eff": "0x Exchange Proxy", + "0x00000000006c3852cbef3e08e8df289169ede581": "OpenSea Seaport 1.1", + "0x00000000000000adc04c56bf30ac9d3c0aaf14dc": "OpenSea Seaport 1.5", + "0x1e0049783f008a0085193e00003d00cd54003c71": "OpenSea Conduit", + "0x000000000000ad05ccc4f10045630fb830b95127": "Blur Marketplace", +} def table_schema() -> Any: @@ -65,17 +79,11 @@ def union(self, a: str, b: str) -> None: def hubs(records: dict[str, dict[str, Any]]) -> set[str]: - senders: dict[str, set[str]] = defaultdict(set) - emitter_senders: dict[str, set[str]] = defaultdict(set) + """Registry accounts that occur in ``records`` (the rest always link rows).""" + seen: set[str] = set() for rec in records.values(): - sender = (rec["tx"].get("from") or "").lower() - for account in parties(rec): - senders[account].add(sender) - for log in (rec.get("receipt") or {}).get("logs") or []: - emitter_senders[log["address"].lower()].add(sender) - return {a for a, s in senders.items() if len(s) >= HUB_MIN_SENDERS} | { - a for a, s in emitter_senders.items() if len(s) >= EMITTER_MIN_SENDERS - } + seen |= parties(rec) + return seen & set(PUBLIC_INFRASTRUCTURE) def assign_groups(records: dict[str, dict[str, Any]], hub_set: set[str]) -> dict[str, str]: @@ -121,7 +129,7 @@ def build_table( "rows": len(table), "not_found": sum(r["status"] == "not_found" for r in records.values()), "hub_accounts": len(hub_set), - "hub_rule": {"min_senders": HUB_MIN_SENDERS, "emitter_min_senders": EMITTER_MIN_SENDERS}, + "hub_rule": "curated public-infrastructure registry only", } return table, facts diff --git a/src/cryptoguard/ml/inference.py b/src/cryptoguard/ml/inference.py new file mode 100644 index 0000000..b78156b --- /dev/null +++ b/src/cryptoguard/ml/inference.py @@ -0,0 +1,108 @@ +"""Shadow-mode scoring of one transaction (experimental; never a finding). + +Reads the same four point-in-time items as training (transaction, receipt, sender nonce and +target code at the previous block), extracts the same features, scores them with the +promoted, hash-verified model, and logs the vector for drift monitoring. +""" + +from __future__ import annotations + +import os +from datetime import UTC, datetime +from functools import lru_cache +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel + +from cryptoguard.blockchain.rpc import JsonRpcClient +from cryptoguard.core.config import Settings +from cryptoguard.core.errors import FeatureDisabledError, MlUnavailableError +from cryptoguard.core.hexutil import parse_hash32 + +DISABLED = ( + "ML scoring is disabled. Set CRYPTOGUARD_ML_SHADOW=shadow (and promote a validated model, " + "see ML.md) to score transactions for review." +) +NOT_A_FINDING = ( + "Experimental shadow-mode score from a model trained on one public dataset (PTXPhish). " + "It is not a finding, does not change any severity, and has a high false-positive rate " + "on ordinary traffic (see ML_EVALUATION.md)." +) + + +class ShadowScore(BaseModel): + experimental: Literal[True] = True + status: Literal["scored", "not_found"] + tx_hash: str + run_id: str + score: float | None = None + threshold: float + above_threshold: bool | None = None + block_number: int | None = None + notes: list[str] + + +@lru_cache(maxsize=4) +def _load(registry: str, mtime: float) -> Any: + from cryptoguard.ml.registry import load_shadow_model + + return load_shadow_model(Path(registry)) + + +def loaded_model(settings: Settings) -> Any: + from cryptoguard.ml import ml_available + from cryptoguard.ml.registry import ModelRegistryError + + if settings.ml_shadow == "off": + raise FeatureDisabledError(DISABLED) + if not ml_available(): + raise MlUnavailableError("The ml extra is not installed (uv sync --extra ml).") + path = settings.ml_registry_path + try: + return _load(path, os.path.getmtime(path) if os.path.exists(path) else 0.0) + except (ModelRegistryError, FileNotFoundError) as exc: + raise MlUnavailableError(str(exc)) from None + + +async def score_transaction(client: JsonRpcClient, tx_hash: str, settings: Settings) -> ShadowScore: + import pandas as pd + + from cryptoguard.ml.collect import collect_one + from cryptoguard.ml.features import extract + from cryptoguard.ml.monitoring import log_score + + model = loaded_model(settings) + tx_hash = parse_hash32(tx_hash) + record = await collect_one(client, tx_hash) + if record["status"] != "ok": + return ShadowScore( + status="not_found", + tx_hash=tx_hash, + run_id=model.run_id, + threshold=model.threshold, + notes=["The transaction is not (or not yet) included in a block.", NOT_A_FINDING], + ) + features = extract(record) + row = pd.DataFrame([[features[c] for c in model.columns]], columns=model.columns) + score = float(model.model.predict_proba(row)[0, 1]) + log_score( + { + "at": datetime.now(UTC).isoformat(), + "run_id": model.run_id, + "tx_hash": tx_hash, + "score": score, + "features": {c: features[c] for c in model.columns}, + }, + Path(settings.ml_score_log_path), + ) + return ShadowScore( + status="scored", + tx_hash=tx_hash, + run_id=model.run_id, + score=score, + threshold=model.threshold, + above_threshold=score >= model.threshold, + block_number=int(record["tx"]["blockNumber"], 16), + notes=[NOT_A_FINDING], + ) diff --git a/src/cryptoguard/ml/monitoring.py b/src/cryptoguard/ml/monitoring.py new file mode 100644 index 0000000..b6e53cf --- /dev/null +++ b/src/cryptoguard/ml/monitoring.py @@ -0,0 +1,73 @@ +"""Feature-distribution monitoring for shadow scoring (population stability index). + +The model card stores training deciles for every feature. Each shadow-scored feature vector +is appended to a local log; ``drift_report`` compares the logged values with the training +deciles. PSI below 0.1 is usually read as stable, 0.1-0.25 as a moderate shift, above 0.25 +as a large one: the model is then scoring data unlike what it was trained on. +""" + +from __future__ import annotations + +import bisect +import json +import math +from pathlib import Path +from typing import Any + +DEFAULT_LOG = Path("data") / "ml" / "shadow_scores.jsonl" +MIN_ROWS = 30 + + +def reference_bins(train_values: list[float]) -> dict[str, list[float]]: + """Bin edges (distinct interior training deciles) and the training share per bin. + Shares are counted, not assumed equal: binary and count features have tied deciles.""" + ordered = sorted(train_values) + n = len(ordered) + deciles = [ordered[min(int(n * q / 10), n - 1)] for q in range(1, 10)] + edges = sorted(set(deciles)) + counts = [0] * (len(edges) + 1) + for v in ordered: + counts[bisect.bisect_right(edges, v)] += 1 + return {"edges": edges, "expected": [c / n for c in counts]} + + +def psi(reference: dict[str, list[float]], values: list[float]) -> float: + """Population stability index of ``values`` against the training bins.""" + edges, expected = reference["edges"], reference["expected"] + counts = [0] * len(expected) + for v in values: + counts[bisect.bisect_right(edges, v)] += 1 + total = len(values) or 1 + eps = 1e-4 + return sum( + (max(c / total, eps) - max(e, eps)) * math.log(max(c / total, eps) / max(e, eps)) + for c, e in zip(counts, expected, strict=True) + ) + + +def log_score(entry: dict[str, Any], path: Path = DEFAULT_LOG) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(entry, separators=(",", ":")) + "\n") + + +def drift_report(card: dict[str, Any], path: Path = DEFAULT_LOG) -> dict[str, Any]: + rows = [] + if path.exists(): + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + rows = [r for r in rows if r.get("run_id") == card["run_id"]] + if len(rows) < MIN_ROWS: + return {"status": "insufficient_data", "rows": len(rows), "min_rows": MIN_ROWS} + reference = card["reference_bins"] + scores = { + feature: psi(reference[feature], [float(r["features"][feature]) for r in rows]) + for feature in card["feature_columns"] + } + worst = sorted(scores.items(), key=lambda kv: -kv[1]) + return { + "status": "ok", + "rows": len(rows), + "psi": dict(worst), + "shifted": [f for f, v in worst if v > 0.25], + "moderate": [f for f, v in worst if 0.1 < v <= 0.25], + } diff --git a/src/cryptoguard/ml/registry.py b/src/cryptoguard/ml/registry.py new file mode 100644 index 0000000..8bc0a72 --- /dev/null +++ b/src/cryptoguard/ml/registry.py @@ -0,0 +1,72 @@ +"""Model registry: which trained run is the shadow-mode model, and safe loading of it. + +Model files are pickles (joblib), and unpickling executes code. A model is therefore loaded +only from the local registry, and only if its SHA-256 matches the hash recorded in its model +card when it was trained; anything else is refused. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from cryptoguard.ml import FEATURE_SET_VERSION + +DEFAULT_REGISTRY = Path("data") / "ml" / "registry.json" + + +class ModelRegistryError(RuntimeError): + """No usable shadow model (none promoted, files missing, or integrity check failed).""" + + +@dataclass(frozen=True) +class LoadedModel: + run_id: str + model: Any + card: dict[str, Any] + + @property + def threshold(self) -> float: + return float(self.card["threshold"]) + + @property + def columns(self) -> list[str]: + return list(self.card["feature_columns"]) + + +def promote(run_dir: Path, registry: Path = DEFAULT_REGISTRY) -> dict[str, Any]: + """Make a run the shadow model. Refused unless its promotion gate passed.""" + card = json.loads((run_dir / "model_card.json").read_text(encoding="utf-8")) + if not card["gate"]["validated_for_shadow"]: + raise ModelRegistryError(f"run {card['run_id']} did not pass its promotion gate") + entry = { + "run_id": card["run_id"], + "run_dir": run_dir.as_posix(), + "model_sha256": card["model_sha256"], + "feature_set_version": card["feature_set_version"], + } + registry.parent.mkdir(parents=True, exist_ok=True) + registry.write_text(json.dumps({"shadow": entry}, indent=1), encoding="utf-8") + return entry + + +def load_shadow_model(registry: Path = DEFAULT_REGISTRY) -> LoadedModel: + if not registry.exists(): + raise ModelRegistryError("no shadow model promoted (cryptoguard ml promote )") + entry = json.loads(registry.read_text(encoding="utf-8"))["shadow"] + run_dir = Path(entry["run_dir"]) + card = json.loads((run_dir / "model_card.json").read_text(encoding="utf-8")) + if card["feature_set_version"] != FEATURE_SET_VERSION: + raise ModelRegistryError( + f"model features {card['feature_set_version']} != code {FEATURE_SET_VERSION}" + ) + model_path = run_dir / "model.joblib" + digest = hashlib.sha256(model_path.read_bytes()).hexdigest() + if digest != entry["model_sha256"] or digest != card["model_sha256"]: + raise ModelRegistryError(f"{model_path}: hash mismatch, refusing to load") + import joblib + + return LoadedModel(entry["run_id"], joblib.load(model_path), card) diff --git a/src/cryptoguard/ml/train.py b/src/cryptoguard/ml/train.py index 7f88fe4..dc0eec8 100644 --- a/src/cryptoguard/ml/train.py +++ b/src/cryptoguard/ml/train.py @@ -27,6 +27,7 @@ from cryptoguard.ml import FEATURE_SET_VERSION, ML_VERSION from cryptoguard.ml.features import FEATURES +from cryptoguard.ml.monitoring import reference_bins if TYPE_CHECKING: import numpy as np @@ -160,25 +161,43 @@ def best_threshold(y: np.ndarray, score: np.ndarray) -> float: return float(candidates[int(np.argmax(f1s))]) +def fast_average_precision(y: np.ndarray, score: np.ndarray) -> float: + """Average precision exactly as ``sklearn.metrics.average_precision_score`` defines it + (sum over distinct thresholds of recall increments times precision), vectorised: the + bootstrap calls it thousands of times, where sklearn's input checks dominate.""" + import numpy as np + + order = np.argsort(-score, kind="mergesort") + ys, ss = y[order], score[order] + last_of_threshold = np.r_[ss[1:] != ss[:-1], True] + tps = np.cumsum(ys)[last_of_threshold] + fps = (np.arange(1, len(ys) + 1) - np.cumsum(ys))[last_of_threshold] + precision = tps / (tps + fps) + recall = tps / tps[-1] + return float(np.sum(np.diff(np.r_[0.0, recall]) * precision)) + + def bootstrap_ci( y: np.ndarray, score: np.ndarray, threshold: float, n: int = 1000 ) -> dict[str, list[float]]: """95% percentile intervals for test AP, recall and false-positive rate (seeded - resamples of rows).""" + resamples of rows). Empty when the split lacks one class: no interval exists.""" + if len(set(y.tolist())) < 2: + return {} import numpy as np - from sklearn.metrics import average_precision_score, recall_score rng = np.random.default_rng(SEED) ap, rec, fpr = [], [], [] for _ in range(n): idx = rng.integers(0, len(y), len(y)) - if len(np.unique(y[idx])) < 2: + yi, si = y[idx], score[idx] + positives = int(yi.sum()) + if positives in (0, len(yi)): continue - pred = (score[idx] >= threshold).astype(int) - ap.append(average_precision_score(y[idx], score[idx])) - rec.append(recall_score(y[idx], pred, zero_division=0)) - neg = y[idx] == 0 - fpr.append(float(pred[neg].mean())) + pred = si >= threshold + ap.append(fast_average_precision(yi, si)) + rec.append(float(pred[yi == 1].mean())) + fpr.append(float(pred[yi == 0].mean())) def q(values: list[float]) -> list[float]: return [float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))] @@ -241,9 +260,12 @@ def make_model(name: str, params: dict[str, Any]): # type: ignore[no-untyped-de raise ValueError(name) -def run_training(table: pd.DataFrame, split: pd.Series) -> dict[str, Any]: +def run_training( + table: pd.DataFrame, + split: pd.Series, + candidates: list[tuple[str, dict[str, Any]]] | None = None, +) -> dict[str, Any]: """Fit everything, select on validation, score test once. Returns the full result.""" - import numpy as np from sklearn.dummy import DummyClassifier from sklearn.inspection import permutation_importance @@ -277,7 +299,7 @@ def run_training(table: pd.DataFrame, split: pd.Series) -> dict[str, Any]: # validation log loss (a proper scoring rule: AP saturates near 1 on this data). best: dict[tuple[str, str], tuple[float, dict[str, Any], Any, np.ndarray]] = {} for fs_name, fs_tuple in FEATURE_SETS.items(): - for name, params in _candidates(): + for name, params in candidates or _candidates(): model = make_model(name, params).fit(train[list(fs_tuple)], y_tr) s_va = model.predict_proba(val[list(fs_tuple)])[:, 1] loss = metrics(y_va, s_va, 0.5)["log_loss"] @@ -336,9 +358,7 @@ def run_training(table: pd.DataFrame, split: pd.Series) -> dict[str, Any]: .to_dict("records"), }, "seconds": round(time.perf_counter() - started, 1), - "reference": { - c: [float(q) for q in np.quantile(train[c], np.linspace(0, 1, 11))] for c in cols - }, + "reference": {c: reference_bins([float(v) for v in train[c]]) for c in cols}, } @@ -360,7 +380,8 @@ def promotion_gate(results: list[ModelResult], selected: ModelResult) -> dict[st model_val = selected.validation["average_precision"] or 0.0 gap_closed = (model_val - base_val) / (1 - base_val) if base_val < 1 else 0.0 val_ok = gap_closed >= GATE_GAP_REDUCTION - test_ok = selected.test["ci95"]["average_precision"][0] > base_test + interval = selected.test["ci95"].get("average_precision") + test_ok = interval is not None and interval[0] > base_test return { "best_baseline_validation_ap": base_val, "best_baseline_test_ap": base_test, @@ -420,7 +441,7 @@ def save_run(run_dir: Path, entry: dict[str, Any], out: dict[str, Any]) -> Path: "selected": entry["selected"], "gate": entry["gate"], "model_sha256": hashlib.sha256(model_path.read_bytes()).hexdigest(), - "reference_quantiles": out["reference"], + "reference_bins": out["reference"], "trained_on": entry["config"], } (run_dir / "model_card.json").write_text(json.dumps(card, indent=1), encoding="utf-8") diff --git a/tests/integration/test_ml_api.py b/tests/integration/test_ml_api.py new file mode 100644 index 0000000..bc3472c --- /dev/null +++ b/tests/integration/test_ml_api.py @@ -0,0 +1,138 @@ +"""Experimental ML endpoints: off by default, explicit about missing models, never findings.""" + +from __future__ import annotations + +import json +import random +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from cryptoguard.api.app import create_app +from cryptoguard.blockchain.provider import EthereumProvider, build_rpc_provider +from cryptoguard.core.config import Settings +from tests.conftest import SleepRecorder +from tests.fakenode import FakeNode +from tests.integration.test_api import ( + LOCAL, + RPC_URL, + make_settings, + memory_repository, + rpc_client_for, +) +from tests.integration.test_api import WALLET as API_WALLET +from tests.integration.test_api import node as api_node # noqa: F401 + +TX = "0x" + "ab" * 32 + + +def test_endpoints_are_off_by_default(api_node: FakeNode) -> None: # noqa: F811 + with rpc_client_for(api_node) as client: + scored = client.post("/api/v1/ml/transactions/score", json={"tx_hash": TX}) + status = client.get("/api/v1/ml/status") + assert scored.status_code == 409 + assert scored.json()["error"]["code"] == "feature_disabled" + assert status.status_code == 409 + + +def test_shadow_without_a_promoted_model_says_so(api_node: FakeNode, tmp_path: Path) -> None: # noqa: F811 + pytest.importorskip("sklearn") + with rpc_client_for( + api_node, ml_shadow="shadow", ml_registry_path=str(tmp_path / "none.json") + ) as client: + response = client.post("/api/v1/ml/transactions/score", json={"tx_hash": TX}) + assert response.status_code == 503 + assert response.json()["error"]["code"] == "ml_unavailable" + + +def test_request_accepts_only_a_transaction_hash(api_node: FakeNode) -> None: # noqa: F811 + with rpc_client_for(api_node, ml_shadow="shadow") as client: + extra = client.post( + "/api/v1/ml/transactions/score", json={"tx_hash": TX, "rpc_url": "https://evil.example"} + ) + malformed = client.post("/api/v1/ml/transactions/score", json={"tx_hash": "0x1234"}) + assert extra.status_code == 422 + assert malformed.status_code == 422 + + +def test_ml_shadow_mode_does_not_change_snapshot_findings(api_node: FakeNode) -> None: # noqa: F811 + def events(**flags: object) -> list[tuple[str, str]]: + with rpc_client_for(api_node, **flags) as client: + response = client.post(f"/api/v1/wallets/{API_WALLET}/snapshots", json={}) + assert response.status_code == 200, response.text + return sorted((e["rule_id"], e["to_status"]) for e in response.json()["finding_events"]) + + off, shadow = events(), events(ml_shadow="shadow") + assert off + assert off == shadow + + +@pytest.fixture +def promoted(tmp_path: Path) -> tuple[Path, dict]: # type: ignore[type-arg] + pd = pytest.importorskip("pandas") + pytest.importorskip("lightgbm") + from cryptoguard.ml.dataset import build_table + from cryptoguard.ml.registry import promote + from cryptoguard.ml.splits import make_splits + from cryptoguard.ml.train import promotion_gate, run_training, save_run + from tests.ml_synthetic import make_records + from tests.unit.test_ml_pipeline import SMALL_GRID + + labels, records = make_records() + table = build_table(pd.DataFrame(labels), records)[0] + split, _ = make_splits(table, records) + out = run_training(table, split, SMALL_GRID) + gate = {**promotion_gate(out["results"], out["selected"]), "validated_for_shadow": True} + entry = { + "run_id": "test-run", + "config": {}, + "gate": gate, + "selected": {"name": out["selected"].name, "threshold": out["selected"].threshold}, + } + registry = tmp_path / "registry.json" + promote(save_run(tmp_path / "run", entry, out), registry) + return registry, records + + +def _client(records: dict, registry: Path, log: Path) -> TestClient: # type: ignore[type-arg] + from tests.ml_synthetic import FakeRpc + + fake = FakeRpc(records) + settings: Settings = make_settings( + rpc_url=RPC_URL, + ml_shadow="shadow", + ml_registry_path=str(registry), + ml_score_log_path=str(log), + ) + + def factory(s: Settings) -> EthereumProvider: + return build_rpc_provider( + s, transport=fake.transport(), sleep=SleepRecorder(), rng=random.Random(0) + ) + + app = create_app(settings, provider_factory=factory, repository=memory_repository()) + return TestClient(app, base_url=LOCAL, raise_server_exceptions=False) + + +def test_scores_a_transaction_in_shadow_mode(promoted: tuple[Path, dict], tmp_path: Path) -> None: # type: ignore[type-arg] + registry, records = promoted + tx_hash = next(iter(records)) + log = tmp_path / "scores.jsonl" + with _client(records, registry, log) as client: + response = client.post("/api/v1/ml/transactions/score", json={"tx_hash": tx_hash}) + missing = client.post("/api/v1/ml/transactions/score", json={"tx_hash": TX}) + status = client.get("/api/v1/ml/status") + assert response.status_code == 200, response.text + body = response.json() + assert body["experimental"] is True + assert body["status"] == "scored" + assert 0.0 <= body["score"] <= 1.0 + assert body["run_id"] == "test-run" + assert any("not a finding" in note for note in body["notes"]) + logged = [json.loads(line) for line in log.read_text().splitlines()] + assert len(logged) == 1 + assert logged[0]["tx_hash"] == tx_hash + assert missing.json()["status"] == "not_found" + assert status.status_code == 200 + assert status.json()["drift"]["status"] == "insufficient_data" diff --git a/tests/ml_synthetic.py b/tests/ml_synthetic.py new file mode 100644 index 0000000..8603b3d --- /dev/null +++ b/tests/ml_synthetic.py @@ -0,0 +1,137 @@ +"""Synthetic, fictional transaction records for ML tests (no real chain data, no labels +from any dataset). The two classes differ in transaction shape, with label noise, so a model +can learn something without the tests depending on PTXPhish.""" + +from __future__ import annotations + +import json +import random +from typing import Any + +import httpx + +from cryptoguard.ml.features import APPROVAL, TRANSFER + +TOKEN = "0xdac17f958d2ee523a2206206994597c13d831ec7" # USDT: public infrastructure + + +def _addr(rng: random.Random) -> str: + return "0x" + "".join(rng.choice("0123456789abcdef") for _ in range(40)) + + +def _topic(address: str) -> str: + return "0x" + "0" * 24 + address[2:] + + +def _hash(i: int) -> str: + return "0x" + f"{i:064x}" + + +def make_records( + n: int = 360, seed: int = 7 +) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]: + """(label rows, records by tx hash). Phishing rows: delegated transfers by attacker + accounts, a few sharing one drainer contract; benign rows: swaps and plain transfers.""" + rng = random.Random(seed) + drainer = _addr(rng) + labels, records = [], {} + for i in range(n): + phishing = i % 2 == 0 + block = 15_000_000 + i * 1_000 + rng.randrange(500) + sender = _addr(rng) + target = drainer if phishing and rng.random() < 0.15 else TOKEN if phishing else _addr(rng) + victim, recipient = _addr(rng), _addr(rng) + noisy = rng.random() < 0.08 # label noise + shape_phish = phishing != noisy + if shape_phish: + data = "0x23b872dd" + "00" * 96 + logs = [ + { + "address": TOKEN, + "topics": [TRANSFER, _topic(victim), _topic(recipient)], + "data": "0x" + f"{rng.randrange(1, 10**9):064x}", + } + ] + value, nonce = 0, rng.randrange(0, 30) + else: + data = "0x" + rng.choice(["7ff36ab5", "a9059cbb", "38ed1739"]) + "00" * 128 + logs = [ + { + "address": TOKEN, + "topics": [TRANSFER, _topic(sender), _topic(recipient)], + "data": "0x" + f"{rng.randrange(1, 10**9):064x}", + }, + { + "address": TOKEN, + "topics": [APPROVAL, _topic(sender), _topic(target)], + "data": "0x" + f"{rng.randrange(1, 10**6):064x}", + }, + ] + value, nonce = rng.randrange(0, 10**18), rng.randrange(100, 5_000) + tx_hash = _hash(i + 1) + records[tx_hash] = { + "tx_hash": tx_hash, + "status": "ok", + "tx": { + "blockNumber": hex(block), + "from": sender, + "to": target, + "value": hex(value), + "gas": hex(rng.randrange(50_000, 400_000)), + "gasPrice": hex(30 * 10**9), + "maxFeePerGas": None, + "maxPriorityFeePerGas": None, + "nonce": hex(nonce), + "type": "0x0", + "input": data, + }, + "receipt": { + "status": "0x1", + "gasUsed": hex(40_000), + "contractAddress": None, + "logs": logs, + }, + "from_nonce_before": hex(nonce), + "to_code_before": {"size": 2_000, "prefix": "0x608060"}, + } + labels.append( + { + "tx_hash": tx_hash, + "family": "ice_phishing" if phishing else "benign", + "subtype": "approve" if phishing else "benign_kol", + "label": int(phishing), + } + ) + return labels, records + + +class FakeRpc: + """JSON-RPC over httpx.MockTransport serving the four methods the collector uses.""" + + def __init__(self, records: dict[str, dict[str, Any]], *, fail: set[str] | None = None): + self.records = records + self.fail = fail or set() + self.calls: list[str] = [] + + def transport(self) -> httpx.MockTransport: + return httpx.MockTransport(self.handle) + + def handle(self, request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content) + method, params = payload["method"], payload["params"] + self.calls.append(method) + if method in self.fail: + return httpx.Response(503, text="unavailable") + result: Any = None + if method == "eth_getTransactionByHash": + rec = self.records.get(params[0]) + result = None if rec is None else {**rec["tx"], "hash": params[0]} + elif method == "eth_getTransactionReceipt": + rec = self.records.get(params[0]) + result = None if rec is None else rec["receipt"] + elif method == "eth_getTransactionCount": + rec = next(r for r in self.records.values() if r["tx"]["from"] == params[0]) + result = rec["from_nonce_before"] + elif method == "eth_getCode": + result = "0x6080604052" + "00" * 10 + return httpx.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": result}) diff --git a/tests/unit/test_ml_features.py b/tests/unit/test_ml_features.py new file mode 100644 index 0000000..f8d849c --- /dev/null +++ b/tests/unit/test_ml_features.py @@ -0,0 +1,144 @@ +"""ML features: point in time, deterministic, no identifiers (pure Python, no ml extra).""" + +from __future__ import annotations + +import copy +import math + +from cryptoguard.ml.features import ( + APPROVAL, + APPROVAL_FOR_ALL, + FEATURES, + TRANSFER, + UNLIMITED, + _vanity_zeros, + affix_match, + extract, + parties, +) + +SENDER = "0x" + "11" * 20 +TARGET = "0x0000553f880ffa3728b290e04e819053a3590000" +VICTIM = "0x" + "22" * 20 +LOOK_A = "0xabcd" + "1" * 32 + "ef12" +LOOK_B = "0xabcd" + "9" * 32 + "ef12" + + +def topic(a: str) -> str: + return "0x" + "0" * 24 + a[2:] + + +def record(**tx: object) -> dict: # type: ignore[type-arg] + base = { + "tx_hash": "0x" + "ab" * 32, + "status": "ok", + "tx": { + "blockNumber": hex(17_000_000), + "from": SENDER, + "to": TARGET, + "value": "0x0", + "gas": hex(100_000), + "gasPrice": hex(20 * 10**9), + "maxFeePerGas": None, + "maxPriorityFeePerGas": None, + "nonce": "0x5", + "type": "0x0", + "input": "0x23b872dd" + "00" * 96, + **tx, + }, + "receipt": { + "status": "0x1", + "gasUsed": hex(50_000), + "contractAddress": None, + "logs": [ + { + "address": TARGET, + "topics": [TRANSFER, topic(VICTIM), topic(LOOK_A)], + "data": "0x" + "00" * 32, + }, + { + "address": TARGET, + "topics": [APPROVAL, topic(VICTIM), topic(LOOK_B)], + "data": "0x" + f"{UNLIMITED:064x}", + }, + { + "address": TARGET, + "topics": [APPROVAL_FOR_ALL, topic(VICTIM), topic(SENDER)], + "data": "0x" + "00" * 31 + "01", + }, + ], + }, + "from_nonce_before": "0x63", + "to_code_before": {"size": 2_000, "prefix": "0x608060"}, + } + return base + + +def test_feature_vector_has_the_declared_order_and_finite_values() -> None: + f = extract(record()) + assert tuple(f) == FEATURES + assert all(math.isfinite(v) for v in f.values()) + + +def test_transaction_shape_is_encoded() -> None: + f = extract(record()) + assert f["fn_transfer_from"] == 1.0 + assert f["fn_other"] == 0.0 + assert f["is_zero_value"] == 1.0 + assert f["n_transfers"] == 1 + assert f["n_zero_value_transfers"] == 1 + assert f["n_transfers_not_from_sender"] == 1 + assert f["n_approvals"] == 1 + assert f["n_unlimited_approvals"] == 1 + assert f["n_approval_for_all_granted"] == 1 + assert f["to_is_contract"] == 1.0 + assert f["to_is_delegated_eoa"] == 0.0 + assert f["to_vanity_zero_nibbles"] == 8 # 0x0000553f…0000 + assert f["sender_prior_txs_log"] == math.log1p(99) + assert f["max_party_affix_match"] == 8 # the two lookalikes share abcd…ef12 + assert f["gas_used_ratio"] == 0.5 + + +def test_block_number_is_never_a_feature() -> None: + """Point in time and no era leakage: moving a transaction in time changes nothing.""" + early, late = record(), record(blockNumber=hex(19_000_000)) + assert extract(early) == extract(late) + + +def test_extract_does_not_mutate_its_input() -> None: + rec = record() + before = copy.deepcopy(rec) + extract(rec) + assert rec == before + + +def test_contract_creation_and_delegated_target() -> None: + created = extract({**record(to=None), "to_code_before": {"size": 0, "prefix": "0x"}}) + assert created["is_contract_creation"] == 1.0 + assert created["to_is_contract"] == 0.0 + delegated = extract({**record(), "to_code_before": {"size": 23, "prefix": "0xef0100"}}) + assert delegated["to_is_delegated_eoa"] == 1.0 + assert delegated["to_is_contract"] == 0.0 + + +def test_reverted_transaction_without_receipt_logs() -> None: + rec = record() + rec["receipt"] = {"status": "0x0", "gasUsed": hex(100_000), "logs": []} + f = extract(rec) + assert f["status_success"] == 0.0 + assert f["n_logs"] == 0 + assert f["n_transfers"] == 0 + + +def test_helpers() -> None: + assert affix_match(LOOK_A, LOOK_B) == 8 + assert affix_match(LOOK_A, LOOK_A) == 0 # identical is not a lookalike + assert _vanity_zeros(None) == 0 + assert _vanity_zeros("0x" + "0" * 39 + "1") == 39 + + +def test_parties_cover_sender_target_spenders_and_recipients() -> None: + got = parties(record()) + assert {SENDER, TARGET.lower(), LOOK_A, LOOK_B} <= got + assert VICTIM not in got # a transfer's source is the victim, not infrastructure + assert "0x" + "0" * 40 not in parties(record(to=None)) diff --git a/tests/unit/test_ml_pipeline.py b/tests/unit/test_ml_pipeline.py new file mode 100644 index 0000000..68149b3 --- /dev/null +++ b/tests/unit/test_ml_pipeline.py @@ -0,0 +1,346 @@ +"""ML pipeline: source integrity, label parsing, sampling, leakage-safe splits, collector +budget, training smoke run, registry and monitoring. Synthetic data only.""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +import pytest + +pytest.importorskip("pandas") +pytest.importorskip("sklearn") +pytest.importorskip("lightgbm") +pytest.importorskip("pandera") +pytest.importorskip("openpyxl") + +import pandas as pd + +from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy +from cryptoguard.ml import collect as collect_mod +from cryptoguard.ml.dataset import build_table, hubs +from cryptoguard.ml.features import parties +from cryptoguard.ml.labels import _PTX_HEADER_ROW, load_ptxphish +from cryptoguard.ml.monitoring import drift_report, log_score, psi, reference_bins +from cryptoguard.ml.registry import ModelRegistryError, load_shadow_model, promote +from cryptoguard.ml.sources import SOURCES, SourceIntegrityError, sha256_file, verify +from cryptoguard.ml.splits import make_splits +from cryptoguard.ml.train import promotion_gate, run_training, save_run +from tests.ml_synthetic import TOKEN, FakeRpc, make_records + +# --- sources and labels --------------------------------------------------------------------- + + +def _write_ptx_sheet(path: Path, columns: dict[str, list[str]]) -> None: + """A workbook shaped like PTXPhish: subtype headers on row 3, hashes below.""" + from openpyxl import Workbook + + wb = Workbook() + ws = wb.active + for col, (header, values) in enumerate(columns.items(), start=1): + ws.cell(row=_PTX_HEADER_ROW + 1, column=col, value=header) + for i, value in enumerate(values): + ws.cell(row=_PTX_HEADER_ROW + 2 + i, column=col, value=value) + path.parent.mkdir(parents=True, exist_ok=True) + wb.save(path) + + +ALL_SUBTYPES = [ + "Approve", + "Permit", + "SetApproveForAll", + "Bulk transfer", + "Proxy upgrade", + "Free buy order", + "Zero value transfer", + "Fake token transfer", + "Dust value transfer", + "Airdrop function", + "Wallet function", + "Benign KOL", + "Benign Developer", +] + + +def _fake_ptx( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, columns: dict[str, list[str]] +) -> Path: + path = tmp_path / "ptxphish" / "dataset" / "PTXPHISH.xlsx" + _write_ptx_sheet(path, columns) + files = tuple( + type(f)(f.path, sha256_file(path) if f.path.endswith("PTXPHISH.xlsx") else f.sha256, 0) + for f in SOURCES["ptxphish"].files[:1] + ) + from dataclasses import replace + + monkeypatch.setitem(SOURCES, "ptxphish", replace(SOURCES["ptxphish"], files=files)) + return tmp_path + + +def test_ptxphish_sheet_becomes_one_validated_row_per_transaction( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + columns = {name: [] for name in ALL_SUBTYPES} + columns["Approve"] = ["0x" + "AB" * 32] # mixed case is normalised + columns["Benign KOL"] = ["0x" + "cd" * 32, "0x" + "ef" * 32] + columns["Source"] = ["https://example.invalid/report"] # ignored column + labels = load_ptxphish(_fake_ptx(tmp_path, monkeypatch, columns)) + assert list(labels.columns) == ["tx_hash", "family", "subtype", "label"] + assert labels.set_index("tx_hash").loc["0x" + "ab" * 32, "family"] == "ice_phishing" + assert labels["label"].tolist().count(0) == 2 + + +def test_malformed_hash_or_layout_change_fails_loudly( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + bad = {name: [] for name in ALL_SUBTYPES} + bad["Permit"] = ["not-a-hash"] + with pytest.raises(ValueError, match="not a tx hash"): + load_ptxphish(_fake_ptx(tmp_path / "a", monkeypatch, bad)) + renamed = {name: [] for name in ALL_SUBTYPES if name != "Permit"} | {"Permit v2": []} + with pytest.raises(ValueError, match="unexpected PTXPhish layout"): + load_ptxphish(_fake_ptx(tmp_path / "b", monkeypatch, renamed)) + + +def test_a_tampered_source_file_is_refused(tmp_path: Path) -> None: + source = SOURCES["forta"] + for f in source.files: + p = tmp_path / source.name / f.path + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text("tampered") + with pytest.raises(SourceIntegrityError): + verify(tmp_path, source) + + +# --- sampling ------------------------------------------------------------------------------ + + +def test_sample_is_deterministic_and_keeps_every_poisoning_row() -> None: + rows = [ + ("0x" + f"{i:064x}", fam, sub, int(fam != "benign")) + for i, (fam, sub) in enumerate( + [("address_poisoning", "zero_value_transfer")] * 10 + + [("ice_phishing", "approve")] * 300 + + [("benign", "benign_kol")] * 400 + ) + ] + labels = pd.DataFrame(rows, columns=["tx_hash", "family", "subtype", "label"]) + plan = collect_mod.SamplePlan(phishing=60, benign=50) + a, b = collect_mod.draw_sample(labels, plan), collect_mod.draw_sample(labels, plan) + assert a.equals(b) + assert (a["family"] == "address_poisoning").sum() == 10 + assert (a["label"] == 0).sum() == 50 + assert len(a) == 110 + + +# --- splits -------------------------------------------------------------------------------- + + +def _table() -> tuple[pd.DataFrame, dict]: # type: ignore[type-arg] + labels, records = make_records() + return build_table(pd.DataFrame(labels), records)[0], records + + +def test_splits_are_time_ordered_and_share_no_account() -> None: + table, records = _table() + split, summary = make_splits(table, records) + blocks = {s: table.loc[split == s, "block_number"] for s in ("train", "validation", "test")} + assert blocks["train"].max() < blocks["validation"].min() + assert blocks["validation"].max() < blocks["test"].min() + train_hubs = hubs({h: records[h] for h in table.loc[split == "train", "tx_hash"]}) + + def accounts(name: str) -> set[str]: + out: set[str] = set() + for h in table.loc[split == name, "tx_hash"]: + out |= parties(records[h]) - train_hubs + return out + + assert not accounts("train") & accounts("validation") + assert not (accounts("train") | accounts("validation")) & accounts("test") + assert summary["counts"]["test"] # something survives the purge + + +def test_reused_attacker_contract_cannot_reach_the_test_split() -> None: + """Leakage regression: the synthetic drainer contract is used before and after the + test boundary; every later use must be purged.""" + from collections import Counter + + table, records = _table() + split, _ = make_splits(table, records) + targets = Counter(r["tx"]["to"] for r in records.values() if r["tx"]["to"] != TOKEN) + drainer, uses = targets.most_common(1)[0] + assert uses >= 10 # called by many different senders, like a popular contract + rows = table.index[[records[h]["tx"]["to"] == drainer for h in table["tx_hash"]]] + assert (split[rows] == "train").any() + assert not split[rows].isin(["validation", "test"]).any() + + +# --- collector ----------------------------------------------------------------------------- + + +def _client(fake: FakeRpc) -> JsonRpcClient: + async def no_sleep(_: float) -> None: + return None + + return JsonRpcClient( + "https://rpc.invalid", + transport=fake.transport(), + retry=RetryPolicy(max_retries=1), + sleep=no_sleep, + max_concurrency=1, + ) + + +def test_collector_respects_the_request_cap_and_resumes(tmp_path: Path) -> None: + labels, records = make_records(n=40) + sample = pd.DataFrame(labels) + out = tmp_path / "chain.jsonl" + fake = FakeRpc(records) + stats = asyncio.run( + collect_mod.collect( + sample, out, rpc_url="unused", max_requests=60, concurrency=1, client=_client(fake) + ) + ) + assert len(fake.calls) <= 60 + assert collect_mod.requests_used(out) == len(fake.calls) # recorded as it went + assert stats["skipped_budget"] > 0 + first = len(collect_mod.load_collected(out)) + fake2 = FakeRpc(records) + asyncio.run( + collect_mod.collect( + sample, out, rpc_url="unused", max_requests=10_000, concurrency=1, client=_client(fake2) + ) + ) + assert len(collect_mod.load_collected(out)) == 40 + assert len(fake2.calls) == (40 - first) * collect_mod.REQUESTS_PER_TX # no refetching + + +def test_collector_records_failures_and_retries_them_later(tmp_path: Path) -> None: + labels, records = make_records(n=3) + out = tmp_path / "chain.jsonl" + asyncio.run( + collect_mod.collect( + pd.DataFrame(labels), + out, + rpc_url="unused", + max_requests=1_000, + concurrency=1, + client=_client(FakeRpc(records, fail={"eth_getCode"})), + ) + ) + rows = [json.loads(line) for line in out.read_text().splitlines()] + assert {r["status"] for r in rows} == {"error"} + assert collect_mod.load_collected(out) == {} + + +# --- training, gate, registry, monitoring -------------------------------------------------- + + +# One candidate per family keeps the smoke run fast; the code path is the full one. +SMALL_GRID = [ + ("logistic_regression", {"C": 1.0}), + ("random_forest", {"min_samples_leaf": 3}), + ("lightgbm", {"num_leaves": 7, "min_child_samples": 5}), +] + + +@pytest.fixture(scope="module") +def trained() -> dict: # type: ignore[type-arg] + labels, records = make_records() + table = build_table(pd.DataFrame(labels), records)[0] + split, _ = make_splits(table, records) + out = run_training(table, split, SMALL_GRID) + return {"out": out, "table": table, "split": split} + + +def test_smoke_training_scores_every_model_on_the_same_test_rows(trained: dict) -> None: # type: ignore[type-arg] + out = trained["out"] + names = {r.name for r in out["results"]} + assert { + "majority", + "stratified", + "rule_phishing_shape", + "rule_cryptoguard_signals", + "logistic_regression", + "random_forest", + "lightgbm", + } <= names + rows = {r.test["rows"] for r in out["results"]} + assert len(rows) == 1 # identical test rows for baselines and models + majority = next(r for r in out["results"] if r.name == "majority") + assert majority.test["roc_auc"] == 0.5 + assert out["selected"].kind == "learned" + assert out["selected"].test["average_precision"] > majority.test["average_precision"] + + +def test_training_is_deterministic(trained: dict) -> None: # type: ignore[type-arg] + again = run_training(trained["table"], trained["split"], SMALL_GRID) + first = [ + (r.name, r.feature_set, r.test["average_precision"]) for r in trained["out"]["results"] + ] + second = [(r.name, r.feature_set, r.test["average_precision"]) for r in again["results"]] + assert first == second + + +def test_registry_refuses_ungated_and_tampered_models(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + out = trained["out"] + gate = promotion_gate(out["results"], out["selected"]) + entry = { + "run_id": "r1", + "config": {}, + "gate": {**gate, "validated_for_shadow": False}, + "selected": {"threshold": out["selected"].threshold}, + } + run_dir = save_run(tmp_path / "r1", entry, out) + with pytest.raises(ModelRegistryError, match="did not pass"): + promote(run_dir, tmp_path / "registry.json") + entry["gate"]["validated_for_shadow"] = True + run_dir = save_run(tmp_path / "r2", {**entry, "run_id": "r2"}, out) + registry = tmp_path / "registry.json" + promote(run_dir, registry) + assert load_shadow_model(registry).run_id == "r2" + (run_dir / "model.joblib").write_bytes(b"not the trained model") + with pytest.raises(ModelRegistryError, match="hash mismatch"): + load_shadow_model(registry) + + +def test_fast_average_precision_matches_sklearn_including_ties() -> None: + import numpy as np + from sklearn.metrics import average_precision_score + + from cryptoguard.ml.train import fast_average_precision + + rng = np.random.default_rng(0) + for _ in range(50): + y = rng.integers(0, 2, 60) + y[0], y[1] = 0, 1 + score = rng.integers(0, 6, 60) / 5 # many ties + assert fast_average_precision(y, score) == pytest.approx( + average_precision_score(y, score), abs=1e-12 + ) + + +def test_psi_is_small_for_training_like_data_and_large_for_shifted_data() -> None: + train = [float(i % 10) for i in range(1_000)] + ref = reference_bins(train) + assert psi(ref, train) < 0.01 + assert psi(ref, [9.0] * 200) > 1.0 + binary = reference_bins([0.0] * 900 + [1.0] * 100) # tied deciles + assert psi(binary, [0.0] * 90 + [1.0] * 10) < 0.01 + assert psi(binary, [1.0] * 100) > 1.0 + + +def test_drift_report_needs_enough_rows(tmp_path: Path) -> None: + card = { + "run_id": "r", + "feature_columns": ["x"], + "reference_bins": {"x": reference_bins([0.0, 1.0] * 50)}, + } + log = tmp_path / "scores.jsonl" + assert drift_report(card, log)["status"] == "insufficient_data" + for i in range(40): + log_score({"run_id": "r", "features": {"x": 5.0 + i}}, log) + report = drift_report(card, log) + assert report["status"] == "ok" + assert report["shifted"] == ["x"] From c83fa53b491aff7f9dea350f34eb184a55cbf107 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Thu, 29 Oct 2026 09:01:05 +0300 Subject: [PATCH 03/92] docs(ml): data card, method, results and decision log - ML.md: verified contents, label-quality findings and licenses of the three sources; collection budget and its accounting; features, study window, splits and purge; models and gate; results of run 20261029T055343Z-41bb2f56 with failure modes (plain token transfers are the blind spot, complementary to the wallet-history poisoning detector); measured runtime, memory and reproducibility; decisions revised after seeing data; limitations. - ML_EVALUATION.md generated by that run. - README, CHANGELOG, SECURITY (pickle loading), .env.example. Co-Authored-By: Claude Opus 5.5 --- .env.example | 6 ++ CHANGELOG.md | 12 ++++ ML.md | 182 +++++++++++++++++++++++++++++++++++++++++++++++ ML_EVALUATION.md | 103 +++++++++++++++++++++++++++ README.md | 13 ++-- SECURITY.md | 4 ++ 6 files changed, 314 insertions(+), 6 deletions(-) create mode 100644 ML.md create mode 100644 ML_EVALUATION.md diff --git a/.env.example b/.env.example index bdb17e6..6c0c30f 100644 --- a/.env.example +++ b/.env.example @@ -55,6 +55,12 @@ CRYPTOGUARD_CAMPAIGN_RUNS_RETAINED=20 # RPC request budget of one `cryptoguard campaigns expand` run. CRYPTOGUARD_CAMPAIGN_EXPANSION_MAX_REQUESTS=600 +# Experimental ML transaction scoring (needs the ml extra and a promoted model; see ML.md). +# "shadow" returns scores for review only: never findings, never severity changes. +CRYPTOGUARD_ML_SHADOW=off +CRYPTOGUARD_ML_REGISTRY_PATH=data/ml/registry.json +CRYPTOGUARD_ML_SCORE_LOG_PATH=data/ml/shadow_scores.jsonl + CRYPTOGUARD_DATABASE_URL=sqlite:///./data/cryptoguard.db # JSON list. Wildcards are rejected. diff --git a/CHANGELOG.md b/CHANGELOG.md index 97fabbf..0896a74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces may change. +## Unreleased (branch `feature/ml-pipeline`) + +### Experimental machine learning (shadow mode, `ml` extra) +- Pinned, hash-verified external label sources (PTXPhish, Poison-Hunter, Forta); the two + without a license are fetched locally, never redistributed (`aee2bf4`). +- Budgeted, resumable collection of point-in-time chain data for a deterministic + stratified sample; validated feature table with an input-hash manifest (`aee2bf4`). +- Study window, time-ordered splits and per-account purge against reused attacker + infrastructure; trivial, rule and learned baselines; run ledger; promotion gate; + hash-pinned model registry; shadow scoring API and CLI; PSI drift monitoring + (`e9b49f1`). Results in ML_EVALUATION.md, data card and decision log in ML.md. + ## 0.1.0 — 2026-10-28 (first release candidate, not independently audited) ### Detection and monitoring diff --git a/ML.md b/ML.md new file mode 100644 index 0000000..599daf7 --- /dev/null +++ b/ML.md @@ -0,0 +1,182 @@ +# Machine learning (experimental, shadow mode only) + +CryptoGuard has an optional ML subsystem (`src/cryptoguard/ml/`, the `ml` extra). It +classifies an Ethereum **transaction** as part of a phishing operation or not, using +features that were knowable when the transaction executed. It is trained and evaluated on +independently labelled public data, compared with trivial and rule baselines on identical +held-out rows, and integrated **only in shadow mode**: scores are returned for review and +monitored for drift, and they never create, change or resolve findings. + +Generated results: [ML_EVALUATION.md](ML_EVALUATION.md). This page is the data card, +method and decision log. + +## Data card + +### Sources (pinned) + +| Source | Content (verified) | License | Use | +|---|---|---|---| +| [PTXPhish](https://github.com/HypoopyH/PTXPhish) @ `18efed8f` (Chen et al., NDSS 2025) | 18,555 unique transaction hashes in 13 subtypes: 4,998 phishing (ice phishing 2,569; NFT order 609; address poisoning 226; payable function 1,594) and 13,557 benign ("KOL" 9,572, "Developer" 3,985). Labels reviewed by two security experts. **No addresses, values or timestamps.** | none published | training and evaluation labels; data fetched locally, never redistributed | +| [Poison-Hunter](https://github.com/DS2L/Poison-Hunter) @ `74ff6f7d` (Guan & Li, CCS 2024) | 5,890 phishing addresses (Etherscan and Forta labels), 1,154 *popular* benign addresses, 150 sample transfers | none published | data card only | +| [Forta labelled-datasets](https://github.com/forta-network/labelled-datasets) @ `40a9c2f2` | Etherscan `phish-hack`, `exploit`, `heist` address labels, last updated January 2023 | MIT | data card only | + +`cryptoguard ml fetch-sources` downloads the files at those commits into `data/external/` +(git-ignored) and refuses any file whose SHA-256 differs from the pinned value +(`ml/sources.py`). + +### Label quality findings + +- PTXPhish holds 4,998 phishing hashes where the paper states 5,000 ("Wallet function": 806 + in the sheet, 808 in the README). No hash appears twice or in two categories. +- Many labelled phishing transactions are the **attacker's** (for ice phishing, the + `transferFrom` that drains the victim), not the victim's approval. The task is therefore + "is this transaction part of a phishing operation", not "is the approval I am about to + sign malicious". +- The benign class consists of transactions by prominent accounts ("KOL") and developers. It + is not a random sample of Ethereum users. Benign transactions span blocks 3.2M to 20.4M + (2017–2024); phishing ones only 15.0M to 18.5M (2022–2023). +- Poison-Hunter's benign addresses are popular accounts, separable from phishing addresses + by popularity alone; its 150-row sample CSV is column-shifted (two more fields per row + than header names). Not used for training. +- Forta's files contain 7,233 duplicate addresses across and within files; Forta and + Poison-Hunter share no address, and Etherscan labels underlie both. +- None of the ~13,000 labelled phishing addresses and none of the 18,555 PTXPhish + transactions appears in CryptoGuard's recorded replay fixtures (2,396 addresses), so + CryptoGuard's own detectors cannot be evaluated on these labels. + +### Chain data (collected once, budgeted) + +`ml sample` draws a deterministic stratified sample (seed 20261029): all 226 address-poisoning +transactions, 1,125 other phishing transactions and 1,350 benign ones (2,701 total). +`ml collect` reads, per transaction, the transaction, its receipt, the sender's nonce and the +target's code **at the previous block**, from `eth.drpc.org`, under a hard cap of 12,000 +requests that counts every attempt including retries and is written after every +transaction. Result: 2,527 transactions collected, 174 skipped by the budget guard, none +missing on chain; 11,953 requests charged in total. One collection run was interrupted +before it could record its count; it was charged a conservative upper estimate (recorded in +the ledger file). Chain data stays local (`data/ml/chain/`). + +## Method + +**Features** (`ml/features.py`, 40, pure Python, shared by training and scoring): value, +gas, fee type, calldata size, known function families by selector (approve, permit, operator +grant, transfer, delegated transfer, multicall, Seaport, proxy upgrade), contract-creation +and target code properties (code size, EIP-7702 delegation, vanity zero runs), sender's prior +transaction count, receipt status and gas ratio, log structure (Transfer, Approval and +ApprovalForAll counts, zero-value and delegated transfers, recipients, unlimited approvals) +and the largest lookalike affix among the transaction's parties. Deliberately **not** +features: block number or time (the classes come from different eras) and raw addresses or +hashes. + +**Study window and splits** (`ml/splits.py`): + +1. Only blocks where both classes occur (15,030,659 to 18,928,566). +2. Time order: train is the earliest 60%, validation the next 20%, test the last 20%; no + block is shared. +3. Account purge: a validation or test row that shares any account (sender, target, + spender, recipient) with an earlier split is dropped, except accounts in a curated + registry of public infrastructure (major tokens, DEX routers, marketplaces, Permit2). + This removed 199 validation and 176 test rows that would otherwise have leaked. + +**Models** (`ml/train.py`): majority and stratified dummies; two rules (a hand-written +"phishing-shaped call" heuristic and a transaction-level proxy of CryptoGuard's signals); +logistic regression, random forest and LightGBM, each on all features and without the three +identity-like features (`no_identity`). Hyperparameters, threshold (F1 on validation), +feature set and the selected model are chosen on validation by log loss; test is scored once. +Every run is appended to `data/ml/runs/ledger.jsonl` with git SHA, package versions, the +dataset manifest hash, configuration and metrics. + +**Promotion gate**: on validation, close at least half of the AP gap between the best +non-learned baseline and 1.0; on test, the model's 95% AP interval must lie above the best +baseline's test AP. Only a gated run can be promoted (`ml promote`). + +## Results (run `20261029T055343Z-41bb2f56`, code `e9b49f1`) + +| Model (test: 129 phishing, 43 benign) | Test AP [95% CI] | ROC-AUC | Recall | False-positive rate [95% CI] | +|---|---|---|---|---| +| Majority | 0.750 | 0.500 | 1.000 | 1.000 | +| Rule: phishing-shaped call | 0.845 [0.797, 0.891] | 0.694 | 0.411 | 0.023 [0.000, 0.077] | +| Rule: CryptoGuard-signal proxy | 0.750 | 0.500 | 0.047 | 0.047 | +| **LightGBM (selected)** | **0.999** [0.996, 1.000] | 0.995 | 0.977 | 0.163 [0.056, 0.273] | +| LightGBM without identity features | 0.991 | 0.976 | 0.977 | 0.209 | +| Logistic regression | 0.978 | 0.951 | 0.891 | 0.047 [0.000, 0.116] | + +Full table, intervals, per-family recall, importance and errors: [ML_EVALUATION.md](ML_EVALUATION.md). + +**What this does and does not show.** On held-out, later, account-disjoint transactions the +learned models rank phishing-operation transactions far better than any rule. The result +holds without the identity-like features. The model relies mostly on transaction *shape*: +delegated `transferFrom` calls (permutation importance 0.30), log count, proxy upgrades, +vanity-mined targets and target code size. The CryptoGuard-signal proxy is at chance +because those signals (unlimited approvals, zero-value transfers) describe wallet exposure +and are common in benign traffic too; CryptoGuard's detectors are wallet-centric and need +wallet history that this dataset lacks, so they could not be run on it. + +**Failure modes.** + +- The false-positive rate is about 16% on prominent accounts' transactions, measured on + only 43 benign rows. On ordinary traffic, where phishing is far rarer than the 75% of this + test set, most alerts would be false. This is why the model stays in shadow mode. +- **Plain token transfers are the blind spot.** 5 of the 7 test false positives and 2 of the 3 + missed phishing transactions (address poisoning) have the same shape: one `transfer()` + call, one Transfer log, no ETH value. By transaction shape alone, a poisoning transfer and + an ordinary payment look the same. Telling them apart needs the wallet's history (does + the recipient imitate an earlier counterparty?), which is exactly what CryptoGuard's + wallet-centric poisoning detector checks: the two are complementary, not substitutes. +- The other 2 false positives call vanity-mined contracts (10 and 14 leading or trailing + zero nibbles), a property the model learned from phishing contracts. +- The third miss is a fake-token transfer whose receipt holds no logs at all. + +## Shadow mode + +```powershell +uv sync --extra ml +uv run cryptoguard ml fetch-sources # labels (hash-verified) +uv run cryptoguard ml sample # deterministic sample +uv run cryptoguard ml collect --rpc-url # budgeted, resumable +uv run cryptoguard ml build # validated table, splits, manifest +uv run cryptoguard ml train # ledger, model card, ML_EVALUATION.md +uv run cryptoguard ml promote data/ml/runs/ # refused unless the gate passed +uv run cryptoguard ml score --rpc-url # one shadow score (4 RPC calls) +uv run cryptoguard ml monitor # feature drift (PSI) of scored txs +``` + +With `CRYPTOGUARD_ML_SHADOW=shadow`, the API offers `POST /api/v1/ml/transactions/score` +(`{"tx_hash"}`; the RPC endpoint is the operator's, never the request's) and +`GET /api/v1/ml/status` (promoted run, gate, drift). With the default `off` both answer 409 +`feature_disabled`; without the extra or a promoted model, 503 `ml_unavailable`. Scores are +logged to `data/ml/shadow_scores.jsonl` for drift monitoring and are never stored as +findings. The promoted model is a pickle; it is loaded only from the local registry and only +if its SHA-256 matches its model card. + +A full training run (10 model configurations after a 36-candidate search, bootstrap +intervals, permutation importance) took 34–44 s on a 4-core CPU with a peak of 197 MiB +(`scripts/peak_memory.py ml train`). It is deterministic: a repeated run gave identical +metrics for every model and a byte-identical model file. No GPU and no graph neural +network: gradient boosting on tabular features already ranks near the ceiling here, and the +data has no graph beyond each transaction's own parties. + +## Decision log (changes made after seeing data) + +These choices were revised during development; each revision was made before the final run +and is kept in the run ledger. + +1. **Study window.** Added after the first data showed the classes come from different eras. +2. **Hub rule.** The first rule exempted accounts used by 10+ distinct senders. A leakage test + showed that a scam contract called by many victims would be exempted, letting its later + victims reach the test split. Replaced by a curated registry; over-linking only costs rows. +3. **Promotion gate.** The first gate ("+0.05 AP over the best baseline") could not be met when + that baseline already exceeded 0.95 (seen on a partial-data dry run). Replaced by "close + half of the remaining gap". +4. **Selection metric.** AP saturates near 1.0 here, so model selection and permutation + importance use log loss. + +## Limitations + +- One labelled source, with a benign class of prominent accounts; precision on real traffic + is unknown and likely low. +- Small evaluation splits after the window and purge; intervals are wide. +- Receipt-based features describe executed transactions; warning before signing would need + transaction simulation (not implemented). +- Live scoring costs 4 RPC requests per transaction and needs historical state. +- Not independently reviewed. diff --git a/ML_EVALUATION.md b/ML_EVALUATION.md new file mode 100644 index 0000000..e669945 --- /dev/null +++ b/ML_EVALUATION.md @@ -0,0 +1,103 @@ +# ML evaluation (experimental, shadow mode only) + +Generated by `cryptoguard ml train` on 2026-10-29 05:53 UTC; do not edit by hand. Run `20261029T055343Z-41bb2f56`, code `e9b49f1795e45b3b4770758496f7256f67b9c46f`, cg-ml/0.1.0, features `ptx-features/1`. Training and evaluation took 44.2 s on CPU. + +## Task + +Classify an Ethereum transaction as part of a phishing operation or not, from information available when it executed: the transaction, its receipt, and the sender's nonce and target's code at the previous block. Labels come from PTXPhish (NDSS 2025), reviewed by two security experts and independent of CryptoGuard. Many labelled phishing transactions are the *attacker's* (for ice phishing, the `transferFrom` that drains the victim), so this is not a pre-signing warning for a victim's own approval. + +## Data + +| Source | Pinned commit | License | Use | +|---|---|---|---| +| [HypoopyH/PTXPhish](https://github.com/HypoopyH/PTXPhish) | `18efed8f8e` | none published (not redistributed) | training and evaluation labels | +| [DS2L/Poison-Hunter](https://github.com/DS2L/Poison-Hunter) | `74ff6f7d14` | none published (not redistributed) | data card only | +| [forta-network/labelled-datasets](https://github.com/forta-network/labelled-datasets) | `40a9c2f2bd` | MIT | data card only | + +- Collected: 2527 labelled transactions with chain data (sample of 2701; 11945 of 12,000 approved RPC requests used; not found on chain: 0). Blocks 3,183,842 to 20,386,042. +- Per subtype: address_poisoning/dust_value_transfer 21, address_poisoning/fake_token_transfer 97, address_poisoning/zero_value_transfer 96, benign/benign_developer 375, benign/benign_kol 891, ice_phishing/approve 273, ice_phishing/permit 178, ice_phishing/setapproveforall 113, nft_order/bulk_transfer 8, nft_order/free_buy_order 104, nft_order/proxy_upgrade 25, payable_function/airdrop_function 174, payable_function/wallet_function 172. +- Account groups (diagnostic): 293 groups, largest 1667 rows, 1 mixed-label group(s) holding 1667 rows; 1056 phishing rows share infrastructure with another phishing row. + +## Splits + +Study window: blocks 15,030,659 to 18,928,566, where both classes occur (benign transactions outside it are excluded, or the era alone would separate the classes). Ordered by block: validation from block 17,638,864, test from 17,988,326. Rows sharing a non-hub account with an earlier split are dropped; hubs come from training rows only (14). + +| Split | Benign | Phishing | +|---|---|---| +| excluded:outside_window | 791 | 0 | +| excluded:shares_account_with_earlier_split(test) | 108 | 68 | +| excluded:shares_account_with_earlier_split(validation) | 102 | 97 | +| test | 43 | 129 | +| train | 190 | 851 | +| validation | 32 | 116 | + +## Results + +Hyperparameters, thresholds and the selected model were chosen on validation; test was scored once. AP = average precision (PR-AUC); intervals are 95% bootstrap intervals over test rows. + +Test rows: 172 (129 phishing, 43 benign; phishing share 0.75, so any ranking scores AP of at least that much — compare AP lift and the false-positive rate, measured on only 43 benign rows). + +| Model | Features | Val log loss | Val AP | Test AP [95% CI] | Test AP lift | Test ROC-AUC | Test bal. acc. | Test recall [95% CI] | Test FPR [95% CI] | +|---|---|---|---|---|---|---|---|---|---| +| majority | — | 2.987 | 0.784 | 0.750 | 0.000 | 0.500 | 0.500 | 1.000 | 1.000 | +| stratified | — | 4.574 | 0.771 | 0.769 | 0.078 | 0.550 | 0.550 | 0.868 | 0.767 | +| rule_phishing_shape | — | — | 0.923 | 0.845 [0.797, 0.891] | 0.380 | 0.694 | 0.694 | 0.411 [0.324, 0.500] | 0.023 [0.000, 0.077] | +| rule_cryptoguard_signals | — | — | 0.789 | 0.750 [0.687, 0.818] | 0.000 | 0.500 | 0.500 | 0.047 [0.016, 0.086] | 0.047 [0.000, 0.115] | +| lightgbm (selected) | full | 0.077 | 0.997 | 0.999 [0.996, 1.000] | 0.994 | 0.995 | 0.907 | 0.977 [0.946, 1.000] | 0.163 [0.056, 0.273] | +| lightgbm | no_identity | 0.109 | 0.990 | 0.991 [0.979, 0.999] | 0.964 | 0.976 | 0.884 | 0.977 [0.946, 1.000] | 0.209 [0.095, 0.333] | +| logistic_regression | full | 0.114 | 0.993 | 0.978 [0.951, 0.997] | 0.911 | 0.951 | 0.922 | 0.891 [0.843, 0.941] | 0.047 [0.000, 0.116] | +| logistic_regression | no_identity | 0.250 | 0.984 | 0.979 [0.960, 0.993] | 0.916 | 0.942 | 0.868 | 0.969 [0.939, 0.993] | 0.233 [0.108, 0.359] | +| random_forest | full | 0.098 | 0.999 | 0.996 [0.990, 1.000] | 0.983 | 0.988 | 0.930 | 0.977 [0.946, 1.000] | 0.116 [0.028, 0.225] | +| random_forest | no_identity | 0.143 | 0.996 | 0.984 [0.963, 0.999] | 0.938 | 0.967 | 0.930 | 0.977 [0.946, 1.000] | 0.116 [0.029, 0.220] | + +Selected: **lightgbm** on `full` features, {'num_leaves': 7, 'min_child_samples': 5}, threshold 0.252. Test confusion: {'tn': 36, 'fp': 7, 'fn': 3, 'tp': 126}. + +Test recall by phishing family: address_poisoning 0.95, ice_phishing 1.00, nft_order 1.00, payable_function 1.00. + +### Promotion gate (shadow mode) + +- On validation, close at least 50% of the AP gap between the best baseline (0.923) and 1.0 (closed: 96%): **True**. +- Test AP interval must lie above the best baseline's test AP (0.845): **True**. +- Validated for shadow mode: **True**. + +### What the selected model relies on + +Permutation importance on validation (increase in log loss when a feature is shuffled): + +- `fn_transfer_from`: 0.297 ± 0.063 +- `n_logs`: 0.101 ± 0.008 +- `fn_upgrade`: 0.089 ± 0.001 +- `to_vanity_zero_nibbles`: 0.077 ± 0.012 +- `to_code_size_log`: 0.052 ± 0.014 +- `fn_transfer`: 0.025 ± 0.007 +- `n_transfers`: 0.017 ± 0.008 +- `value_eth_log`: 0.008 ± 0.002 +- `sender_prior_txs_log`: 0.007 ± 0.009 +- `gas_price_gwei_log`: 0.005 ± 0.003 + +### Errors on test + +Missed phishing (lowest scores first, up to 15 of 3): + +- `0x92aee8b3fdf9ce62fd466a92f2916a2581297fb779be087ef7de57f60f458b24` address_poisoning/zero_value_transfer, score 0.041 +- `0xa8d0ac9c1f495af05b748749833e2b94012410132ac40c3aa0aa5200a65a6523` address_poisoning/fake_token_transfer, score 0.086 +- `0xa1d7ed71f72770f320ed68efac1fe45295575ba1ebe9be87f624c128713defa9` address_poisoning/zero_value_transfer, score 0.086 + +Benign flagged (highest scores first, up to 15 of 7): + +- `0x1a03582da5059429673e4c988990da5eae851d73dffe69c9ec16f1fa9aa365c8` benign_kol, score 0.793 +- `0x23dc9650b82bd84206dec77cec6e26073fdac808b331a3f610f94941057becea` benign_kol, score 0.450 +- `0x906693a0700648f8f2b8dcc2d40f6b7426222c5c818d58dc9ce9a8d65137cc25` benign_kol, score 0.365 +- `0xd4d346531ca5347601099708d99594c55ff80ec2c4b2f798dba7e3dd72c80e16` benign_kol, score 0.311 +- `0x3f2f560a11d0e02576c8393166a515309898832047f6b431f74288e4e8f9beb9` benign_kol, score 0.307 +- `0xad114373e700c534cd09bacd665640bd6e7b162323f3640714424b51493b3866` benign_kol, score 0.303 +- `0x86d61c0e265682633ddcb86b597d3adf2ea752419fd7380cd1088b1cea32474b` benign_kol, score 0.255 + +## Limitations + +- One labelled source. PTXPhish's benign class is transactions of prominent accounts ("KOL") and developers, not a random sample of Ethereum users; precision on real traffic, where phishing is far rarer than here, will be much lower than measured. +- The `no_identity` rows show how much depends on who sends a transaction (long histories, vanity addresses) rather than what it does; those signals partly reflect how the dataset was built. +- Small test split after the time window and account purge; intervals are wide. +- The CryptoGuard comparison is a transaction-level proxy of its signals, not its wallet-centric detectors, which need wallet history this dataset lacks. +- Features use the receipt (logs of the executed transaction). Scoring a transaction before it is signed would need a simulation, which is not implemented. +- Not independently reviewed. The model never creates findings (shadow mode only). diff --git a/README.md b/README.md index 62b463d..9c28c6f 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,8 @@ evidence of common ownership ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). | Cross-wallet poisoning campaign analysis: canonical attempts, planting-side relationship evidence (shared planting transaction, verified signer, lookalike), conservative clustering with hub and transitivity guards, budgeted resumable expansion around planting signers and lookalikes, read-only API and UI section ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)) | Experimental, **off by default** (shadow mode): real cross-wallet links found, no earlier theft warning than the existing detector | | Network, structural and activity-rate analyses (graph propagation, spectral features, robust burst statistics) over stored observations, coverage-aware and point in time | Experimental, **off by default**: evaluated with no measurable gain over the existing detector; available in shadow mode only (see [DETECTION_METHODS.md](DETECTION_METHODS.md)) | | Wallet-signed transactions (incl. native-ETH payments) located by nonce search in snapshots and scans; used by the poisoning detector and the graph; degrades to explicit "unlocated" counts without archive state | Implemented | -| Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals, ML | Not yet | +| Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, hash-pinned model registry, drift monitoring ([ML.md](ML.md), [ML_EVALUATION.md](ML_EVALUATION.md)) | Experimental, **off by default** (shadow mode, `ml` extra): test AP 0.999 vs 0.845 for the best rule, but a 16% false-positive rate on 43 benign test rows; never creates findings | +| Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals | Not yet | ## Quick start @@ -333,11 +334,11 @@ See [SECURITY.md](SECURITY.md) for reporting and the threat model. wallets; more needed before any rate can be estimated). Experimental graph, spectral, temporal and cross-wallet campaign analyses were evaluated on top; none is enabled by default ([EVALUATION.md](EVALUATION.md), [CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). -8. **Machine learning: deferred, deliberately.** The brief allows ML only once enough data - exists. It does not: 4 labelled thefts, 9 unlabelled background wallets, and no - independent labels for attempts or campaigns. Any classifier trained here would either - overfit 4 positives or learn to imitate CryptoGuard's own rules (circular). Revisit when a - labelled, time-split dataset exists that a deterministic baseline can be measured on. +8. ~~Machine learning~~ (experimental, shadow mode; [ML.md](ML.md)). Not trained on + CryptoGuard's own 4 incidents (too few, and circular), but on an independently labelled + public dataset of 18,555 transactions (PTXPhish), with chain features collected under a + fixed request budget. Next: a benign class drawn from ordinary users rather than + prominent accounts, and pre-signing scoring by simulation. 9. ~~Release quality~~: security, dependency, reproducibility and packaging review (see [CHANGELOG.md](CHANGELOG.md)). Not independently audited. diff --git a/SECURITY.md b/SECURITY.md index eac4112..dcbd946 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,6 +18,10 @@ characters and truncated, and is always labelled untrusted. Responses are JSON only (`Content-Security-Policy: default-src 'none'`, `nosniff`), and validation errors do not echo input. - **Chain verification.** `eth_chainId` must match the configured chain before any state read. +- **Experimental ML model files** are pickles, and loading a pickle runs code. The shadow + model is loaded only from the local registry and only if its SHA-256 matches the hash its + model card recorded at training time; a model file from anywhere else must never be placed + there. ML scoring is off by default and accepts only a transaction hash. - **Resource limits.** Request timeouts, bounded retries (with capped `Retry-After`), bounded RPC concurrency, a response-size cap, bounded `eth_getLogs` block ranges, a request-body limit (POST requires `Content-Length`), and per-client rate limiting with bounded memory. From 91036ba02d5c0e407e54bf22c2860ef9fdb42a69 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Thu, 29 Oct 2026 09:02:07 +0300 Subject: [PATCH 04/92] fix(ml): write ML_EVALUATION.md with LF line endings on every OS Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 0b9c618..2b5fd10 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -190,7 +190,7 @@ def _train(args: argparse.Namespace) -> int: with (RUNS / "ledger.jsonl").open("a", encoding="utf-8") as fh: fh.write(json.dumps({k: entry[k] for k in entry if k != "results"}, default=str) + "\n") report = render_report(entry, out, json.loads(manifest_path.read_text())) - args.report.write_text(report, encoding="utf-8") + args.report.write_text(report, encoding="utf-8", newline="\n") # same bytes on every OS sel = entry["selected"] print( f"run {run_id}: selected {sel['name']} ({sel['feature_set']}), " From c11e5fb524e42a18eef0ad65c7cc6f7b472977d0 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Sun, 1 Nov 2026 19:38:28 +0300 Subject: [PATCH 05/92] fix(ml): Phase 11.1 hardening and offline audit tooling Defects found by the audit, each with regression tests: - Scoring skipped chain verification (raw client): now verify_chain() and mainnet only, the chain the model was trained on. - A mined transaction without a receipt was scored as 'failed, no logs': now status incomplete, never scored or checkpointed as done. - The API scored with a model that had no untouched-holdout evidence: approval levels research_only / shadow_approved; the API needs the latter, promotion to it needs a passed untouched holdout in the card. - Request budget counted attempts after the fact (an interrupted run lost its count; concurrent collectors could overspend): every HTTP attempt now reserves a unit first in a locked, atomically replaced, fail-closed ledger; cut-off checkpoint tails are repaired. A thread race test found and fixed a Windows lock error. - Registry trusted a path from registry.json: validated run ids inside the runs root, card schema, size limit, library-version check. LightGBM models are now stored as LightGBM text (no pickle). - Bootstrap resampled rows although PTXPhish rows cluster by account: intervals now resample account groups. Runs store per-row predictions and are keyed on table and split hashes. - Monitoring: outcomes, latency, score distribution, schema mismatches, bounded log reads. New: ml/audit.py (cryptoguard ml audit: recomputed metrics, Wilson and cluster intervals, prevalence arithmetic, fixed-hyperparameter shortcut experiments, hub-policy sensitivity, duplicates, calibration, errors) and ml/history.py (point-in-time wallet-history features with an explicit zero-versus-unknown contract; infrastructure, no accuracy claim). Scoring is bounded (one at a time, 30 s timeout) and labelled as an uncalibrated ranking score, post-inclusion. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/api/ml_routes.py | 10 +- src/cryptoguard/ml/audit.py | 767 +++++++++++++++++++++++++++++++ src/cryptoguard/ml/cli.py | 89 +++- src/cryptoguard/ml/collect.py | 249 +++++++--- src/cryptoguard/ml/history.py | 226 +++++++++ src/cryptoguard/ml/inference.py | 126 ++++- src/cryptoguard/ml/monitoring.py | 64 ++- src/cryptoguard/ml/registry.py | 188 ++++++-- src/cryptoguard/ml/splits.py | 12 +- src/cryptoguard/ml/train.py | 65 ++- tests/integration/test_ml_api.py | 127 ++++- tests/ml_synthetic.py | 17 +- tests/unit/test_ml_audit.py | 88 ++++ tests/unit/test_ml_collector.py | 236 ++++++++++ tests/unit/test_ml_history.py | 156 +++++++ tests/unit/test_ml_pipeline.py | 317 ++++++++++--- 16 files changed, 2510 insertions(+), 227 deletions(-) create mode 100644 src/cryptoguard/ml/audit.py create mode 100644 src/cryptoguard/ml/history.py create mode 100644 tests/unit/test_ml_audit.py create mode 100644 tests/unit/test_ml_collector.py create mode 100644 tests/unit/test_ml_history.py diff --git a/src/cryptoguard/api/ml_routes.py b/src/cryptoguard/api/ml_routes.py index b16c6f2..fbd9ab0 100644 --- a/src/cryptoguard/api/ml_routes.py +++ b/src/cryptoguard/api/ml_routes.py @@ -31,6 +31,8 @@ class ScoreRequest(BaseModel): class MlStatus(BaseModel): experimental: bool = True run_id: str + approval: str + score_semantics: str = "uncalibrated_ranking" selected: dict[str, Any] gate: dict[str, Any] drift: dict[str, Any] @@ -40,11 +42,12 @@ class MlStatus(BaseModel): async def score(request: Request, body: ScoreRequest) -> ShadowScore: """EXPERIMENTAL: shadow-mode phishing score for one transaction (never a finding).""" state = get_state(request) - loaded_model(state.settings) # 409 / 503 before any RPC call + loaded_model(state.settings) # 409 / 503 (off, unavailable, not shadow-approved) before RPC provider = require_provider(state.provider) if not isinstance(provider, RpcEthereumProvider): raise MlUnavailableError("ML scoring needs a real RPC provider (not demo fixtures).") - return await score_transaction(provider.client, body.tx_hash, state.settings) + chain_id = await provider.verify_chain() # the raw client below bypasses the provider + return await score_transaction(provider.client, body.tx_hash, state.settings, chain_id=chain_id) @router.get("/ml/status", response_model=MlStatus) @@ -53,9 +56,10 @@ async def status(request: Request) -> MlStatus: from cryptoguard.ml.monitoring import drift_report settings = get_state(request).settings - model = loaded_model(settings) + model = loaded_model(settings, require_shadow_approval=False) # status of any registered model return MlStatus( run_id=model.run_id, + approval=model.approval, selected=model.card["selected"], gate=model.card["gate"], drift=drift_report(model.card, Path(settings.ml_score_log_path)), diff --git a/src/cryptoguard/ml/audit.py b/src/cryptoguard/ml/audit.py new file mode 100644 index 0000000..00489b3 --- /dev/null +++ b/src/cryptoguard/ml/audit.py @@ -0,0 +1,767 @@ +"""Generalization audit of a trained run (Phase 11.1). Offline only: no RPC calls. + +Everything here reads stored artifacts (feature table, splits, collected chain records, a +run's model) and recomputes evidence independently of ``train.py``: + +- metrics recomputed with this module's own NumPy implementations; +- Wilson intervals for proportions and a *cluster* bootstrap (rows from one account + component are resampled together: PTXPhish draws up to 200 benign transactions per + account and up to 50 per scammer address, so rows are not independent); +- low-prevalence alert arithmetic (scenarios, not deployment measurements); +- shortcut experiments: fixed hyperparameters on restricted feature sets, no per-subset + tuning; +- sensitivity of split sizes and scores to the hub policy (reported, never used to choose); +- exact feature-vector duplicates across splits; calibration bins; per-error features. + +The old test split has been looked at during development (see ML_GENERALIZATION_AUDIT.md), +so every number on it is a *development benchmark*, never an untouched holdout. +""" + +from __future__ import annotations + +import hashlib +import itertools +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from cryptoguard.ml.features import FEATURES, SELECTORS, parties + +if TYPE_CHECKING: + import numpy as np + import pandas as pd + +SEED = 20261101 +PREVALENCES = (0.0001, 0.001, 0.01, 0.05) + +# Restricted feature sets for the shortcut experiments (fixed before running them). +SELECTOR = (*(f"fn_{n}" for n in SELECTORS), "fn_other", "input_is_bare_selector") +TX_TYPE = ("is_typed_fee", "is_contract_creation", "is_zero_value", "input_bytes_log") +INTERACTION = ( + "to_is_contract", + "to_code_size_log", + "to_is_delegated_eoa", + "gas_used_ratio", + "status_success", +) +HISTORY = ("sender_prior_txs_log",) +SIMILARITY = ("max_party_affix_match", "to_vanity_zero_nibbles", "from_vanity_zero_nibbles") +LOG_STRUCTURE = ( + "n_logs", + "n_log_emitters", + "n_transfers", + "n_zero_value_transfers", + "n_transfers_not_from_sender", + "n_transfers_from_sender", + "n_transfers_to_sender", + "n_transfer_recipients", + "n_approvals", + "n_unlimited_approvals", + "n_approval_for_all_granted", +) +ERA_PROXIES = ("is_typed_fee", "gas_price_gwei_log", "gas_limit_log") + + +def _minus(*groups: tuple[str, ...]) -> tuple[str, ...]: + drop = {f for g in groups for f in g} + return tuple(f for f in FEATURES if f not in drop) + + +ABLATIONS: dict[str, tuple[str, ...]] = { + "full": FEATURES, + "selector_only": SELECTOR, + "tx_type_only": TX_TYPE, + "interaction_only": INTERACTION, + "history_only": HISTORY, + "similarity_only": SIMILARITY, + "log_structure_only": LOG_STRUCTURE, + "all_minus_selector": _minus(SELECTOR), + "all_minus_history": _minus(HISTORY), + "all_minus_identity": _minus(HISTORY, SIMILARITY[1:]), + "all_minus_era_proxies": _minus(ERA_PROXIES), + "all_minus_shortcuts": _minus(SELECTOR, HISTORY, SIMILARITY[1:], ERA_PROXIES), +} +FIXED_LIGHTGBM = {"num_leaves": 7, "min_child_samples": 5} # the Phase 11 selection +FIXED_LOGREG = {"C": 1.0} + + +# --- metrics (independent of sklearn) ------------------------------------------------------- + + +def roc_auc(y: np.ndarray, score: np.ndarray) -> float | None: + """Mann-Whitney AUC with average ranks for ties.""" + import pandas as pd + + pos, neg = int(y.sum()), int(len(y) - y.sum()) + if pos == 0 or neg == 0: + return None + ranks = pd.Series(score).rank(method="average").to_numpy() + return float((ranks[y == 1].sum() - pos * (pos + 1) / 2) / (pos * neg)) + + +def confusion(y: np.ndarray, score: np.ndarray, threshold: float) -> dict[str, int]: + pred = score >= threshold # a score equal to the threshold counts as positive + return { + "tp": int(((y == 1) & pred).sum()), + "fp": int(((y == 0) & pred).sum()), + "fn": int(((y == 1) & ~pred).sum()), + "tn": int(((y == 0) & ~pred).sum()), + } + + +def wilson(k: int, n: int, z: float = 1.959964) -> list[float] | None: + """Wilson score interval for k successes in n trials.""" + if n == 0: + return None + p = k / n + denom = 1 + z * z / n + centre = (p + z * z / (2 * n)) / denom + half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom + # The analytic endpoints at k = 0 and k = n are exactly 0 and 1 (avoid 0.9999999999999999). + lo = 0.0 if k == 0 else max(0.0, centre - half) + hi = 1.0 if k == n else min(1.0, centre + half) + return [lo, hi] + + +def evaluate(y: np.ndarray, score: np.ndarray, threshold: float) -> dict[str, Any]: + import numpy as np + + from cryptoguard.ml.train import fast_average_precision + + c = confusion(y, score, threshold) + pos, neg = c["tp"] + c["fn"], c["fp"] + c["tn"] + flagged = c["tp"] + c["fp"] + prevalence = pos / len(y) if len(y) else 0.0 + ap = fast_average_precision(y, score) if pos and neg else None + clipped = np.clip(score, 1e-6, 1 - 1e-6) + return { + "rows": len(y), + "positives": pos, + "negatives": neg, + "prevalence": prevalence, + "confusion": c, + "recall": c["tp"] / pos if pos else None, + "recall_wilson": wilson(c["tp"], pos), + "false_positive_rate": c["fp"] / neg if neg else None, + "fpr_wilson": wilson(c["fp"], neg), + "precision": c["tp"] / flagged if flagged else None, + "precision_wilson": wilson(c["tp"], flagged), + "f1": 2 * c["tp"] / (2 * c["tp"] + c["fp"] + c["fn"]) if pos else None, + "balanced_accuracy": (c["tp"] / pos + c["tn"] / neg) / 2 if pos and neg else None, + "average_precision": ap, + "ap_above_prevalence": None if ap is None else ap - prevalence, + "ap_lift": None if ap is None or prevalence >= 1 else (ap - prevalence) / (1 - prevalence), + "roc_auc": roc_auc(y, score), + "log_loss": float(-np.mean(y * np.log(clipped) + (1 - y) * np.log(1 - clipped))), + "brier": float(np.mean((score - y) ** 2)), + } + + +def cluster_bootstrap( + y: np.ndarray, score: np.ndarray, threshold: float, clusters: np.ndarray, n: int = 2000 +) -> dict[str, Any]: + """Percentile intervals from resampling whole clusters (account components).""" + import numpy as np + + from cryptoguard.ml.train import fast_average_precision + + rng = np.random.default_rng(SEED) + ids = np.unique(clusters) + members = [np.flatnonzero(clusters == c) for c in ids] + ap, rec, fpr = [], [], [] + for _ in range(n): + idx = np.concatenate([members[i] for i in rng.integers(0, len(ids), len(ids))]) + yi, si = y[idx], score[idx] + if yi.sum() in (0, len(yi)): + continue + pred = si >= threshold + ap.append(fast_average_precision(yi, si)) + rec.append(float(pred[yi == 1].mean())) + fpr.append(float(pred[yi == 0].mean())) + + def q(v: list[float]) -> list[float]: + return [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] + + return { + "clusters": len(ids), + "positive_clusters": len(np.unique(clusters[y == 1])), + "negative_clusters": len(np.unique(clusters[y == 0])), + "resamples_used": len(ap), + "average_precision": q(ap), + "recall": q(rec), + "false_positive_rate": q(fpr), + } + + +def prevalence_scenarios( + recall: float, fpr: float, fpr_interval: list[float] +) -> list[dict[str, Any]]: + """Alerts per 10,000 transactions at assumed base rates (arithmetic, not measurement).""" + out = [] + for p in PREVALENCES: + tp, fp = 10_000 * p * recall, 10_000 * (1 - p) * fpr + lo_fp, hi_fp = (10_000 * (1 - p) * f for f in fpr_interval) + out.append( + { + "prevalence": p, + "true_alerts": tp, + "false_alerts": fp, + "alerts": tp + fp, + "precision": tp / (tp + fp) if tp + fp else None, + "false_alerts_range": [lo_fp, hi_fp], + "precision_range": [ + tp / (tp + hi_fp) if tp + hi_fp else None, + tp / (tp + lo_fp) if tp + lo_fp else None, + ], + } + ) + return out + + +def negatives_needed(target_fpr: float, confidence: float = 0.95) -> int: + """Benign rows needed so that observing zero false positives bounds the FPR below the + target at this confidence (exact binomial; about 3 / target at 95%).""" + return math.ceil(math.log(1 - confidence) / math.log(1 - target_fpr)) + + +# --- data helpers --------------------------------------------------------------------------- + + +def degree_hub_policy(records: dict[str, dict[str, Any]]) -> set[str]: + """The Phase 11 policy that was replaced (kept for the sensitivity audit only).""" + senders: dict[str, set[str]] = defaultdict(set) + emitters: dict[str, set[str]] = defaultdict(set) + for rec in records.values(): + sender = (rec["tx"].get("from") or "").lower() + for account in parties(rec): + senders[account].add(sender) + for log in (rec.get("receipt") or {}).get("logs") or []: + emitters[log["address"].lower()].add(sender) + return {a for a, s in senders.items() if len(s) >= 10} | { + a for a, s in emitters.items() if len(s) >= 2 + } + + +def no_hub_policy(records: dict[str, dict[str, Any]]) -> set[str]: + return set() + + +def account_clusters( + table: pd.DataFrame, records: dict[str, dict[str, Any]], index: Any +) -> np.ndarray: + """Union-find components over sender/target/spender/recipient (registry hubs excluded) + for the given rows only: the unit of resampling.""" + import numpy as np + + from cryptoguard.ml.dataset import _UnionFind, hubs + + rows = table.loc[index, "tx_hash"].tolist() + sub = {h: records[h] for h in rows} + hub_set = hubs(sub) + uf = _UnionFind() + for h in rows: + uf.find(h) + for account in sorted(parties(sub[h]) - hub_set): + uf.union(h, "acct:" + account) + return np.array([uf.find(h) for h in rows]) + + +def _fit_predict( + name: str, params: dict[str, Any], train: pd.DataFrame, cols: list[str], *others: pd.DataFrame +) -> list[np.ndarray]: + from cryptoguard.ml.train import make_model + + model = make_model(name, params).fit(train[cols], train["label"].to_numpy()) + return [model.predict_proba(o[cols])[:, 1] for o in others] + + +# --- the audit ------------------------------------------------------------------------------ + + +def run_audit( + table: pd.DataFrame, + split: pd.Series, + records: dict[str, dict[str, Any]], + run_dir: Path, +) -> dict[str, Any]: + import numpy as np + + from cryptoguard.ml.registry import _verified_model + from cryptoguard.ml.splits import make_splits + from cryptoguard.ml.train import best_threshold + + train, val, test = (table[split == s] for s in ("train", "validation", "test")) + y_va, y_te = val["label"].to_numpy(), test["label"].to_numpy() + out: dict[str, Any] = {"seed": SEED} + + # 1. Recompute the run's selected-model metrics from its stored artifact. + card, model = _verified_model(run_dir) + cols = card["feature_columns"] + thr = float(card["threshold"]) + s_va, s_te = (model.predict_proba(p[cols])[:, 1] for p in (val, test)) + recorded = json.loads((run_dir / "run.json").read_text(encoding="utf-8")) + mine_va, mine_te = evaluate(y_va, s_va, thr), evaluate(y_te, s_te, thr) + out["baseline"] = { + "run_id": card["run_id"], + "model_sha256": card["model_sha256"], + "threshold": thr, + "threshold_from_validation_only": abs(best_threshold(y_va, s_va) - thr) < 1e-12, + "validation": mine_va, + "test": mine_te, + "matches_recorded": { + k: abs((mine_te[k] or 0) - (recorded["test"][k] or 0)) < 1e-9 + for k in ( + "average_precision", + "roc_auc", + "recall", + "false_positive_rate", + "precision", + "balanced_accuracy", + "brier", + ) + } + | {"confusion": mine_te["confusion"] == recorded["test"]["confusion"]}, + } + clusters = account_clusters(table, records, test.index) + out["baseline"]["test_cluster_bootstrap"] = cluster_bootstrap(y_te, s_te, thr, clusters) + senders = np.array([records[h]["tx"]["from"].lower() for h in test["tx_hash"]]) + out["baseline"]["test_distinct_senders"] = { + "benign": len(set(senders[y_te == 0])), + "phishing": len(set(senders[y_te == 1])), + } + + # 2. Operating-point arithmetic and sample-size requirements. + out["prevalence_scenarios"] = prevalence_scenarios( + mine_te["recall"], mine_te["false_positive_rate"], mine_te["fpr_wilson"] + ) + out["negatives_needed"] = {str(t): negatives_needed(t) for t in (0.05, 0.01, 0.001)} + + # 3. Errors on the development test split. + flagged = s_te >= thr + err = test.assign(score=s_te) + keep = [ + "tx_hash", + "family", + "subtype", + "score", + *[ + f + for f in ( + "fn_transfer", + "fn_transfer_from", + "fn_other", + "n_logs", + "n_transfers", + "n_zero_value_transfers", + "to_vanity_zero_nibbles", + "sender_prior_txs_log", + "is_zero_value", + ) + if f in err + ], + ] + out["errors"] = { + "false_positives": err[(y_te == 0) & flagged][keep].sort_values("score").to_dict("records"), + "false_negatives": err[(y_te == 1) & ~flagged][keep] + .sort_values("score") + .to_dict("records"), + } + + # 4. Shortcut experiments: fixed hyperparameters, threshold from validation. + ablations = [] + for name, feats in ABLATIONS.items(): + for family, params in (("lightgbm", FIXED_LIGHTGBM), ("logistic_regression", FIXED_LOGREG)): + pv, pt = _fit_predict(family, params, train, list(feats), val, test) + t = best_threshold(y_va, pv) + ev_va, ev_te = evaluate(y_va, pv, t), evaluate(y_te, pt, t) + ablations.append( + { + "features": name, + "n_features": len(feats), + "model": family, + "validation": ev_va, + "test": ev_te, + } + ) + out["ablations"] = ablations + + # 5. Hub-policy sensitivity (descriptive; the production split never changes). + sens = [] + for policy_name, policy in ( + ("registry (used)", None), + ("degree rule (replaced)", degree_hub_policy), + ("no exemptions", no_hub_policy), + ): + alt_split = split if policy is None else make_splits(table, records, hub_policy=policy)[0] + a_tr, a_va, a_te = (table[alt_split == s] for s in ("train", "validation", "test")) + row: dict[str, Any] = { + "policy": policy_name, + "counts": { + s: { + "benign": int((p["label"] == 0).sum()), + "phishing": int((p["label"] == 1).sum()), + } + for s, p in (("train", a_tr), ("validation", a_va), ("test", a_te)) + }, + } + if ( + len(a_va) + and len(a_te) + and a_te["label"].nunique() == 2 + and a_va["label"].nunique() == 2 + ): + pv, pt = _fit_predict("lightgbm", FIXED_LIGHTGBM, a_tr, list(FEATURES), a_va, a_te) + row["test"] = evaluate( + a_te["label"].to_numpy(), pt, best_threshold(a_va["label"].to_numpy(), pv) + ) + sens.append(row) + out["hub_policy_sensitivity"] = sens + + # 6. Exact feature-vector duplicates between training and evaluation rows. + def vectors(p: pd.DataFrame) -> dict[tuple[float, ...], set[int]]: + d: dict[tuple[float, ...], set[int]] = defaultdict(set) + for vec, lab in zip(map(tuple, p[list(FEATURES)].to_numpy()), p["label"], strict=True): + d[vec].add(int(lab)) + return d + + train_vecs = vectors(train) + out["duplicate_vectors"] = { + name: { + "rows": len(p), + "same_vector_in_train": int( + sum(tuple(v) in train_vecs for v in p[list(FEATURES)].to_numpy()) + ), + "same_vector_and_label_in_train": int( + sum( + lab in train_vecs.get(tuple(v), set()) + for v, lab in zip(p[list(FEATURES)].to_numpy(), p["label"], strict=True) + ) + ), + } + for name, p in (("validation", val), ("test", test)) + } + + # 7. Calibration bins (descriptive: too few benign rows to fit a calibrator). + def bins(y: np.ndarray, s: np.ndarray) -> list[dict[str, Any]]: + edges = np.linspace(0, 1, 6) + rows = [] + for lo, hi in itertools.pairwise(edges): + m = (s >= lo) & ((s < hi) if hi < 1 else (s <= hi)) + rows.append( + { + "bin": [float(lo), float(hi)], + "rows": int(m.sum()), + "mean_score": float(s[m].mean()) if m.any() else None, + "phishing_share": float(y[m].mean()) if m.any() else None, + } + ) + return rows + + out["calibration"] = { + "validation": bins(y_va, s_va), + "test": bins(y_te, s_te), + "train_phishing_share": float(train["label"].mean()), + } + + # 8. Class description inside the study window (training + evaluation rows). + used = table[split.isin(["train", "validation", "test"])] + sel = used[list(SELECTOR)].idxmax(axis=1).where(used[list(SELECTOR)].max(axis=1) > 0, "none") + out["class_profile"] = { + str(lab): { + "rows": len(g), + "function_family": {k: int(v) for k, v in sel[g.index].value_counts().items()}, + "share_typed_fee": float(g["is_typed_fee"].mean()), + "share_zero_value": float(g["is_zero_value"].mean()), + "share_contract_target": float(g["to_is_contract"].mean()), + "share_vanity_target": float((g["to_vanity_zero_nibbles"] >= 4).mean()), + "share_failed": float(1 - g["status_success"].mean()), + "median_sender_prior_txs": float(np.expm1(g["sender_prior_txs_log"].median())), + "median_logs": float(g["n_logs"].median()), + } + for lab, g in used.groupby("label") + } + return out + + +def audit_id(payload: dict[str, Any]) -> str: + return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()[ + :12 + ] + + +def _p(x: float | None, d: int = 3) -> str: + return "—" if x is None else f"{x:.{d}f}" + + +def _iv(v: list[float] | None, d: int = 3) -> str: + return "—" if not v else f"[{v[0]:.{d}f}, {v[1]:.{d}f}]" + + +def _row(*cells: object) -> str: + return "| " + " | ".join(str(c) for c in cells) + " |" + + +def _head(*cells: str) -> list[str]: + return [_row(*cells), _row(*("---" for _ in cells))] + + +def render_tables(a: dict[str, Any], ident: str) -> str: + """ML_AUDIT_TABLES.md: every number traceable to audit-.json (generated).""" + b = a["baseline"] + te, va = b["test"], b["validation"] + c = te["confusion"] + boot = b["test_cluster_bootstrap"] + inp = a["inputs"] + out: list[str] = ["# ML audit tables (generated)\n"] + add = out.append + add( + f"Generated by `cryptoguard ml audit`; do not edit by hand. Audit `{ident}` of run " + f"`{b['run_id']}` (model sha256 `{b['model_sha256'][:16]}…`), table sha256 " + f"`{inp['table_sha256'][:16]}…`, splits sha256 `{inp['splits_sha256'][:16]}…`, seed " + f"{a['seed']}, {a['seconds']} s. Offline: no RPC calls. Narrative and caveats: " + "ML_GENERALIZATION_AUDIT.md.\n" + ) + add( + "**The test split below is a development benchmark** (examined while the method was " + "still changing), not an untouched holdout.\n" + ) + + add("## 1. Recomputed baseline metrics\n") + add( + "Recomputed from the stored model with this module's own implementations and compared " + "with the values recorded at training time.\n" + ) + out += _head("Quantity", "Validation", "Test (dev benchmark)", "Matches recorded") + m = b["matches_recorded"] + for key, label in ( + ("average_precision", "AP"), + ("roc_auc", "ROC-AUC"), + ("recall", "Recall"), + ("false_positive_rate", "False-positive rate"), + ("precision", "Precision"), + ("balanced_accuracy", "Balanced accuracy"), + ("brier", "Brier score"), + ): + add(_row(label, _p(va[key]), _p(te[key]), m.get(key))) + add(_row("Log loss", _p(va["log_loss"]), _p(te["log_loss"]), "—")) + cm = f"{c['tp']}/{c['fp']}/{c['fn']}/{c['tn']}" + add(_row("Confusion (tp/fp/fn/tn)", "—", cm, m["confusion"])) + add(_row("Prevalence (phishing share)", _p(va["prevalence"]), _p(te["prevalence"]), "—")) + add( + _row( + "AP above prevalence", + _p(va["ap_above_prevalence"]), + _p(te["ap_above_prevalence"]), + "—", + ) + ) + add( + f"\nThreshold {b['threshold']:.4f}; reproduced from validation scores alone: " + f"**{b['threshold_from_validation_only']}**.\n" + ) + + add("## 2. Uncertainty on the development test split\n") + s = b["test_distinct_senders"] + add( + f"Test rows: {te['positives']} phishing from {s['phishing']} distinct senders, " + f"{te['negatives']} benign from **{s['benign']} distinct senders**. Account clusters " + f"(union-find over sender, target, spender, recipient): {boot['clusters']} " + f"({boot['positive_clusters']} with phishing rows, {boot['negative_clusters']} with " + "benign rows).\n" + ) + out += _head("Quantity", "Estimate", "Wilson 95% (rows independent)", "Cluster bootstrap 95%") + flagged = c["tp"] + c["fp"] + add( + _row( + "Recall", + f"{c['tp']}/{te['positives']} = {_p(te['recall'])}", + _iv(te["recall_wilson"]), + _iv(boot["recall"]), + ) + ) + add( + _row( + "False-positive rate", + f"{c['fp']}/{te['negatives']} = {_p(te['false_positive_rate'])}", + _iv(te["fpr_wilson"]), + _iv(boot["false_positive_rate"]), + ) + ) + add( + _row( + "Precision", + f"{c['tp']}/{flagged} = {_p(te['precision'])}", + _iv(te["precision_wilson"]), + "—", + ) + ) + add(_row("AP", _p(te["average_precision"]), "—", _iv(boot["average_precision"]))) + add(f"\nBootstrap: {boot['resamples_used']} resamples containing both classes.\n") + add( + "Benign rows needed to bound the false-positive rate below a target with 95% " + "confidence when **zero** false positives are observed:\n" + ) + out += _head("Target FPR", "Benign rows needed") + for t, n in a["negatives_needed"].items(): + add(_row(f"{float(t):.1%}", f"{n:,}")) + add("") + + add("## 3. Low-prevalence scenarios (arithmetic, not measurement)\n") + add( + f"Using the development-test recall {_p(te['recall'])} and false-positive rate " + f"{_p(te['false_positive_rate'])} (Wilson range {_iv(te['fpr_wilson'])}), per 10,000 " + "transactions:\n" + ) + out += _head( + "Assumed phishing prevalence", + "True alerts", + "False alerts (range)", + "Alerts", + "Precision (range)", + ) + for r in a["prevalence_scenarios"]: + fr, pr = r["false_alerts_range"], r["precision_range"] + add( + _row( + f"{r['prevalence']:.2%}", + f"{r['true_alerts']:.1f}", + f"{r['false_alerts']:.0f} ({fr[0]:.0f} to {fr[1]:.0f})", + f"{r['alerts']:.0f}", + f"{_p(r['precision'])} ({_p(pr[0])} to {_p(pr[1])})", + ) + ) + add("") + + add("## 4. Shortcut experiments\n") + add( + "Fixed hyperparameters (LightGBM: the Phase 11 selection; logistic regression: C=1), " + "threshold from validation, no tuning per feature set. Test = development benchmark.\n" + ) + out += _head( + "Features", "n", "Model", "Val AP", "Test AP", "Test ROC-AUC", "Test recall", "Test FPR" + ) + for r in a["ablations"]: + v, t = r["validation"], r["test"] + add( + _row( + r["features"], + r["n_features"], + r["model"], + _p(v["average_precision"]), + _p(t["average_precision"]), + _p(t["roc_auc"]), + _p(t["recall"]), + _p(t["false_positive_rate"]), + ) + ) + add("") + + add("## 5. Sensitivity to the hub policy (descriptive; the split is not chosen by this)\n") + out += _head( + "Policy", "Train b/p", "Validation b/p", "Test b/p", "Test AP", "Test ROC-AUC", "Test FPR" + ) + for r in a["hub_policy_sensitivity"]: + k, t = r["counts"], r.get("test") or {} + add( + _row( + r["policy"], + f"{k['train']['benign']}/{k['train']['phishing']}", + f"{k['validation']['benign']}/{k['validation']['phishing']}", + f"{k['test']['benign']}/{k['test']['phishing']}", + _p(t.get("average_precision")), + _p(t.get("roc_auc")), + _p(t.get("false_positive_rate")), + ) + ) + add("") + + add("## 6. Identical feature vectors across splits\n") + out += _head("Split", "Rows", "Same vector in train", "Same vector and label in train") + for name, d in a["duplicate_vectors"].items(): + add(_row(name, d["rows"], d["same_vector_in_train"], d["same_vector_and_label_in_train"])) + add("") + + add("## 7. Calibration (descriptive)\n") + add(f"Training data were {a['calibration']['train_phishing_share']:.0%} phishing.\n") + out += _head( + "Score bin", + "Val rows", + "Val mean score", + "Val phishing share", + "Test rows", + "Test mean score", + "Test phishing share", + ) + for bv, bt in zip(a["calibration"]["validation"], a["calibration"]["test"], strict=True): + add( + _row( + f"{bv['bin'][0]:.1f} to {bv['bin'][1]:.1f}", + bv["rows"], + _p(bv["mean_score"]), + _p(bv["phishing_share"]), + bt["rows"], + _p(bt["mean_score"]), + _p(bt["phishing_share"]), + ) + ) + add("") + + add("## 8. Class profile inside the study window (train, validation and test rows)\n") + prof = a["class_profile"] + out += _head("Property", "Benign", "Phishing") + for key, label in ( + ("rows", "Rows"), + ("share_typed_fee", "EIP-1559 fee fields present"), + ("share_zero_value", "Zero ETH value"), + ("share_contract_target", "Target is a contract"), + ("share_vanity_target", "Target has 4+ vanity zero nibbles"), + ("share_failed", "Reverted"), + ("median_sender_prior_txs", "Median sender prior transactions"), + ("median_logs", "Median logs"), + ): + add(_row(label, f"{prof['0'][key]:.3g}", f"{prof['1'][key]:.3g}")) + families = sorted(set(prof["0"]["function_family"]) | set(prof["1"]["function_family"])) + for f in families: + add( + _row( + f"Function family `{f}`", + prof["0"]["function_family"].get(f, 0), + prof["1"]["function_family"].get(f, 0), + ) + ) + add("") + + add("## 9. Errors on the development test split\n") + for kind in ("false_positives", "false_negatives"): + add(f"**{kind.replace('_', ' ').capitalize()}** ({len(a['errors'][kind])}):\n") + out += _head( + "Transaction", + "Subtype", + "Score", + "transfer()", + "transferFrom()", + "Other fn", + "Logs", + "Transfers", + "Vanity nibbles", + "Zero ETH", + ) + for e in a["errors"][kind]: + add( + _row( + f"`{e['tx_hash'][:18]}…`", + e["subtype"], + f"{e['score']:.3f}", + f"{e['fn_transfer']:.0f}", + f"{e['fn_transfer_from']:.0f}", + f"{e['fn_other']:.0f}", + f"{e['n_logs']:.0f}", + f"{e['n_transfers']:.0f}", + f"{e['to_vanity_zero_nibbles']:.0f}", + f"{e['is_zero_value']:.0f}", + ) + ) + add("") + return "\n".join(out) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 2b5fd10..2eabefd 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -32,8 +32,18 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None b.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) t = ml.add_parser("train", help="train, select on validation, test once, record the run") t.add_argument("--report", type=Path, default=Path("ML_EVALUATION.md")) - pr = ml.add_parser("promote", help="make a run the shadow model (only if its gate passed)") + pr = ml.add_parser("promote", help="register a run at an approval level it has evidence for") pr.add_argument("run_dir", type=Path) + pr.add_argument( + "--approval", + choices=("research_only", "shadow_approved"), + default="research_only", + help="shadow_approved needs a pass on an untouched holdout recorded in the model card", + ) + au = ml.add_parser("audit", help="offline generalization audit of a run (no RPC)") + au.add_argument("run_dir", type=Path) + au.add_argument("--out", type=Path, default=ML_DIR / "audit") + au.add_argument("--tables", type=Path, default=Path("ML_AUDIT_TABLES.md")) sc = ml.add_parser("score", help="shadow-mode score for one transaction (not a finding)") sc.add_argument("tx_hash") sc.add_argument("--rpc-url", required=True) @@ -66,19 +76,23 @@ def run(args: argparse.Namespace) -> int: if args.ml_command == "collect": import pandas as pd - from cryptoguard.ml.collect import collect, requests_used + from cryptoguard.ml.collect import RequestLedger, budget_path, collect sample = pd.read_csv(args.sample, dtype={"tx_hash": str}) if args.limit is not None: sample = sample.head(args.limit) - remaining = min(args.max_requests, TOTAL_REQUEST_CAP) - requests_used(args.out) - if remaining <= 0: - print(f"Request budget exhausted ({requests_used(args.out)} used).") + # The cap is a total over all runs: this run may use what is left, or less. + probe = RequestLedger(budget_path(args.out), cap=TOTAL_REQUEST_CAP) + cap = min(TOTAL_REQUEST_CAP, probe.used() + args.max_requests) + ledger = RequestLedger(budget_path(args.out), cap=cap) + if ledger.used() >= cap: + print(f"Request budget exhausted ({ledger.used()} of {cap} used).") return 1 - stats = asyncio.run(collect(sample, args.out, rpc_url=args.rpc_url, max_requests=remaining)) - # The collector records its attempts in the ledger itself, after every transaction. - print({**stats, "requests_total": requests_used(args.out), "cap": TOTAL_REQUEST_CAP}) + stats = asyncio.run(collect(sample, args.out, ledger=ledger, rpc_url=args.rpc_url)) + print({**stats, "requests_total": ledger.used(), "cap": cap}) return 0 + if args.ml_command == "audit": + return _audit(args) if args.ml_command == "build": return _build(args) if args.ml_command == "train": @@ -87,7 +101,7 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml.registry import ModelRegistryError, promote try: - print(promote(args.run_dir)) + print(promote(args.run_dir, approval=args.approval)) except ModelRegistryError as exc: print(f"error [not_promoted]: {exc}") return 1 @@ -107,16 +121,21 @@ def _shadow(args: argparse.Namespace) -> int: settings = Settings(ml_shadow="shadow") # the command itself is the opt-in if args.ml_command == "monitor": - model = loaded_model(settings) + model = loaded_model(settings, require_shadow_approval=False) print(json.dumps(drift_report(model.card, Path(settings.ml_score_log_path)), indent=1)) return 0 async def run() -> str: + from cryptoguard.core.hexutil import parse_quantity + client = JsonRpcClient(args.rpc_url, timeout=20) try: - return (await score_transaction(client, args.tx_hash, settings)).model_dump_json( - indent=1 + chain_id = parse_quantity(await client.call("eth_chainId", [])) + # Explicit CLI use may score with a research-only model; the output says so. + result = await score_transaction( + client, args.tx_hash, settings, chain_id=chain_id, require_shadow_approval=False ) + return result.model_dump_json(indent=1) finally: await client.aclose() @@ -129,6 +148,42 @@ async def run() -> str: RUNS = ML_DIR / "runs" +def _load_table_and_splits() -> tuple[object, object]: + import pandas as pd + + table = pd.read_csv(TABLE, dtype={"tx_hash": str, "group": str}) + split = pd.read_csv(SPLITS, dtype=str).set_index("tx_hash").loc[table["tx_hash"], "split"] + split.index = table.index + return table, split + + +def _audit(args: argparse.Namespace) -> int: + import hashlib + import json + import time + + from cryptoguard.ml.audit import audit_id, render_tables, run_audit + from cryptoguard.ml.collect import load_collected + + started = time.perf_counter() + table, split = _load_table_and_splits() + result = run_audit(table, split, load_collected(CHAIN), args.run_dir) # type: ignore[arg-type] + result["inputs"] = { + "table_sha256": hashlib.sha256(TABLE.read_bytes()).hexdigest(), + "splits_sha256": hashlib.sha256(SPLITS.read_bytes()).hexdigest(), + "chain_sha256": hashlib.sha256(CHAIN.read_bytes()).hexdigest(), + "run": args.run_dir.name, + } + result["seconds"] = round(time.perf_counter() - started, 1) + ident = audit_id({k: v for k, v in result.items() if k != "seconds"}) + args.out.mkdir(parents=True, exist_ok=True) + path = args.out / f"audit-{ident}.json" + path.write_text(json.dumps(result, indent=1, default=str), encoding="utf-8", newline="\n") + args.tables.write_text(render_tables(result, ident), encoding="utf-8", newline="\n") + print(f"audit {ident} in {result['seconds']} s -> {path}; wrote {args.tables}") + return 0 + + def _build(args: argparse.Namespace) -> int: import json @@ -178,11 +233,17 @@ def _train(args: argparse.Namespace) -> int: split.index = table.index manifest_path = TABLE.with_suffix(".manifest.json") manifest_sha = hashlib.sha256(manifest_path.read_bytes()).hexdigest() + # Dataset identity = the table and split bytes (the manifest also holds bookkeeping such + # as the cumulative RPC count, which changes without the data changing). + table_sha = hashlib.sha256(TABLE.read_bytes()).hexdigest() + splits_sha = hashlib.sha256(SPLITS.read_bytes()).hexdigest() + data_id = hashlib.sha256(f"{table_sha}:{splits_sha}".encode()).hexdigest() out = run_training(table, split) gate = promotion_gate(out["results"], out["selected"]) - run_id = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + manifest_sha[:8] + run_id = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + data_id[:8] config = { - "table_sha256": json.loads(manifest_path.read_text())["table"]["sha256"], + "table_sha256": table_sha, + "splits_sha256": splits_sha, "splits": json.loads(manifest_path.read_text())["splits"], } entry = ledger_entry(run_id, config, out, gate, manifest_sha) diff --git a/src/cryptoguard/ml/collect.py b/src/cryptoguard/ml/collect.py index 94d976f..2c22217 100644 --- a/src/cryptoguard/ml/collect.py +++ b/src/cryptoguard/ml/collect.py @@ -10,21 +10,29 @@ creations). Nothing after the transaction's own block is read, so features describe what was knowable -when the transaction executed. Labels are never sent anywhere: the sample order is fixed by -a seed before collection starts. Every HTTP attempt counts against ``max_requests`` -(retries included); the run stops cleanly before exceeding it and resumes from its JSONL -checkpoint, skipping transactions already collected. +when the transaction executed (post-inclusion: the receipt is part of the input). Labels are +never sent anywhere: the sample order is fixed by a seed before collection starts. + +Budget: every HTTP attempt (retries included) reserves one unit in a durable ledger *before* +it is sent (``RequestLedger``, ``BudgetedTransport``). The run stops when the ledger is full +and resumes from its JSONL checkpoint, skipping transactions already collected. """ from __future__ import annotations import asyncio import json +import os import random +import threading +import time +from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any +import httpx + from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy from cryptoguard.core.errors import RpcError @@ -93,12 +101,15 @@ async def collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: if tx is None or tx.get("blockNumber") is None: return {"tx_hash": tx_hash, "status": "not_found"} receipt = await client.call("eth_getTransactionReceipt", [tx_hash]) + if receipt is None: + # Mined but no receipt served: never stand in "no logs, failed" for missing data. + return {"tx_hash": tx_hash, "status": "incomplete"} before = hex(int(tx["blockNumber"], 16) - 1) nonce = await client.call("eth_getTransactionCount", [tx["from"], before]) code = "0x" if tx.get("to"): code = await client.call("eth_getCode", [tx["to"], before]) - logs = receipt.get("logs", []) if receipt else [] + logs = receipt.get("logs") or [] return { "tx_hash": tx_hash, "status": "ok", @@ -118,9 +129,7 @@ async def collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: "input", ) }, - "receipt": None - if receipt is None - else { + "receipt": { "status": receipt.get("status"), "gasUsed": receipt.get("gasUsed"), "contractAddress": receipt.get("contractAddress"), @@ -134,63 +143,199 @@ async def collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: } +class BudgetExhaustedError(RuntimeError): + """The request ledger has no room for another attempt.""" + + +class LedgerCorruptError(RuntimeError): + """The request ledger cannot be read; collection refuses to guess (fail closed).""" + + +class RequestLedger: + """Durable, cross-process request budget: one unit is *reserved before* every HTTP + attempt (retries included), under an exclusive lock file, with an atomic write. + + A crash after reserving over-counts (safe); it can never under-count. Two collectors on + the same ledger cannot together exceed the cap. The file keeps the Phase 11 format + (``{"requests": n, "notes": [...]}``) so earlier usage still counts. + """ + + def __init__(self, path: Path, cap: int, *, lock_timeout: float = 30.0) -> None: + self.path = path + self.cap = cap + self.lock_timeout = lock_timeout + self._lock = path.with_name(path.name + ".lock") + + def _acquire(self) -> None: + deadline = time.monotonic() + self.lock_timeout + while True: + try: + fd = os.open(self._lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + os.write(fd, str(os.getpid()).encode()) + os.close(fd) + return + except (FileExistsError, PermissionError): + # PermissionError: Windows reports it while the holder is deleting the file. + # A holder that crashed leaves the file; reservations are quick, so an old + # lock is stale. + try: + if time.time() - self._lock.stat().st_mtime > 60: + self._lock.unlink(missing_ok=True) + continue + except FileNotFoundError: + continue + if time.monotonic() > deadline: + raise TimeoutError(f"request ledger lock {self._lock} is held") from None + time.sleep(0.01) + + def _read(self) -> dict[str, Any]: + if not self.path.exists(): + return {"requests": 0} + try: + state = json.loads(self.path.read_text(encoding="utf-8")) + int(state["requests"]) + except (ValueError, KeyError, TypeError): + raise LedgerCorruptError(f"{self.path} is unreadable; fix it by hand") from None + return dict(state) + + def _write(self, state: dict[str, Any]) -> None: + tmp = self.path.with_name(self.path.name + f".{os.getpid()}.{threading.get_ident()}.tmp") + tmp.write_text(json.dumps(state, indent=1), encoding="utf-8") + for attempt in range(50): + try: + os.replace(tmp, self.path) # atomic on Windows and POSIX + return + except PermissionError: # Windows: a scanner may hold the target for a moment + if attempt == 49: + raise + time.sleep(0.01) + + def used(self) -> int: + self._acquire() # never read while another process replaces the file + try: + return int(self._read()["requests"]) + finally: + self._lock.unlink(missing_ok=True) + + def reserve(self, n: int = 1) -> int: + """Reserve ``n`` attempts or raise; returns the total reserved afterwards.""" + self._acquire() + try: + state = self._read() + total = int(state["requests"]) + n + if total > self.cap: + raise BudgetExhaustedError(f"{state['requests']} of {self.cap} requests used") + state["requests"] = total + self._write(state) + return total + finally: + self._lock.unlink(missing_ok=True) + + def note(self, text: str, requests: int = 0) -> int: + """Record a manual charge (e.g. requests made outside the collector).""" + self._acquire() + try: + state = self._read() + state["requests"] = int(state["requests"]) + requests + state.setdefault("notes", []).append(text) + self._write(state) + return int(state["requests"]) + finally: + self._lock.unlink(missing_ok=True) + + +class BudgetedTransport(httpx.AsyncBaseTransport): + """Reserves one ledger unit before handing each HTTP attempt to the real transport.""" + + def __init__(self, inner: httpx.AsyncBaseTransport, ledger: RequestLedger) -> None: + self.inner = inner + self.ledger = ledger + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + self.ledger.reserve(1) + return await self.inner.handle_async_request(request) + + async def aclose(self) -> None: + await self.inner.aclose() + + +def _repair_tail(out: Path) -> bool: + """Drop a final checkpoint line cut off by a crash (its transaction is fetched again).""" + if not out.exists(): + return False + data = out.read_bytes() + if not data or data.endswith(b"\n"): + return False + cut = data.rfind(b"\n") + 1 + with out.open("r+b") as fh: + fh.truncate(cut) + return True + + async def collect( sample: pd.DataFrame, out: Path, *, - rpc_url: str, - max_requests: int, + ledger: RequestLedger, + rpc_url: str = "https://rpc.invalid", + transport: httpx.AsyncBaseTransport | None = None, concurrency: int = 3, - client: JsonRpcClient | None = None, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, ) -> dict[str, int]: - """Collect chain data for the sample in order until done or the budget is spent.""" + """Collect chain data for the sample in order until done or the ledger is full. Every + HTTP attempt is reserved in ``ledger`` first, so the cap holds under retries, crashes + and concurrent collectors.""" out.parent.mkdir(parents=True, exist_ok=True) + repaired = _repair_tail(out) done = _done(out) todo = [h for h in sample["tx_hash"] if h not in done] - retry = RetryPolicy(max_retries=4) - rpc = client or JsonRpcClient(rpc_url, timeout=20, retry=retry, max_concurrency=concurrency) - # Worst case still in flight when a worker checks: every worker's transaction with every - # call retried to the limit. Stopping this far below the cap makes it a hard cap. - margin = concurrency * REQUESTS_PER_TX * (retry.max_retries + 1) - stats = {"already": len(done), "ok": 0, "not_found": 0, "error": 0, "skipped_budget": 0} + rpc = JsonRpcClient( + rpc_url, + timeout=20, + retry=RetryPolicy(max_retries=4), + max_concurrency=concurrency, + transport=BudgetedTransport(transport or httpx.AsyncHTTPTransport(), ledger), + sleep=sleep, + ) + stats = { + "already": len(done), + "ok": 0, + "not_found": 0, + "incomplete": 0, + "error": 0, + "skipped_budget": 0, + "repaired_tail": int(repaired), + } lock = asyncio.Lock() queue: asyncio.Queue[str] = asyncio.Queue() for h in todo: queue.put_nowait(h) - recorded = 0 - - def flush_budget() -> None: - # Written after every transaction, so an interrupted run never loses its count. - nonlocal recorded - delta = rpc.metrics.requests - recorded - if delta: - record_requests(out, delta) - recorded += delta + exhausted = False async def worker() -> None: - while not queue.empty(): + nonlocal exhausted + while not queue.empty() and not exhausted: tx_hash = queue.get_nowait() - if rpc.metrics.requests + margin > max_requests: - stats["skipped_budget"] += 1 - continue try: row = await collect_one(rpc, tx_hash) + except BudgetExhaustedError: + exhausted = True + stats["skipped_budget"] += 1 + return except RpcError as exc: row = {"tx_hash": tx_hash, "status": "error", "error": exc.code} async with lock: stats[row["status"]] += 1 with out.open("a", encoding="utf-8") as fh: fh.write(json.dumps(row, separators=(",", ":")) + "\n") - flush_budget() try: await asyncio.gather(*(worker() for _ in range(concurrency))) finally: - flush_budget() + stats["skipped_budget"] += queue.qsize() stats["requests"] = rpc.metrics.requests stats["retries"] = rpc.metrics.retries - if client is None: - await rpc.aclose() + await rpc.aclose() return stats @@ -199,30 +344,22 @@ def budget_path(out: Path) -> Path: def requests_used(out: Path) -> int: - """Cumulative RPC attempts over every run that wrote ``out`` (the cap is a total).""" - path = budget_path(out) - return int(json.loads(path.read_text(encoding="utf-8"))["requests"]) if path.exists() else 0 - - -def record_requests(out: Path, requests: int, note: str | None = None) -> int: - path = budget_path(out) - state: dict[str, Any] = ( - json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"requests": 0} - ) - state["requests"] = int(state["requests"]) + requests - if note: - notes: list[str] = state.setdefault("notes", []) - notes.append(note) - path.write_text(json.dumps(state, indent=1), encoding="utf-8") - return int(state["requests"]) + """Cumulative RPC attempts reserved by every run that wrote ``out`` (the cap is a total).""" + return RequestLedger(budget_path(out), cap=0).used() def load_collected(path: Path) -> dict[str, dict[str, Any]]: - """Latest successful record per transaction.""" + """Latest successful record per transaction. A cut-off final line (crash during a + write) is ignored; a corrupt line anywhere else raises.""" rows: dict[str, dict[str, Any]] = {} - for line in path.read_text(encoding="utf-8").splitlines(): - if line.strip(): + lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + for i, line in enumerate(lines): + try: row = json.loads(line) - if row["status"] in ("ok", "not_found"): - rows[row["tx_hash"]] = row + except ValueError: + if i == len(lines) - 1: + break + raise ValueError(f"{path}: corrupt checkpoint line {i + 1}") from None + if row["status"] in ("ok", "not_found"): + rows[row["tx_hash"]] = row return rows diff --git a/src/cryptoguard/ml/history.py b/src/cryptoguard/ml/history.py new file mode 100644 index 0000000..72812fa --- /dev/null +++ b/src/cryptoguard/ml/history.py @@ -0,0 +1,226 @@ +"""Point-in-time wallet-history features for one outgoing payment (pure Python). + +The Phase 11 transaction classifier sees a transaction in isolation, and its main blind spot +is a plain token transfer: by shape alone, a payment to a poisoned lookalike and an ordinary +payment look the same. What separates them is the wallet's own history: has it paid this +address before, and does the address imitate one it has paid? These features answer that, +from events strictly before an explicit observation boundary. + +Data contract: + +- **Input**: canonical wallet events (``WalletEvent``: direction, counterparty, position) and + a ``Coverage`` stating which blocks were observed and whether the scan was complete. Reorg + handling belongs to the caller: CryptoGuard's stored history is rebased on reorgs, replay + fixtures are recorded at confirmed blocks. +- **Boundary**: ``pre_signing`` sees blocks before the payment's block only; ``pre_execution`` + also sees earlier transactions in the same block (what executed before it). +- **Zero versus unknown**: every count is ``None`` when the history is unavailable for the + boundary, and ``history_status`` says why. A wallet with no events in a complete window + gets real zeros. ``as_model_row`` encodes ``None`` as -1 next to explicit indicators, so + the two states never collapse. +- **Reverted payments**: identify a counterparty the wallet chose (they count for + "known counterparties" and lookalike checks) but never as a completed payment. +- **Cost**: O(n) in the number of events for one query. + +These features are infrastructure: no independently labelled dataset with wallet histories +exists here, so no accuracy is claimed (see ML_GENERALIZATION_AUDIT.md). +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from typing import Literal + +from cryptoguard.detectors.poisoning import PoisoningConfig, affix_match, is_lookalike + +Boundary = Literal["pre_signing", "pre_execution"] +Status = Literal["available", "partial", "unavailable"] +RECENT_PAYMENTS = 20 +HISTORY_FEATURE_VERSION = "wallet-history/1" + + +@dataclass(frozen=True) +class WalletEvent: + block: int + tx_index: int + log_index: int # -1 for a transaction's own value (moves before its logs) + direction: Literal["out", "in"] + counterparty: str + value: int + wallet_signed: bool | None = None # outgoing only: did the wallet sign it? + succeeded: bool | None = None # None = unknown (treated as executed) + + @property + def position(self) -> tuple[int, int, int]: + return (self.block, self.tx_index, self.log_index) + + +@dataclass(frozen=True) +class Coverage: + from_block: int # first block whose events were scanned + to_block: int # last block scanned (inclusive) + complete: bool # every relevant event in [from_block, to_block] was observed + + +@dataclass(frozen=True) +class HistoryFeatures: + history_status: Status + observed_from_block: int | None + prior_payments_to_recipient: int | None + prior_interactions_with_recipient: int | None + blocks_since_first_interaction: int | None + blocks_since_last_interaction: int | None + distinct_prior_recipients: int | None + recent_new_recipient_share: float | None + recipient_lookalike_of_known: bool | None + recipient_max_affix_to_known: int | None + unsolicited_events_with_recipient: int | None + lookalike_plantings_observed: int | None + + def as_model_row(self) -> dict[str, float]: + """Numeric row: ``None`` -> -1, with indicator columns that keep zero and unknown apart.""" + row: dict[str, float] = { + "history_available": float(self.history_status == "available"), + "history_partial": float(self.history_status == "partial"), + } + for key, value in asdict(self).items(): + if key in ("history_status", "observed_from_block"): + continue + row[key] = -1.0 if value is None else float(value) + return row + + +def _unavailable(status: Status = "unavailable") -> HistoryFeatures: + return HistoryFeatures(status, None, None, None, None, None, None, None, None, None, None, None) + + +def _unsolicited(e: WalletEvent) -> bool: + """A planting-shaped event: a zero-value transfer in, or a transfer out of the wallet that + the wallet did not sign (the spoofed ``transferFrom`` used in address poisoning).""" + return (e.direction == "in" and not e.value) or ( + e.direction == "out" and e.wallet_signed is False + ) + + +def _visible(event: WalletEvent, block: int, tx_index: int, boundary: Boundary) -> bool: + if boundary == "pre_signing": + return event.block < block + return (event.block, event.tx_index) < (block, tx_index) + + +def history_features( + events: list[WalletEvent], + coverage: Coverage | None, + *, + recipient: str, + block: int, + tx_index: int, + boundary: Boundary = "pre_signing", + config: PoisoningConfig | None = None, +) -> HistoryFeatures: + """Features for a payment to ``recipient`` at (``block``, ``tx_index``).""" + config = config or PoisoningConfig() + if coverage is None or coverage.from_block > block: + return _unavailable() + last_needed = block - 1 if boundary == "pre_signing" else block + status: Status = ( + "available" if coverage.complete and coverage.to_block >= last_needed else "partial" + ) + if status == "partial": + # Counts would silently undercount; only say what is known to exist. + return _unavailable("partial") + recipient = recipient.lower() + seen = sorted( + (e for e in events if _visible(e, block, tx_index, boundary)), key=lambda e: e.position + ) + + paid: dict[str, int] = {} + chosen: set[str] = set() # counterparties the wallet itself picked (incl. reverted sends) + first_block: int | None = None + last_block: int | None = None + interactions = 0 + unsolicited_with_recipient = 0 + new_flags: list[bool] = [] + for e in seen: + party = e.counterparty.lower() + if party == recipient: + interactions += 1 + first_block = e.block if first_block is None else first_block + last_block = e.block + unsolicited_with_recipient += _unsolicited(e) + if e.direction == "out" and e.wallet_signed is not False: + new_flags.append(party not in chosen) + chosen.add(party) + if e.succeeded is not False: + paid[party] = paid.get(party, 0) + 1 + + known = chosen - {recipient} + affixes = [sum(affix_match(recipient, k)) for k in known] + lookalike = any(is_lookalike(recipient, k, config) for k in known) + plantings = sum( + 1 + for e in seen + if _unsolicited(e) + and any(is_lookalike(e.counterparty, k, config) for k in chosen - {e.counterparty.lower()}) + ) + recent = new_flags[-RECENT_PAYMENTS:] + return HistoryFeatures( + history_status="available", + observed_from_block=coverage.from_block, + prior_payments_to_recipient=paid.get(recipient, 0), + prior_interactions_with_recipient=interactions, + blocks_since_first_interaction=None if first_block is None else block - first_block, + blocks_since_last_interaction=None if last_block is None else block - last_block, + distinct_prior_recipients=len(chosen), + recent_new_recipient_share=(sum(recent) / len(recent)) if recent else None, + recipient_lookalike_of_known=lookalike, + recipient_max_affix_to_known=max(affixes, default=0), + unsolicited_events_with_recipient=unsolicited_with_recipient, + lookalike_plantings_observed=plantings, + ) + + +def events_from_fixture(fixture: object) -> tuple[list[WalletEvent], Coverage]: + """Adapter: a recorded replay fixture (``replay.models.ReplayFixture``) as wallet events. + Token transfers in both directions plus the wallet's own ETH-carrying transactions.""" + from cryptoguard.replay.models import ReplayFixture + + assert isinstance(fixture, ReplayFixture) + wallet = fixture.wallet.lower() + events: list[WalletEvent] = [] + for t in fixture.transfers: + if t.sender.lower() == wallet: + signer = None if t.tx_sender is None else t.tx_sender.lower() == wallet + events.append( + WalletEvent( + t.block_number, + t.transaction_index, + t.log_index, + "out", + t.recipient, + int(t.value), + wallet_signed=signer, + ) + ) + elif t.recipient.lower() == wallet: + events.append( + WalletEvent( + t.block_number, t.transaction_index, t.log_index, "in", t.sender, int(t.value) + ) + ) + for tx in fixture.wallet_transactions: + if tx.to and int(tx.value): + events.append( + WalletEvent( + tx.block_number, + tx.transaction_index, + -1, + "out", + tx.to, + int(tx.value), + wallet_signed=True, + succeeded=tx.succeeded, + ) + ) + complete = fixture.transfer_scan_complete and fixture.sender_lookups_skipped == 0 + return events, Coverage(fixture.from_block, fixture.to_block, complete) diff --git a/src/cryptoguard/ml/inference.py b/src/cryptoguard/ml/inference.py index b78156b..f0830f3 100644 --- a/src/cryptoguard/ml/inference.py +++ b/src/cryptoguard/ml/inference.py @@ -2,12 +2,19 @@ Reads the same four point-in-time items as training (transaction, receipt, sender nonce and target code at the previous block), extracts the same features, scores them with the -promoted, hash-verified model, and logs the vector for drift monitoring. +registered, hash-verified model, and logs the vector for drift monitoring. + +Observation boundary: **post-inclusion**. The transaction must be mined and its receipt +available; the score describes an executed transaction, it is not a pre-signing warning. +The score is an uncalibrated ranking score, not a probability of fraud. """ from __future__ import annotations +import asyncio import os +import time +import weakref from datetime import UTC, datetime from functools import lru_cache from pathlib import Path @@ -17,25 +24,48 @@ from cryptoguard.blockchain.rpc import JsonRpcClient from cryptoguard.core.config import Settings -from cryptoguard.core.errors import FeatureDisabledError, MlUnavailableError +from cryptoguard.core.errors import FeatureDisabledError, MlUnavailableError, RpcTimeoutError from cryptoguard.core.hexutil import parse_hash32 +TRAINED_CHAIN_ID = 1 # PTXPhish is Ethereum mainnet +SCORE_TIMEOUT_SECONDS = 30.0 +_SCORING: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Semaphore] = ( + weakref.WeakKeyDictionary() +) + + +def _scoring_slot() -> asyncio.Semaphore: + """One scoring at a time per event loop (bounded RPC load). Per loop, because an asyncio + semaphore is bound to the loop it first waits on.""" + loop = asyncio.get_running_loop() + if loop not in _SCORING: + _SCORING[loop] = asyncio.Semaphore(1) + return _SCORING[loop] + + DISABLED = ( - "ML scoring is disabled. Set CRYPTOGUARD_ML_SHADOW=shadow (and promote a validated model, " + "ML scoring is disabled. Set CRYPTOGUARD_ML_SHADOW=shadow (and register an approved model, " "see ML.md) to score transactions for review." ) NOT_A_FINDING = ( "Experimental shadow-mode score from a model trained on one public dataset (PTXPhish). " "It is not a finding, does not change any severity, and has a high false-positive rate " - "on ordinary traffic (see ML_EVALUATION.md)." + "on ordinary traffic (see ML_GENERALIZATION_AUDIT.md)." +) +UNCALIBRATED = ( + "Uncalibrated ranking score in [0, 1], not a probability: the training data were 82% " + "phishing, far from real-world rates." ) class ShadowScore(BaseModel): experimental: Literal[True] = True - status: Literal["scored", "not_found"] + status: Literal["scored", "not_found", "incomplete"] tx_hash: str run_id: str + approval: Literal["research_only", "shadow_approved"] + observation: Literal["post_inclusion"] = "post_inclusion" + score_semantics: Literal["uncalibrated_ranking"] = "uncalibrated_ranking" score: float | None = None threshold: float above_threshold: bool | None = None @@ -45,12 +75,13 @@ class ShadowScore(BaseModel): @lru_cache(maxsize=4) def _load(registry: str, mtime: float) -> Any: - from cryptoguard.ml.registry import load_shadow_model + from cryptoguard.ml.registry import load_registered_model - return load_shadow_model(Path(registry)) + return load_registered_model(Path(registry)) -def loaded_model(settings: Settings) -> Any: +def loaded_model(settings: Settings, *, require_shadow_approval: bool = True) -> Any: + """The registered model, or a clear refusal (409 off, 503 unavailable/not approved).""" from cryptoguard.ml import ml_available from cryptoguard.ml.registry import ModelRegistryError @@ -60,29 +91,76 @@ def loaded_model(settings: Settings) -> Any: raise MlUnavailableError("The ml extra is not installed (uv sync --extra ml).") path = settings.ml_registry_path try: - return _load(path, os.path.getmtime(path) if os.path.exists(path) else 0.0) + model = _load(path, os.path.getmtime(path) if os.path.exists(path) else 0.0) except (ModelRegistryError, FileNotFoundError) as exc: raise MlUnavailableError(str(exc)) from None - - -async def score_transaction(client: JsonRpcClient, tx_hash: str, settings: Settings) -> ShadowScore: + if require_shadow_approval and model.approval != "shadow_approved": + raise MlUnavailableError( + f"Model {model.run_id} is approved for research only: its benchmark is not an " + "untouched holdout (see ML_GENERALIZATION_AUDIT.md). Shadow scoring is refused." + ) + return model + + +async def score_transaction( + client: JsonRpcClient, + tx_hash: str, + settings: Settings, + *, + chain_id: int, + require_shadow_approval: bool = True, +) -> ShadowScore: + """Score one mined transaction. ``chain_id`` must come from a verified provider.""" + model = loaded_model(settings, require_shadow_approval=require_shadow_approval) + if chain_id != TRAINED_CHAIN_ID: + raise MlUnavailableError( + f"The model was trained on chain {TRAINED_CHAIN_ID}; the provider serves {chain_id}." + ) + tx_hash = parse_hash32(tx_hash) + started = time.perf_counter() + try: + async with _scoring_slot(): + return await asyncio.wait_for( + _score(client, tx_hash, settings, model, started), SCORE_TIMEOUT_SECONDS + ) + except TimeoutError: + raise RpcTimeoutError( + f"ML scoring did not finish within {SCORE_TIMEOUT_SECONDS:.0f} s." + ) from None + + +async def _score( + client: JsonRpcClient, tx_hash: str, settings: Settings, model: Any, started: float +) -> ShadowScore: import pandas as pd from cryptoguard.ml.collect import collect_one from cryptoguard.ml.features import extract from cryptoguard.ml.monitoring import log_score - model = loaded_model(settings) - tx_hash = parse_hash32(tx_hash) + base = { + "tx_hash": tx_hash, + "run_id": model.run_id, + "approval": model.approval, + "threshold": model.threshold, + } record = await collect_one(client, tx_hash) if record["status"] != "ok": - return ShadowScore( - status="not_found", - tx_hash=tx_hash, - run_id=model.run_id, - threshold=model.threshold, - notes=["The transaction is not (or not yet) included in a block.", NOT_A_FINDING], + reason = ( + "The transaction is not (or not yet) included in a block." + if record["status"] == "not_found" + else "The provider returned no receipt for a mined transaction; nothing was scored." + ) + log_score( + { + "at": datetime.now(UTC).isoformat(), + "run_id": model.run_id, + "status": record["status"], + "latency_ms": round((time.perf_counter() - started) * 1000), + }, + Path(settings.ml_score_log_path), ) + return ShadowScore(status=record["status"], notes=[reason, NOT_A_FINDING], **base) features = extract(record) row = pd.DataFrame([[features[c] for c in model.columns]], columns=model.columns) score = float(model.model.predict_proba(row)[0, 1]) @@ -90,19 +168,19 @@ async def score_transaction(client: JsonRpcClient, tx_hash: str, settings: Setti { "at": datetime.now(UTC).isoformat(), "run_id": model.run_id, + "status": "scored", "tx_hash": tx_hash, "score": score, + "latency_ms": round((time.perf_counter() - started) * 1000), "features": {c: features[c] for c in model.columns}, }, Path(settings.ml_score_log_path), ) return ShadowScore( status="scored", - tx_hash=tx_hash, - run_id=model.run_id, score=score, - threshold=model.threshold, above_threshold=score >= model.threshold, block_number=int(record["tx"]["blockNumber"], 16), - notes=[NOT_A_FINDING], + notes=[NOT_A_FINDING, UNCALIBRATED], + **base, ) diff --git a/src/cryptoguard/ml/monitoring.py b/src/cryptoguard/ml/monitoring.py index b6e53cf..cc58286 100644 --- a/src/cryptoguard/ml/monitoring.py +++ b/src/cryptoguard/ml/monitoring.py @@ -51,22 +51,70 @@ def log_score(entry: dict[str, Any], path: Path = DEFAULT_LOG) -> None: fh.write(json.dumps(entry, separators=(",", ":")) + "\n") +MAX_LOG_ROWS = 10_000 # only the most recent scores are read (the log is append-only) + + +def _quantiles(values: list[float], qs: tuple[float, ...]) -> dict[str, float] | None: + if not values: + return None + ordered = sorted(values) + return {f"p{round(q * 100)}": ordered[min(int(q * len(ordered)), len(ordered) - 1)] for q in qs} + + def drift_report(card: dict[str, Any], path: Path = DEFAULT_LOG) -> dict[str, Any]: - rows = [] + """Input drift of recent shadow scores against the training reference. + + This measures *data* drift (PSI per feature) and *prediction* drift (score + distribution), plus coverage failures and latency. Without labels it cannot show that + accuracy degraded (concept drift or performance loss): a stable PSI is not evidence of + a working model.""" + lines: list[str] = [] if path.exists(): - rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] - rows = [r for r in rows if r.get("run_id") == card["run_id"]] - if len(rows) < MIN_ROWS: - return {"status": "insufficient_data", "rows": len(rows), "min_rows": MIN_ROWS} + lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line][ + -MAX_LOG_ROWS: + ] + rows: list[dict[str, Any]] = [] + unreadable = 0 + for line in lines: + try: + row = json.loads(line) + except ValueError: + unreadable += 1 + continue + if row.get("run_id") == card["run_id"]: + rows.append(row) + columns = list(card["feature_columns"]) + scored = [r for r in rows if r.get("status", "scored") == "scored" and "features" in r] + valid = [r for r in scored if sorted(r["features"]) == sorted(columns)] + statuses: dict[str, int] = {} + for r in rows: + statuses[r.get("status", "scored")] = statuses.get(r.get("status", "scored"), 0) + 1 + latencies = [float(r["latency_ms"]) for r in rows if "latency_ms" in r] + summary: dict[str, Any] = { + "rows": len(rows), + "status_counts": statuses, + "schema_mismatches": len(scored) - len(valid), + "unreadable_lines": unreadable, + "latency_ms": _quantiles(latencies, (0.5, 0.95)), + "scores": _quantiles([float(r["score"]) for r in valid], (0.1, 0.5, 0.9)), + "share_above_threshold": ( + sum(float(r["score"]) >= float(card["threshold"]) for r in valid) / len(valid) + if valid + else None + ), + "note": "Data and prediction drift only; without labels, accuracy cannot be monitored.", + } + if len(valid) < MIN_ROWS: + return {"status": "insufficient_data", "min_rows": MIN_ROWS, **summary} reference = card["reference_bins"] scores = { - feature: psi(reference[feature], [float(r["features"][feature]) for r in rows]) - for feature in card["feature_columns"] + feature: psi(reference[feature], [float(r["features"][feature]) for r in valid]) + for feature in columns } worst = sorted(scores.items(), key=lambda kv: -kv[1]) return { "status": "ok", - "rows": len(rows), + **summary, "psi": dict(worst), "shifted": [f for f, v in worst if v > 0.25], "moderate": [f for f, v in worst if 0.1 < v <= 0.25], diff --git a/src/cryptoguard/ml/registry.py b/src/cryptoguard/ml/registry.py index 8bc0a72..f084534 100644 --- a/src/cryptoguard/ml/registry.py +++ b/src/cryptoguard/ml/registry.py @@ -1,25 +1,51 @@ -"""Model registry: which trained run is the shadow-mode model, and safe loading of it. +"""Model registry: which trained run is approved for what, and safe loading of it. -Model files are pickles (joblib), and unpickling executes code. A model is therefore loaded -only from the local registry, and only if its SHA-256 matches the hash recorded in its model -card when it was trained; anything else is refused. +Trust boundary: the local ``data/ml`` directory. A SHA-256 check proves that the model file +is the one its card describes; it does not prove the card itself is trustworthy, so a model +is only ever loaded from the local runs directory, by a validated run id, never from a path +or URL supplied by a request or a registry entry. + +Approval levels (separate from "the artifact is valid"): + +- ``research_only``: the run passed its promotion gate on a development benchmark. Offline + use and explicit CLI scoring only. +- ``shadow_approved``: additionally evaluated once on an untouched holdout and passed there. + Required for the API's shadow scoring. Never a production detector: nothing here creates + findings. + +Serialization: LightGBM models are stored in LightGBM's own text format (no pickle). Other +model families fall back to joblib (a pickle: unpickling runs code), loaded only after the +hash check. """ from __future__ import annotations import hashlib import json +import re from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, Literal from cryptoguard.ml import FEATURE_SET_VERSION +from cryptoguard.ml.features import FEATURES DEFAULT_REGISTRY = Path("data") / "ml" / "registry.json" +RUN_ID = re.compile(r"^\d{8}T\d{6}Z-[0-9a-f]{8}$") +MAX_MODEL_BYTES = 50 * 1024 * 1024 +Approval = Literal["research_only", "shadow_approved"] +CARD_KEYS = { + "run_id", + "feature_set_version", + "feature_columns", + "threshold", + "gate", + "model_sha256", +} class ModelRegistryError(RuntimeError): - """No usable shadow model (none promoted, files missing, or integrity check failed).""" + """No usable model (none promoted, invalid entry, files missing, integrity failure).""" @dataclass(frozen=True) @@ -27,6 +53,7 @@ class LoadedModel: run_id: str model: Any card: dict[str, Any] + approval: Approval @property def threshold(self) -> float: @@ -37,36 +64,141 @@ def columns(self) -> list[str]: return list(self.card["feature_columns"]) -def promote(run_dir: Path, registry: Path = DEFAULT_REGISTRY) -> dict[str, Any]: - """Make a run the shadow model. Refused unless its promotion gate passed.""" - card = json.loads((run_dir / "model_card.json").read_text(encoding="utf-8")) - if not card["gate"]["validated_for_shadow"]: +class BoosterModel: + """A LightGBM booster loaded from text, with the sklearn ``predict_proba`` contract.""" + + def __init__(self, booster: Any) -> None: + self.booster = booster + + def predict_proba(self, frame: Any) -> Any: + import numpy as np + + p = np.asarray(self.booster.predict(frame), dtype=float) + return np.column_stack([1 - p, p]) + + +def model_file(run_dir: Path, card: dict[str, Any]) -> Path: + return run_dir / ( + "model.txt" if card.get("serialization") == "lightgbm-text" else "model.joblib" + ) + + +def _check_card(card: Any) -> dict[str, Any]: + if not isinstance(card, dict) or not set(card) >= CARD_KEYS: + raise ModelRegistryError(f"model card lacks {sorted(CARD_KEYS - set(card or {}))}") + if not RUN_ID.match(str(card["run_id"])): + raise ModelRegistryError(f"invalid run id {card['run_id']!r}") + if card["feature_set_version"] != FEATURE_SET_VERSION: + raise ModelRegistryError( + f"model features {card['feature_set_version']} != code {FEATURE_SET_VERSION}" + ) + columns = card["feature_columns"] + if not isinstance(columns, list) or not columns or not set(columns) <= set(FEATURES): + raise ModelRegistryError("model card feature columns do not match this code") + if not isinstance(card["threshold"], (int, float)) or not 0 <= card["threshold"] <= 1: + raise ModelRegistryError("model card threshold must be a number in [0, 1]") + return card + + +def _training_versions(run_dir: Path, card: dict[str, Any]) -> dict[str, str]: + if isinstance(card.get("versions"), dict): + return dict(card["versions"]) + run = run_dir / "run.json" # cards written before versions were recorded in them + if run.exists(): + return dict(json.loads(run.read_text(encoding="utf-8")).get("versions") or {}) + return {} + + +def _check_versions(trained: dict[str, str]) -> None: + """Refuse a model trained with another major.minor of the libraries that load it.""" + import importlib.metadata as md + + for pkg in ("lightgbm", "scikit-learn"): + want = trained.get(pkg) + if not want or want == "missing": + raise ModelRegistryError(f"training run does not record its {pkg} version") + have = md.version(pkg) + if want.split(".")[:2] != have.split(".")[:2]: + raise ModelRegistryError(f"model trained with {pkg} {want}, installed {have}") + + +def run_dir_for(run_id: str, runs_root: Path) -> Path: + if not RUN_ID.match(run_id): + raise ModelRegistryError(f"invalid run id {run_id!r}") + path = (runs_root / run_id).resolve() + if path.parent != runs_root.resolve(): + raise ModelRegistryError("run directory outside the runs root") + return path + + +def _verified_model( + run_dir: Path, expected_sha256: str | None = None +) -> tuple[dict[str, Any], Any]: + """Validate a run's card, versions, size and hash, then load its model.""" + try: + card = _check_card(json.loads((run_dir / "model_card.json").read_text(encoding="utf-8"))) + except (OSError, ValueError) as exc: + raise ModelRegistryError(f"unreadable model card in {run_dir.name}: {exc}") from None + _check_versions(_training_versions(run_dir, card)) + path = model_file(run_dir, card) + if not path.exists(): + raise ModelRegistryError(f"{path.name} missing in {run_dir.name}") + if path.stat().st_size > MAX_MODEL_BYTES: + raise ModelRegistryError(f"{path.name} exceeds {MAX_MODEL_BYTES} bytes") + data = path.read_bytes() + digest = hashlib.sha256(data).hexdigest() + if digest != card["model_sha256"] or (expected_sha256 and digest != expected_sha256): + raise ModelRegistryError(f"{path.name}: hash mismatch, refusing to load") + if card.get("serialization") == "lightgbm-text": + import lightgbm + + return card, BoosterModel(lightgbm.Booster(model_str=data.decode("utf-8"))) + import io + + import joblib + + return card, joblib.load(io.BytesIO(data)) # hash-checked pickle (non-LightGBM models) + + +def promote( + run_dir: Path, registry: Path = DEFAULT_REGISTRY, approval: Approval = "research_only" +) -> dict[str, Any]: + """Record a run in the registry at an approval level it has evidence for.""" + card, _ = _verified_model(run_dir) + if not card["gate"].get("validated_for_shadow"): raise ModelRegistryError(f"run {card['run_id']} did not pass its promotion gate") + if approval == "shadow_approved": + holdout = card.get("holdout") or {} + if not ( + holdout.get("untouched") and holdout.get("evaluated_once") and holdout.get("passed") + ): + raise ModelRegistryError( + "shadow approval needs a pass on an untouched, once-evaluated holdout; this run " + "has none (its test split is a development benchmark)" + ) entry = { "run_id": card["run_id"], - "run_dir": run_dir.as_posix(), "model_sha256": card["model_sha256"], "feature_set_version": card["feature_set_version"], + "approval": approval, } registry.parent.mkdir(parents=True, exist_ok=True) - registry.write_text(json.dumps({"shadow": entry}, indent=1), encoding="utf-8") + registry.write_text(json.dumps({"model": entry}, indent=1), encoding="utf-8") return entry -def load_shadow_model(registry: Path = DEFAULT_REGISTRY) -> LoadedModel: +def load_registered_model( + registry: Path = DEFAULT_REGISTRY, runs_root: Path | None = None +) -> LoadedModel: if not registry.exists(): - raise ModelRegistryError("no shadow model promoted (cryptoguard ml promote )") - entry = json.loads(registry.read_text(encoding="utf-8"))["shadow"] - run_dir = Path(entry["run_dir"]) - card = json.loads((run_dir / "model_card.json").read_text(encoding="utf-8")) - if card["feature_set_version"] != FEATURE_SET_VERSION: - raise ModelRegistryError( - f"model features {card['feature_set_version']} != code {FEATURE_SET_VERSION}" - ) - model_path = run_dir / "model.joblib" - digest = hashlib.sha256(model_path.read_bytes()).hexdigest() - if digest != entry["model_sha256"] or digest != card["model_sha256"]: - raise ModelRegistryError(f"{model_path}: hash mismatch, refusing to load") - import joblib - - return LoadedModel(entry["run_id"], joblib.load(model_path), card) + raise ModelRegistryError("no model promoted (cryptoguard ml promote )") + try: + entry = json.loads(registry.read_text(encoding="utf-8"))["model"] + run_id, approval = str(entry["run_id"]), entry["approval"] + except (ValueError, KeyError, TypeError): + raise ModelRegistryError("registry entry is malformed; promote the run again") from None + if approval not in ("research_only", "shadow_approved"): + raise ModelRegistryError(f"unknown approval {approval!r}") + root = runs_root or registry.parent / "runs" + card, model = _verified_model(run_dir_for(run_id, root), entry.get("model_sha256")) + return LoadedModel(run_id, model, card, approval) diff --git a/src/cryptoguard/ml/splits.py b/src/cryptoguard/ml/splits.py index 520df96..bfbd108 100644 --- a/src/cryptoguard/ml/splits.py +++ b/src/cryptoguard/ml/splits.py @@ -15,6 +15,7 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -50,8 +51,15 @@ def make_splits( table: pd.DataFrame, records: dict[str, dict[str, Any]], plan: SplitPlan = DEFAULT_SPLIT, + hub_policy: Callable[[dict[str, dict[str, Any]]], set[str]] = hubs, ) -> tuple[pd.Series, dict[str, Any]]: - """A split name per row ("train", "validation", "test", or "excluded:").""" + """A split name per row ("train", "validation", "test", or "excluded:"). + + ``hub_policy`` decides which accounts do not link rows (default: the curated registry). + Alternatives exist for the sensitivity audit only (``ml/audit.py``); the production + split always uses the default. Rows that share accounts *within* one split are kept, so + evaluation rows are not independent: intervals must resample account clusters. + """ import pandas as pd lo, hi = study_window(table) @@ -67,7 +75,7 @@ def make_splits( split[inside.index[inside["block_number"] >= test_start]] = "test" train_records = {h: records[h] for h in table.loc[split == "train", "tx_hash"]} - hub_set = hubs(train_records) + hub_set = hub_policy(train_records) def accounts(tx_hash: str) -> set[str]: return parties(records[tx_hash]) - hub_set diff --git a/src/cryptoguard/ml/train.py b/src/cryptoguard/ml/train.py index dc0eec8..e82cc48 100644 --- a/src/cryptoguard/ml/train.py +++ b/src/cryptoguard/ml/train.py @@ -178,18 +178,30 @@ def fast_average_precision(y: np.ndarray, score: np.ndarray) -> float: def bootstrap_ci( - y: np.ndarray, score: np.ndarray, threshold: float, n: int = 1000 + y: np.ndarray, + score: np.ndarray, + threshold: float, + n: int = 1000, + clusters: np.ndarray | None = None, ) -> dict[str, list[float]]: - """95% percentile intervals for test AP, recall and false-positive rate (seeded - resamples of rows). Empty when the split lacks one class: no interval exists.""" + """95% percentile intervals for test AP, recall and false-positive rate (seeded). + + With ``clusters`` (the account group of each row), whole clusters are resampled: PTXPhish + rows come in batches per account (up to 200 benign transactions per account, up to 50 per + scammer address), so resampling rows as if independent understates the uncertainty. + Empty when the split lacks one class: no interval exists.""" if len(set(y.tolist())) < 2: return {} import numpy as np rng = np.random.default_rng(SEED) + if clusters is None: + clusters = np.arange(len(y)) + ids = np.unique(clusters) + members = [np.flatnonzero(clusters == c) for c in ids] ap, rec, fpr = [], [], [] for _ in range(n): - idx = rng.integers(0, len(y), len(y)) + idx = np.concatenate([members[i] for i in rng.integers(0, len(ids), len(ids))]) yi, si = y[idx], score[idx] positives = int(yi.sum()) if positives in (0, len(yi)): @@ -289,10 +301,13 @@ def run_training( ) res.test = metrics(y_te, dummy.predict_proba(test[list(FEATURES)])[:, 1], 0.5) results.append(res) + groups = test["group"].to_numpy() if "group" in test else None + predictions: dict[str, Any] = {} for rule in ("rule_phishing_shape", "rule_cryptoguard_signals"): res = ModelResult(rule, "rule", None, {}, metrics(y_va, rule_scores(val, rule), 0.5)) res.test = metrics(y_te, rule_scores(test, rule), 0.5) - res.test["ci95"] = bootstrap_ci(y_te, rule_scores(test, rule), 0.5) + res.test["ci95"] = bootstrap_ci(y_te, rule_scores(test, rule), 0.5, clusters=groups) + predictions[rule] = (rule_scores(val, rule), rule_scores(test, rule)) results.append(res) # Learned models: every candidate scored on validation; best per (family, feature set) by @@ -312,7 +327,8 @@ def run_training( res = ModelResult(name, "learned", fs_name, params, metrics(y_va, s_va, thr), threshold=thr) s_te = model.predict_proba(test[fs_cols])[:, 1] res.test = metrics(y_te, s_te, thr) - res.test["ci95"] = bootstrap_ci(y_te, s_te, thr) + res.test["ci95"] = bootstrap_ci(y_te, s_te, thr, clusters=groups) + predictions[f"{name}/{fs_name}"] = (s_va, s_te) res.test["recall_by_family"] = { fam: float( ((s_te >= thr) & (test["family"] == fam).to_numpy()).sum() @@ -339,6 +355,16 @@ def run_training( ) s_te = model.predict_proba(test[cols])[:, 1] errors = test.assign(score=s_te) + import pandas as pd + + # Every model's scores per evaluated row, so metrics can be recomputed from the artifact. + frames = [] + for part, rows in (("validation", val), ("test", test)): + frame = rows[["tx_hash", "label"]].assign(split=part) + for pred_name, (sv, st) in predictions.items(): + frame[pred_name] = sv if part == "validation" else st + frames.append(frame) + prediction_table = pd.concat(frames, ignore_index=True) fn = errors[(errors["label"] == 1) & (errors["score"] < selected.threshold)] fp = errors[(errors["label"] == 0) & (errors["score"] >= selected.threshold)] return { @@ -359,6 +385,7 @@ def run_training( }, "seconds": round(time.perf_counter() - started, 1), "reference": {c: reference_bins([float(v) for v in train[c]]) for c in cols}, + "predictions": prediction_table, } @@ -424,14 +451,23 @@ def ledger_entry( def save_run(run_dir: Path, entry: dict[str, Any], out: dict[str, Any]) -> Path: - """Persist the selected model with a hash-pinned card (``registry.load_model`` checks it).""" - import hashlib + """Persist the selected model with a hash-pinned card (``registry`` checks it), plus every + model's validation and test scores (``predictions.csv``). - import joblib + LightGBM models are written in LightGBM's own text format, so loading them never + unpickles anything; other families fall back to joblib.""" + import hashlib run_dir.mkdir(parents=True, exist_ok=True) - model_path = run_dir / "model.joblib" - joblib.dump(out["model"], model_path) + model = out["model"] + if hasattr(model, "booster_"): + model_path, serialization = run_dir / "model.txt", "lightgbm-text" + model_path.write_bytes(model.booster_.model_to_string().encode("utf-8")) + else: + import joblib + + model_path, serialization = run_dir / "model.joblib", "joblib" + joblib.dump(model, model_path) card = { "run_id": entry["run_id"], "ml_version": ML_VERSION, @@ -440,10 +476,17 @@ def save_run(run_dir: Path, entry: dict[str, Any], out: dict[str, Any]) -> Path: "threshold": entry["selected"]["threshold"], "selected": entry["selected"], "gate": entry["gate"], + "serialization": serialization, "model_sha256": hashlib.sha256(model_path.read_bytes()).hexdigest(), + "versions": entry.get("versions") or _versions(), + "score_semantics": "uncalibrated ranking score (see ML_GENERALIZATION_AUDIT.md)", "reference_bins": out["reference"], "trained_on": entry["config"], } (run_dir / "model_card.json").write_text(json.dumps(card, indent=1), encoding="utf-8") (run_dir / "run.json").write_text(json.dumps(entry, indent=1, default=str), encoding="utf-8") + if "predictions" in out: + out["predictions"].to_csv( + run_dir / "predictions.csv", index=False, lineterminator="\n", float_format="%.17g" + ) return run_dir diff --git a/tests/integration/test_ml_api.py b/tests/integration/test_ml_api.py index bc3472c..0b7cb4c 100644 --- a/tests/integration/test_ml_api.py +++ b/tests/integration/test_ml_api.py @@ -68,8 +68,10 @@ def events(**flags: object) -> list[tuple[str, str]]: assert off == shadow -@pytest.fixture -def promoted(tmp_path: Path) -> tuple[Path, dict]: # type: ignore[type-arg] +RUN = "20261101T120000Z-cccccccc" + + +def _trained_run(tmp_path: Path, *, holdout_passed: bool) -> tuple[Path, dict]: # type: ignore[type-arg] pd = pytest.importorskip("pandas") pytest.importorskip("lightgbm") from cryptoguard.ml.dataset import build_table @@ -85,20 +87,43 @@ def promoted(tmp_path: Path) -> tuple[Path, dict]: # type: ignore[type-arg] out = run_training(table, split, SMALL_GRID) gate = {**promotion_gate(out["results"], out["selected"]), "validated_for_shadow": True} entry = { - "run_id": "test-run", + "run_id": RUN, "config": {}, "gate": gate, "selected": {"name": out["selected"].name, "threshold": out["selected"].threshold}, } + run_dir = save_run(tmp_path / "runs" / RUN, entry, out) + approval = "research_only" + if holdout_passed: # synthetic stand-in for a real untouched-holdout evaluation record + card_path = run_dir / "model_card.json" + card = json.loads(card_path.read_text()) + card["holdout"] = { + "untouched": True, + "evaluated_once": True, + "passed": True, + "note": "synthetic test fixture, not evidence", + } + card_path.write_text(json.dumps(card)) + approval = "shadow_approved" registry = tmp_path / "registry.json" - promote(save_run(tmp_path / "run", entry, out), registry) + promote(run_dir, registry, approval=approval) # type: ignore[arg-type] return registry, records -def _client(records: dict, registry: Path, log: Path) -> TestClient: # type: ignore[type-arg] +@pytest.fixture +def promoted(tmp_path: Path) -> tuple[Path, dict]: # type: ignore[type-arg] + return _trained_run(tmp_path, holdout_passed=True) + + +def _client( # type: ignore[no-untyped-def] + records: dict, # type: ignore[type-arg] + registry: Path, + log: Path, + **rpc: object, +) -> TestClient: from tests.ml_synthetic import FakeRpc - fake = FakeRpc(records) + fake = FakeRpc(records, **rpc) # type: ignore[arg-type] settings: Settings = make_settings( rpc_url=RPC_URL, ml_shadow="shadow", @@ -128,11 +153,95 @@ def test_scores_a_transaction_in_shadow_mode(promoted: tuple[Path, dict], tmp_pa assert body["experimental"] is True assert body["status"] == "scored" assert 0.0 <= body["score"] <= 1.0 - assert body["run_id"] == "test-run" + assert body["run_id"] == RUN + assert body["approval"] == "shadow_approved" + assert body["observation"] == "post_inclusion" + assert body["score_semantics"] == "uncalibrated_ranking" assert any("not a finding" in note for note in body["notes"]) logged = [json.loads(line) for line in log.read_text().splitlines()] - assert len(logged) == 1 - assert logged[0]["tx_hash"] == tx_hash + scored = [entry for entry in logged if entry["status"] == "scored"] + assert len(scored) == 1 + assert scored[0]["tx_hash"] == tx_hash + assert "latency_ms" in scored[0] assert missing.json()["status"] == "not_found" assert status.status_code == 200 + assert status.json()["approval"] == "shadow_approved" assert status.json()["drift"]["status"] == "insufficient_data" + + +def test_mixed_case_hash_is_accepted_and_normalised(promoted, tmp_path: Path) -> None: # type: ignore[no-untyped-def] + registry, records = promoted + tx_hash = next(iter(records)) + with _client(records, registry, tmp_path / "s.jsonl") as client: + response = client.post( + "/api/v1/ml/transactions/score", json={"tx_hash": tx_hash.upper().replace("0X", "0x")} + ) + assert response.status_code == 200, response.text + assert response.json()["tx_hash"] == tx_hash + + +def test_research_only_model_is_refused_by_the_api(tmp_path: Path) -> None: + registry, records = _trained_run(tmp_path, holdout_passed=False) + with _client(records, registry, tmp_path / "s.jsonl") as client: + response = client.post( + "/api/v1/ml/transactions/score", json={"tx_hash": next(iter(records))} + ) + status = client.get("/api/v1/ml/status") + assert response.status_code == 503 + assert "research only" in response.json()["error"]["message"] + assert status.status_code == 200 # the status of a research-only model is still readable + assert status.json()["approval"] == "research_only" + + +def test_a_provider_on_another_chain_is_refused(promoted, tmp_path: Path) -> None: # type: ignore[no-untyped-def] + registry, records = promoted + with _client(records, registry, tmp_path / "s.jsonl", chain_id=11155111) as client: + response = client.post( + "/api/v1/ml/transactions/score", json={"tx_hash": next(iter(records))} + ) + assert response.status_code >= 400 + assert response.json()["error"]["code"] in ("chain_mismatch", "ml_unavailable") + assert not (tmp_path / "s.jsonl").exists() # nothing scored, nothing logged + + +def test_missing_receipt_is_incomplete_not_a_score(promoted, tmp_path: Path) -> None: # type: ignore[no-untyped-def] + registry, records = promoted + tx_hash = next(iter(records)) + with _client(records, registry, tmp_path / "s.jsonl", no_receipt={tx_hash}) as client: + response = client.post("/api/v1/ml/transactions/score", json={"tx_hash": tx_hash}) + assert response.status_code == 200, response.text + assert response.json()["status"] == "incomplete" + assert response.json()["score"] is None + + +def test_rpc_failure_is_an_error_not_a_low_score(promoted, tmp_path: Path) -> None: # type: ignore[no-untyped-def] + registry, records = promoted + with _client(records, registry, tmp_path / "s.jsonl", fail={"eth_getCode"}) as client: + response = client.post( + "/api/v1/ml/transactions/score", json={"tx_hash": next(iter(records))} + ) + assert response.status_code >= 500 + assert "score" not in response.json() + + +def test_scoring_writes_nothing_to_the_database(promoted, tmp_path: Path) -> None: # type: ignore[no-untyped-def] + from sqlalchemy import inspect, text + + registry, records = promoted + with _client(records, registry, tmp_path / "s.jsonl") as client: + engine = client.app.state.cryptoguard.repository._engine # type: ignore[attr-defined] + + def counts() -> dict[str, int]: + with engine.connect() as conn: + return { + t: conn.execute(text(f'SELECT COUNT(*) FROM "{t}"')).scalar_one() # noqa: S608 + for t in inspect(engine).get_table_names() + } + + before = counts() + for tx_hash in list(records)[:3]: + assert ( + client.post("/api/v1/ml/transactions/score", json={"tx_hash": tx_hash}).status_code + == 200 + ) + assert counts() == before diff --git a/tests/ml_synthetic.py b/tests/ml_synthetic.py index 8603b3d..4cea4e7 100644 --- a/tests/ml_synthetic.py +++ b/tests/ml_synthetic.py @@ -108,9 +108,18 @@ def make_records( class FakeRpc: """JSON-RPC over httpx.MockTransport serving the four methods the collector uses.""" - def __init__(self, records: dict[str, dict[str, Any]], *, fail: set[str] | None = None): + def __init__( + self, + records: dict[str, dict[str, Any]], + *, + fail: set[str] | None = None, + chain_id: int = 1, + no_receipt: set[str] | None = None, + ): self.records = records self.fail = fail or set() + self.chain_id = chain_id + self.no_receipt = no_receipt or set() self.calls: list[str] = [] def transport(self) -> httpx.MockTransport: @@ -123,12 +132,14 @@ def handle(self, request: httpx.Request) -> httpx.Response: if method in self.fail: return httpx.Response(503, text="unavailable") result: Any = None - if method == "eth_getTransactionByHash": + if method == "eth_chainId": + result = hex(self.chain_id) + elif method == "eth_getTransactionByHash": rec = self.records.get(params[0]) result = None if rec is None else {**rec["tx"], "hash": params[0]} elif method == "eth_getTransactionReceipt": rec = self.records.get(params[0]) - result = None if rec is None else rec["receipt"] + result = None if rec is None or params[0] in self.no_receipt else rec["receipt"] elif method == "eth_getTransactionCount": rec = next(r for r in self.records.values() if r["tx"]["from"] == params[0]) result = rec["from_nonce_before"] diff --git a/tests/unit/test_ml_audit.py b/tests/unit/test_ml_audit.py new file mode 100644 index 0000000..4eedfdf --- /dev/null +++ b/tests/unit/test_ml_audit.py @@ -0,0 +1,88 @@ +"""Audit statistics are correct (they decide what the generalization report claims).""" + +from __future__ import annotations + +import pytest + +pytest.importorskip("sklearn") + +import numpy as np + +from cryptoguard.ml.audit import ( + cluster_bootstrap, + confusion, + evaluate, + negatives_needed, + prevalence_scenarios, + roc_auc, + wilson, +) + + +def test_wilson_matches_reference_values() -> None: + # Reference: Wilson score interval, z = 1.96 (e.g. statsmodels proportion_confint). + lo, hi = wilson(7, 43) + assert lo == pytest.approx(0.0810, abs=5e-4) + assert hi == pytest.approx(0.2999, abs=5e-4) + assert wilson(0, 10)[0] == 0.0 + assert wilson(10, 10)[1] == 1.0 + assert wilson(0, 0) is None + + +def test_auc_matches_sklearn_with_ties() -> None: + from sklearn.metrics import roc_auc_score + + rng = np.random.default_rng(1) + for _ in range(30): + y = rng.integers(0, 2, 50) + y[:2] = [0, 1] + s = rng.integers(0, 4, 50) / 3 + assert roc_auc(y, s) == pytest.approx(roc_auc_score(y, s), abs=1e-12) + assert roc_auc(np.ones(5), np.arange(5.0)) is None + + +def test_threshold_boundary_counts_as_flagged() -> None: + y = np.array([1, 0, 1, 0]) + s = np.array([0.5, 0.5, 0.49, 0.1]) + assert confusion(y, s, 0.5) == {"tp": 1, "fp": 1, "fn": 1, "tn": 1} + + +def test_evaluate_reports_prevalence_and_handles_one_class() -> None: + y = np.array([1, 1, 1, 0]) + e = evaluate(y, np.array([0.9, 0.8, 0.7, 0.1]), 0.5) + assert e["prevalence"] == 0.75 + assert e["average_precision"] == 1.0 + assert e["ap_above_prevalence"] == pytest.approx(0.25) + one = evaluate(np.ones(3, dtype=int), np.array([0.2, 0.3, 0.9]), 0.5) + assert one["average_precision"] is None + assert one["false_positive_rate"] is None + assert one["fpr_wilson"] is None + + +def test_cluster_bootstrap_is_wider_than_pretending_rows_are_independent() -> None: + rng = np.random.default_rng(3) + clusters = np.repeat(np.arange(12), 10) # 12 accounts x 10 rows + y = np.tile([0, 1], 60) + # Whole clusters err together: cluster-level dependence. + noisy = np.isin(clusters, [0, 1, 2]) + s = np.where(noisy, 1 - y, y) * 0.8 + rng.uniform(0, 0.2, 120) + by_cluster = cluster_bootstrap(y, s, 0.5, clusters, n=500) + by_row = cluster_bootstrap(y, s, 0.5, np.arange(120), n=500) + width = lambda iv: iv[1] - iv[0] # noqa: E731 + assert width(by_cluster["false_positive_rate"]) > width(by_row["false_positive_rate"]) + assert by_cluster["clusters"] == 12 + + +def test_negatives_needed_follows_the_rule_of_three() -> None: + assert negatives_needed(0.01) == 299 + assert negatives_needed(0.001) == 2_995 + assert negatives_needed(0.05) == 59 + + +def test_prevalence_scenarios_arithmetic() -> None: + rows = prevalence_scenarios(recall=1.0, fpr=0.1, fpr_interval=[0.05, 0.2]) + one_percent = next(r for r in rows if r["prevalence"] == 0.01) + assert one_percent["true_alerts"] == pytest.approx(100) + assert one_percent["false_alerts"] == pytest.approx(990) + assert one_percent["precision"] == pytest.approx(100 / 1090) + assert one_percent["false_alerts_range"] == pytest.approx([495, 1980]) diff --git a/tests/unit/test_ml_collector.py b/tests/unit/test_ml_collector.py new file mode 100644 index 0000000..86641ad --- /dev/null +++ b/tests/unit/test_ml_collector.py @@ -0,0 +1,236 @@ +"""Collector and request budget: the cap must hold under retries, crashes and concurrency. + +Mock transports only (no RPC). Every test counts real HTTP attempts and compares them with +the ledger: reservations may exceed attempts (a crash after reserving), never the reverse. +""" + +from __future__ import annotations + +import asyncio +import json +import threading +from pathlib import Path + +import httpx +import pytest + +pytest.importorskip("pandas") + +import pandas as pd + +from cryptoguard.ml import collect as collect_mod +from cryptoguard.ml.collect import ( + BudgetExhaustedError, + LedgerCorruptError, + RequestLedger, + collect, + load_collected, +) +from tests.ml_synthetic import FakeRpc, make_records + + +async def _no_sleep(_: float) -> None: + return None + + +class Counting(httpx.AsyncBaseTransport): + """Wraps a transport; counts attempts and can fail or crash on chosen attempts.""" + + def __init__(self, inner: httpx.AsyncBaseTransport, *, crash_after: int | None = None): + self.inner = inner + self.attempts = 0 + self.crash_after = crash_after + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + self.attempts += 1 + if self.crash_after is not None and self.attempts > self.crash_after: + raise KeyboardInterrupt # the process dies mid-collection + return await self.inner.handle_async_request(request) + + +def _run( + sample: pd.DataFrame, + out: Path, + ledger: RequestLedger, + transport: httpx.AsyncBaseTransport, + concurrency: int = 1, +) -> dict[str, int]: + return asyncio.run( + collect( + sample, + out, + ledger=ledger, + transport=transport, + concurrency=concurrency, + sleep=_no_sleep, + ) + ) + + +def test_cap_holds_and_resume_does_not_refetch(tmp_path: Path) -> None: + labels, records = make_records(n=40) + sample, out = pd.DataFrame(labels), tmp_path / "chain.jsonl" + ledger = RequestLedger(tmp_path / "budget.json", cap=60) + first = Counting(FakeRpc(records).transport()) + stats = _run(sample, out, ledger, first) + assert first.attempts <= 60 + assert ledger.used() == first.attempts # every attempt reserved, nothing else + assert stats["skipped_budget"] > 0 + done = len(load_collected(out)) + second = Counting(FakeRpc(records).transport()) + _run(sample, out, RequestLedger(tmp_path / "budget.json", cap=10_000), second) + assert len(load_collected(out)) == 40 + assert second.attempts == (40 - done) * collect_mod.REQUESTS_PER_TX + + +def test_retries_are_reserved_before_they_are_sent(tmp_path: Path) -> None: + labels, records = make_records(n=3) + ledger = RequestLedger(tmp_path / "budget.json", cap=1_000) + transport = Counting(FakeRpc(records, fail={"eth_getCode"}).transport()) + _run(pd.DataFrame(labels), tmp_path / "c.jsonl", ledger, transport) + # Each transaction: 3 good calls + eth_getCode tried 1 + 4 retries, all reserved. + assert transport.attempts == 3 * (3 + 5) + assert ledger.used() == transport.attempts + rows = [json.loads(line) for line in (tmp_path / "c.jsonl").read_text().splitlines()] + assert {r["status"] for r in rows} == {"error"} + assert load_collected(tmp_path / "c.jsonl") == {} # failures are retried next time + + +def test_crash_mid_run_never_undercounts(tmp_path: Path) -> None: + labels, records = make_records(n=20) + ledger = RequestLedger(tmp_path / "budget.json", cap=1_000) + transport = Counting(FakeRpc(records).transport(), crash_after=13) + with pytest.raises(KeyboardInterrupt): + _run(pd.DataFrame(labels), tmp_path / "c.jsonl", ledger, transport) + # The 14th attempt was reserved, then the process died while sending it. + assert ledger.used() >= transport.attempts + assert ledger.used() == 14 + + +def test_concurrent_collectors_cannot_exceed_a_shared_cap(tmp_path: Path) -> None: + labels, records = make_records(n=30) + ledger_path = tmp_path / "budget.json" + t1, t2 = (Counting(FakeRpc(records).transport()) for _ in range(2)) + + async def both() -> None: + await asyncio.gather( + collect( + pd.DataFrame(labels[:15]), + tmp_path / "a.jsonl", + ledger=RequestLedger(ledger_path, cap=50), + transport=t1, + concurrency=3, + sleep=_no_sleep, + ), + collect( + pd.DataFrame(labels[15:]), + tmp_path / "b.jsonl", + ledger=RequestLedger(ledger_path, cap=50), + transport=t2, + concurrency=3, + sleep=_no_sleep, + ), + ) + + asyncio.run(both()) + assert t1.attempts + t2.attempts <= 50 + assert RequestLedger(ledger_path, cap=50).used() == t1.attempts + t2.attempts + + +def test_ledger_reservations_from_many_threads_are_never_lost(tmp_path: Path) -> None: + ledger_path = tmp_path / "budget.json" + granted: list[int] = [] + errors: list[BaseException] = [] + + def worker() -> None: + ledger = RequestLedger(ledger_path, cap=150) + for _ in range(40): + try: + ledger.reserve(1) + granted.append(1) + except BudgetExhaustedError: + return + except BaseException as exc: # any other failure fails the test + errors.append(exc) + return + + threads = [threading.Thread(target=worker) for _ in range(5)] + for t in threads: + t.start() + for t in threads: + t.join() + assert errors == [] + assert len(granted) == 150 # 200 asked, exactly the cap granted + assert RequestLedger(ledger_path, cap=150).used() == 150 + + +def test_corrupt_ledger_stops_collection(tmp_path: Path) -> None: + labels, records = make_records(n=2) + (tmp_path / "budget.json").write_text("{not json") + transport = Counting(FakeRpc(records).transport()) + with pytest.raises(LedgerCorruptError): + _run( + pd.DataFrame(labels), + tmp_path / "c.jsonl", + RequestLedger(tmp_path / "budget.json", cap=100), + transport, + ) + assert transport.attempts == 0 # nothing sent without a valid budget + + +def test_phase11_ledger_usage_still_counts(tmp_path: Path) -> None: + path = tmp_path / "budget.json" + path.write_text(json.dumps({"requests": 11_953, "notes": ["interrupted run"]})) + ledger = RequestLedger(path, cap=12_000) + assert ledger.reserve(47) == 12_000 + with pytest.raises(BudgetExhaustedError): + ledger.reserve(1) + assert json.loads(path.read_text())["notes"] == ["interrupted run"] + + +def test_cut_off_checkpoint_line_is_repaired_and_refetched(tmp_path: Path) -> None: + labels, records = make_records(n=4) + out = tmp_path / "c.jsonl" + ledger = RequestLedger(tmp_path / "budget.json", cap=1_000) + _run(pd.DataFrame(labels[:2]), out, ledger, FakeRpc(records).transport()) + with out.open("a", encoding="utf-8") as fh: + fh.write('{"tx_hash": "0x' + "0" * 20) # the process died while writing + assert len(load_collected(out)) == 2 # the cut-off tail is ignored when reading + stats = _run(pd.DataFrame(labels), out, ledger, FakeRpc(records).transport()) + assert stats["repaired_tail"] == 1 + assert len(load_collected(out)) == 4 + for line in out.read_text().splitlines(): + json.loads(line) # no corrupt line left behind + + +def test_corrupt_line_in_the_middle_is_an_error(tmp_path: Path) -> None: + out = tmp_path / "c.jsonl" + out.write_text( + '{"tx_hash": "0xa", "status": "ok"}\n{broken\n{"tx_hash": "0xb", "status": "ok"}\n' + ) + with pytest.raises(ValueError, match="corrupt checkpoint line 2"): + load_collected(out) + + +def test_missing_receipt_is_incomplete_not_a_failed_transaction(tmp_path: Path) -> None: + labels, records = make_records(n=3) + gone = labels[0]["tx_hash"] + out = tmp_path / "c.jsonl" + stats = _run( + pd.DataFrame(labels), + out, + RequestLedger(tmp_path / "b.json", cap=1_000), + FakeRpc(records, no_receipt={gone}).transport(), + ) + assert stats["incomplete"] == 1 + assert gone not in load_collected(out) # not a finished record: retried next run + + +def test_duplicate_records_keep_the_latest_success(tmp_path: Path) -> None: + out = tmp_path / "c.jsonl" + out.write_text( + '{"tx_hash": "0xa", "status": "error", "error": "rpc_unavailable"}\n' + '{"tx_hash": "0xa", "status": "ok", "tx": {"n": 1}}\n' + '{"tx_hash": "0xa", "status": "ok", "tx": {"n": 2}}\n' + ) + assert load_collected(out)["0xa"]["tx"] == {"n": 2} diff --git a/tests/unit/test_ml_history.py b/tests/unit/test_ml_history.py new file mode 100644 index 0000000..684a45d --- /dev/null +++ b/tests/unit/test_ml_history.py @@ -0,0 +1,156 @@ +"""Wallet-history features: point in time, zero versus unknown, reverted payments, lookalikes.""" + +from __future__ import annotations + +import random + +from cryptoguard.ml.history import Coverage, WalletEvent, history_features + +FRIEND = "0xd296222fb44f5ec8d9600a8c91ed70ed5657d7d5" +LOOKALIKE = "0xd296261b103d698c272887274f38d7ea8097d7d5" # same first and last 5 hex characters +STRANGER = "0x" + "3c" * 20 +FULL = Coverage(from_block=100, to_block=10_000, complete=True) + + +def pay(block: int, to: str, *, idx: int = 0, succeeded: bool | None = True) -> WalletEvent: + return WalletEvent(block, idx, -1, "out", to, 10**18, wallet_signed=True, succeeded=succeeded) + + +def plant_in(block: int, sender: str) -> WalletEvent: + return WalletEvent(block, 0, 3, "in", sender, 0) + + +def spoof_out(block: int, to: str) -> WalletEvent: + return WalletEvent(block, 0, 4, "out", to, 0, wallet_signed=False) + + +def features(events: list[WalletEvent], to: str, block: int = 5_000, **kw: object): # type: ignore[no-untyped-def] + return history_features( + events, + kw.pop("coverage", FULL), + recipient=to, + block=block, # type: ignore[arg-type] + tx_index=kw.pop("tx_index", 5), + **kw, + ) # type: ignore[arg-type] + + +def test_empty_complete_history_gives_real_zeros() -> None: + f = features([], FRIEND) + assert f.history_status == "available" + assert f.prior_payments_to_recipient == 0 + assert f.distinct_prior_recipients == 0 + assert f.recipient_lookalike_of_known is False + assert f.blocks_since_first_interaction is None # never interacted: no duration + + +def test_unavailable_and_partial_history_are_not_zero() -> None: + none = features([pay(200, FRIEND)], FRIEND, coverage=None) + assert none.history_status == "unavailable" + assert none.prior_payments_to_recipient is None + gap = features([pay(200, FRIEND)], FRIEND, coverage=Coverage(100, 4_000, complete=True)) + assert gap.history_status == "partial" # scan stops before the payment's block + assert gap.prior_payments_to_recipient is None + incomplete = features([pay(200, FRIEND)], FRIEND, coverage=Coverage(100, 9_000, complete=False)) + assert incomplete.history_status == "partial" + starts_later = features([], FRIEND, coverage=Coverage(6_000, 9_000, complete=True)) + assert starts_later.history_status == "unavailable" + row, zero_row = gap.as_model_row(), features([], FRIEND).as_model_row() + assert row["history_partial"] == 1.0 + assert row["prior_payments_to_recipient"] == -1.0 + assert zero_row["prior_payments_to_recipient"] == 0.0 # zero and unknown stay distinct + + +def test_one_and_several_prior_payments() -> None: + once = features([pay(1_000, FRIEND)], FRIEND) + assert once.prior_payments_to_recipient == 1 + assert once.blocks_since_first_interaction == 4_000 + many = features([pay(1_000, FRIEND), pay(2_000, FRIEND), pay(3_000, STRANGER)], FRIEND) + assert many.prior_payments_to_recipient == 2 + assert many.blocks_since_last_interaction == 3_000 + assert many.distinct_prior_recipients == 2 + + +def test_new_recipient_that_imitates_a_known_one() -> None: + events = [pay(1_000, FRIEND), plant_in(1_500, LOOKALIKE), spoof_out(1_600, LOOKALIKE)] + f = features(events, LOOKALIKE) + assert f.prior_payments_to_recipient == 0 + assert f.recipient_lookalike_of_known is True + assert f.recipient_max_affix_to_known == 10 + assert f.unsolicited_events_with_recipient == 2 # one planted in, one spoofed out + assert f.lookalike_plantings_observed == 2 + honest = features(events, FRIEND) + assert honest.recipient_lookalike_of_known is False + + +def test_reverted_payment_identifies_a_counterparty_but_is_not_a_payment() -> None: + f = features([pay(1_000, FRIEND, succeeded=False)], FRIEND) + assert f.prior_payments_to_recipient == 0 + assert f.distinct_prior_recipients == 1 + lookalike = features([pay(1_000, FRIEND, succeeded=False)], LOOKALIKE) + assert lookalike.recipient_lookalike_of_known is True + + +def test_unknown_receipt_counts_as_executed_like_the_detector() -> None: + assert features([pay(1_000, FRIEND, succeeded=None)], FRIEND).prior_payments_to_recipient == 1 + + +def test_recent_new_recipient_share() -> None: + events = [pay(1_000 + i, f"0x{i:040x}") for i in range(1, 6)] + [ + pay(2_000, "0x" + "0" * 39 + "1") + ] + f = features(events, FRIEND) + assert f.recent_new_recipient_share == 5 / 6 # six payments, the last to a known address + + +def test_future_events_never_change_earlier_features() -> None: + """Metamorphic: adding events after the boundary changes nothing.""" + past = [pay(1_000, FRIEND), plant_in(1_500, LOOKALIKE)] + future = [pay(6_000, LOOKALIKE), pay(5_000, LOOKALIKE, idx=9), plant_in(7_000, STRANGER)] + assert features(past + future, LOOKALIKE) == features(past, LOOKALIKE) + + +def test_event_order_does_not_matter() -> None: + events = [ + pay(1_000, FRIEND), + pay(2_000, STRANGER), + plant_in(1_500, LOOKALIKE), + pay(3_000, FRIEND, succeeded=False), + ] + shuffled = events[:] + random.Random(0).shuffle(shuffled) + assert features(shuffled, LOOKALIKE) == features(events, LOOKALIKE) + + +def test_same_block_ordering_depends_on_the_boundary() -> None: + same_block = [pay(5_000, FRIEND, idx=2)] + pre_signing = features(same_block, FRIEND, tx_index=5, boundary="pre_signing") + pre_execution = features(same_block, FRIEND, tx_index=5, boundary="pre_execution") + assert pre_signing.prior_payments_to_recipient == 0 # same block: not yet known + assert pre_execution.prior_payments_to_recipient == 1 # executed before it in the block + later_in_block = features( + [pay(5_000, FRIEND, idx=7)], FRIEND, tx_index=5, boundary="pre_execution" + ) + assert later_in_block.prior_payments_to_recipient == 0 + + +def test_pre_execution_needs_coverage_of_the_payment_block() -> None: + cov = Coverage(100, 4_999, complete=True) + assert features([], FRIEND, coverage=cov, boundary="pre_signing").history_status == "available" + assert features([], FRIEND, coverage=cov, boundary="pre_execution").history_status == "partial" + + +def test_address_casing_is_irrelevant() -> None: + upper = [pay(1_000, FRIEND.upper().replace("0X", "0x"))] + assert features(upper, FRIEND).prior_payments_to_recipient == 1 + + +def test_replay_fixture_adapter_respects_coverage() -> None: + from cryptoguard.ml.history import events_from_fixture + from cryptoguard.replay.models import load_cases + + case = next(c for c in load_cases() if c.fixture is not None) + events, coverage = events_from_fixture(case.fixture) + assert coverage.from_block == case.fixture.from_block + assert events + assert all(e.direction in ("in", "out") for e in events) diff --git a/tests/unit/test_ml_pipeline.py b/tests/unit/test_ml_pipeline.py index 68149b3..987e1de 100644 --- a/tests/unit/test_ml_pipeline.py +++ b/tests/unit/test_ml_pipeline.py @@ -1,9 +1,8 @@ -"""ML pipeline: source integrity, label parsing, sampling, leakage-safe splits, collector -budget, training smoke run, registry and monitoring. Synthetic data only.""" +"""ML pipeline: source integrity, label parsing, sampling, leakage-safe splits, training +smoke run, registry and monitoring. Synthetic data only.""" from __future__ import annotations -import asyncio import json from pathlib import Path @@ -17,17 +16,16 @@ import pandas as pd -from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy from cryptoguard.ml import collect as collect_mod from cryptoguard.ml.dataset import build_table, hubs from cryptoguard.ml.features import parties from cryptoguard.ml.labels import _PTX_HEADER_ROW, load_ptxphish from cryptoguard.ml.monitoring import drift_report, log_score, psi, reference_bins -from cryptoguard.ml.registry import ModelRegistryError, load_shadow_model, promote +from cryptoguard.ml.registry import ModelRegistryError, load_registered_model, promote from cryptoguard.ml.sources import SOURCES, SourceIntegrityError, sha256_file, verify from cryptoguard.ml.splits import make_splits from cryptoguard.ml.train import promotion_gate, run_training, save_run -from tests.ml_synthetic import TOKEN, FakeRpc, make_records +from tests.ml_synthetic import TOKEN, make_records # --- sources and labels --------------------------------------------------------------------- @@ -103,6 +101,19 @@ def test_malformed_hash_or_layout_change_fails_loudly( load_ptxphish(_fake_ptx(tmp_path / "b", monkeypatch, renamed)) +def test_a_hash_in_two_categories_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Conflicting labels (same transaction, two categories, any casing) fail validation.""" + import pandera.errors + + columns: dict[str, list[str]] = {name: [] for name in ALL_SUBTYPES} + columns["Approve"] = ["0x" + "ab" * 32] + columns["Benign KOL"] = ["0x" + "AB" * 32] + with pytest.raises(pandera.errors.SchemaError): + load_ptxphish(_fake_ptx(tmp_path, monkeypatch, columns)) + + def test_a_tampered_source_file_is_refused(tmp_path: Path) -> None: source = SOURCES["forta"] for f in source.files: @@ -176,63 +187,127 @@ def test_reused_attacker_contract_cannot_reach_the_test_split() -> None: assert not split[rows].isin(["validation", "test"]).any() -# --- collector ----------------------------------------------------------------------------- +def _rec(tx_hash: str, block: int, sender: str, to: str, logs: list[dict] | None = None) -> dict: # type: ignore[type-arg] + return { + "tx_hash": tx_hash, + "status": "ok", + "tx": { + "blockNumber": hex(block), + "from": sender, + "to": to, + "value": "0x0", + "gas": hex(60_000), + "gasPrice": hex(10**9), + "input": "0xa9059cbb" + "00" * 64, + }, + "receipt": {"status": "0x1", "gasUsed": hex(50_000), "logs": logs or []}, + "from_nonce_before": "0x1", + "to_code_before": {"size": 100, "prefix": "0x608060"}, + } -def _client(fake: FakeRpc) -> JsonRpcClient: - async def no_sleep(_: float) -> None: - return None +def _transfer_log(token: str, src: str, dst: str) -> dict: # type: ignore[type-arg] + from cryptoguard.ml.features import TRANSFER - return JsonRpcClient( - "https://rpc.invalid", - transport=fake.transport(), - retry=RetryPolicy(max_retries=1), - sleep=no_sleep, - max_concurrency=1, - ) + return { + "address": token, + "topics": [TRANSFER, "0x" + "0" * 24 + src[2:], "0x" + "0" * 24 + dst[2:]], + "data": "0x" + "00" * 32, + } -def test_collector_respects_the_request_cap_and_resumes(tmp_path: Path) -> None: - labels, records = make_records(n=40) - sample = pd.DataFrame(labels) - out = tmp_path / "chain.jsonl" - fake = FakeRpc(records) - stats = asyncio.run( - collect_mod.collect( - sample, out, rpc_url="unused", max_requests=60, concurrency=1, client=_client(fake) - ) - ) - assert len(fake.calls) <= 60 - assert collect_mod.requests_used(out) == len(fake.calls) # recorded as it went - assert stats["skipped_budget"] > 0 - first = len(collect_mod.load_collected(out)) - fake2 = FakeRpc(records) - asyncio.run( - collect_mod.collect( - sample, out, rpc_url="unused", max_requests=10_000, concurrency=1, client=_client(fake2) - ) - ) - assert len(collect_mod.load_collected(out)) == 40 - assert len(fake2.calls) == (40 - first) * collect_mod.REQUESTS_PER_TX # no refetching - - -def test_collector_records_failures_and_retries_them_later(tmp_path: Path) -> None: - labels, records = make_records(n=3) - out = tmp_path / "chain.jsonl" - asyncio.run( - collect_mod.collect( - pd.DataFrame(labels), - out, - rpc_url="unused", - max_requests=1_000, - concurrency=1, - client=_client(FakeRpc(records, fail={"eth_getCode"})), - ) +def _scenario(rows: list[tuple[str, int, str, str, int, list[dict] | None]]): # type: ignore[no-untyped-def,type-arg] + """Build a table from (hash, block, sender, to, label, logs) rows and split it.""" + records = {h: _rec(h, b, s, t, logs) for h, b, s, t, _, logs in rows} + labels = pd.DataFrame( + [ + { + "tx_hash": h, + "family": "ice_phishing" if y else "benign", + "subtype": "approve" if y else "benign_kol", + "label": y, + } + for h, _, _, _, y, _ in rows + ] ) - rows = [json.loads(line) for line in out.read_text().splitlines()] - assert {r["status"] for r in rows} == {"error"} - assert collect_mod.load_collected(out) == {} + table = build_table(labels, records)[0] + split, _ = make_splits(table, records) + return dict(zip(table["tx_hash"], split, strict=True)) + + +def _h(i: int) -> str: + return "0x" + f"{i:064x}" + + +def _a(i: int) -> str: + return "0x" + f"{i:040x}" + + +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" # in the public-infrastructure registry + + +def _background(n: int = 40, start: int = 1_000) -> list[tuple[str, int, str, str, int, None]]: + """Unrelated rows of both classes spread over time, so every split has both labels.""" + return [ + (_h(10_000 + i), 15_000_000 + start + i * 100, _a(50_000 + i), _a(60_000 + i), i % 2, None) + for i in range(n) + ] + + +# Row 1 sits early inside the study window (both classes occur before it); row 2 late but +# still inside (the background's benign rows end at block 15_004_800, which closes the window). +EARLY, LATE = 15_001_150, 15_004_750 +PURGED = "excluded:shares_account_with_earlier_split" + + +def test_shared_attacker_signer_never_spans_splits() -> None: + signer = _a(1) + rows = [ + *_background(), + (_h(1), EARLY, signer, _a(2), 1, None), + (_h(2), LATE, signer, _a(3), 1, None), + ] + split = _scenario(rows) + assert split[_h(1)] == "train" + assert split[_h(2)].startswith(PURGED) + + +def test_shared_lookalike_recipient_never_spans_splits() -> None: + lookalike = _a(7) + rows = [ + *_background(), + (_h(1), EARLY, _a(5), USDT, 1, [_transfer_log(USDT, _a(8), lookalike)]), + (_h(2), LATE, _a(6), USDT, 1, [_transfer_log(USDT, _a(9), lookalike)]), + ] + split = _scenario(rows) + assert split[_h(1)] == "train" + assert split[_h(2)].startswith(PURGED) + + +def test_public_token_alone_does_not_link_unrelated_wallets() -> None: + rows = [ + *_background(), + (_h(1), EARLY, _a(5), USDT, 0, None), + (_h(2), LATE, _a(6), USDT, 0, None), + ] + split = _scenario(rows) + assert split[_h(1)] == "train" + assert split[_h(2)] == "test" # USDT is registry infrastructure; nothing else is shared + + +def test_mixed_case_addresses_are_the_same_entity() -> None: + signer = "0x" + "ab" * 20 + rows = [ + *_background(), + (_h(1), EARLY, signer, _a(2), 1, None), + (_h(2), LATE, signer.upper().replace("0X", "0x"), _a(3), 1, None), + ] + split = _scenario(rows) + assert split[_h(1)] == "train" + assert split[_h(2)].startswith(PURGED) + +# Collector and request-budget tests: tests/unit/test_ml_collector.py. # --- training, gate, registry, monitoring -------------------------------------------------- @@ -283,26 +358,111 @@ def test_training_is_deterministic(trained: dict) -> None: # type: ignore[type- assert first == second -def test_registry_refuses_ungated_and_tampered_models(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] +RUN_A = "20261101T000000Z-aaaaaaaa" +RUN_B = "20261101T000001Z-bbbbbbbb" + + +def _saved(trained: dict, runs: Path, run_id: str, gate_ok: bool) -> Path: # type: ignore[type-arg] out = trained["out"] - gate = promotion_gate(out["results"], out["selected"]) + gate = {**promotion_gate(out["results"], out["selected"]), "validated_for_shadow": gate_ok} entry = { - "run_id": "r1", + "run_id": run_id, "config": {}, - "gate": {**gate, "validated_for_shadow": False}, + "gate": gate, "selected": {"threshold": out["selected"].threshold}, } - run_dir = save_run(tmp_path / "r1", entry, out) + return save_run(runs / run_id, entry, out) + + +def test_registry_refuses_ungated_and_tampered_models(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + runs, registry = tmp_path / "runs", tmp_path / "registry.json" with pytest.raises(ModelRegistryError, match="did not pass"): - promote(run_dir, tmp_path / "registry.json") - entry["gate"]["validated_for_shadow"] = True - run_dir = save_run(tmp_path / "r2", {**entry, "run_id": "r2"}, out) - registry = tmp_path / "registry.json" + promote(_saved(trained, runs, RUN_A, gate_ok=False), registry) + run_dir = _saved(trained, runs, RUN_B, gate_ok=True) promote(run_dir, registry) - assert load_shadow_model(registry).run_id == "r2" - (run_dir / "model.joblib").write_bytes(b"not the trained model") + loaded = load_registered_model(registry) + assert loaded.run_id == RUN_B + assert loaded.approval == "research_only" # the default: a development benchmark only + model_file = next(run_dir.glob("model.*")) + model_file.write_bytes(model_file.read_bytes() + b"\n") with pytest.raises(ModelRegistryError, match="hash mismatch"): - load_shadow_model(registry) + load_registered_model(registry) + + +def test_shadow_approval_needs_an_untouched_holdout(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + run_dir = _saved(trained, tmp_path / "runs", RUN_A, gate_ok=True) + with pytest.raises(ModelRegistryError, match="untouched"): + promote(run_dir, tmp_path / "registry.json", approval="shadow_approved") + + +def test_lightgbm_is_stored_as_text_and_scores_identically(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + """No pickle for LightGBM: the text model must reproduce the trained classifier's scores.""" + import numpy as np + + from cryptoguard.ml.registry import _verified_model + from cryptoguard.ml.train import make_model + + table, split = trained["table"], trained["split"] + train = table[split == "train"] + cols = list(trained["out"]["feature_columns"]) + model = make_model("lightgbm", {"num_leaves": 7, "min_child_samples": 5}) + model.fit(train[cols], train["label"]) + out = {**trained["out"], "model": model, "feature_columns": cols} + entry = { + "run_id": RUN_A, + "config": {}, + "gate": {"validated_for_shadow": True}, + "selected": {"threshold": 0.5}, + } + run_dir = save_run(tmp_path / "runs" / RUN_A, entry, out) + assert (run_dir / "model.txt").exists() + assert not (run_dir / "model.joblib").exists() + _, loaded = _verified_model(run_dir) + rows = table[split == "test"][cols] + assert np.allclose(loaded.predict_proba(rows), model.predict_proba(rows), atol=1e-12) + + +def test_registry_rejects_paths_and_malformed_entries(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + from cryptoguard.ml.registry import run_dir_for + + runs = tmp_path / "runs" + for bad in ("../outside", "20261101T000000Z-aaaaaaaa/../x", "r1", ""): + with pytest.raises(ModelRegistryError, match="invalid run id"): + run_dir_for(bad, runs) + registry = tmp_path / "registry.json" + registry.write_text(json.dumps({"shadow": {"run_dir": "C:/anything"}})) # Phase 11 format + with pytest.raises(ModelRegistryError, match="malformed"): + load_registered_model(registry) + registry.write_text(json.dumps({"model": {"run_id": "../../etc", "approval": "research_only"}})) + with pytest.raises(ModelRegistryError, match="invalid run id"): + load_registered_model(registry, runs) + + +def test_registry_refuses_cards_that_do_not_match_this_code(trained: dict, tmp_path: Path) -> None: # type: ignore[type-arg] + from cryptoguard.ml.registry import _verified_model + + run_dir = _saved(trained, tmp_path / "runs", RUN_A, gate_ok=True) + card_path = run_dir / "model_card.json" + card = json.loads(card_path.read_text()) + for change, message in ( + ({"feature_set_version": "ptx-features/0"}, "features"), + ({"feature_columns": ["not_a_feature"]}, "feature columns"), + ({"threshold": 7}, "threshold"), + ({"versions": {**card["versions"], "lightgbm": "1.0.0"}}, "lightgbm"), + ): + card_path.write_text(json.dumps({**card, **change})) + with pytest.raises(ModelRegistryError, match=message): + _verified_model(run_dir) + card_path.write_text("{not json") + with pytest.raises(ModelRegistryError, match="unreadable"): + _verified_model(run_dir) + + +def test_training_records_predictions_for_every_model(trained: dict) -> None: # type: ignore[type-arg] + preds = trained["out"]["predictions"] + assert set(preds["split"]) == {"validation", "test"} + assert {"lightgbm/full", "rule_phishing_shape"} <= set(preds.columns) + assert len(preds) == int(trained["split"].isin(["validation", "test"]).sum()) def test_fast_average_precision_matches_sklearn_including_ties() -> None: @@ -334,13 +494,32 @@ def test_psi_is_small_for_training_like_data_and_large_for_shifted_data() -> Non def test_drift_report_needs_enough_rows(tmp_path: Path) -> None: card = { "run_id": "r", + "threshold": 0.5, "feature_columns": ["x"], "reference_bins": {"x": reference_bins([0.0, 1.0] * 50)}, } log = tmp_path / "scores.jsonl" assert drift_report(card, log)["status"] == "insufficient_data" for i in range(40): - log_score({"run_id": "r", "features": {"x": 5.0 + i}}, log) + log_score( + { + "run_id": "r", + "status": "scored", + "score": i / 40, + "latency_ms": 10 + i, + "features": {"x": 5.0 + i}, + }, + log, + ) + log_score({"run_id": "r", "status": "incomplete", "latency_ms": 3}, log) + log_score({"run_id": "r", "status": "scored", "score": 0.1, "features": {"y": 1.0}}, log) + with log.open("a") as fh: + fh.write("{cut off\n") report = drift_report(card, log) assert report["status"] == "ok" assert report["shifted"] == ["x"] + assert report["status_counts"] == {"scored": 41, "incomplete": 1} + assert report["schema_mismatches"] == 1 # a vector for other features is not compared + assert report["unreadable_lines"] == 1 + assert report["share_above_threshold"] == 0.5 + assert report["latency_ms"] is not None From 9e1bf6e23446d9bce7dd318b13a48043a1ab9dc7 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Sun, 1 Nov 2026 19:42:10 +0300 Subject: [PATCH 06/92] docs(ml): Phase 11.1 generalization audit; model is research-only - ML_GENERALIZATION_AUDIT.md: reproduction, label provenance (benign = about 60 prominent accounts; phishing expanded from 101 reports), sample accounting, holdout timeline (the test split was viewed before the gate, selection metric and hub rule were revised: a development benchmark), leakage, temporal boundary (post-inclusion), shortcut experiments, cluster-bootstrap uncertainty (FPR 7/43 from 12 senders, 0.043 to 0.364), base-rate arithmetic (precision 0.057 at 1%), errors, wallet-history design, calibration, security fixes, budget, next dataset and experiment. - ML_AUDIT_TABLES.md generated by audit b90137901e25 (deterministic: a second run gave the same id). - docs/ml/baseline-phase11.json: frozen baseline with dataset, config and model hashes, versions, metrics and reproductions; LightGBM text form scores identical to the pickle on the real rows. - ML.md, README, CHANGELOG, SECURITY: status and corrections; Phase 11 history kept and marked. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 ++ ML.md | 77 +++++--- ML_AUDIT_TABLES.md | 159 +++++++++++++++++ ML_GENERALIZATION_AUDIT.md | 312 +++++++++++++++++++++++++++++++++ README.md | 2 +- SECURITY.md | 13 +- docs/ml/baseline-phase11.json | 318 ++++++++++++++++++++++++++++++++++ 7 files changed, 866 insertions(+), 27 deletions(-) create mode 100644 ML_AUDIT_TABLES.md create mode 100644 ML_GENERALIZATION_AUDIT.md create mode 100644 docs/ml/baseline-phase11.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 0896a74..20f6f95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,18 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m hash-pinned model registry; shadow scoring API and CLI; PSI drift monitoring (`e9b49f1`). Results in ML_EVALUATION.md, data card and decision log in ML.md. +### ML generalization audit (Phase 11.1) +- Baseline reproduced exactly (metrics, model bytes) and frozen in + `docs/ml/baseline-phase11.json`; its test split reclassified as a development benchmark. + The model is now research-only: the API refuses to score with it (`c11e5fb`). +- Fixed: scoring skipped chain verification; a missing receipt was scored; the request + budget could be lost on a crash or overspent by concurrent collectors; the registry + trusted a path from its JSON file; intervals resampled rows despite account clustering. +- Added: `cryptoguard ml audit` (recomputed metrics, cluster intervals, prevalence arithmetic, + shortcut experiments, hub-policy sensitivity, calibration, errors), approval levels, + LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). + Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. + ## 0.1.0 — 2026-10-28 (first release candidate, not independently audited) ### Detection and monitoring diff --git a/ML.md b/ML.md index 599daf7..afb67ed 100644 --- a/ML.md +++ b/ML.md @@ -1,13 +1,23 @@ -# Machine learning (experimental, shadow mode only) +# Machine learning (experimental, research-only) + +> **Status after the Phase 11.1 audit ([ML_GENERALIZATION_AUDIT.md](ML_GENERALIZATION_AUDIT.md)): +> research-only; independent data required.** The Phase 11 test split was examined while the +> method was still changing, so it is a *development benchmark*, not an untouched holdout. Its +> 43 benign rows come from 12 senders (false-positive rate 7/43, cluster-bootstrap interval +> 0.04 to 0.36), and the benign class is about 60 prominent accounts, not ordinary users. The +> model is registered `research_only`: the API refuses to score with it; explicit CLI scoring +> remains for research. The sections below describe Phase 11 as it was; corrections are +> marked. CryptoGuard has an optional ML subsystem (`src/cryptoguard/ml/`, the `ml` extra). It classifies an Ethereum **transaction** as part of a phishing operation or not, using -features that were knowable when the transaction executed. It is trained and evaluated on -independently labelled public data, compared with trivial and rule baselines on identical -held-out rows, and integrated **only in shadow mode**: scores are returned for review and -monitored for drift, and they never create, change or resolve findings. +features that were knowable when the transaction executed (**post-inclusion**: the receipt is +an input). It is trained and evaluated on independently labelled public data and compared +with trivial and rule baselines on identical held-out rows. Scores never create, change or +resolve findings. -Generated results: [ML_EVALUATION.md](ML_EVALUATION.md). This page is the data card, +Generated results: [ML_EVALUATION.md](ML_EVALUATION.md) (Phase 11, historical) and +[ML_AUDIT_TABLES.md](ML_AUDIT_TABLES.md) (Phase 11.1 audit). This page is the data card, method and decision log. ## Data card @@ -103,6 +113,11 @@ baseline's test AP. Only a gated run can be promoted (`ml promote`). Full table, intervals, per-family recall, importance and errors: [ML_EVALUATION.md](ML_EVALUATION.md). +> **Correction (Phase 11.1):** the intervals above resampled rows as independent. Rows cluster +> by account (12 benign senders on test); resampling account clusters gives a false-positive +> interval of 0.043 to 0.364 and an AP interval of 0.994 to 1.000 ([ML_AUDIT_TABLES.md](ML_AUDIT_TABLES.md)). +> "Held-out" below means the development benchmark described in the audit. + **What this does and does not show.** On held-out, later, account-disjoint transactions the learned models rank phishing-operation transactions far better than any rule. The result holds without the identity-like features. The model relies mostly on transaction *shape*: @@ -116,7 +131,8 @@ wallet history that this dataset lacks, so they could not be run on it. - The false-positive rate is about 16% on prominent accounts' transactions, measured on only 43 benign rows. On ordinary traffic, where phishing is far rarer than the 75% of this - test set, most alerts would be false. This is why the model stays in shadow mode. + test set, most alerts would be false. This is why the model was kept to shadow mode (and, + after the Phase 11.1 audit, to research only). - **Plain token transfers are the blind spot.** 5 of the 7 test false positives and 2 of the 3 missed phishing transactions (address poisoning) have the same shape: one `transfer()` call, one Transfer log, no ETH value. By transaction shape alone, a poisoning transfer and @@ -127,32 +143,41 @@ wallet history that this dataset lacks, so they could not be run on it. zero nibbles), a property the model learned from phishing contracts. - The third miss is a fake-token transfer whose receipt holds no logs at all. -## Shadow mode +## Commands and shadow scoring ```powershell uv sync --extra ml uv run cryptoguard ml fetch-sources # labels (hash-verified) uv run cryptoguard ml sample # deterministic sample -uv run cryptoguard ml collect --rpc-url # budgeted, resumable +uv run cryptoguard ml collect --rpc-url # reserved, capped, resumable uv run cryptoguard ml build # validated table, splits, manifest -uv run cryptoguard ml train # ledger, model card, ML_EVALUATION.md -uv run cryptoguard ml promote data/ml/runs/ # refused unless the gate passed -uv run cryptoguard ml score --rpc-url # one shadow score (4 RPC calls) -uv run cryptoguard ml monitor # feature drift (PSI) of scored txs +uv run cryptoguard ml train # ledger, model card, predictions +uv run cryptoguard ml audit data/ml/runs/ # offline audit, ML_AUDIT_TABLES.md +uv run cryptoguard ml promote data/ml/runs/ # research_only (gate must pass) +uv run cryptoguard ml score --rpc-url # explicit research score (5 RPC calls) +uv run cryptoguard ml monitor # drift of logged scores ``` -With `CRYPTOGUARD_ML_SHADOW=shadow`, the API offers `POST /api/v1/ml/transactions/score` -(`{"tx_hash"}`; the RPC endpoint is the operator's, never the request's) and -`GET /api/v1/ml/status` (promoted run, gate, drift). With the default `off` both answer 409 -`feature_disabled`; without the extra or a promoted model, 503 `ml_unavailable`. Scores are -logged to `data/ml/shadow_scores.jsonl` for drift monitoring and are never stored as -findings. The promoted model is a pickle; it is loaded only from the local registry and only -if its SHA-256 matches its model card. +Approval levels: `research_only` (the gate passed on a development benchmark) and +`shadow_approved` (additionally passed an untouched holdout evaluated once, recorded in the +model card; `--approval shadow_approved` refuses otherwise). With +`CRYPTOGUARD_ML_SHADOW=shadow`, `POST /api/v1/ml/transactions/score` (`{"tx_hash"}` only) +scores with a `shadow_approved` model and answers 503 `ml_unavailable` for a research-only +one; `GET /api/v1/ml/status` shows the registered run, its approval, gate and drift. With the +default `off` both answer 409 `feature_disabled`. Scoring verifies the provider's chain +(mainnet only), refuses a mined transaction without a receipt (`incomplete`), runs one at a +time with a 30 s limit, and returns an **uncalibrated ranking score**, never a probability. +Scores are logged to `data/ml/shadow_scores.jsonl` for drift monitoring and are never stored +as findings. Models load only from the local runs directory, by validated run id, after hash, +schema, size and library-version checks; LightGBM models are stored as LightGBM text (no +pickle) since Phase 11.1. A full training run (10 model configurations after a 36-candidate search, bootstrap intervals, permutation importance) took 34–44 s on a 4-core CPU with a peak of 197 MiB (`scripts/peak_memory.py ml train`). It is deterministic: a repeated run gave identical -metrics for every model and a byte-identical model file. No GPU and no graph neural +metrics for every model and a byte-identical model file (same machine and library versions; +byte identity across platforms or versions is not claimed, see the audit). Under heavy load +from other workloads, the same computation once took 700 s of wall time. No GPU and no graph neural network: gradient boosting on tabular features already ranks near the ceiling here, and the data has no graph beyond each transaction's own parties. @@ -171,6 +196,11 @@ and is kept in the run ledger. 4. **Selection metric.** AP saturates near 1.0 here, so model selection and permutation importance use log loss. +**Correction (Phase 11.1):** "made before the final run" is true but incomplete. Revisions 2 to +4 were made *after* runs whose test results had been displayed (a partial-data dry run and a +full-data run), so the test split is a previously examined development benchmark. Timeline: +ML_GENERALIZATION_AUDIT.md §4. + ## Limitations - One labelled source, with a benign class of prominent accounts; precision on real traffic @@ -178,5 +208,8 @@ and is kept in the run ledger. - Small evaluation splits after the window and purge; intervals are wide. - Receipt-based features describe executed transactions; warning before signing would need transaction simulation (not implemented). -- Live scoring costs 4 RPC requests per transaction and needs historical state. +- Live scoring costs 5 RPC requests per transaction (chain check, transaction, receipt, nonce, + code) and needs historical state. +- No untouched holdout; the benign class is about 60 prominent accounts. Next dataset and + experiment: ML_GENERALIZATION_AUDIT.md §16 to 17. - Not independently reviewed. diff --git a/ML_AUDIT_TABLES.md b/ML_AUDIT_TABLES.md new file mode 100644 index 0000000..ef73c19 --- /dev/null +++ b/ML_AUDIT_TABLES.md @@ -0,0 +1,159 @@ +# ML audit tables (generated) + +Generated by `cryptoguard ml audit`; do not edit by hand. Audit `b90137901e25` of run `20261029T055343Z-41bb2f56` (model sha256 `57e1f2d719749115…`), table sha256 `afcd1e41d9d31238…`, splits sha256 `d4837df6d9cdafe4…`, seed 20261101, 44.7 s. Offline: no RPC calls. Narrative and caveats: ML_GENERALIZATION_AUDIT.md. + +**The test split below is a development benchmark** (examined while the method was still changing), not an untouched holdout. + +## 1. Recomputed baseline metrics + +Recomputed from the stored model with this module's own implementations and compared with the values recorded at training time. + +| Quantity | Validation | Test (dev benchmark) | Matches recorded | +| --- | --- | --- | --- | +| AP | 0.997 | 0.999 | True | +| ROC-AUC | 0.991 | 0.995 | True | +| Recall | 1.000 | 0.977 | True | +| False-positive rate | 0.062 | 0.163 | True | +| Precision | 0.983 | 0.947 | True | +| Balanced accuracy | 0.969 | 0.907 | True | +| Brier score | 0.019 | 0.024 | True | +| Log loss | 0.077 | 0.087 | — | +| Confusion (tp/fp/fn/tn) | — | 126/7/3/36 | True | +| Prevalence (phishing share) | 0.784 | 0.750 | — | +| AP above prevalence | 0.213 | 0.249 | — | + +Threshold 0.2516; reproduced from validation scores alone: **True**. + +## 2. Uncertainty on the development test split + +Test rows: 129 phishing from 93 distinct senders, 43 benign from **12 distinct senders**. Account clusters (union-find over sender, target, spender, recipient): 76 (65 with phishing rows, 11 with benign rows). + +| Quantity | Estimate | Wilson 95% (rows independent) | Cluster bootstrap 95% | +| --- | --- | --- | --- | +| Recall | 126/129 = 0.977 | [0.934, 0.992] | [0.933, 1.000] | +| False-positive rate | 7/43 = 0.163 | [0.081, 0.300] | [0.043, 0.364] | +| Precision | 126/133 = 0.947 | [0.895, 0.974] | — | +| AP | 0.999 | — | [0.994, 1.000] | + +Bootstrap: 2000 resamples containing both classes. + +Benign rows needed to bound the false-positive rate below a target with 95% confidence when **zero** false positives are observed: + +| Target FPR | Benign rows needed | +| --- | --- | +| 5.0% | 59 | +| 1.0% | 299 | +| 0.1% | 2,995 | + +## 3. Low-prevalence scenarios (arithmetic, not measurement) + +Using the development-test recall 0.977 and false-positive rate 0.163 (Wilson range [0.081, 0.300]), per 10,000 transactions: + +| Assumed phishing prevalence | True alerts | False alerts (range) | Alerts | Precision (range) | +| --- | --- | --- | --- | --- | +| 0.01% | 1.0 | 1628 (812 to 2997) | 1629 | 0.001 (0.000 to 0.001) | +| 0.10% | 9.8 | 1626 (811 to 2994) | 1636 | 0.006 (0.003 to 0.012) | +| 1.00% | 97.7 | 1612 (804 to 2967) | 1709 | 0.057 (0.032 to 0.108) | +| 5.00% | 488.4 | 1547 (771 to 2847) | 2035 | 0.240 (0.146 to 0.388) | + +## 4. Shortcut experiments + +Fixed hyperparameters (LightGBM: the Phase 11 selection; logistic regression: C=1), threshold from validation, no tuning per feature set. Test = development benchmark. + +| Features | n | Model | Val AP | Test AP | Test ROC-AUC | Test recall | Test FPR | +| --- | --- | --- | --- | --- | --- | --- | --- | +| full | 37 | lightgbm | 0.997 | 0.999 | 0.995 | 0.977 | 0.163 | +| full | 37 | logistic_regression | 0.993 | 0.978 | 0.951 | 0.891 | 0.047 | +| selector_only | 10 | lightgbm | 0.960 | 0.931 | 0.870 | 0.822 | 0.163 | +| selector_only | 10 | logistic_regression | 0.960 | 0.931 | 0.870 | 0.822 | 0.163 | +| tx_type_only | 4 | lightgbm | 0.984 | 0.947 | 0.875 | 0.977 | 0.651 | +| tx_type_only | 4 | logistic_regression | 0.965 | 0.898 | 0.758 | 0.946 | 0.698 | +| interaction_only | 5 | lightgbm | 0.941 | 0.823 | 0.575 | 0.891 | 0.884 | +| interaction_only | 5 | logistic_regression | 0.962 | 0.869 | 0.670 | 0.860 | 0.791 | +| history_only | 1 | lightgbm | 0.729 | 0.777 | 0.458 | 0.837 | 0.674 | +| history_only | 1 | logistic_regression | 0.990 | 0.925 | 0.806 | 0.837 | 0.488 | +| similarity_only | 3 | lightgbm | 0.890 | 0.841 | 0.649 | 0.977 | 1.000 | +| similarity_only | 3 | logistic_regression | 0.896 | 0.833 | 0.631 | 1.000 | 1.000 | +| log_structure_only | 11 | lightgbm | 0.958 | 0.936 | 0.873 | 0.899 | 0.279 | +| log_structure_only | 11 | logistic_regression | 0.886 | 0.834 | 0.669 | 0.845 | 0.512 | +| all_minus_selector | 27 | lightgbm | 0.999 | 0.997 | 0.991 | 0.969 | 0.093 | +| all_minus_selector | 27 | logistic_regression | 0.931 | 0.944 | 0.873 | 0.829 | 0.209 | +| all_minus_history | 36 | lightgbm | 0.989 | 0.998 | 0.993 | 0.977 | 0.209 | +| all_minus_history | 36 | logistic_regression | 0.985 | 0.966 | 0.924 | 0.977 | 0.186 | +| all_minus_identity | 34 | lightgbm | 0.990 | 0.991 | 0.976 | 0.977 | 0.209 | +| all_minus_identity | 34 | logistic_regression | 0.975 | 0.961 | 0.913 | 0.984 | 0.233 | +| all_minus_era_proxies | 34 | lightgbm | 0.995 | 0.997 | 0.991 | 0.977 | 0.163 | +| all_minus_era_proxies | 34 | logistic_regression | 0.994 | 0.978 | 0.951 | 0.907 | 0.047 | +| all_minus_shortcuts | 21 | lightgbm | 0.996 | 0.988 | 0.965 | 0.829 | 0.070 | +| all_minus_shortcuts | 21 | logistic_regression | 0.915 | 0.884 | 0.779 | 0.977 | 0.558 | + +## 5. Sensitivity to the hub policy (descriptive; the split is not chosen by this) + +| Policy | Train b/p | Validation b/p | Test b/p | Test AP | Test ROC-AUC | Test FPR | +| --- | --- | --- | --- | --- | --- | --- | +| registry (used) | 190/851 | 32/116 | 43/129 | 0.999 | 0.995 | 0.163 | +| degree rule (replaced) | 190/851 | 14/117 | 37/128 | 0.999 | 0.995 | 0.162 | +| no exemptions | 190/851 | 13/61 | 26/54 | 1.000 | 0.999 | 0.000 | + +## 6. Identical feature vectors across splits + +| Split | Rows | Same vector in train | Same vector and label in train | +| --- | --- | --- | --- | +| validation | 148 | 0 | 0 | +| test | 172 | 0 | 0 | + +## 7. Calibration (descriptive) + +Training data were 82% phishing. + +| Score bin | Val rows | Val mean score | Val phishing share | Test rows | Test mean score | Test phishing share | +| --- | --- | --- | --- | --- | --- | --- | +| 0.0 to 0.2 | 30 | 0.001 | 0.000 | 38 | 0.011 | 0.079 | +| 0.2 to 0.4 | 2 | 0.302 | 1.000 | 6 | 0.296 | 0.000 | +| 0.4 to 0.6 | 0 | — | — | 1 | 0.450 | 0.000 | +| 0.6 to 0.8 | 0 | — | — | 1 | 0.793 | 0.000 | +| 0.8 to 1.0 | 116 | 0.993 | 0.983 | 126 | 0.982 | 1.000 | + +## 8. Class profile inside the study window (train, validation and test rows) + +| Property | Benign | Phishing | +| --- | --- | --- | +| Rows | 265 | 1.1e+03 | +| EIP-1559 fee fields present | 0.955 | 0.667 | +| Zero ETH value | 0.774 | 0.688 | +| Target is a contract | 0.864 | 0.999 | +| Target has 4+ vanity zero nibbles | 0.0415 | 0.178 | +| Reverted | 0.034 | 0 | +| Median sender prior transactions | 306 | 74 | +| Median logs | 2 | 1 | +| Function family `fn_approve` | 25 | 0 | +| Function family `fn_multicall` | 4 | 0 | +| Function family `fn_other` | 201 | 422 | +| Function family `fn_seaport` | 1 | 0 | +| Function family `fn_set_approval_for_all` | 4 | 0 | +| Function family `fn_transfer` | 16 | 203 | +| Function family `fn_transfer_from` | 1 | 445 | +| Function family `fn_upgrade` | 0 | 25 | +| Function family `none` | 13 | 1 | + +## 9. Errors on the development test split + +**False positives** (7): + +| Transaction | Subtype | Score | transfer() | transferFrom() | Other fn | Logs | Transfers | Vanity nibbles | Zero ETH | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `0x86d61c0e26568263…` | benign_kol | 0.255 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | +| `0xad114373e700c534…` | benign_kol | 0.303 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | +| `0x3f2f560a11d0e025…` | benign_kol | 0.307 | 0 | 0 | 1 | 10 | 6 | 10 | 1 | +| `0xd4d346531ca53476…` | benign_kol | 0.311 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | +| `0x906693a0700648f8…` | benign_kol | 0.365 | 0 | 0 | 1 | 2 | 1 | 14 | 0 | +| `0x23dc9650b82bd842…` | benign_kol | 0.450 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | +| `0x1a03582da5059429…` | benign_kol | 0.793 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | + +**False negatives** (3): + +| Transaction | Subtype | Score | transfer() | transferFrom() | Other fn | Logs | Transfers | Vanity nibbles | Zero ETH | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `0x92aee8b3fdf9ce62…` | zero_value_transfer | 0.041 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | +| `0xa8d0ac9c1f495af0…` | fake_token_transfer | 0.086 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| `0xa1d7ed71f72770f3…` | zero_value_transfer | 0.086 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | diff --git a/ML_GENERALIZATION_AUDIT.md b/ML_GENERALIZATION_AUDIT.md new file mode 100644 index 0000000..6024c4e --- /dev/null +++ b/ML_GENERALIZATION_AUDIT.md @@ -0,0 +1,312 @@ +# ML generalization audit (Phase 11.1) + +Audit of the experimental phishing-transaction classifier from Phase 11 (`ML.md`). Offline +only: no Ethereum RPC request was made in this phase. Every number below comes from +`ML_AUDIT_TABLES.md` (generated by `cryptoguard ml audit`), the frozen baseline record +`docs/ml/baseline-phase11.json`, or a command named next to it. Not an independent review. + +**Decision: research-only, and independent data required** (outcomes B and D of the +assignment). The model and its evaluation are technically valid and reproducible, but its +benchmark cannot establish generalization to CryptoGuard's use case, and its measured false- +positive rate makes it unusable for warnings at realistic base rates. The API no longer +scores with it; production findings were never affected. + +## 1. Objective + +Establish what the Phase 11 result (test AP 0.999, recall 0.977, false-positive rate 0.163) +does and does not show, fix defects that affect correctness or safety, and define the data +needed for a defensible next experiment. + +## 2. Baseline reproduction + +| Item | Value | +|---|---| +| Run | `20261029T055343Z-41bb2f56`, code `e9b49f1` | +| Feature table sha256 | `afcd1e41d9d31238…` (rebuilt from local data: identical) | +| Splits sha256 | `d4837df6d9cdafe4…` (rebuilt: identical) | +| Model sha256 | `57e1f2d719749115…` (retrained at `91036ba`: byte-identical) | +| Libraries | Python 3.12.15, scikit-learn 1.9.1, LightGBM 4.7.0, pandas 3.1.0, NumPy 2.5.4 | + +`cryptoguard ml build` followed by `cryptoguard ml train` reproduced all ten model +configurations' validation and test metrics exactly, and the same model file. The audit then +recomputed the selected model's metrics from the stored artifact with independent +implementations (rank-based AUC, its own confusion matrix, Wilson intervals): every value +matched the recorded one, and the decision threshold (0.2516) is reproduced from validation +scores alone. + +**Scope of byte-level reproducibility:** verified only on one machine (Windows 11, the versions +above, 4 cores). LightGBM's `deterministic=True` makes results repeatable for the same data, +parameters, thread count and library build; it does not promise identical trees or bytes across +LightGBM versions, operating systems or CPU architectures, and joblib pickles also embed +library internals. Metric-level reproducibility is the claim; byte-level is a same-environment +observation. The registry now refuses a model whose training recorded a different major.minor +LightGBM or scikit-learn version. + +**Defect found here (P2):** the dataset manifest's hash also covered the cumulative RPC request +count, so it changed without the data changing. Runs are now keyed on the table and split +hashes (`ml/cli.py`). + +## 3. Dataset construction and label provenance + +From the PTXPhish paper (Chen et al., NDSS 2025): + +- **Phishing** transactions started from 101 public reports (social media, security blogs) + collected over three months, then were expanded by sampling up to 50 more transactions per + scammer address. Two security experts reviewed each and kept consensus labels; no + agreement statistic is reported. Labels are hindsight-based (after the reports). +- **Benign** transactions come from about 60 accounts: the top 50 DeBank "Key Opinion + Leaders" and the top 10 DeFi protocol developers, with up to 200 transactions each. +- Many "phishing" rows are the **attacker's** transactions (for ice phishing, the + `transferFrom` that drains the victim), not victim-signed ones. + +The target is therefore "is this transaction part of a known phishing operation, as opposed to +a prominent account's activity" — not "is the payment I am about to make going to a scammer". + +Sample accounting (distinct quantities, not to be conflated): + +| Stage | Count | +|---|---| +| Labelled hashes in PTXPhish | 18,555 (4,998 phishing, 13,557 benign) | +| Deterministic sample drawn | 2,701 | +| Collected with chain data | 2,527 (174 not reached under the request cap) | +| Valid feature rows | 2,527 | +| Outside the study window (all benign) | 791 | +| Purged: shared an account with an earlier split | 199 validation, 176 test | +| Train / validation / test | 1,041 / 148 / 172 | + +Parsing re-checked: one sheet; 13 subtype columns plus "Source" columns; all 18,555 values +are valid 32-byte hashes, unique, and in exactly one category. A hash appearing in two +categories (in any letter case) is rejected (`test_a_hash_in_two_categories_is_refused`). +Poison-Hunter and Forta remain auxiliary (data card only): address-level labels, a +popularity-selected benign class, a column-shifted sample file, and Etherscan-derived labels +shared between them. Adding them would add rows, not independent evidence. + +## 4. Holdout integrity + +From the run ledger and git history (times UTC): + +| Time | Event | Test split viewed | +|---|---|---| +| 29 Oct 05:07 | Dry run on partial data, uncommitted code; gate failed | yes | +| 05:13 | `aee2bf4`: promotion gate redesigned, selection switched to log loss | — | +| 05:14 | Full-data run with the degree-based hub rule | yes | +| 05:48 | `e9b49f1`: hub rule replaced (after a synthetic leakage test) | — | +| 05:53 | Final run `055343Z` | yes | + +The study window was fixed before any training, from class block ranges (no outcomes). The +promotion criteria and model-selection metric changed after a run whose test results had been +displayed; the hub rule changed after a second one. The feature set did not change after any +test result was seen (the dry run used uncommitted code, so this rests on the session record, +not on git). The gate itself also uses the test split. + +**Conclusion:** the test split is a **previously examined development benchmark**, not an +untouched holdout. No untouched holdout exists among the collected data. The 2,527 rows cannot +be reshuffled into one, and the uncollected PTXPhish hashes would not be one either: they come +from the same ~60 benign accounts and the same expanded scammer addresses, so after the account +purge few would remain, and those would share the dataset's construction. + +## 5. Entity leakage + +The account purge holds: on the real splits, no non-hub account appears in two splits (checked +directly), and synthetic scenarios cover a shared attacker signer, a shared lookalike +recipient, a public token, mixed-case addresses and a high-degree drainer contract +(`tests/unit/test_ml_pipeline.py`). + +| Hub policy | Validation benign/phishing | Test benign/phishing | Test AP | Test FPR | +|---|---|---|---|---| +| Registry (used) | 32/116 | 43/129 | 0.999 | 0.163 | +| Degree rule (replaced) | 14/117 | 37/128 | 0.999 | 0.162 | +| No exemptions | 13/61 | 26/54 | 1.000 | 0.000 | + +The registry (15 public contracts: major tokens, routers, marketplaces, Permit2) was compiled +after seeing a diagnostic list of bridging accounts that showed label counts. Every entry is a +well-known contract identifiable by name, and exempting fewer accounts only removes rows. The +policy does not move the headline metrics; it changes how many rows are left to measure on. + +Residual dependence: the purge separates splits, not rows within a split. The 43 benign test +rows come from **12 senders** (11 account clusters); 129 phishing rows from 93 senders. No +feature vector in validation or test is identical to one in training. + +## 6. Temporal validity and observation boundary + +Feature lineage: every feature comes from the transaction, its receipt, or state read at +block − 1 (sender nonce, target code). Block number and time are never features. Missing +historical state fails the collection (an error, retried), never a zero. A receipt missing +for a mined transaction used to be scored as "no logs, failed"; it is now `incomplete` and +never scored (fixed, tested). + +The boundary is **post-inclusion**: the receipt is part of the input. The model cannot be used +before signing without transaction simulation. Same-block effects: the nonce and code are read +at the previous block, so a contract deployed earlier in the same block reads as "no code" (a +conservative choice, documented). + +## 7. Selection bias and shortcuts + +Inside the study window (`ML_AUDIT_TABLES.md` §8): + +| Property | Benign | Phishing | +|---|---|---| +| `transferFrom` calls | 1 of 265 | 445 of 1,106 | +| `approve` calls | 25 | 0 | +| EIP-1559 fee fields present | 95.5% | 66.7% | +| Median prior transactions of the sender | 306 | 74 | +| Target has 4+ vanity zero nibbles | 4.2% | 17.8% | + +Fixed-hyperparameter experiments (no per-subset tuning), test = development benchmark: + +| Features | Test ROC-AUC (LightGBM) | Test ROC-AUC (logistic) | +|---|---|---| +| All 37 | 0.995 | 0.951 | +| Function family only (10) | 0.870 | 0.870 | +| Transaction type only (4: fee format, creation, zero value, calldata size) | 0.875 | 0.758 | +| Sender history only (1) | 0.458 | 0.806 | +| All except shortcut groups (21) | 0.965 | 0.779 | + +How a transaction was *sent* (fee format, function family, sender history) separates the +classes almost as well as anything else: attacker tooling versus prominent humans. Removing +those groups still leaves LightGBM at ROC-AUC 0.965 from log structure and contract +properties, so not everything is a shortcut. None of this shows that the model would recognise +phishing against ordinary users, who are absent from the benign class. + +## 8. Statistical uncertainty + +| Quantity | Estimate | Wilson 95% (rows independent) | Cluster bootstrap 95% | +|---|---|---|---| +| Recall | 126/129 = 0.977 | 0.934 to 0.992 | 0.933 to 1.000 | +| False-positive rate | 7/43 = 0.163 | 0.081 to 0.300 | 0.043 to 0.364 | +| Precision | 126/133 = 0.947 | 0.895 to 0.974 | — | +| AP | 0.999 | — | 0.994 to 1.000 | + +The cluster bootstrap resamples account components, the honest unit here. Training-time +intervals now do the same (`train.bootstrap_ci(..., clusters=...)`); Phase 11's row bootstrap +understated the uncertainty. AP must be read against the test prevalence of 0.75: AP above +prevalence is 0.249. To bound the false-positive rate below 1% at 95% confidence with zero +observed false positives requires 299 independent benign rows; below 0.1%, 2,995. With 43 +rows from 12 senders, one more false positive moves the rate by 2.3 points. + +## 9. Real-world base rates (arithmetic, not measurement) + +Per 10,000 transactions, using recall 0.977 and false-positive rate 0.163: + +| Assumed phishing prevalence | True alerts | False alerts | Precision | +|---|---|---|---| +| 0.01% | 1.0 | 1,628 | 0.001 | +| 0.1% | 9.8 | 1,626 | 0.006 | +| 1% | 97.7 | 1,612 | 0.057 | +| 5% | 488 | 1,547 | 0.240 | + +Even at 5% prevalence, three alerts in four would be false. The model is not suitable for +automated security warnings. + +## 10. Errors (development benchmark) + +Confirmed from the stored model: 7 false positives and 3 false negatives. Five of the seven +false positives and two of the three misses are single `transfer()` calls with one Transfer +log and no ETH value; two false positives call vanity-mined contracts (10 and 14 zero nibbles); +one miss is a fake-token transfer whose receipt has no logs. These are hypotheses for the next +experiment, not tuning targets: nothing was changed in response to them. + +## 11. Wallet-history features + +`ml/history.py` implements point-in-time features for a payment from the paying wallet's own +history: prior payments and interactions with the recipient, time since first and last +interaction, distinct prior recipients, share of recent payments to new recipients, whether the +recipient imitates a counterparty the wallet chose (reusing the poisoning detector's +`is_lookalike`), unsolicited events with the recipient, and observed lookalike plantings +(including spoofed outgoing transfers). Data contract: explicit coverage, two boundaries +(pre-signing, pre-execution), `None` for unknown with indicator columns in the model row, and +reverted payments counted as choices but not payments. 13 tests cover empty, partial and +missing history, reverted and unknown receipts, same-block ordering, casing, and metamorphic +properties (future events and reordering change nothing). + +**No accuracy claim:** PTXPhish has no wallet histories, CryptoGuard's replay fixtures have +histories but only 4 labelled incidents, and no RPC budget was available to fetch histories. +The infrastructure is ready for the next dataset (§16). + +## 12. Calibration + +Scores are bimodal: on validation, 30 of 32 benign rows score below 0.2 and 116 rows score +above 0.8; on test, all eight rows between 0.2 and 0.8 are benign. Training data were 82% +phishing, so even a calibrated score would describe that mix, not real traffic. With 32 benign +validation rows from 5 senders, no calibrator can be fitted reliably, and none was. The API, +the CLI and the model card now state that the score is an **uncalibrated ranking score**. + +## 13. Registry and inference security + +Defects fixed: + +- **P1: wrong chain could be scored.** The scoring route read through the provider's raw client + and skipped `verify_chain()`; it now verifies the chain and refuses anything but mainnet, + where the model was trained. +- **P1: missing receipt scored as a failed transaction** (§6). +- **P1: the API scored with a model that had no untouched-holdout evidence.** Approval levels + now separate `research_only` (gate passed on a development benchmark; CLI scoring only) from + `shadow_approved` (requires an untouched, once-evaluated holdout recorded in the model card); + the API requires the latter. +- **P2: registry trusted a path from `registry.json`.** Runs are now addressed by a validated + run id inside the runs directory; model cards are schema-checked; files over 50 MB are + refused; library versions must match. +- **P2: pickle for LightGBM.** New runs store LightGBM's text format (no pickle). On the 320 + real validation and test rows, the baseline model's text form and its pickle gave identical + scores (maximum absolute difference 0.0, `docs/ml/baseline-phase11.json`). Other model + families still use a hash-checked pickle. +- **P2: unbounded scoring.** One scoring at a time per event loop, 30 s overall timeout. + +A hash check proves a file matches its card; it does not make a card trustworthy. The trust +boundary is the local `data/ml` directory. + +## 14. Collector and request budget + +**P1: the budget could be exceeded or lost.** Phase 11 counted attempts after the fact and +stopped at a margin; a killed session lost its count (charged later by estimate), and two +collectors could each spend the full remainder. Now every HTTP attempt, retries included, +reserves one unit in a durable ledger first (`RequestLedger`, `BudgetedTransport`): exclusive +lock file, atomic replace, fail-closed on a corrupt ledger. A crash after reserving over-counts; +nothing can under-count. 11 tests with counting mock transports cover the cap, retries, a crash +mid-run, two concurrent collectors, five threads racing (this found a Windows lock bug, fixed), +a corrupt ledger, a cut-off checkpoint line (repaired and re-fetched), a corrupt middle line, a +missing receipt and duplicate records. The ledger reads 11,953 of 12,000; the authorization is +treated as exhausted. + +## 15. Monitoring + +PSI uses per-bin training shares (ties handled). The drift report now also gives scoring +outcomes, schema mismatches, unreadable lines, latency and score distribution, reads only the +last 10,000 entries, and states that unlabelled drift cannot show accuracy loss. + +## 16. Required next dataset + +To measure what CryptoGuard needs — whether an outgoing payment from an ordinary wallet goes +to a poisoned lookalike — the next dataset must have: + +- **Unit:** outgoing payments (token transfers and ETH sends) from ordinary wallets, each with + the wallet's history up to the payment. +- **Positives:** payments to address-poisoning lookalikes confirmed by an independent source + (incident reports or a labelled list), ideally several hundred across many attackers. +- **Negatives:** at least 300 payments, from at least 100 distinct ordinary wallets (not + prominent accounts), drawn at random from the same period, for a 1% false-positive bound. +- **Independence:** split by wallet and attacker infrastructure and by time; holdout frozen + before any model sees it, evaluated once. +- **Sources:** the 4 replay incidents and 9 background wallets as a seed; Poison-Hunter's + phishing addresses as candidate positives (address labels only: payments to them still need + confirming); random wallets sampled from blocks. Licensing: Poison-Hunter has no license, + so its addresses can be used locally but not redistributed. +- **Cost estimate:** the 13 recorded replay fixtures cost 443 to 1,361 requests each for a + 21,600-block (about three-day) history window on the free endpoint, with retries included. + At that rate, 100 negative wallets plus 50 positive incidents is roughly 70,000 to 200,000 + requests for three-day windows, more for longer histories: a new, explicit budget decision, + well beyond the exhausted 12,000. + +## 17. Recommended next experiment + +Wallet-history features against a simple history rule ("recipient imitates a past counterparty +and was never paid") on the dataset above, with the holdout frozen first. The single question: +does a learned model beat the rule CryptoGuard already applies, on ordinary wallets? + +## 18. Remaining limitations + +- No untouched holdout; one labelled source; a benign class of about 60 prominent accounts. +- Post-inclusion only; no simulation-based pre-signing scoring. +- Byte-identical models verified on one environment only. +- The development benchmark has 43 benign rows from 12 senders. +- The model card's gate uses the test split, so passing it is not independent evidence. diff --git a/README.md b/README.md index 9c28c6f..36e2bc6 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ evidence of common ownership ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). | Cross-wallet poisoning campaign analysis: canonical attempts, planting-side relationship evidence (shared planting transaction, verified signer, lookalike), conservative clustering with hub and transitivity guards, budgeted resumable expansion around planting signers and lookalikes, read-only API and UI section ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)) | Experimental, **off by default** (shadow mode): real cross-wallet links found, no earlier theft warning than the existing detector | | Network, structural and activity-rate analyses (graph propagation, spectral features, robust burst statistics) over stored observations, coverage-aware and point in time | Experimental, **off by default**: evaluated with no measurable gain over the existing detector; available in shadow mode only (see [DETECTION_METHODS.md](DETECTION_METHODS.md)) | | Wallet-signed transactions (incl. native-ETH payments) located by nonce search in snapshots and scans; used by the poisoning detector and the graph; degrades to explicit "unlocated" counts without archive state | Implemented | -| Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, hash-pinned model registry, drift monitoring ([ML.md](ML.md), [ML_EVALUATION.md](ML_EVALUATION.md)) | Experimental, **off by default** (shadow mode, `ml` extra): test AP 0.999 vs 0.845 for the best rule, but a 16% false-positive rate on 43 benign test rows; never creates findings | +| Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, approval-gated model registry, offline generalization audit, wallet-history feature infrastructure ([ML.md](ML.md), [ML_GENERALIZATION_AUDIT.md](ML_GENERALIZATION_AUDIT.md)) | Experimental, **research-only** (`ml` extra): AP 0.999 on a development benchmark (not an untouched holdout), false-positive rate 7/43 from 12 benign senders (cluster interval 4% to 36%); the API does not score with it; never creates findings | | Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals | Not yet | ## Quick start diff --git a/SECURITY.md b/SECURITY.md index dcbd946..a43f8c4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,10 +18,15 @@ characters and truncated, and is always labelled untrusted. Responses are JSON only (`Content-Security-Policy: default-src 'none'`, `nosniff`), and validation errors do not echo input. - **Chain verification.** `eth_chainId` must match the configured chain before any state read. -- **Experimental ML model files** are pickles, and loading a pickle runs code. The shadow - model is loaded only from the local registry and only if its SHA-256 matches the hash its - model card recorded at training time; a model file from anywhere else must never be placed - there. ML scoring is off by default and accepts only a transaction hash. +- **Experimental ML models** load only from the local runs directory, addressed by a + validated run id (no paths from the registry file or a request), after checks of the + model card's schema, the file's size and SHA-256, and the training library versions. + LightGBM models are stored in LightGBM's text format; other model families are hash-checked + pickles, and loading a pickle runs code, so a model file from anywhere else must never be + placed there. A hash proves the file matches its card, not that the card is trustworthy: + the trust boundary is the local `data/ml` directory. ML scoring is off by default, accepts + only a transaction hash, verifies the provider's chain, and needs a `shadow_approved` model + for the API (none exists: see ML_GENERALIZATION_AUDIT.md). - **Resource limits.** Request timeouts, bounded retries (with capped `Retry-After`), bounded RPC concurrency, a response-size cap, bounded `eth_getLogs` block ranges, a request-body limit (POST requires `Content-Length`), and per-client rate limiting with bounded memory. diff --git a/docs/ml/baseline-phase11.json b/docs/ml/baseline-phase11.json new file mode 100644 index 0000000..ad12a91 --- /dev/null +++ b/docs/ml/baseline-phase11.json @@ -0,0 +1,318 @@ +{ + "description": "Frozen Phase 11 baseline. Do not edit; Phase 11.1 compares against it.", + "run_id": "20261029T055343Z-41bb2f56", + "git": "e9b49f1795e45b3b4770758496f7256f67b9c46f", + "feature_set_version": "ptx-features/1", + "dataset": { + "table_sha256": "afcd1e41d9d312385b019119c0415cbd511abf404b8d6e6f1b438cafd39528af", + "splits_sha256": "d4837df6d9cdafe4e411eda1ce3fa76020656b9092416ba513ee18fd59a04183", + "chain_records_sha256": "cdf92821f87507eb5ad80c3d0cd2781d9f2f82df420358f0894425267f5725ce", + "sample_sha256": "4d11c93f95a02a2d7dfea103c4cee9f2c9a84efbb0426e2e5d71f2145c0a134f" + }, + "training_config_sha256": "10aa1aa701cb45e236e131d75adec3b0dcb887c60c7b077fdc854ff04b6a66c7", + "training_config": { + "selected": { + "name": "lightgbm", + "feature_set": "full", + "params": { + "num_leaves": 7, + "min_child_samples": 5 + }, + "threshold": 0.25162152697739393 + }, + "candidate_grid": [ + [ + "logistic_regression", + { + "C": 0.01 + } + ], + [ + "logistic_regression", + { + "C": 0.1 + } + ], + [ + "logistic_regression", + { + "C": 1.0 + } + ], + [ + "logistic_regression", + { + "C": 10.0 + } + ], + [ + "random_forest", + { + "min_samples_leaf": 1 + } + ], + [ + "random_forest", + { + "min_samples_leaf": 3 + } + ], + [ + "random_forest", + { + "min_samples_leaf": 10 + } + ], + [ + "lightgbm", + { + "num_leaves": 7, + "min_child_samples": 5 + } + ], + [ + "lightgbm", + { + "num_leaves": 7, + "min_child_samples": 20 + } + ], + [ + "lightgbm", + { + "num_leaves": 15, + "min_child_samples": 5 + } + ], + [ + "lightgbm", + { + "num_leaves": 15, + "min_child_samples": 20 + } + ] + ], + "feature_sets": { + "full": [ + "value_eth_log", + "is_zero_value", + "gas_limit_log", + "gas_price_gwei_log", + "is_typed_fee", + "input_bytes_log", + "input_is_bare_selector", + "fn_approve", + "fn_permit", + "fn_set_approval_for_all", + "fn_transfer", + "fn_transfer_from", + "fn_multicall", + "fn_seaport", + "fn_upgrade", + "fn_other", + "is_contract_creation", + "to_is_contract", + "to_code_size_log", + "to_is_delegated_eoa", + "to_vanity_zero_nibbles", + "from_vanity_zero_nibbles", + "sender_prior_txs_log", + "status_success", + "gas_used_ratio", + "n_logs", + "n_log_emitters", + "n_transfers", + "n_zero_value_transfers", + "n_transfers_not_from_sender", + "n_transfers_from_sender", + "n_transfers_to_sender", + "n_transfer_recipients", + "n_approvals", + "n_unlimited_approvals", + "n_approval_for_all_granted", + "max_party_affix_match" + ], + "no_identity": [ + "value_eth_log", + "is_zero_value", + "gas_limit_log", + "gas_price_gwei_log", + "is_typed_fee", + "input_bytes_log", + "input_is_bare_selector", + "fn_approve", + "fn_permit", + "fn_set_approval_for_all", + "fn_transfer", + "fn_transfer_from", + "fn_multicall", + "fn_seaport", + "fn_upgrade", + "fn_other", + "is_contract_creation", + "to_is_contract", + "to_code_size_log", + "to_is_delegated_eoa", + "status_success", + "gas_used_ratio", + "n_logs", + "n_log_emitters", + "n_transfers", + "n_zero_value_transfers", + "n_transfers_not_from_sender", + "n_transfers_from_sender", + "n_transfers_to_sender", + "n_transfer_recipients", + "n_approvals", + "n_unlimited_approvals", + "n_approval_for_all_granted", + "max_party_affix_match" + ] + }, + "seed": 20261029, + "split_plan": { + "train": 0.6, + "validation": 0.2 + }, + "features": [ + "value_eth_log", + "is_zero_value", + "gas_limit_log", + "gas_price_gwei_log", + "is_typed_fee", + "input_bytes_log", + "input_is_bare_selector", + "fn_approve", + "fn_permit", + "fn_set_approval_for_all", + "fn_transfer", + "fn_transfer_from", + "fn_multicall", + "fn_seaport", + "fn_upgrade", + "fn_other", + "is_contract_creation", + "to_is_contract", + "to_code_size_log", + "to_is_delegated_eoa", + "to_vanity_zero_nibbles", + "from_vanity_zero_nibbles", + "sender_prior_txs_log", + "status_success", + "gas_used_ratio", + "n_logs", + "n_log_emitters", + "n_transfers", + "n_zero_value_transfers", + "n_transfers_not_from_sender", + "n_transfers_from_sender", + "n_transfers_to_sender", + "n_transfer_recipients", + "n_approvals", + "n_unlimited_approvals", + "n_approval_for_all_granted", + "max_party_affix_match" + ] + }, + "model": { + "sha256": "57e1f2d719749115c73c0aab85679b5ca984dfecf0f55f2b392ba00e9296393c", + "serialization": "joblib (pickle)", + "threshold": 0.25162152697739393, + "lightgbm_text_max_abs_score_difference": 0.0 + }, + "versions": { + "python": "3.12.15", + "cryptoguard": "0.1.0", + "numpy": "2.5.4", + "pandas": "3.1.0", + "scikit-learn": "1.9.1", + "lightgbm": "4.7.0", + "pandera": "0.35.0" + }, + "metrics": { + "validation": { + "rows": 148, + "positives": 116, + "prevalence": 0.7837837837837838, + "average_precision": 0.9971138383847302, + "ap_lift": 0.9866515025293773, + "roc_auc": 0.9908405172413793, + "log_loss": 0.07696393284613016, + "balanced_accuracy": 0.96875, + "brier": 0.019035173109007986, + "precision": 0.9830508474576272, + "recall": 1.0, + "f1": 0.9914529914529915, + "false_positive_rate": 0.0625, + "confusion": { + "tn": 30, + "fp": 2, + "fn": 0, + "tp": 116 + } + }, + "test": { + "rows": 172, + "positives": 129, + "prevalence": 0.75, + "average_precision": 0.9985790683722839, + "ap_lift": 0.9943162734891358, + "roc_auc": 0.9954930593113395, + "log_loss": 0.08725277560199958, + "balanced_accuracy": 0.9069767441860466, + "brier": 0.02408798918879566, + "precision": 0.9473684210526315, + "recall": 0.9767441860465116, + "f1": 0.9618320610687023, + "false_positive_rate": 0.16279069767441862, + "confusion": { + "tn": 36, + "fp": 7, + "fn": 3, + "tp": 126 + }, + "ci95": { + "average_precision": [ + 0.9959677359231381, + 1.0 + ], + "recall": [ + 0.9461434108527131, + 1.0 + ], + "false_positive_rate": [ + 0.05553030303030303, + 0.2727272727272727 + ] + }, + "recall_by_family": { + "address_poisoning": 0.9464285714285714, + "ice_phishing": 1.0, + "nft_order": 1.0, + "payable_function": 1.0 + } + } + }, + "gate": { + "best_baseline_validation_ap": 0.922521551724138, + "best_baseline_test_ap": 0.8451047947171978, + "validation_gap_closed": 0.9627488459113998, + "required_gap_reduction": 0.5, + "validation_beats_baselines": true, + "test_interval_above_best_baseline": true, + "validated_for_shadow": true + }, + "status": "test split = previously examined development benchmark (see ML_GENERALIZATION_AUDIT.md)", + "reproductions": [ + { + "run_id": "20261029T055811Z-41bb2f56", + "git": "e9b49f1795e45b3b4770758496f7256f67b9c46f+dirty", + "identical_test_metrics": true + }, + { + "run_id": "20261101T155743Z-1e842455", + "git": "91036ba02d5c0e407e54bf22c2860ef9fdb42a69", + "identical_test_metrics": true + } + ] +} From d1961e9251490b42b9407fa65749709363242b6f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 00:40:27 +0300 Subject: [PATCH 07/92] docs(ml): wallet-history dataset proposal and option A pilot results The pilot used 2,636 of its 3,000-request cap on eth.drpc.org. It found: - 0 confirmed payments to the attacker in 52 resolved Poison-Hunter rows (Wilson 95% upper bound 0.069); - about 1,500-2,500 requests per ordinary wallet-week (extrapolated from three 1-day recordings); - drpc's free plan limits eth_getLogs to under 250 blocks; - throughput of about 4 requests/s. Option B is not viable as costed. Raw pilot data stays local in the git-ignored data/ml/pilot/. Co-Authored-By: Claude Opus 5.5 --- docs/ml/proposal-next-dataset.md | 246 +++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 docs/ml/proposal-next-dataset.md diff --git a/docs/ml/proposal-next-dataset.md b/docs/ml/proposal-next-dataset.md new file mode 100644 index 0000000..8ac95df --- /dev/null +++ b/docs/ml/proposal-next-dataset.md @@ -0,0 +1,246 @@ +# Proposal: wallet-history dataset for poisoning-payment detection + +**Status: option A (pilot) approved and run on 2026-11-01; results in §11. Options B and C +are not approved.** The Phase 11 authorization (12,000 requests) is exhausted (11,953 used); +the pilot used 2,636 of its separate 3,000-request cap. Background: +ML_GENERALIZATION_AUDIT.md §16–17. + +**Pilot verdict: option B as costed here is not viable.** Cost per wallet is about twice the +§7 estimate, the free endpoint's throughput is about a third of the Phase 11 figure, and no +positive was confirmed. See §11 before deciding on B, C or stopping. + +## 1. Decision requested + +| Option | Provider | Requests (estimate) | Wall time (estimate) | What it buys | +|---|---|---|---|---| +| **A. Pilot only** | free `eth.drpc.org` | cap **3,000** | ~5 min | Measured cost per wallet and positive yield; go/no-go for B or C | +| **B. Full, free endpoint** | free `eth.drpc.org` | cap **240,000** | ~5 h | The full dataset below | +| **C. Full, keyed endpoint** | your own provider key (e.g. a free tier with ≥2,000-block log ranges) | cap **30,000** | ~40 min | The same dataset, ~8× fewer requests | + +Recommendation: **approve A now**; decide between B and C after its report. C needs you to +create a provider account and put the key in `.env` yourself: I cannot create accounts or +handle keys. + +## 2. Prediction task + +- **Unit:** one outgoing payment (ERC-20 transfer signed by the wallet, or an ETH send) from a + wallet. +- **Question:** does this payment go to an address-poisoning lookalike? +- **Observation boundary:** *pre-signing* — only events in blocks before the payment's block + (`ml/history.py`, `boundary="pre_signing"`). No receipt of the payment itself is used, so + unlike Phase 11 a result would apply *before* the user signs. +- **Features:** the wallet-history features of `ml/history.py` (prior payments to the + recipient, lookalike-of-known-counterparty, unsolicited events with the recipient, + plantings observed, recent new-recipient share), plus nothing from the payment's own + outcome. +- **Baselines (fixed in advance):** (1) CryptoGuard's existing rule — recipient imitates a + counterparty the wallet chose and was never paid; (2) "first payment to this recipient"; + (3) majority class. The question the experiment answers: **does a learned model beat + rule (1) on ordinary wallets?** If not, the rule stays and no model ships. + +## 3. Labels and sources + +| Role | Source | License | Independence from CryptoGuard | +|---|---|---|---| +| Positives (seed) | The 4 replay incidents (already recorded, 0 requests) | public reports, cited in manifests | independent (public incident reports) | +| Positive candidates | Poison-Hunter `phishing_transfers_sample.csv`: 150 planting transfers with victim, attacker address and block | none published: local use, never redistributed | labels from Etherscan and Forta | +| Positive confirmation | A candidate counts only if the **victim later paid the labelled attacker address** (on-chain fact) | — | uses the label list, **not** CryptoGuard's lookalike test | +| Negatives | Payments by randomly sampled ordinary wallets (§4) | public chain data | — | +| Contamination check | Forta and Poison-Hunter phishing lists (13,000+ addresses) | MIT / none | independent label lists | + +Two rules keep the evaluation honest: + +- **Positives are never defined by CryptoGuard's own lookalike test.** Otherwise rule (1) + would score perfectly by construction. +- **Negatives are "no evidence of phishing", not "proven benign".** No synthetic labels are + assigned. Any negative payment whose recipient appears on an independent phishing list is + removed and counted; the report states the residual contamination risk (phishing is far + rarer than 1% of random payments, so it is small but not zero). + +## 4. Sampling design (frozen before collection) + +**Negatives — ordinary wallets.** +- Period: blocks 18,000,000 to 19,300,000 (about Aug 2023 to Feb 2024), inside the + Poison-Hunter labelling period (Nov 2022 to Feb 2024) so the contamination check is + meaningful. +- Draw: seeded random blocks; from each, a random transaction's sender. +- Eligibility, fixed now: externally owned account (no code), 20 to 2,000 lifetime + transactions (excludes bots, exchanges and empty wallets), at least one outgoing payment in + its 7-day window. +- Target: **120 wallets** to reach **≥300 payments from ≥100 wallets** (the minimum for a 1% + false-positive bound, audit §8). The draw continues until eligibility is met, within the cap. + +**Positives.** +- 4 replay incidents (already recorded). +- From the 150 Poison-Hunter sample rows: each victim's outgoing payments in the 7 days after + the planting; confirmed if any payment went to the labelled attacker address. +- **Expected yield is low** (most planting attempts fail): perhaps 0 to 15 confirmed + positives. The pilot measures it. Recall will therefore be estimated on tens of incidents, + with wide intervals; the primary endpoint is the false-positive rate (§6), which is what + blocked deployment. + +**Holdout, pre-registered.** Before any collection: the seed, the eligibility rules, the +sampled wallet list (written locally) and its SHA-256 (committed) are frozen. 30% of wallets +(both classes, chosen by wallet, latest-in-time first) form the holdout. It is not opened until +the model, features, threshold and baselines are fixed, and it is evaluated **once**. The +promotion record then gets the `holdout` entry that `shadow_approved` requires. + +## 5. Stages, budgets and stop rules + +| Stage | Work | Request cap | Stop rule | +|---|---|---|---| +| 0 (offline) | Repair the column-shifted Poison-Hunter sample (verify the field mapping on rows with known structure; reject if ambiguous); freeze the sampling plan and holdout hash | 0 | If the sample cannot be repaired unambiguously, positives fall back to the 4 incidents plus manually curated public reports | +| 1 = Option A (pilot) | As run (§11): payment check for all 149 candidate rows; 1-day recordings of random wallets. The original design (10 + 10 wallets, 7-day windows) needed ~25,000 requests and was replaced before collection | 3,000 | Report: requests per wallet, eligibility rate, positive yield. Stop for your decision | +| 2 = B or C | Remaining negatives and candidates | 240,000 (B) or 30,000 (C) | Stop at the cap; report what was reached | + +All stages use the Phase 11.1 collector: every HTTP attempt, retries included, is reserved in +a locked ledger before it is sent, so the cap is hard and survives crashes (§14 of the audit). +A separate ledger is used per approved budget. + +## 6. Evaluation plan (fixed in advance) + +- **Primary endpoint:** false-positive rate on holdout negative payments at the operating + point that flags the training positives, with Wilson and wallet-cluster bootstrap intervals. +- **Secondary:** recall on holdout positives (with the caveat of small counts); precision + under assumed prevalences of 0.01% to 1% (arithmetic). +- **Comparison:** model versus rule (1) on the same holdout payments, paired by payment. +- **Success criteria, stated now:** the model is considered for `shadow_approved` only if its + holdout false-positive upper bound (95%) is below rule (1)'s point estimate **and** it + catches every positive that rule (1) catches. Otherwise the result is reported as negative + and the rule remains. +- Training stays under 2 minutes per run on CPU (a few hundred rows); one job at a time. + +## 7. Cost model and its evidence + +- The 13 recorded replay fixtures cost **443 to 1,361 requests** for a 21,600-block (~3-day) + window on the free endpoint, retries included. Most of it is `eth_getLogs` in ~100-block + chunks for both transfer directions. +- A 7-day window is 50,400 blocks: about **1,000 to 1,300 requests per wallet** on the free + endpoint, or **~110** where the provider allows ≥2,000-block log ranges. +- Positive candidates need two windows (7 days before for features, 7 days after the planting + to confirm a payment): ~2× per wallet. +- Totals: B ≈ 120 × 1,300 + 150 × 2 × 1,300 × ≈ 0.6 (early stop when a victim has no payments) + ≈ 390,000 at worst; capped at **240,000** by fetching the "after" window first and the + "before" window only for confirmed positives. C ≈ one eighth of that, capped at **30,000**. +- Throughput measured in Phase 11: ~13.7 requests/s on the free endpoint, giving the wall-time + estimates in §1. + +These are estimates from recorded fixtures, not measurements of this design: the pilot +replaces them with measured numbers before any larger budget is used. + +## 8. Storage, compute and privacy + +- Raw records stay in the git-ignored `data/ml/` (estimated 50 to 300 MB for option B); only + manifests, hashes and code are committed. Poison-Hunter-derived rows are never + redistributed. +- Compute: CPU only, peak memory expected under 500 MB. +- The sampled wallets are public addresses, but a list of "wallets studied" is still + personal-looking data: it stays local, and reports show aggregates only. + +## 9. Risks + +- **Too few positives** (likely): recall stays imprecise; the decision then rests on the + false-positive rate alone, which is the deployment blocker anyway. +- **Repair of the Poison-Hunter sample fails:** fall back as in stage 0. +- **Free-endpoint limits change:** the collector stops at errors and caps; nothing is lost. +- **Selection of "ordinary" wallets:** the eligibility rules shape the population; they are + fixed before collection and reported, not tuned. + +## 10. What I need from you + +1. Approve **option A (3,000 requests on `eth.drpc.org`)**, or not. +2. After the pilot report: choose **B**, **C** (you create the provider key), or stop. +3. Confirm the success criteria in §6 before any model is trained. + +## 11. Pilot results (option A, 2026-11-01) + +Endpoint `eth.drpc.org` (free plan). **2,636 requests used of the 3,000 cap**, retries +included, all reserved in a separate locked ledger. 364 were left unused. The plan was frozen +before the run (local `data/ml/pilot/plan.json`, SHA-256 `82ae27e0…`). Raw outputs stay in +the git-ignored `data/ml/pilot/`, and only aggregates appear here. + +### 11.1 Changes from §5 made before collection + +- **The original pilot did not fit the cap.** 10 victims plus 10 wallets with 7-day windows + needed about 25,000 requests. It was replaced by the design below, which keeps the + pilot's two measurements: cost per wallet and positive yield. +- **drpc's free plan rejects `eth_getLogs` ranges of 250 blocks or more.** 100 blocks + works. The error message claims a 10,000-block limit, which is wrong. The limit was found + with 8 probe requests. At 100 blocks, scanning one victim's 7-day window costs about 504 + requests, so the payment check uses the victim's own transactions instead: + - compare the nonce at the start and end of the window (2 requests); + - for victims who signed 1–8 transactions, locate each one by nonce bisection; + - decode each transaction (ETH send, or `transfer(attacker, amount > 0)`). +- **"Zero" and "fake" plantings forge `Transfer(victim → attacker)` logs.** A log match + would therefore confirm every such victim. Only transactions the victim signed are + counted. +- **Stage 0 repaired the Poison-Hunter sample.** Every row has 17 fields against a 15-name + header. Field types identify the mapping: [0] lookalike, [1] victim, [2] imitated address, + [13] block. In 100 rows (types "zero" and "fake") the transaction sender is a batch + operator, as expected for those attacks. 149 of 150 rows validate: 123 victims, blocks + 15.86M–17.97M. One row was rejected (no address similarity). +- 70 requests went to smoke tests and the range probes. + +### 11.2 Positive yield + +| | Rows | Victims | +|---|---|---| +| Candidate rows | 149 | 123 | +| Victim signed nothing in the 7 days after planting | 35 | — | +| Signed 1–8 transactions, all located and decoded | 17 | — | +| Signed 1–8, not reached before the phase cap | 51 | — | +| Signed 9–100 (not resolved in the pilot) | 33 | — | +| Signed more than 100 (bot- or exchange-like) | 13 | — | +| **Confirmed payment to the labelled attacker** | **0** | **0** | + +- **Confirmed: 0 of 52 resolved rows.** + - Upper bound (Wilson 95%) on the share of candidate rows that end in a payment: + **0.069**. + - Among rows where the victim was active: 0 of 17, upper bound 0.18. +- **Not covered:** + - `transferFrom`, permit and router payments; + - payments made after 7 days; + - the 97 unresolved rows, which are the more active victims. +- 90 of 123 "victims" were active. 13 rows belong to addresses that signed more than 100 + transactions in a week, so the sample's victim list includes automated accounts. +- **Consequence:** under the full design, the 149 candidate rows would yield at most about + 10 positives, and plausibly 0. The positive class cannot come from this sample alone. + +### 11.3 Cost per wallet and eligibility (random wallets, blocks 18.0M–19.3M) + +**Eligibility of 25 random draws** (a random transaction's sender): +- 14 ineligible: 5 had a nonce below 20; 9 had a nonce above 2,000, 7 of them in the + hundreds of thousands to millions (exchange or bot scale). None had code. +- 11 eligible (44%). Of those, 6 signed more than 12 transactions in the drawn day and + were not recorded in the pilot. + +**Recorded: 3 wallet-days** (`replay.record_window`, 100-block chunks). They cost **216, +224 and 351 requests**: 3, 6 and 12 transactions signed. +- A 4th recording hit a rate limit after 170 requests. +- The 3 recordings completed, but a field-name bug in the pilot script dropped their + contents afterwards. Their request counts are exact; their payment counts were not kept. + +**Extrapolation (estimate, not measured):** +- Log scanning grows linearly with the window, and locating costs a median of about 26 + requests per signed transaction (17 victims: median 57, maximum 179 per row). +- A 7-day window is therefore about **1,500–2,500 requests per ordinary wallet**. That is + about twice §7's 1,000–1,300. +- The figure is biased low, because the busier half of eligible wallets was not recorded. + +**Throughput:** 2,566 requests in 646 s, **about 4 requests/s**, with one rate-limit +failure. Phase 11 measured 13.7. + +### 11.4 What this means for the decision + +- **Option B (free endpoint, 240,000 cap).** 120 negative wallets alone would need + 180,000–300,000 requests, about 12–21 hours at 4 requests/s, and it adds few or no + positives. Not recommended. +- **Option C (keyed provider).** + - Ranges of 2,000 blocks or more cut the log part about 20×. + - Nonce bisection is unchanged. + - Per wallet-week: about 150–400 requests. 120 wallets: 20,000–50,000 requests. + - This still solves only the negatives. +- **Positives need another source:** victims with confirmed losses from public incident + reports, or a labelled loss dataset that records the actual payment. Without one, the + study can measure false positives on ordinary wallets but not recall. +- **Alternative: stop.** The existing rule stays, and the model stays research-only. From 492803065e6cdbc0950f561ec1765c2837127971 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:01:11 +0300 Subject: [PATCH 08/92] fix(ml): crash-safe request ledger locking The ledger's lock file was treated as stale after 60 s. Two processes waiting on a crashed holder could both break it, and both would then hold the lock. Changes: - use an OS file lock (msvcrt/flock), which the OS releases when the holder dies; - fsync each reservation before the atomic replace; - make threads of one process queue on a blocking in-process lock, so none starves while polling under load. New mock-only tests cover: - two processes sharing a cap; - a process killed while holding the lock; - a live holder (times out, the lock is not broken); - a zero budget; - rate limits and timeouts; - the cap reached during retries; - five async workers; - a truncated ledger file. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/collect.py | 115 ++++++++++++++----- tests/unit/test_ml_collector.py | 197 +++++++++++++++++++++++++++++++- 2 files changed, 280 insertions(+), 32 deletions(-) diff --git a/src/cryptoguard/ml/collect.py b/src/cryptoguard/ml/collect.py index 2c22217..9295ca9 100644 --- a/src/cryptoguard/ml/collect.py +++ b/src/cryptoguard/ml/collect.py @@ -24,12 +24,13 @@ import json import os import random +import sys import threading import time from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar import httpx @@ -151,12 +152,49 @@ class LedgerCorruptError(RuntimeError): """The request ledger cannot be read; collection refuses to guess (fail closed).""" +def _try_os_lock(fd: int) -> bool: + """Non-blocking exclusive lock on byte 0 of ``fd``; the OS drops it when the process dies.""" + try: + if sys.platform == "win32": + import msvcrt + + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + return True + + +def _os_unlock(fd: int) -> None: + if sys.platform == "win32": + import msvcrt + + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_UN) + + class RequestLedger: """Durable, cross-process request budget: one unit is *reserved before* every HTTP - attempt (retries included), under an exclusive lock file, with an atomic write. - - A crash after reserving over-counts (safe); it can never under-count. Two collectors on - the same ledger cannot together exceed the cap. The file keeps the Phase 11 format + attempt (retries included), under an exclusive OS file lock, with an fsynced atomic write. + + Guarantee: the recorded count is never below the number of attempts budgeted clients + have sent. A crash after reserving over-counts by the attempts it never sent (safe); it + cannot under-count. Collectors in any number of threads or processes on the same ledger + cannot together exceed the cap. The lock is an OS lock (``msvcrt``/``flock``), released + by the OS if its holder dies, so no stale-lock breaking (and its race) is needed. What the + provider bills is not reconstructed: an attempt cut off in flight may or may not have + reached it, and the ledger counts it either way. Each reservation is fsynced before the + request is sent (about 50 ms on a desktop disk), which caps one ledger at roughly 20 + reservations per second: far above free-endpoint rate limits, and the price of surviving + power loss. A lock timeout raises before anything is sent. The file keeps the Phase 11 format (``{"requests": n, "notes": [...]}``) so earlier usage still counts. """ @@ -166,27 +204,39 @@ def __init__(self, path: Path, cap: int, *, lock_timeout: float = 30.0) -> None: self.lock_timeout = lock_timeout self._lock = path.with_name(path.name + ".lock") - def _acquire(self) -> None: + _local_locks: ClassVar[dict[str, threading.Lock]] = {} + _local_guard: ClassVar[threading.Lock] = threading.Lock() + + def _local(self) -> threading.Lock: + key = os.path.abspath(self._lock) + with self._local_guard: + return self._local_locks.setdefault(key, threading.Lock()) + + def _acquire(self) -> int: + """Threads of one process queue on a blocking in-process lock (no polling, so none + starves under load); the OS lock then excludes other processes.""" deadline = time.monotonic() + self.lock_timeout - while True: - try: - fd = os.open(self._lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) - os.write(fd, str(os.getpid()).encode()) - os.close(fd) - return - except (FileExistsError, PermissionError): - # PermissionError: Windows reports it while the holder is deleting the file. - # A holder that crashed leaves the file; reservations are quick, so an old - # lock is stale. - try: - if time.time() - self._lock.stat().st_mtime > 60: - self._lock.unlink(missing_ok=True) - continue - except FileNotFoundError: - continue + local = self._local() + if not local.acquire(timeout=self.lock_timeout): + raise TimeoutError(f"request ledger lock {self._lock} is held") + try: + fd = os.open(self._lock, os.O_CREAT | os.O_RDWR) + while not _try_os_lock(fd): if time.monotonic() > deadline: - raise TimeoutError(f"request ledger lock {self._lock} is held") from None - time.sleep(0.01) + os.close(fd) + raise TimeoutError(f"request ledger lock {self._lock} is held") + time.sleep(0.005) + except BaseException: + local.release() + raise + return fd + + def _release(self, fd: int) -> None: + try: + _os_unlock(fd) + finally: + os.close(fd) + self._local().release() def _read(self) -> dict[str, Any]: if not self.path.exists(): @@ -200,7 +250,10 @@ def _read(self) -> dict[str, Any]: def _write(self, state: dict[str, Any]) -> None: tmp = self.path.with_name(self.path.name + f".{os.getpid()}.{threading.get_ident()}.tmp") - tmp.write_text(json.dumps(state, indent=1), encoding="utf-8") + with tmp.open("w", encoding="utf-8") as fh: + fh.write(json.dumps(state, indent=1)) + fh.flush() + os.fsync(fh.fileno()) # the count is on disk before it can be relied on for attempt in range(50): try: os.replace(tmp, self.path) # atomic on Windows and POSIX @@ -211,15 +264,15 @@ def _write(self, state: dict[str, Any]) -> None: time.sleep(0.01) def used(self) -> int: - self._acquire() # never read while another process replaces the file + fd = self._acquire() # never read while another process replaces the file try: return int(self._read()["requests"]) finally: - self._lock.unlink(missing_ok=True) + self._release(fd) def reserve(self, n: int = 1) -> int: """Reserve ``n`` attempts or raise; returns the total reserved afterwards.""" - self._acquire() + fd = self._acquire() try: state = self._read() total = int(state["requests"]) + n @@ -229,11 +282,11 @@ def reserve(self, n: int = 1) -> int: self._write(state) return total finally: - self._lock.unlink(missing_ok=True) + self._release(fd) def note(self, text: str, requests: int = 0) -> int: """Record a manual charge (e.g. requests made outside the collector).""" - self._acquire() + fd = self._acquire() try: state = self._read() state["requests"] = int(state["requests"]) + requests @@ -241,7 +294,7 @@ def note(self, text: str, requests: int = 0) -> int: self._write(state) return int(state["requests"]) finally: - self._lock.unlink(missing_ok=True) + self._release(fd) class BudgetedTransport(httpx.AsyncBaseTransport): diff --git a/tests/unit/test_ml_collector.py b/tests/unit/test_ml_collector.py index 86641ad..5ff3b3e 100644 --- a/tests/unit/test_ml_collector.py +++ b/tests/unit/test_ml_collector.py @@ -143,7 +143,7 @@ def test_ledger_reservations_from_many_threads_are_never_lost(tmp_path: Path) -> errors: list[BaseException] = [] def worker() -> None: - ledger = RequestLedger(ledger_path, cap=150) + ledger = RequestLedger(ledger_path, cap=150, lock_timeout=300) # timeouts are fail-safe for _ in range(40): try: ledger.reserve(1) @@ -234,3 +234,198 @@ def test_duplicate_records_keep_the_latest_success(tmp_path: Path) -> None: '{"tx_hash": "0xa", "status": "ok", "tx": {"n": 2}}\n' ) assert load_collected(out)["0xa"]["tx"] == {"n": 2} + + +# --- Phase 11.2: process-level failure modes ------------------------------------------ + +_WORKER = """ +import sys +from pathlib import Path +from cryptoguard.ml.collect import BudgetExhaustedError, RequestLedger +ledger = RequestLedger(Path(sys.argv[1]), cap=int(sys.argv[2])) +granted = 0 +for _ in range(int(sys.argv[3])): + try: + ledger.reserve(1) + granted += 1 + except BudgetExhaustedError: + break +print(granted) +""" + +_DIES_HOLDING_LOCK = """ +import os, sys +from pathlib import Path +from cryptoguard.ml.collect import RequestLedger +ledger = RequestLedger(Path(sys.argv[1]), cap=10) +ledger._acquire() # take the lock, then die without releasing it +os._exit(0) +""" + + +def _python(code: str, *args: str) -> str: + import subprocess + import sys + + done = subprocess.run( # noqa: S603 - fixed test code + [sys.executable, "-c", code, *args], + capture_output=True, + text=True, + timeout=60, + ) + assert done.returncode == 0, done.stderr + return done.stdout.strip() + + +def test_two_processes_cannot_exceed_a_shared_cap(tmp_path: Path) -> None: + import subprocess + import sys + + path = tmp_path / "budget.json" + procs = [ + subprocess.Popen( # noqa: S603 - fixed test code + [sys.executable, "-c", _WORKER, str(path), "120", "100"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + for _ in range(2) + ] + granted = [] + for p in procs: + out, err = p.communicate(timeout=60) + assert p.returncode == 0, err + granted.append(int(out)) + assert sum(granted) == 120 # 200 asked across two processes, exactly the cap granted + assert RequestLedger(path, cap=120).used() == 120 + + +def test_a_process_that_dies_holding_the_lock_does_not_block_or_corrupt(tmp_path: Path) -> None: + path = tmp_path / "budget.json" + RequestLedger(path, cap=10).reserve(3) + _python(_DIES_HOLDING_LOCK, str(path)) + ledger = RequestLedger(path, cap=10, lock_timeout=5) + assert ledger.reserve(1) == 4 # the OS released the dead holder's lock at once + + +def test_lock_held_by_a_live_holder_times_out_instead_of_being_broken(tmp_path: Path) -> None: + path = tmp_path / "budget.json" + holder = RequestLedger(path, cap=10) + fd = holder._acquire() + try: + with pytest.raises(TimeoutError): + RequestLedger(path, cap=10, lock_timeout=0.2).reserve(1) + finally: + holder._release(fd) + assert RequestLedger(path, cap=10).used() == 0 + + +def test_zero_budget_sends_nothing(tmp_path: Path) -> None: + labels, records = make_records(n=3) + transport = Counting(FakeRpc(records).transport()) + stats = _run( + pd.DataFrame(labels), + tmp_path / "c.jsonl", + RequestLedger(tmp_path / "b.json", cap=0), + transport, + ) + assert transport.attempts == 0 + assert stats["skipped_budget"] == 3 + + +class Flaky(httpx.AsyncBaseTransport): + """Answers 429 or times out on chosen attempts, else a valid eth_chainId reply.""" + + def __init__(self, plan: list[str]): + self.plan = plan + self.attempts = 0 + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + kind = self.plan[self.attempts] if self.attempts < len(self.plan) else "ok" + self.attempts += 1 + if kind == "429": + return httpx.Response(429, json={"error": "rate limited"}) + if kind == "timeout": + raise httpx.ReadTimeout("slow", request=request) + body = json.loads(request.content) + return httpx.Response(200, json={"jsonrpc": "2.0", "id": body["id"], "result": "0x1"}) + + +def _client(transport: httpx.AsyncBaseTransport, ledger: RequestLedger): # type: ignore[no-untyped-def] + from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy + from cryptoguard.ml.collect import BudgetedTransport + + return JsonRpcClient( + "https://rpc.invalid", + retry=RetryPolicy(max_retries=4, base_delay=0, max_delay=0), + transport=BudgetedTransport(transport, ledger), + sleep=_no_sleep, + ) + + +def test_rate_limits_and_timeouts_are_counted_as_attempts(tmp_path: Path) -> None: + ledger = RequestLedger(tmp_path / "b.json", cap=100) + inner = Flaky(["429", "timeout", "429"]) + + async def go() -> object: + client = _client(inner, ledger) + try: + return await client.call("eth_chainId", []) + finally: + await client.aclose() + + assert asyncio.run(go()) == "0x1" + assert inner.attempts == 4 + assert ledger.used() == 4 # three failed attempts and the success, all reserved first + + +def test_retries_stop_at_the_cap_mid_call(tmp_path: Path) -> None: + ledger = RequestLedger(tmp_path / "b.json", cap=2) + inner = Flaky(["429"] * 10) + + async def go() -> None: + client = _client(inner, ledger) + try: + await client.call("eth_chainId", []) + finally: + await client.aclose() + + with pytest.raises(BudgetExhaustedError): + asyncio.run(go()) + assert inner.attempts == 2 + assert ledger.used() == 2 + + +def test_five_async_workers_on_one_client_stay_under_the_cap(tmp_path: Path) -> None: + ledger = RequestLedger(tmp_path / "b.json", cap=37) + inner = Flaky([]) + + async def go() -> int: + client = _client(inner, ledger) + + async def worker() -> int: + done = 0 + for _ in range(20): + try: + await client.call("eth_chainId", []) + except BudgetExhaustedError: + break + done += 1 + return done + + try: + return sum(await asyncio.gather(*(worker() for _ in range(5)))) + finally: + await client.aclose() + + assert asyncio.run(go()) == 37 + assert inner.attempts == 37 + assert ledger.used() == 37 + + +def test_truncated_ledger_file_fails_closed(tmp_path: Path) -> None: + path = tmp_path / "budget.json" + path.write_text("") # e.g. a filesystem that lost an unsynced write + with pytest.raises(LedgerCorruptError): + RequestLedger(path, cap=10).reserve(1) + assert path.read_text() == "" # never silently reset to zero From 502680c90db9b33fe9ec03acad7d6acec1ca66cf Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:01:14 +0300 Subject: [PATCH 09/92] fix(ml): PSI blind spots and model task isolation PSI fixes: - Reference bins put a value equal to a decile edge in the upper bin, so a mostly-constant feature fell into one bin and a 0 to 40 shift gave PSI 0. New references use closed="left". Phase 11 cards keep their original binning, so they show no false drift. - An empty batch gave a large PSI; it now gives None. - NaN values were binned silently; they are now excluded and reported as missing_share. Task isolation: model cards record a task identifier, and the transaction scorer refuses cards for any other task. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/__init__.py | 3 ++ src/cryptoguard/ml/inference.py | 1 + src/cryptoguard/ml/monitoring.py | 76 ++++++++++++++++++++++++-------- src/cryptoguard/ml/registry.py | 6 ++- src/cryptoguard/ml/train.py | 3 +- tests/unit/test_ml_pipeline.py | 1 + 6 files changed, 69 insertions(+), 21 deletions(-) diff --git a/src/cryptoguard/ml/__init__.py b/src/cryptoguard/ml/__init__.py index bb76697..176f0b3 100644 --- a/src/cryptoguard/ml/__init__.py +++ b/src/cryptoguard/ml/__init__.py @@ -13,6 +13,9 @@ ML_VERSION = "cg-ml/0.1.0" FEATURE_SET_VERSION = "ptx-features/1" +# The Phase 11 model's task: is a mined transaction part of a phishing operation? Cards +# without a task field predate it and belong to this task. +TRANSACTION_TASK_ID = "ptxphish-transaction-phishing/1" def ml_available() -> bool: diff --git a/src/cryptoguard/ml/inference.py b/src/cryptoguard/ml/inference.py index f0830f3..8346eb9 100644 --- a/src/cryptoguard/ml/inference.py +++ b/src/cryptoguard/ml/inference.py @@ -60,6 +60,7 @@ def _scoring_slot() -> asyncio.Semaphore: class ShadowScore(BaseModel): experimental: Literal[True] = True + task: Literal["ptxphish-transaction-phishing/1"] = "ptxphish-transaction-phishing/1" status: Literal["scored", "not_found", "incomplete"] tx_hash: str run_id: str diff --git a/src/cryptoguard/ml/monitoring.py b/src/cryptoguard/ml/monitoring.py index cc58286..99d6e38 100644 --- a/src/cryptoguard/ml/monitoring.py +++ b/src/cryptoguard/ml/monitoring.py @@ -18,30 +18,62 @@ MIN_ROWS = 30 -def reference_bins(train_values: list[float]) -> dict[str, list[float]]: +def _bin(edges: list[float], value: float, closed: str) -> int: + # "right": a value equal to an edge goes to the upper bin (Phase 11 cards, bisect_right). + # "left": a value equal to an edge stays in the lower bin, so a tied decile (e.g. a + # mostly-zero count feature) keeps its own bin and a shift away from it is visible. + if closed == "left": + return bisect.bisect_left(edges, value) + return bisect.bisect_right(edges, value) + + +def reference_bins(train_values: list[float]) -> dict[str, Any]: """Bin edges (distinct interior training deciles) and the training share per bin. - Shares are counted, not assumed equal: binary and count features have tied deciles.""" + Shares are counted, not assumed equal: binary and count features have tied deciles. + + New references use ``closed="left"``. Phase 11 cards have no ``closed`` key and keep + their original ``bisect_right`` binning, with which a feature that is mostly one value + falls into a single bin (its shifts are invisible); see ML.md.""" ordered = sorted(train_values) n = len(ordered) deciles = [ordered[min(int(n * q / 10), n - 1)] for q in range(1, 10)] edges = sorted(set(deciles)) counts = [0] * (len(edges) + 1) for v in ordered: - counts[bisect.bisect_right(edges, v)] += 1 - return {"edges": edges, "expected": [c / n for c in counts]} + counts[_bin(edges, v, "left")] += 1 + return {"edges": edges, "expected": [c / n for c in counts], "closed": "left"} + + +def _present(values: list[float | None]) -> list[float]: + return [v for v in values if v is not None and not math.isnan(v)] + + +def missing_share(values: list[float | None]) -> float | None: + """Share of missing (None or NaN) values; None for an empty batch.""" + return None if not values else 1 - len(_present(values)) / len(values) -def psi(reference: dict[str, list[float]], values: list[float]) -> float: - """Population stability index of ``values`` against the training bins.""" +def psi(reference: dict[str, Any], values: list[float | None]) -> float | None: + """Population stability index of the present ``values`` against the training bins. + + Missing values are excluded (report them with ``missing_share``; NaN would otherwise + fall into the first bin silently) and an empty batch has no PSI (None, not 0 or a large + number). Zero-frequency bins are floored at 1e-4 on both sides.""" + present = _present(values) + if not present: + return None edges, expected = reference["edges"], reference["expected"] counts = [0] * len(expected) - for v in values: - counts[bisect.bisect_right(edges, v)] += 1 - total = len(values) or 1 + closed = reference.get("closed", "right") + for v in present: + counts[_bin(edges, v, closed)] += 1 + total = len(present) eps = 1e-4 - return sum( - (max(c / total, eps) - max(e, eps)) * math.log(max(c / total, eps) / max(e, eps)) - for c, e in zip(counts, expected, strict=True) + return float( + sum( + (max(c / total, eps) - max(e, eps)) * math.log(max(c / total, eps) / max(e, eps)) + for c, e in zip(counts, expected, strict=True) + ) ) @@ -107,15 +139,21 @@ def drift_report(card: dict[str, Any], path: Path = DEFAULT_LOG) -> dict[str, An if len(valid) < MIN_ROWS: return {"status": "insufficient_data", "min_rows": MIN_ROWS, **summary} reference = card["reference_bins"] - scores = { - feature: psi(reference[feature], [float(r["features"][feature]) for r in valid]) - for feature in columns - } - worst = sorted(scores.items(), key=lambda kv: -kv[1]) + values = {feature: [_as_float(r["features"][feature]) for r in valid] for feature in columns} + scores = {feature: psi(reference[feature], values[feature]) for feature in columns} + worst = sorted(scores.items(), key=lambda kv: -(kv[1] if kv[1] is not None else -1.0)) return { "status": "ok", **summary, "psi": dict(worst), - "shifted": [f for f, v in worst if v > 0.25], - "moderate": [f for f, v in worst if 0.1 < v <= 0.25], + "missing_share": {f: missing_share(values[f]) for f in columns}, + "shifted": [f for f, v in worst if v is not None and v > 0.25], + "moderate": [f for f, v in worst if v is not None and 0.1 < v <= 0.25], } + + +def _as_float(value: Any) -> float | None: + try: + return None if value is None else float(value) + except (TypeError, ValueError): + return None diff --git a/src/cryptoguard/ml/registry.py b/src/cryptoguard/ml/registry.py index f084534..ef3c810 100644 --- a/src/cryptoguard/ml/registry.py +++ b/src/cryptoguard/ml/registry.py @@ -27,7 +27,7 @@ from pathlib import Path from typing import Any, Literal -from cryptoguard.ml import FEATURE_SET_VERSION +from cryptoguard.ml import FEATURE_SET_VERSION, TRANSACTION_TASK_ID from cryptoguard.ml.features import FEATURES DEFAULT_REGISTRY = Path("data") / "ml" / "registry.json" @@ -88,6 +88,10 @@ def _check_card(card: Any) -> dict[str, Any]: raise ModelRegistryError(f"model card lacks {sorted(CARD_KEYS - set(card or {}))}") if not RUN_ID.match(str(card["run_id"])): raise ModelRegistryError(f"invalid run id {card['run_id']!r}") + if card.get("task", TRANSACTION_TASK_ID) != TRANSACTION_TASK_ID: + raise ModelRegistryError( + f"model task {card.get('task')!r} cannot be served by the transaction scorer" + ) if card["feature_set_version"] != FEATURE_SET_VERSION: raise ModelRegistryError( f"model features {card['feature_set_version']} != code {FEATURE_SET_VERSION}" diff --git a/src/cryptoguard/ml/train.py b/src/cryptoguard/ml/train.py index e82cc48..3dc66cb 100644 --- a/src/cryptoguard/ml/train.py +++ b/src/cryptoguard/ml/train.py @@ -25,7 +25,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any -from cryptoguard.ml import FEATURE_SET_VERSION, ML_VERSION +from cryptoguard.ml import FEATURE_SET_VERSION, ML_VERSION, TRANSACTION_TASK_ID from cryptoguard.ml.features import FEATURES from cryptoguard.ml.monitoring import reference_bins @@ -431,6 +431,7 @@ def ledger_entry( return { "run_id": run_id, "ml_version": ML_VERSION, + "task": TRANSACTION_TASK_ID, "feature_set_version": FEATURE_SET_VERSION, "git": _git_sha(), "versions": _versions(), diff --git a/tests/unit/test_ml_pipeline.py b/tests/unit/test_ml_pipeline.py index 987e1de..8ec1ed6 100644 --- a/tests/unit/test_ml_pipeline.py +++ b/tests/unit/test_ml_pipeline.py @@ -449,6 +449,7 @@ def test_registry_refuses_cards_that_do_not_match_this_code(trained: dict, tmp_p ({"feature_columns": ["not_a_feature"]}, "feature columns"), ({"threshold": 7}, "threshold"), ({"versions": {**card["versions"], "lightgbm": "1.0.0"}}, "lightgbm"), + ({"task": "poisoning-attempt/1"}, "transaction scorer"), # another task's model ): card_path.write_text(json.dumps({**card, **change})) with pytest.raises(ModelRegistryError, match=message): From 3411c6d3cc5f596b1044f430e616a20ae24a4cbd Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:01:15 +0300 Subject: [PATCH 10/92] feat(ml): wallet-centric poisoning research platform Adds task poisoning-attempt/1, kept separate from the PTXPhish transaction classifier: - events: the event schema, victim-event identity, campaign groups (public infrastructure exempt), grouped temporal splits, label tiers that keep weak, verified and conflicting labels apart, outcome records separate from labels, quality gates and a deterministic manifest; - poison_hunter: typed parser with field provenance; failing rows are quarantined with reasons, never dropped; - pilot: versioned pilot records. Fixes the pilot data loss: the post-processing read a non-existent 'transactions' field. A schema mismatch now raises instead of reading as zero, and legacy lines migrate with lost values set to None; - payments: offline payment verification. A loss needs a reviewed token, a successful receipt and a matching log; otherwise the result is unresolved; - candidates: structural candidate generation, independent of the detector, plus point-in-time event features; - review: score-free review packets and append-only label import; - planner: collection cost planning that never collects; - poisoning_report: the offline report. New CLI commands: ml poisoning-report and ml plan-collection. No RPC calls anywhere. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/candidates.py | 286 ++++++++++++ src/cryptoguard/ml/cli.py | 42 ++ src/cryptoguard/ml/events.py | 308 +++++++++++++ src/cryptoguard/ml/payments.py | 183 ++++++++ src/cryptoguard/ml/pilot.py | 417 +++++++++++++++++ src/cryptoguard/ml/planner.py | 82 ++++ src/cryptoguard/ml/poison_hunter.py | 256 +++++++++++ src/cryptoguard/ml/poisoning_report.py | 291 ++++++++++++ src/cryptoguard/ml/review.py | 119 +++++ tests/unit/test_ml_poisoning.py | 613 +++++++++++++++++++++++++ 10 files changed, 2597 insertions(+) create mode 100644 src/cryptoguard/ml/candidates.py create mode 100644 src/cryptoguard/ml/events.py create mode 100644 src/cryptoguard/ml/payments.py create mode 100644 src/cryptoguard/ml/pilot.py create mode 100644 src/cryptoguard/ml/planner.py create mode 100644 src/cryptoguard/ml/poison_hunter.py create mode 100644 src/cryptoguard/ml/poisoning_report.py create mode 100644 src/cryptoguard/ml/review.py create mode 100644 tests/unit/test_ml_poisoning.py diff --git a/src/cryptoguard/ml/candidates.py b/src/cryptoguard/ml/candidates.py new file mode 100644 index 0000000..a0b639a --- /dev/null +++ b/src/cryptoguard/ml/candidates.py @@ -0,0 +1,286 @@ +"""Offline candidate generation and point-in-time event features (task ``poisoning-attempt/1``). + +The generator turns a wallet's recorded observations into candidate poisoning events. It is +deliberately independent of the production detector (``detectors.poisoning``) and of any +model score: its rules are looser and purely structural, so a model scored on its output can +find events the detector never considered, and candidate recall can be measured separately +from classifier recall. + +Rules (an event may match several; ``methods`` lists them): + +- ``zero_value_in``: an incoming token transfer of value 0. +- ``spoofed_out``: a transfer out of the wallet in a transaction the wallet did not sign. +- ``lookalike_in``: an incoming transfer from an address that shares at least + ``MIN_AFFIX`` leading+trailing hex characters (``MIN_SUFFIX`` trailing) with a counterparty + the wallet itself chose before the event. +- ``untrusted_token_in``: an incoming transfer from a token outside the reviewed list whose + sender matches ``lookalike_in`` (a fake-token planting). +- ``dust_in``: an incoming transfer of a reviewed stablecoin below ``DUST_MAX_BASE_UNITS``. + +Cutoff: an event is scored after its own transaction executes and before anything later in +the same block (``history.Boundary`` ``pre_execution``, with the event's transaction +excluded). Features see only strictly earlier positions; the cross-wallet index sees only +earlier blocks. +""" + +from __future__ import annotations + +import time +import tracemalloc +from collections import defaultdict +from dataclasses import asdict, dataclass, field + +from cryptoguard.detectors.poisoning import affix_match +from cryptoguard.ml.events import PoisoningEvent, Subtype +from cryptoguard.ml.history import ( + Coverage, + HistoryFeatures, + WalletEvent, + events_from_fixture, + history_features, +) +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.replay.models import ReplayFixture + +CANDIDATE_VERSION = "candidates/1" +EVENT_FEATURE_VERSION = "event-features/1" +MIN_AFFIX = 6 +MIN_SUFFIX = 3 +DUST_MAX_BASE_UNITS = 10_000 # 0.01 of a 6-decimal stablecoin +STABLECOINS = frozenset( + {"0xdac17f958d2ee523a2206206994597c13d831ec7", "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"} +) +RECENT_BLOCKS = 7_200 # about one day + + +def _similar(a: str, b: str) -> tuple[int, int] | None: + if a == b: + return None + prefix, suffix = affix_match(a, b) + return (prefix, suffix) if prefix + suffix >= MIN_AFFIX and suffix >= MIN_SUFFIX else None + + +@dataclass(frozen=True) +class Candidate: + event: PoisoningEvent + methods: tuple[str, ...] + value: int + best_match: tuple[int, int] | None # (prefix, suffix) to the imitated counterparty + + +def _chosen_before(events: list[WalletEvent], position: tuple[int, int, int]) -> dict[str, int]: + """Counterparties the wallet chose (signed outgoing events) strictly before ``position``, + with the block they were last chosen.""" + chosen: dict[str, int] = {} + for e in events: + if e.position < position and e.direction == "out" and e.wallet_signed is not False: + chosen[e.counterparty.lower()] = e.block + return chosen + + +def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: + """Candidate events from one recorded wallet window, in chain order.""" + wallet = fixture.wallet.lower() + events, coverage = events_from_fixture(fixture) + events.sort(key=lambda e: e.position) + status = "complete" if coverage.complete else "partial" + out: list[Candidate] = [] + for t in sorted( + fixture.transfers, key=lambda t: (t.block_number, t.transaction_index, t.log_index) + ): + incoming = t.recipient.lower() == wallet + outgoing = t.sender.lower() == wallet + if not (incoming or outgoing): + continue + position = (t.block_number, t.transaction_index, t.log_index) + token = t.token.lower() + value = int(t.value) + methods: list[str] = [] + party = (t.sender if incoming else t.recipient).lower() + chosen = _chosen_before(events, position) + match = max( + ((k, m) for k in chosen if (m := _similar(party, k)) is not None), + key=lambda km: (sum(km[1]), km[1][1], km[0]), + default=None, + ) + if incoming and value == 0: + methods.append("zero_value_in") + if outgoing and t.tx_sender is not None and t.tx_sender.lower() != wallet: + methods.append("spoofed_out") + if incoming and match is not None: + methods.append("lookalike_in") + if token not in TRUSTED_TOKENS: + methods.append("untrusted_token_in") + if incoming and token in STABLECOINS and 0 < value <= DUST_MAX_BASE_UNITS: + methods.append("dust_in") + if not methods: + continue + out.append( + Candidate( + event=PoisoningEvent( + chain_id=chain_id, + victim=wallet, + lookalike=party, + imitated=match[0] if match else None, + planting_tx=t.transaction_hash.lower(), + planting_block=t.block_number, + planting_tx_index=t.transaction_index, + planting_log_index=t.log_index, + observation_timestamp=None, + subtype=_subtype(methods), + tx_signer=None if t.tx_sender is None else t.tx_sender.lower(), + log_contract=token, + token_contract=token if token in TRUSTED_TOKENS else None, + candidate_method=CANDIDATE_VERSION + ":" + "+".join(methods), + evidence_refs=(f"fixture:{fixture.case_id}",), + coverage=status, + ), + methods=tuple(methods), + value=value, + best_match=match[1] if match else None, + ) + ) + return out + + +def _subtype(methods: list[str]) -> Subtype: + if "spoofed_out" in methods: + return "spoofed_transfer_from" + if "zero_value_in" in methods: + return "zero_value" + if "untrusted_token_in" in methods: + return "fake_token" + if "dust_in" in methods: + return "dust" + return "other" + + +@dataclass +class PriorIndex: + """Cross-wallet relations, queried strictly before a block (no same-block leakage).""" + + seen: dict[tuple[str, str], list[tuple[int, str]]] = field( + default_factory=lambda: defaultdict(list) + ) + + def add(self, e: PoisoningEvent) -> None: + for kind, key in (("lookalike", e.lookalike), ("signer", e.tx_signer)): + if key: + self.seen[(kind, key)].append((e.planting_block, e.victim)) + + def distinct_victims_before(self, kind: str, key: str | None, block: int) -> int | None: + if key is None: + return None + return len({v for b, v in self.seen.get((kind, key), []) if b < block}) + + +@dataclass(frozen=True) +class EventFeatures: + feature_version: str + history: HistoryFeatures + subtype: str + value_is_zero: bool + token_trusted: bool + prefix_to_imitated: int | None + suffix_to_imitated: int | None + plausible_impersonated: int | None # chosen counterparties the sender resembles + blocks_since_imitated_chosen: int | None + recent_unsolicited_in: int | None + observed_blocks: int | None + lookalike_victims_before: int | None + signer_victims_before: int | None + + def as_model_row(self) -> dict[str, float]: + row = self.history.as_model_row() + for key, value in asdict(self).items(): + if key in ("feature_version", "history", "subtype"): + continue + row[key] = -1.0 if value is None else float(value) + for sub in ("zero_value", "dust", "fake_token", "spoofed_transfer_from", "other"): + row[f"subtype_{sub}"] = float(self.subtype == sub) + return row + + +def event_features( + c: Candidate, + events: list[WalletEvent], + coverage: Coverage | None, + index: PriorIndex | None = None, +) -> EventFeatures: + """Features of candidate ``c`` from events strictly before its transaction.""" + e = c.event + tx_index = e.planting_tx_index if e.planting_tx_index is not None else 0 + hist = history_features( + events, + coverage, + recipient=e.lookalike, + block=e.planting_block, + tx_index=tx_index, + boundary="pre_execution" if e.planting_tx_index is not None else "pre_signing", + ) + known = hist.history_status == "available" + position = (e.planting_block, tx_index, -2) # before the event's own transaction + visible = [x for x in events if (x.block, x.tx_index) < (e.planting_block, tx_index)] + chosen = _chosen_before(visible, position) if known else {} + recent = ( + sum( + 1 + for x in visible + if x.direction == "in" and not x.value and x.block > e.planting_block - RECENT_BLOCKS + ) + if known + else None + ) + return EventFeatures( + feature_version=EVENT_FEATURE_VERSION, + history=hist, + subtype=e.subtype, + value_is_zero=c.value == 0, + token_trusted=(e.log_contract or "") in TRUSTED_TOKENS, + prefix_to_imitated=c.best_match[0] if c.best_match else None, + suffix_to_imitated=c.best_match[1] if c.best_match else None, + plausible_impersonated=sum(1 for k in chosen if _similar(e.lookalike, k)) + if known + else None, + blocks_since_imitated_chosen=( + e.planting_block - chosen[e.imitated] if known and e.imitated in chosen else None + ), + recent_unsolicited_in=recent, + observed_blocks=None if coverage is None else e.planting_block - coverage.from_block, + lookalike_victims_before=None + if index is None + else index.distinct_victims_before("lookalike", e.lookalike, e.planting_block), + signer_victims_before=None + if index is None + else index.distinct_victims_before("signer", e.tx_signer, e.planting_block), + ) + + +@dataclass(frozen=True) +class GenerationStats: + candidates: int + by_method: dict[str, int] + duplicate_identities: int + runtime_ms: float + peak_kib: float + + +def generate_with_stats(fixture: ReplayFixture) -> tuple[list[Candidate], GenerationStats]: + tracemalloc.start() + t0 = time.perf_counter() + cands = generate(fixture) + runtime = (time.perf_counter() - t0) * 1000 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + by_method: dict[str, int] = defaultdict(int) + for c in cands: + for m in c.methods: + by_method[m] += 1 + ids = [c.event.victim_event_id for c in cands] + return cands, GenerationStats( + candidates=len(cands), + by_method=dict(sorted(by_method.items())), + duplicate_identities=len(ids) - len(set(ids)), + runtime_ms=round(runtime, 2), + peak_kib=round(peak / 1024, 1), + ) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 2eabefd..e2dd07e 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -48,11 +48,53 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None sc.add_argument("tx_hash") sc.add_argument("--rpc-url", required=True) ml.add_parser("monitor", help="feature drift of shadow-scored transactions") + pz = ml.add_parser( + "poisoning-report", + help="offline Phase 11.2 report: Poison-Hunter validation, pilot, candidates (no RPC)", + ) + pz.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + pz.add_argument("--pilot-dir", type=Path, default=ML_DIR / "pilot") + pz.add_argument("--out", type=Path, default=ML_DIR / "poisoning") + pz.add_argument("--tables", type=Path, default=Path("ML_POISONING_TABLES.md")) + pc = ml.add_parser( + "plan-collection", help="estimate a wallet-history collection job (never collects)" + ) + pc.add_argument("--wallets", type=int, required=True) + pc.add_argument("--window-blocks", type=int, required=True) + pc.add_argument("--request-cap", type=int, required=True) + pc.add_argument("--log-range-blocks", type=int, default=100) def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available + # Pure-Python commands: no ml extra needed. + if args.ml_command == "poisoning-report": + from cryptoguard.ml.poisoning_report import build, write + + written = write(build(args.data_dir, args.pilot_dir), args.out, args.tables) + print(f"Wrote {written} and {args.tables} (0 RPC requests).") + return 0 + if args.ml_command == "plan-collection": + import json + + from cryptoguard.ml.planner import ( + CollectionAssumptions, + CollectionJob, + PlanRejected, + plan, + ) + + job = CollectionJob( + wallets=args.wallets, window_blocks=args.window_blocks, request_cap=args.request_cap + ) + try: + body = plan(job, CollectionAssumptions(log_range_blocks=args.log_range_blocks)) + except PlanRejected as exc: + print(f"rejected: {exc}") + return 2 + print(json.dumps(body, indent=1)) + return 0 if not ml_available(): print("error [ml_unavailable]: install the ml extra (uv sync --extra ml)") return 1 diff --git a/src/cryptoguard/ml/events.py b/src/cryptoguard/ml/events.py new file mode 100644 index 0000000..c5b2f25 --- /dev/null +++ b/src/cryptoguard/ml/events.py @@ -0,0 +1,308 @@ +"""Wallet-centric poisoning research data model (task ``poisoning-attempt/1``). + +Prediction unit: ``(chain_id, victim, candidate_event_id, observation_cutoff)``. A candidate +event is one suspicious transfer seen by one wallet; the question is whether it is a +poisoning attempt *against that wallet*, judged at the cutoff. Whether the victim later lost +money is a separate outcome, stored apart and never available as a feature. + +Identity: + +- ``planting_tx_id``: ``chain_id:tx_hash``. One batched transaction can plant many victims. +- ``victim_event_id``: hash of chain, victim, planting tx, lookalike and log index. Rows of a + source that repeat the same victim-event are duplicates, not independent examples. +- ``group_id``: connected component over victims, lookalikes, planting txs and signers + (public infrastructure exempt): all events of one campaign stay on one side of a split. + +Labels, outcomes and features each carry their own availability block, so a label assigned +in retrospect can be a target but never an input. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter, defaultdict +from collections.abc import Iterable, Sequence +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + +from cryptoguard.ml.dataset import PUBLIC_INFRASTRUCTURE as _PUBLIC + +TASK_ID = "poisoning-attempt/1" +EVENT_SCHEMA_VERSION = "poisoning-event/1" + +LabelTier = Literal[ + "verified_attempt", # independent review confirmed a poisoning attempt + "verified_legitimate", # independent review confirmed a legitimate interaction + "weak_attempt", # a source pipeline says attempt; not independently reviewed + "likely_legitimate", # limited evidence of legitimacy + "conflicting", + "unknown", +] +OutcomeStatus = Literal[ + "confirmed_direct_payment", + "no_direct_payment_observed_with_complete_declared_coverage", + "partial_coverage", + "unresolved", + "not_evaluated", +] +Subtype = Literal["zero_value", "dust", "fake_token", "spoofed_transfer_from", "other", "unknown"] +CoverageStatus = Literal["complete", "partial", "unavailable"] +TRAINABLE_POSITIVE: frozenset[LabelTier] = frozenset({"verified_attempt"}) +TRAINABLE_NEGATIVE: frozenset[LabelTier] = frozenset({"verified_legitimate"}) + + +def _norm(address: str | None) -> str | None: + return None if address is None else address.lower() + + +class PoisoningEvent(BaseModel): + """One candidate event against one wallet. Unknown values are ``None``, never guessed.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-event/1"] = "poisoning-event/1" + chain_id: int + victim: str + lookalike: str + imitated: str | None + planting_tx: str + planting_block: int + planting_tx_index: int | None + planting_log_index: int | None + observation_timestamp: int | None + subtype: Subtype + tx_signer: str | None # verified signer of the planting transaction + log_contract: str | None # contract that emitted the planting log + token_contract: str | None # token being imitated, when known + candidate_method: str # how the event entered the dataset (source or rule id) + evidence_refs: tuple[str, ...] = () + coverage: CoverageStatus = "unavailable" + dataset_version: str | None = None + + @property + def planting_tx_id(self) -> str: + return f"{self.chain_id}:{self.planting_tx.lower()}" + + @property + def victim_event_id(self) -> str: + key = "|".join( + [ + str(self.chain_id), + self.victim.lower(), + self.planting_tx.lower(), + self.lookalike.lower(), + "" if self.planting_log_index is None else str(self.planting_log_index), + ] + ) + return hashlib.sha256(key.encode()).hexdigest()[:16] + + @property + def cutoff(self) -> tuple[int, int]: + """Scored after the planting transaction executes, before anything later in its block. + An unknown transaction index means only earlier blocks are visible.""" + return ( + self.planting_block, + -1 if self.planting_tx_index is None else self.planting_tx_index, + ) + + +class LabelRecord(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + victim_event_id: str + tier: LabelTier + source: str # e.g. "poison-hunter-sample", "review:" + confidence: float | None = Field(default=None, ge=0, le=1) + available_at: str | None # when the label became known (ISO date or block); not a feature + rationale: str | None = None + + +class OutcomeRecord(BaseModel): + """What happened to the victim afterwards (secondary target, never a feature).""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + victim_event_id: str + status: OutcomeStatus + window_from: int | None + window_to: int | None + declared_coverage: str + evidence_refs: tuple[str, ...] = () + + +def deduplicate(events: Iterable[PoisoningEvent]) -> tuple[list[PoisoningEvent], int]: + """Keep the first event per victim-event identity; returns (events, duplicates dropped).""" + seen: set[str] = set() + kept: list[PoisoningEvent] = [] + dropped = 0 + for e in events: + if e.victim_event_id in seen: + dropped += 1 + continue + seen.add(e.victim_event_id) + kept.append(e) + return kept, dropped + + +def resolve_labels(labels: Sequence[LabelRecord]) -> dict[str, LabelTier]: + """One tier per event. Verified labels win over weak ones; verified disagreement is + ``conflicting``; nothing is overwritten, the input history stays as it is.""" + by_event: dict[str, set[LabelTier]] = defaultdict(set) + for lab in labels: + by_event[lab.victim_event_id].add(lab.tier) + out: dict[str, LabelTier] = {} + for event_id, tiers in by_event.items(): + verified = tiers & {"verified_attempt", "verified_legitimate"} + if len(verified) == 2 or "conflicting" in tiers: + out[event_id] = "conflicting" + elif verified: + out[event_id] = ( + "verified_attempt" if "verified_attempt" in verified else "verified_legitimate" + ) + elif {"weak_attempt", "likely_legitimate"} <= tiers: + out[event_id] = "conflicting" + elif "weak_attempt" in tiers: + out[event_id] = "weak_attempt" + elif "likely_legitimate" in tiers: + out[event_id] = "likely_legitimate" + else: + out[event_id] = "unknown" + return out + + +class _UnionFind: + def __init__(self) -> None: + self.parent: dict[str, str] = {} + + def find(self, x: str) -> str: + self.parent.setdefault(x, x) + while self.parent[x] != x: + self.parent[x] = self.parent[self.parent[x]] + x = self.parent[x] + return x + + def union(self, a: str, b: str) -> None: + self.parent[self.find(a)] = self.find(b) + + +def campaign_groups( + events: Sequence[PoisoningEvent], exempt: frozenset[str] = frozenset(_PUBLIC) +) -> dict[str, str]: + """``victim_event_id -> group id``. Events sharing a victim, lookalike, planting tx or + planting signer are linked; reviewed public infrastructure (routers, token contracts) is + exempt so it does not merge unrelated campaigns.""" + uf = _UnionFind() + exempt = frozenset(a.lower() for a in exempt) + for e in events: + node = "e:" + e.victim_event_id + uf.find(node) + for kind, value in ( + ("v", e.victim), + ("l", e.lookalike), + ("t", e.planting_tx_id), + ("s", e.tx_signer), + ): + if value and value.lower() not in exempt: + uf.union(node, f"{kind}:{value.lower()}") + roots = {e.victim_event_id: uf.find("e:" + e.victim_event_id) for e in events} + names = {root: f"g{i:04d}" for i, root in enumerate(sorted(set(roots.values())))} + return {event_id: names[root] for event_id, root in roots.items()} + + +def grouped_temporal_split( + events: Sequence[PoisoningEvent], + groups: dict[str, str], + *, + test_fraction: float = 0.3, +) -> dict[str, Literal["train", "test"]]: + """Whole groups go to one side; the groups that start latest form the test set, so the + test set is both later in time and disjoint in campaigns, victims and infrastructure.""" + first: dict[str, int] = {} + size: Counter[str] = Counter() + for e in events: + g = groups[e.victim_event_id] + first[g] = min(first.get(g, e.planting_block), e.planting_block) + size[g] += 1 + target = test_fraction * len(events) + test: set[str] = set() + taken = 0 + for g in sorted(first, key=lambda g: (-first[g], g)): + if taken >= target: + break + test.add(g) + taken += size[g] + return { + e.victim_event_id: "test" if groups[e.victim_event_id] in test else "train" for e in events + } + + +class GateResult(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + gate: str + passed: bool + detail: str + + +def quality_gates( + events: Sequence[PoisoningEvent], + labels: dict[str, LabelTier], + *, + license_ok: bool, + min_per_class: int = 30, +) -> list[GateResult]: + """Dataset acceptance checks run before any training. Failing gates block training.""" + ids = [e.victim_event_id for e in events] + tiers: Counter[str] = Counter(labels.get(i, "unknown") for i in ids) + positives = sum(tiers[t] for t in TRAINABLE_POSITIVE) + negatives = sum(tiers[t] for t in TRAINABLE_NEGATIVE) + groups = campaign_groups(events) + pos_groups = {groups[i] for i in ids if labels.get(i) in TRAINABLE_POSITIVE} + neg_groups = {groups[i] for i in ids if labels.get(i) in TRAINABLE_NEGATIVE} + return [ + GateResult( + gate="A_data_validity", + passed=len(ids) == len(set(ids)) and len(ids) > 0, + detail=f"{len(ids)} events, {len(ids) - len(set(ids))} duplicate identities", + ), + GateResult( + gate="B_label_validity", + passed=positives >= min_per_class and negatives >= min_per_class, + detail=( + f"verified positives {positives}, verified negatives {negatives} " + f"(need {min_per_class} each); weak {tiers['weak_attempt']}, " + f"unknown {tiers['unknown']}, conflicting {tiers['conflicting']}" + ), + ), + GateResult( + gate="C_temporal_validity", + passed=all(e.planting_block > 0 for e in events), + detail="every event has a planting block; cutoff = after the planting transaction", + ), + GateResult( + gate="D_split_validity", + passed=len(pos_groups) >= 5 and len(neg_groups) >= 5, + detail=f"{len(pos_groups)} positive and {len(neg_groups)} negative campaign groups", + ), + GateResult( + gate="license", + passed=license_ok, + detail="raw rows stay local" if not license_ok else "redistributable", + ), + ] + + +def manifest(events: Sequence[PoisoningEvent], labels: Sequence[LabelRecord]) -> dict[str, object]: + """Deterministic dataset manifest: content hash over canonical event and label JSON.""" + ev = sorted(e.model_dump_json() for e in events) + lab = sorted(lab.model_dump_json() for lab in labels) + digest = hashlib.sha256(json.dumps([ev, lab]).encode()).hexdigest() + return { + "task": TASK_ID, + "event_schema": EVENT_SCHEMA_VERSION, + "events": len(ev), + "labels": len(lab), + "sha256": digest, + } diff --git a/src/cryptoguard/ml/payments.py b/src/cryptoguard/ml/payments.py new file mode 100644 index 0000000..65708d2 --- /dev/null +++ b/src/cryptoguard/ml/payments.py @@ -0,0 +1,183 @@ +"""Offline verification of a suspected victim payment from recorded transaction data. + +A Transfer log alone proves nothing: any contract can emit one (fake tokens), and the +genuine token emits one for a spoofed ``transferFrom(victim, x, 0)``. A victim-signed +transaction alone proves nothing about a specific log either. The verifier therefore combines +the transaction, its receipt and its logs, and returns ``unresolved`` whenever the recorded +evidence does not support a confirmed asset movement. It makes no RPC calls. + +Attribution is kept apart from movement: the result records where value went and whether +that address imitates another one, but never claims who controls it. +""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict + +from cryptoguard.blockchain.abi import TRANSFER_TOPIC + +TRANSFER_SELECTOR = "0xa9059cbb" +TRANSFER_FROM_SELECTOR = "0x23b872dd" + +# Reviewed token contracts whose Transfer logs reflect real balance changes (mainnet). +TRUSTED_TOKENS: dict[str, str] = { + "0xdac17f958d2ee523a2206206994597c13d831ec7": "USDT", + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": "USDC", + "0x6b175474e89094c44da98b954eedeac495271d0f": "DAI", + "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2": "WETH", + "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599": "WBTC", +} + +Status = Literal["confirmed_direct_payment", "not_a_payment", "reverted", "unresolved"] +Evidence = Literal[ + "native_transfer", + "trusted_token_transfer_call", + "matching_trusted_log", + "receipt_success", + "receipt_reverted", + "receipt_missing", + "untrusted_token", + "signer_is_not_victim", + "spender_mediated_transfer_from", + "log_without_matching_call", + "calldata_not_a_direct_transfer", + "zero_amount", + "destination_mismatch", +] + + +class PaymentVerification(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + status: Status + evidence: tuple[Evidence, ...] + tx_hash: str | None + observed_destination: str | None + asset: str | None # "ETH", a trusted symbol, or a token address + amount: int | None + # Attribution, kept separate from movement: + destination_is_candidate: bool + ownership_claim: None = None # never asserted from on-chain data alone + + +def _addr_topic(topic: str) -> str: + return "0x" + topic.lower()[-40:] + + +def _receipt_status(receipt: dict[str, Any] | None) -> bool | None: + if not receipt: + return None + status = receipt.get("status") + return True if status == "0x1" else False if status == "0x0" else None + + +def _result( + status: Status, + evidence: list[Evidence], + tx: dict[str, Any] | None, + destination: str | None, + asset: str | None, + amount: int | None, + candidate: str, +) -> PaymentVerification: + return PaymentVerification( + status=status, + evidence=tuple(evidence), + tx_hash=(tx or {}).get("hash"), + observed_destination=destination, + asset=asset, + amount=amount, + destination_is_candidate=destination is not None and destination == candidate, + ) + + +def verify_payment( + *, + victim: str, + candidate: str, + tx: dict[str, Any], + receipt: dict[str, Any] | None, + trusted_tokens: dict[str, str] | None = None, +) -> PaymentVerification: + """Did ``victim`` move value to ``candidate`` in ``tx``? Evidence-based, fail-safe.""" + trusted = {k.lower(): v for k, v in (trusted_tokens or TRUSTED_TOKENS).items()} + victim, candidate = victim.lower(), candidate.lower() + signer = str(tx.get("from", "")).lower() + to = str(tx.get("to") or "").lower() or None + raw_value = str(tx.get("value") or "0") + value = int(raw_value, 16) if raw_value.startswith("0x") else int(raw_value) + data = str(tx.get("input", "0x")).lower() + ok = _receipt_status(receipt) + ev: list[Evidence] = [] + + if signer != victim: + # A genuine movement out of the victim can still happen through an approved spender + # (transferFrom); proving it needs approval history, which this record lacks. + logs = [ + lg + for lg in (receipt or {}).get("logs", []) + if lg.get("topics") + and lg["topics"][0].lower() == TRANSFER_TOPIC + and len(lg["topics"]) == 3 + and _addr_topic(lg["topics"][1]) == victim + and _addr_topic(lg["topics"][2]) == candidate + ] + ev.append("signer_is_not_victim") + if logs and any(lg.get("address", "").lower() in trusted for lg in logs): + ev.append("spender_mediated_transfer_from") + return _result( + "unresolved" if logs else "not_a_payment", ev, tx, None, None, None, candidate + ) + + if ok is None: + ev.append("receipt_missing") + return _result("unresolved", ev, tx, to, None, None, candidate) + if ok is False: + ev.append("receipt_reverted") + return _result("reverted", ev, tx, to, None, None, candidate) + ev.append("receipt_success") + + if value > 0 and data in ("0x", ""): + ev.append("native_transfer") + if to != candidate: + ev.append("destination_mismatch") + return _result("not_a_payment", ev, tx, to, "ETH", value, candidate) + return _result("confirmed_direct_payment", ev, tx, to, "ETH", value, candidate) + + if data.startswith(TRANSFER_SELECTOR) and len(data) >= 138: + recipient = "0x" + data[34:74] + amount = int(data[74:138], 16) + if to not in trusted: + ev.append("untrusted_token") + return _result("unresolved", ev, tx, recipient, to, amount, candidate) + ev.append("trusted_token_transfer_call") + if amount == 0: + ev.append("zero_amount") + return _result("not_a_payment", ev, tx, recipient, trusted[to or ""], 0, candidate) + matching = [ + lg + for lg in (receipt or {}).get("logs", []) + if str(lg.get("address", "")).lower() == to + and lg.get("topics") + and lg["topics"][0].lower() == TRANSFER_TOPIC + and len(lg["topics"]) == 3 + and _addr_topic(lg["topics"][1]) == victim + and _addr_topic(lg["topics"][2]) == recipient + and int(str(lg.get("data", "0x0")), 16) == amount + ] + if not matching: + ev.append("log_without_matching_call") + return _result("unresolved", ev, tx, recipient, trusted[to or ""], amount, candidate) + ev.append("matching_trusted_log") + if recipient != candidate: + ev.append("destination_mismatch") + return _result("not_a_payment", ev, tx, recipient, trusted[to or ""], amount, candidate) + return _result( + "confirmed_direct_payment", ev, tx, recipient, trusted[to or ""], amount, candidate + ) + + # Router, multicall, contract-wallet or other calls: value may move, but not provably here. + ev.append("calldata_not_a_direct_transfer") + return _result("unresolved", ev, tx, to, None, None, candidate) diff --git a/src/cryptoguard/ml/pilot.py b/src/cryptoguard/ml/pilot.py new file mode 100644 index 0000000..9a0c14c --- /dev/null +++ b/src/cryptoguard/ml/pilot.py @@ -0,0 +1,417 @@ +"""Typed pilot records and an offline reconstruction of the option A pilot (0 RPC requests). + +The pilot script that collected ``data/ml/pilot/`` lived outside the package: it read +untyped dictionaries and one attribute, ``fixture.transactions``, that does not exist (the +replay model's field is ``wallet_transactions``). The ``AttributeError`` was caught by a +broad handler, so three completed wallet recordings were logged as errors and their contents +were never written. This module is the fix: + +- every record is a versioned pydantic model (``extra="forbid"``): a misspelled or missing + field is a validation error, never an empty list or a zero; +- ``summarize_fixture`` reads ``ReplayFixture`` through typed attributes that mypy checks; +- legacy (unversioned) pilot lines are migrated explicitly, with what could not be recovered + recorded as ``None`` and a reason, never invented; +- outcomes use explicit coverage terms: a victim with no observed payment is not "benign". +""" + +from __future__ import annotations + +import hashlib +import json +import math +from collections import Counter +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +from cryptoguard.replay.models import ReplayFixture + +YIELD_SCHEMA = "pilot-yield/2" +COST_SCHEMA = "pilot-cost/2" +FIXTURE_SUMMARY_SCHEMA = "pilot-fixture-summary/1" + +Outcome = Literal[ + "confirmed_direct_payment", + "no_direct_payment_observed_with_complete_declared_coverage", + "partial_coverage", + "unresolved", + "not_evaluated", +] +DECLARED_COVERAGE = ( + "victim-signed transactions in [planting_block + 1, planting_block + 50400]: native ETH " + "sends and ERC-20 transfer(recipient, amount) calls" +) +NOT_COVERED = ( + "transferFrom by a spender, router or aggregator payments, contract-wallet (relayed) " + "payments, permit-based transfers, payments after the window" +) + + +class PilotRecordError(ValueError): + """A pilot record does not match any known schema version: refuse to guess.""" + + +class PaymentObservation(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + tx: str + kind: Literal["eth", "token"] + token: str | None = None + succeeded: bool | None + + +class YieldRecord(BaseModel): + """Payment check for one Poison-Hunter row (victim, lookalike, planting block).""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["pilot-yield/2"] = "pilot-yield/2" + source_line: int | None # Poison-Hunter CSV line; None when it cannot be matched + victim: str + lookalike: str + subtype: str + window_from: int + window_to: int + nonce_before: int | None + signed_in_window: int | None + located_complete: bool | None # None = location not attempted + payments_to_lookalike: tuple[PaymentObservation, ...] | None # None = not inspected + error: str | None = None + skipped: str | None = None + requests: int = Field(ge=0) + migrated_from: str | None = None + + @property + def outcome(self) -> Outcome: + if self.error is not None: + return "unresolved" + if self.signed_in_window is None: + return "not_evaluated" + if any(p.succeeded is not False for p in self.payments_to_lookalike or ()): + # Calldata-level evidence only; see payments.verify_* for the stricter verifier. + return "confirmed_direct_payment" + if self.signed_in_window == 0: + return "no_direct_payment_observed_with_complete_declared_coverage" + if self.payments_to_lookalike is None: + return "not_evaluated" if self.skipped else "unresolved" + if self.located_complete: + return "no_direct_payment_observed_with_complete_declared_coverage" + return "partial_coverage" + + +class CostRecord(BaseModel): + """One random-wallet draw of the cost phase.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["pilot-cost/2"] = "pilot-cost/2" + draw: int + block: int + wallet_sha: str | None + has_code: bool | None + nonce_end: int | None + signed_in_window: int | None + result: Literal[ + "recorded", + "recorded_contents_lost", + "ineligible", + "too_many_sends_for_pilot", + "skipped_budget", + "empty_block", + "error", + ] + error: str | None = None + requests: int = Field(ge=0) + record_requests: int | None # requests spent inside record_window + transfers: int | None # None = unknown, never "zero" + wallet_transactions: int | None + outgoing_payments: int | None + scan_complete: bool | None + migrated_from: str | None = None + + +class FixtureSummary(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["pilot-fixture-summary/1"] = "pilot-fixture-summary/1" + transfers: int + wallet_transactions: int + outgoing_payments: int + scan_complete: bool + + +def summarize_fixture(fx: ReplayFixture) -> FixtureSummary: + """Counts from a recorded window (the corrected version of the pilot's post-processing). + + Outgoing payments: the wallet's own ETH-carrying transactions that did not revert, plus + token transfers out of the wallet in transactions the wallet signed (spoofed + ``transferFrom`` logs and zero-value plantings are not payments).""" + wallet = fx.wallet.lower() + eth = sum(1 for t in fx.wallet_transactions if int(t.value) > 0 and t.succeeded is not False) + tokens = sum( + 1 + for t in fx.transfers + if t.sender.lower() == wallet and (t.tx_sender or "").lower() == wallet and int(t.value) > 0 + ) + return FixtureSummary( + transfers=len(fx.transfers), + wallet_transactions=len(fx.wallet_transactions), + outgoing_payments=eth + tokens, + scan_complete=fx.transfer_scan_complete and fx.sender_lookups_skipped == 0, + ) + + +def summarize_fixture_json(data: dict[str, Any]) -> FixtureSummary: + """Summary of a stored fixture; a schema mismatch (e.g. ``transactions`` instead of + ``wallet_transactions``) raises instead of being read as zero transactions.""" + try: + return summarize_fixture(ReplayFixture.model_validate(data)) + except ValidationError as exc: + raise PilotRecordError(f"stored fixture does not match ReplayFixture: {exc}") from None + + +# --- loading and migration ------------------------------------------------------------- + +_LEGACY_YIELD_KEYS = {"victim", "attacker", "type", "lo", "hi", "requests"} +_LEGACY_COST_KEYS = {"draw", "block", "requests", "result"} +_LOST_CONTENTS = "AttributeError: 'ReplayFixture' object has no attribute 'transactions'" +# Requests spent before record_window in a legacy draw: block, code, nonce at end and start. +_LEGACY_ELIGIBILITY_REQUESTS = 4 + + +def read_jsonl(path: Path) -> tuple[list[dict[str, Any]], bool]: + """Lines as objects. A cut-off final line (crash while writing) is reported and skipped; + a corrupt line elsewhere is an error.""" + lines = path.read_text(encoding="utf-8").split("\n") + truncated = False + out: list[dict[str, Any]] = [] + for i, line in enumerate(lines): + if not line.strip(): + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + if i == len(lines) - 1: # no newline after it: the write was cut off + truncated = True + continue + raise PilotRecordError(f"{path}: corrupt line {i + 1}") from None + if not isinstance(obj, dict): + raise PilotRecordError(f"{path}: line {i + 1} is not an object") + out.append(obj) + return out, truncated + + +def yield_record(obj: dict[str, Any], source_line: int | None = None) -> YieldRecord: + version = obj.get("schema_version") + if version == YIELD_SCHEMA: + return YieldRecord.model_validate(obj) + if version is not None: + raise PilotRecordError(f"unsupported yield schema {version!r}") + if not obj.keys() >= _LEGACY_YIELD_KEYS: + missing = sorted(_LEGACY_YIELD_KEYS - obj.keys()) + raise PilotRecordError(f"legacy yield line lacks {missing}") + known = _LEGACY_YIELD_KEYS | { + "n0", + "sent_in_window", + "resolved", + "paid_attacker", + "error", + "skipped", + } + if extra := sorted(obj.keys() - known): + raise PilotRecordError(f"legacy yield line has unknown fields {extra}") + paid = obj.get("paid_attacker") + located = None if paid is None else bool(obj.get("resolved")) + return YieldRecord( + source_line=source_line, + victim=obj["victim"], + lookalike=obj["attacker"], + subtype=obj["type"], + window_from=obj["lo"], + window_to=obj["hi"], + nonce_before=obj.get("n0"), + signed_in_window=obj.get("sent_in_window"), + located_complete=located, + payments_to_lookalike=None + if paid is None + else tuple(PaymentObservation.model_validate(p) for p in paid), + error=obj.get("error"), + skipped=obj.get("skipped"), + requests=obj["requests"], + migrated_from="pilot-yield/legacy-1", + ) + + +def cost_record(obj: dict[str, Any]) -> CostRecord: + version = obj.get("schema_version") + if version == COST_SCHEMA: + return CostRecord.model_validate(obj) + if version is not None: + raise PilotRecordError(f"unsupported cost schema {version!r}") + if not obj.keys() >= _LEGACY_COST_KEYS: + raise PilotRecordError(f"legacy cost line lacks {sorted(_LEGACY_COST_KEYS - obj.keys())}") + lost = obj.get("error") == _LOST_CONTENTS + recorded = obj["result"] == "recorded" + return CostRecord( + draw=obj["draw"], + block=obj["block"], + wallet_sha=obj.get("wallet_sha"), + has_code=obj.get("has_code"), + nonce_end=obj.get("nonce_end"), + signed_in_window=obj.get("sends"), # nonce difference: recoverable from the log + result="recorded_contents_lost" if lost else obj["result"], + error=None if lost else obj.get("error"), + requests=obj["requests"], + record_requests=obj["requests"] - _LEGACY_ELIGIBILITY_REQUESTS + if lost + else obj.get("record_requests"), + transfers=obj.get("transfers") if recorded else None, + wallet_transactions=obj.get("transactions") if recorded else None, + outgoing_payments=obj.get("outgoing_payments") if recorded else None, + scan_complete=obj.get("scan_complete") if recorded else None, + migrated_from="pilot-cost/legacy-1", + ) + + +# --- reconstruction -------------------------------------------------------------------- + + +def wilson_upper(k: int, n: int, z: float = 1.959964) -> float | None: + if n == 0: + return None + if k == 0: + return z * z / (n + z * z) + p = k / n + centre = p + z * z / (2 * n) + spread = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return (centre + spread) / (1 + z * z / n) + + +def reconstruct( + pilot_dir: Path, candidates: list[tuple[int, str, str]] | None = None +) -> dict[str, Any]: + """Recompute the pilot report from its raw outputs. + + ``candidates``: ``(source_line, victim, lookalike)`` of the parser's valid rows in file + order; the yield file is checked against it row by row.""" + yield_raw, y_trunc = read_jsonl(pilot_dir / "yield.jsonl") + cost_raw, c_trunc = read_jsonl(pilot_dir / "cost.jsonl") + if candidates is not None: + if len(candidates) != len(yield_raw): + raise PilotRecordError( + f"{len(yield_raw)} yield lines for {len(candidates)} candidate rows" + ) + for (_, victim, lookalike), obj in zip(candidates, yield_raw, strict=True): + if (obj.get("victim"), obj.get("attacker", obj.get("lookalike"))) != ( + victim, + lookalike, + ): + raise PilotRecordError("yield lines are not in candidate order") + lines = [c[0] for c in candidates] if candidates else [None] * len(yield_raw) + ys = [yield_record(o, line) for o, line in zip(yield_raw, lines, strict=True)] + cs = [cost_record(o) for o in cost_raw] + budget = json.loads((pilot_dir / "budget.json").read_text(encoding="utf-8")) + summary = json.loads((pilot_dir / "summary.json").read_text(encoding="utf-8")) + plan_sha = hashlib.sha256((pilot_dir / "plan.json").read_bytes()).hexdigest() + + outcomes = Counter(y.outcome for y in ys) + events = Counter((y.victim, y.lookalike, y.window_from) for y in ys) + signed = [y.signed_in_window for y in ys if y.signed_in_window is not None] + complete = outcomes["no_direct_payment_observed_with_complete_declared_coverage"] + confirmed = outcomes["confirmed_direct_payment"] + located = [y for y in ys if y.payments_to_lookalike is not None] + yield_requests = sum(y.requests for y in ys) + cost_requests = sum(c.requests for c in cs) + recorded = [c for c in cs if c.result in ("recorded", "recorded_contents_lost")] + eligible = [ + c + for c in cs + if c.has_code is False and c.nonce_end is not None and 20 <= c.nonce_end <= 2_000 + ] + return { + "plan_sha256": plan_sha, + "truncated_tail": {"yield": y_trunc, "cost": c_trunc}, + "requests": { + "ledger_total": int(budget["requests"]), + "before_final_run": int(summary["started_used"]), + "yield_phase": yield_requests, + "cost_phase": cost_requests, + "run_overhead": int(summary["ended_used"]) + - int(summary["started_used"]) + - yield_requests + - cost_requests, + "cap": 3_000, + }, + "yield": { + "rows": len(ys), + "distinct_victim_events": len(events), + "duplicate_rows": len(ys) - len(events), + "distinct_victims": len({y.victim for y in ys}), + "distinct_lookalikes": len({y.lookalike for y in ys}), + "outcomes": {k: outcomes.get(k, 0) for k in Outcome.__args__}, # type: ignore[attr-defined] + "signed_zero": sum(1 for v in signed if v == 0), + "signed_1_8": sum(1 for v in signed if 1 <= v <= 8), + "signed_9_100": sum(1 for v in signed if 9 <= v <= 100), + "signed_over_100": sum(1 for v in signed if v > 100), + "located_rows": len(located), + "provider_errors": sum(1 for y in ys if y.error), + "migrated": sum(1 for y in ys if y.migrated_from), + "observed_complete": complete, + "confirmed": confirmed, + "conditional_wilson_upper_95": wilson_upper(confirmed, complete + confirmed), + "conditional_on": ( + "only rows with complete declared coverage; they are the less active victims " + "and not a random sample, so this bound does not extend to all 149 rows" + ), + }, + "cost": { + "draws": len(cs), + "results": dict(sorted(Counter(c.result for c in cs).items())), + "eligible": len(eligible), + "recorded_wallet_days": len(recorded), + "record_requests": sorted(c.record_requests for c in recorded if c.record_requests), + "recorded_signed_in_window": sorted( + c.signed_in_window for c in recorded if c.signed_in_window is not None + ), + "contents_lost": sum(1 for c in cs if c.result == "recorded_contents_lost"), + "unknown_payment_counts": sum(1 for c in recorded if c.outgoing_payments is None), + "rate_limited": sum(1 for c in cs if c.error and "RateLimited" in c.error), + }, + "seconds": summary.get("seconds"), + } + + +def render_markdown(report: dict[str, Any]) -> str: + y, c, r = report["yield"], report["cost"], report["requests"] + out = [ + "| Quantity | Value | Source |", + "|---|---|---|", + f"| Ledger total (cap {r['cap']}) | {r['ledger_total']} | `budget.json` |", + f"| Before the final run (smoke tests, probes) | {r['before_final_run']} " + "| `summary.json` |", + f"| Yield phase | {r['yield_phase']} | sum over `yield.jsonl` |", + f"| Cost phase | {r['cost_phase']} | sum over `cost.jsonl` |", + f"| Run overhead (chain check) | {r['run_overhead']} | difference |", + f"| Candidate rows / distinct victim-events | {y['rows']} / " + f"{y['distinct_victim_events']} | `yield.jsonl` |", + ] + for k, v in y["outcomes"].items(): + out.append(f"| Outcome `{k}` | {v} | derived |") + out += [ + f"| Signed 0 / 1-8 / 9-100 / >100 in window | {y['signed_zero']} / {y['signed_1_8']} / " + f"{y['signed_9_100']} / {y['signed_over_100']} | nonce differences |", + f"| Cost draws / eligible / recorded wallet-days | {c['draws']} / {c['eligible']} / " + f"{c['recorded_wallet_days']} | `cost.jsonl` |", + f"| Requests per recorded wallet-day | {', '.join(map(str, c['record_requests']))} | " + "`cost.jsonl` (minus 4 eligibility requests) |", + f"| Recordings whose contents were lost | {c['contents_lost']} | migration |", + ] + bound = y["conditional_wilson_upper_95"] + out.append( + f"| Conditional Wilson 95% upper bound | {bound:.3f} | {y['confirmed']} of " + f"{y['observed_complete'] + y['confirmed']} complete rows; not a population bound |" + if bound is not None + else "| Conditional bound | n/a | no complete rows |" + ) + return "\n".join(out) + "\n" diff --git a/src/cryptoguard/ml/planner.py b/src/cryptoguard/ml/planner.py new file mode 100644 index 0000000..a9a9f11 --- /dev/null +++ b/src/cryptoguard/ml/planner.py @@ -0,0 +1,82 @@ +"""Cost planner for a proposed wallet-history collection job. It never collects anything. + +Inputs are explicit assumptions (provider log range, transactions signed per wallet-window, +retry overhead); the output is a reproducible plan with a conservative request estimate that +is rejected when it exceeds the configured cap. Running a plan needs a separate, explicit +authorization; this module has no network code. + +Default assumptions come from the option A pilot on ``eth.drpc.org`` (free plan, 2026-11-01; +ML_PILOT_AUDIT.md) and do not describe other providers. +""" + +from __future__ import annotations + +import hashlib +import json +import math +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +PLAN_SCHEMA = "collection-plan/1" + + +class CollectionAssumptions(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + log_range_blocks: int = Field(100, ge=1) # largest accepted eth_getLogs range + log_queries_per_chunk: int = Field(2, ge=1) # incoming and outgoing transfer scans + requests_per_signed_tx: float = Field(26.0, gt=0) # nonce bisection + block + decode + fixed_requests_per_wallet: int = Field(10, ge=0) # chain check, nonces, code, timestamps + signed_tx_per_wallet_window_p90: float = Field(30.0, ge=0) + retry_overhead: float = Field(0.10, ge=0) # fraction added for retries + requests_per_second: float = Field(4.0, gt=0) + source: str = "option A pilot, eth.drpc.org free plan, 2026-11-01" + + +class CollectionJob(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + wallets: int = Field(ge=1, le=100_000) + window_blocks: int = Field(ge=1, le=2_628_000) # at most about a year + request_cap: int = Field(ge=0) + expected_coverage: float = Field(0.8, gt=0, le=1) # share of wallets fully resolved + + +class PlanRejected(ValueError): + pass + + +def plan(job: CollectionJob, a: CollectionAssumptions | None = None) -> dict[str, Any]: + """Conservative estimate; raises ``PlanRejected`` above the cap.""" + a = a or CollectionAssumptions() + chunks = math.ceil(job.window_blocks / a.log_range_blocks) + per_wallet = ( + chunks * a.log_queries_per_chunk + + a.signed_tx_per_wallet_window_p90 * a.requests_per_signed_tx + + a.fixed_requests_per_wallet + ) + per_wallet_with_retries = math.ceil(per_wallet * (1 + a.retry_overhead)) + total = per_wallet_with_retries * job.wallets + body: dict[str, Any] = { + "schema": PLAN_SCHEMA, + "job": job.model_dump(), + "assumptions": a.model_dump(), + "estimate": { + "log_requests_per_wallet": chunks * a.log_queries_per_chunk, + "requests_per_wallet_conservative": per_wallet_with_retries, + "total_requests_conservative": total, + "expected_fully_resolved_wallets": math.floor(job.wallets * job.expected_coverage), + "hours_at_assumed_throughput": round(total / a.requests_per_second / 3600, 2), + }, + "within_cap": total <= job.request_cap, + "executes": False, + "requires": "explicit user authorization of this plan's request cap before any run", + } + body["plan_sha256"] = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + if total > job.request_cap: + raise PlanRejected( + f"estimated {total} requests exceed the cap of {job.request_cap}: " + + json.dumps(body["estimate"]) + ) + return body diff --git a/src/cryptoguard/ml/poison_hunter.py b/src/cryptoguard/ml/poison_hunter.py new file mode 100644 index 0000000..af4956b --- /dev/null +++ b/src/cryptoguard/ml/poison_hunter.py @@ -0,0 +1,256 @@ +"""Typed parser for Poison-Hunter's ``phishing_transfers_sample.csv`` (150 planting transfers). + +The file has a 15-name header and 17 fields per row. Field identification (checked on all +150 rows of the pinned revision; see ML_POISONING_DATASET.md): + +==== ========================== ==================================================== +idx header name observed content +==== ========================== ==================================================== +0 attacker lowercase address: the lookalike that sent the planting +1 victim lowercase address: the wallet the planting targeted +2 similar_norm lowercase address: the address the lookalike imitates +3 tx_hash planting transaction hash (shared by batched rows) +4 symbol ``usdc`` or ``usdt``: the token imitated +5 phishing_type ``dust`` / ``zero`` / ``fake`` +6 fake_token_address token contract emitting the planting log: the genuine + USDC/USDT for ``dust``/``zero``, a fake token for ``fake`` +7 fake_token_deployer deployer of the fake token (empty unless ``fake``) +8 tx_from planting transaction signer (= attacker for ``dust``; a + batch operator for ``zero``/``fake``) +9 tx_to transaction target (the token for ``dust``, a batch + contract otherwise) +10 tx_fee fee in ETH +11 is_batching batch size (a count, not a flag; 1 for ``dust``) +12 batch_contract_deployer batch contract deployer (empty for ``dust``) +13 block_number planting block +14 block_distance blocks since the victim's imitated transfer (inferred) +15 (unnamed) ``from``/``to``: direction of the imitated transfer +16 (unnamed) small integer, close to the matched hex-character count +==== ========================== ==================================================== + +The header is aligned for fields 0-14; fields 15-16 are unnamed and their meaning is +inferred, not documented by the source. Two names do not describe their content (6, 11). + +Labels from this file are **weak**: they come from the source's pipeline (Etherscan/Forta +ground truth plus their detector), not from independent review. Structural validity is not +proof that a planting was malicious. The source has no license: the raw file stays local. +""" + +from __future__ import annotations + +import csv +import hashlib +import re +from collections import Counter +from pathlib import Path +from typing import Literal + +from pydantic import BaseModel, ConfigDict + +from cryptoguard.detectors.poisoning import PoisoningConfig, affix_match, is_lookalike + +PARSER_VERSION = "poison-hunter-sample/1" +SOURCE_REPOSITORY = "DS2L/Poison-Hunter" +SOURCE_FILE = "phishing_transfers_sample.csv" +EXPECTED_HEADER = [ + "attacker", + "victim", + "similar_norm", + "tx_hash", + "symbol", + "phishing_type", + "fake_token_address", + "fake_token_deployer", + "tx_from", + "tx_to", + "tx_fee", + "is_batching", + "batch_contract_deployer", + "block_number", + "block_distance", +] +FIELDS = 17 +STUDY_BLOCKS = (15_000_000, 19_500_000) # Nov 2022 - Feb 2024 per the source, with margin +MIN_AFFIX_TOTAL = 5 # below any published lookalike definition (CryptoGuard, Tsuchiya 3+4) + +_ADDR = re.compile(r"^0x[0-9a-f]{40}$") +_ADDR_ANY_CASE = re.compile(r"^0x[0-9a-fA-F]{40}$") +_HASH = re.compile(r"^0x[0-9a-f]{64}$") + +Subtype = Literal["dust", "zero", "fake"] +Status = Literal["valid", "quarantined"] + + +class PoisonHunterRecord(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + source_line: int # 1-based line in the CSV (header = line 1) + status: Status + issues: tuple[str, ...] + lookalike: str + victim: str + imitated: str + planting_tx: str + token_symbol: str + subtype: str + log_contract: str # contract that emitted the planting Transfer log + fake_token_deployer: str | None + tx_signer: str + tx_target: str + batch_size: int | None + block_number: int | None + block_distance: int | None + imitated_direction: str | None + source_similarity: int | None + prefix_match: int + suffix_match: int + cryptoguard_lookalike: bool # CryptoGuard's detector predicate (for comparison only) + tsuchiya_lookalike: bool # >= 3 leading and >= 4 trailing hex characters + + +class ParseResult(BaseModel): + model_config = ConfigDict(extra="forbid") + + parser_version: str + source_sha256: str + header: list[str] + records: list[PoisonHunterRecord] + + @property + def valid(self) -> list[PoisonHunterRecord]: + return [r for r in self.records if r.status == "valid"] + + @property + def quarantined(self) -> list[PoisonHunterRecord]: + return [r for r in self.records if r.status == "quarantined"] + + +class SchemaMismatchError(ValueError): + """The file's header or row width differs from the identified layout: refuse to guess.""" + + +def _int(text: str) -> int | None: + try: + return int(float(text)) if text.strip() else None + except ValueError: + return None + + +def _parse_row(line: int, r: list[str], config: PoisoningConfig) -> PoisonHunterRecord: + issues: list[str] = [] + lookalike, victim, imitated = (r[0].lower(), r[1].lower(), r[2].lower()) + for name, value in (("attacker", r[0]), ("victim", r[1]), ("similar_norm", r[2])): + if not _ADDR.match(value): + issues.append(f"{name} is not a lowercase address") + for name, value in (("tx_from", r[8]), ("tx_to", r[9]), ("token", r[6])): + if not _ADDR_ANY_CASE.match(value): + issues.append(f"{name} is not an address") + if not _HASH.match(r[3]): + issues.append("tx_hash is not a 32-byte hash") + if r[5] not in ("dust", "zero", "fake"): + issues.append(f"unknown phishing_type {r[5]!r}") + block = _int(r[13]) + if block is None or not STUDY_BLOCKS[0] <= block <= STUDY_BLOCKS[1]: + issues.append("block_number missing or outside the source's study period") + if victim in (imitated, lookalike): + issues.append("victim equals the imitated or lookalike address") + if r[5] == "dust" and r[8].lower() != lookalike: + issues.append("dust planting not signed by the lookalike") + if r[5] == "fake" and not r[7]: + issues.append("fake planting without a fake-token deployer") + if r[15] not in ("from", "to"): + issues.append(f"unknown direction field {r[15]!r}") + elif r[15] == "to": + issues.append("only direction 'to' row: imitation mapping for this direction unverified") + valid_addresses = bool(_ADDR_ANY_CASE.match(r[0]) and _ADDR_ANY_CASE.match(r[2])) + prefix, suffix = affix_match(lookalike, imitated) if valid_addresses else (0, 0) + if valid_addresses and prefix + suffix < MIN_AFFIX_TOTAL: + issues.append( + f"lookalike shares {prefix}+{suffix} hex characters with the imitated address, " + "below any published lookalike definition" + ) + return PoisonHunterRecord( + source_line=line, + status="quarantined" if issues else "valid", + issues=tuple(issues), + lookalike=lookalike, + victim=victim, + imitated=imitated, + planting_tx=r[3].lower(), + token_symbol=r[4], + subtype=r[5], + log_contract=r[6].lower(), + fake_token_deployer=r[7].lower() or None, + tx_signer=r[8].lower(), + tx_target=r[9].lower(), + batch_size=_int(r[11]), + block_number=block, + block_distance=_int(r[14]), + imitated_direction=r[15] or None, + source_similarity=_int(r[16]), + prefix_match=prefix, + suffix_match=suffix, + cryptoguard_lookalike=bool(valid_addresses and is_lookalike(lookalike, imitated, config)), + tsuchiya_lookalike=prefix >= 3 and suffix >= 4, + ) + + +def parse_sample(path: Path, config: PoisoningConfig | None = None) -> ParseResult: + """Parse every row; rows failing a check are quarantined with reasons, never dropped.""" + config = config or PoisoningConfig() + raw = path.read_bytes() + with path.open(newline="", encoding="utf-8") as fh: + rows = list(csv.reader(fh)) + if not rows or rows[0] != EXPECTED_HEADER: + raise SchemaMismatchError(f"{path}: header differs from the identified layout") + widths = Counter(len(r) for r in rows[1:]) + if set(widths) != {FIELDS}: + raise SchemaMismatchError(f"{path}: expected {FIELDS} fields per row, got {dict(widths)}") + records = [_parse_row(i + 2, r, config) for i, r in enumerate(rows[1:])] + return ParseResult( + parser_version=PARSER_VERSION, + source_sha256=hashlib.sha256(raw).hexdigest(), + header=rows[0], + records=records, + ) + + +def profile(result: ParseResult) -> dict[str, object]: + """Aggregate validation report (no addresses): counts, reuse, duplicates, similarity.""" + rs = result.records + valid = result.valid + pairs = Counter((r.planting_tx, r.victim, r.lookalike) for r in rs) + return { + "parser_version": result.parser_version, + "source_sha256": result.source_sha256, + "rows": len(rs), + "valid": len(valid), + "quarantined": [ + {"line": r.source_line, "issues": list(r.issues)} for r in result.quarantined + ], + "subtypes": dict(Counter(r.subtype for r in rs)), + "distinct_victims": len({r.victim for r in valid}), + "distinct_lookalikes": len({r.lookalike for r in valid}), + "distinct_planting_txs": len({r.planting_tx for r in valid}), + "planting_txs_with_several_rows": sum( + 1 for c in Counter(r.planting_tx for r in valid).values() if c > 1 + ), + "duplicate_victim_events": sum(c - 1 for c in pairs.values() if c > 1), + "victims_in_several_rows": sum( + 1 for c in Counter(r.victim for r in valid).values() if c > 1 + ), + "lookalikes_in_several_rows": sum( + 1 for c in Counter(r.lookalike for r in valid).values() if c > 1 + ), + "block_range": [ + min(r.block_number for r in valid if r.block_number), + max(r.block_number for r in valid if r.block_number), + ] + if valid + else None, + "cryptoguard_lookalike": sum(r.cryptoguard_lookalike for r in valid), + "tsuchiya_lookalike": sum(r.tsuchiya_lookalike for r in valid), + "source_similarity_equals_prefix_plus_suffix": sum( + 1 for r in valid if r.source_similarity == r.prefix_match + r.suffix_match + ), + } diff --git a/src/cryptoguard/ml/poisoning_report.py b/src/cryptoguard/ml/poisoning_report.py new file mode 100644 index 0000000..4f56e11 --- /dev/null +++ b/src/cryptoguard/ml/poisoning_report.py @@ -0,0 +1,291 @@ +"""Offline Phase 11.2 report: Poison-Hunter validation, pilot reconstruction, candidate +generation on the recorded replay fixtures, and the dataset decision gates (0 RPC requests). + +Every number in ML_PILOT_AUDIT.md and ML_POISONING_DATASET.md is produced here from local +artifacts, and the JSON written next to the tables records their hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import platform +import subprocess +import time +import tracemalloc +from pathlib import Path +from typing import Any + +from cryptoguard.ml.candidates import ( + CANDIDATE_VERSION, + EVENT_FEATURE_VERSION, + PriorIndex, + event_features, + generate_with_stats, +) +from cryptoguard.ml.events import ( + TASK_ID, + LabelRecord, + PoisoningEvent, + campaign_groups, + deduplicate, + manifest, + quality_gates, + resolve_labels, +) +from cryptoguard.ml.history import events_from_fixture +from cryptoguard.ml.pilot import reconstruct, render_markdown +from cryptoguard.ml.poison_hunter import PoisonHunterRecord, parse_sample, profile + +_SUBTYPE = {"dust": "dust", "zero": "zero_value", "fake": "fake_token"} + + +def poison_hunter_events(records: list[PoisonHunterRecord]) -> list[PoisoningEvent]: + """Valid Poison-Hunter rows as events (weak labels; no wallet history recorded).""" + return [ + PoisoningEvent( + chain_id=1, + victim=r.victim, + lookalike=r.lookalike, + imitated=r.imitated, + planting_tx=r.planting_tx, + planting_block=r.block_number or 0, + planting_tx_index=None, + planting_log_index=None, # not in the source: batch rows differ by victim only + observation_timestamp=None, + subtype=_SUBTYPE.get(r.subtype, "unknown"), + tx_signer=r.tx_signer, + log_contract=r.log_contract, + token_contract=r.log_contract if r.subtype != "fake" else None, + candidate_method=f"poison-hunter-sample:line{r.source_line}", + coverage="unavailable", + ) + for r in records + if r.status == "valid" + ] + + +def _git_sha() -> str | None: + try: + out = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + timeout=10, + check=False, + ) + except OSError: + return None + return out.stdout.strip() or None + + +def candidate_evaluation() -> dict[str, Any]: + """Candidate recall on the 4 recorded incidents and candidate volume on background + wallets. The incidents were used while developing the detector: not untouched data.""" + from cryptoguard.replay.background import load_background + from cryptoguard.replay.engine import replay + from cryptoguard.replay.models import load_cases + + index = PriorIndex() + incidents: list[dict[str, Any]] = [] + for case in load_cases(): + m, fx = case.manifest, case.fixture + if fx is None: + continue + cands, stats = generate_with_stats(fx) + harm = m.harm.recipient.lower() + hits = [ + c + for c in cands + if c.event.lookalike == harm and c.event.planting_block <= m.harm.block_number + ] + events, coverage = events_from_fixture(fx) + feats = [event_features(c, events, coverage, index) for c in hits[:1]] + for c in cands: + index.add(c.event) + detector = replay(m, fx) + lead = [r.lead_time_blocks for r in detector.results if r.lead_time_blocks is not None] + incidents.append( + { + "case": m.case_id, + "candidates": stats.candidates, + "by_method": stats.by_method, + "harmful_lookalike_found": bool(hits), + "candidate_lead_blocks": ( + m.harm.block_number - min(c.event.planting_block for c in hits) + if hits + else None + ), + "detector_best_lead_blocks": max(lead) if lead else None, + "first_hit_methods": list(hits[0].methods) if hits else [], + "first_hit_history_status": feats[0].history.history_status if feats else None, + "runtime_ms": stats.runtime_ms, + "peak_kib": stats.peak_kib, + } + ) + background: list[dict[str, Any]] = [] + for bg in load_background(): + fx = bg.fixture + if fx is None: + continue + cands, stats = generate_with_stats(fx) + background.append( + { + "case": fx.case_id, + "blocks": fx.to_block - fx.from_block + 1, + "candidates": stats.candidates, + "by_method": stats.by_method, + } + ) + blocks = sum(b["blocks"] for b in background) + return { + "version": CANDIDATE_VERSION, + "incidents": incidents, + "incident_recall": f"{sum(i['harmful_lookalike_found'] for i in incidents)}/" + f"{len(incidents)}", + "background": background, + "background_candidates_per_wallet_day": round( + sum(b["candidates"] for b in background) / (blocks / 7_200), 3 + ) + if blocks + else None, + "caveat": "Incidents were used during detector development; background candidates " + "are unlabelled (not false positives).", + } + + +def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: + tracemalloc.start() + t0 = time.perf_counter() + sample = data_dir / "poison-hunter" / "phishing_transfers_sample.csv" + parsed = parse_sample(sample) + ph = profile(parsed) + events, dropped = deduplicate(poison_hunter_events(parsed.records)) + labels = [ + LabelRecord( + victim_event_id=e.victim_event_id, + tier="weak_attempt", + source="poison-hunter-sample", + available_at="2024 (publication)", + ) + for e in events + ] + resolved = resolve_labels(labels) + groups = campaign_groups(events) + gates = quality_gates(events, resolved, license_ok=False) + candidates = [(r.source_line, r.victim, r.lookalike) for r in parsed.valid] + pilot = reconstruct(pilot_dir, candidates) if (pilot_dir / "yield.jsonl").exists() else None + cand_eval = candidate_evaluation() + runtime = time.perf_counter() - t0 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + return { + "task": TASK_ID, + "git": _git_sha(), + "python": platform.python_version(), + "versions": {"candidates": CANDIDATE_VERSION, "event_features": EVENT_FEATURE_VERSION}, + "poison_hunter": ph, + "events": { + "victim_events": len(events), + "duplicates_dropped": dropped, + "campaign_groups": len(set(groups.values())), + "largest_group": max( + (list(groups.values()).count(g) for g in set(groups.values())), default=0 + ), + "manifest": manifest(events, labels), + "label_tiers": { + t: list(resolved.values()).count(t) for t in sorted(set(resolved.values())) + }, + }, + "gates": [g.model_dump() for g in gates], + "pilot": pilot, + "candidates": cand_eval, + "runtime_seconds": round(runtime, 2), + "peak_python_mib": round(peak / 2**20, 1), + "rpc_requests": 0, + } + + +def render(report: dict[str, Any]) -> str: + ph, ev, cand = report["poison_hunter"], report["events"], report["candidates"] + lines = [ + "# ML Phase 11.2 tables", + "", + "Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests).", + f"Git `{report['git']}`; runtime {report['runtime_seconds']} s; peak Python heap " + f"{report['peak_python_mib']} MiB.", + "", + "## Poison-Hunter sample", + "", + "| Quantity | Value |", + "|---|---|", + f"| Source SHA-256 | `{ph['source_sha256'][:16]}…` (matches the pinned hash) |", + f"| Rows / valid / quarantined | {ph['rows']} / {ph['valid']} / {len(ph['quarantined'])} |", + f"| Subtypes | {', '.join(f'{k} {v}' for k, v in ph['subtypes'].items())} |", + f"| Distinct victims / lookalikes / planting txs | {ph['distinct_victims']} / " + f"{ph['distinct_lookalikes']} / {ph['distinct_planting_txs']} |", + f"| Planting txs with several rows (batches) | {ph['planting_txs_with_several_rows']} |", + f"| Duplicate victim-events | {ph['duplicate_victim_events']} |", + f"| Victims / lookalikes in several rows | {ph['victims_in_several_rows']} / " + f"{ph['lookalikes_in_several_rows']} |", + f"| Block range | {ph['block_range'][0]:,}-{ph['block_range'][1]:,} |", + f"| Lookalike by CryptoGuard's detector predicate | {ph['cryptoguard_lookalike']} of " + f"{ph['valid']} |", + f"| Lookalike by Tsuchiya et al. (≥3 leading, ≥4 trailing) | {ph['tsuchiya_lookalike']} " + f"of {ph['valid']} |", + f"| Source field 16 equals prefix+suffix match | " + f"{ph['source_similarity_equals_prefix_plus_suffix']} of {ph['valid']} |", + "", + ] + for q in ph["quarantined"]: + lines.append(f"Quarantined line {q['line']}: " + "; ".join(q["issues"]) + ".") + lines += [ + "", + "## Event dataset and gates", + "", + f"{ev['victim_events']} victim-events after dropping {ev['duplicates_dropped']} " + f"duplicates; {ev['campaign_groups']} campaign groups (largest {ev['largest_group']} " + f"events); labels: {ev['label_tiers']}; manifest `{ev['manifest']['sha256'][:16]}…`.", + "", + "| Gate | Passed | Detail |", + "|---|---|---|", + *( + f"| {g['gate']} | {'yes' if g['passed'] else '**no**'} | {g['detail']} |" + for g in report["gates"] + ), + "", + ] + if report["pilot"] is not None: + lines += ["## Pilot reconstruction", "", render_markdown(report["pilot"])] + lines += [ + "## Candidate generation (recorded replay fixtures)", + "", + "| Incident | Candidates | Harmful lookalike found | Candidate lead (blocks) | " + "Detector lead (blocks) | First-hit rules |", + "|---|---|---|---|---|---|", + ] + for i in cand["incidents"]: + lines.append( + f"| {i['case']} | {i['candidates']} | {'yes' if i['harmful_lookalike_found'] else 'no'}" + f" | {i['candidate_lead_blocks']} | {i['detector_best_lead_blocks']} | " + f"{', '.join(i['first_hit_methods'])} |" + ) + lines += [ + "", + f"Background wallets: {len(cand['background'])} recorded windows, " + f"{sum(b['candidates'] for b in cand['background'])} candidates, " + f"{cand['background_candidates_per_wallet_day']} per wallet-day (unlabelled). " + + cand["caveat"], + "", + ] + return "\n".join(lines) + + +def write(report: dict[str, Any], out_dir: Path, tables: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + text = render(report) + tables.write_text(text, encoding="utf-8", newline="\n") + report = {**report, "tables_sha256": hashlib.sha256(text.encode()).hexdigest()} + path = out_dir / "poisoning-report.json" + path.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8") + return path diff --git a/src/cryptoguard/ml/review.py b/src/cryptoguard/ml/review.py new file mode 100644 index 0000000..156988c --- /dev/null +++ b/src/cryptoguard/ml/review.py @@ -0,0 +1,119 @@ +"""Offline label review for candidate poisoning events (no hosted service). + +``export_packets`` writes one JSON line per event with the evidence a reviewer needs and +nothing else: no model score is included, so the independent label is not anchored on the +model. ``import_reviews`` validates returned decisions and appends them to a label history; +earlier labels and disagreements are kept, never overwritten (``events.resolve_labels`` +turns verified disagreement into ``conflicting``). +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable, Sequence +from pathlib import Path +from typing import Literal + +from pydantic import BaseModel, ConfigDict, ValidationError + +from cryptoguard.ml.events import LabelRecord, LabelTier, PoisoningEvent + +REVIEW_SCHEMA = "poisoning-review/1" + +Decision = Literal[ + "confirmed_poisoning_attempt", + "likely_poisoning_attempt", + "confirmed_legitimate_interaction", + "insufficient_evidence", + "conflicting_evidence", +] +DECISION_TIER: dict[str, LabelTier] = { + "confirmed_poisoning_attempt": "verified_attempt", + "likely_poisoning_attempt": "weak_attempt", + "confirmed_legitimate_interaction": "verified_legitimate", + "insufficient_evidence": "unknown", + "conflicting_evidence": "conflicting", +} + + +class ReviewPacket(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-review/1"] = "poisoning-review/1" + victim_event_id: str + victim: str + lookalike: str + imitated: str | None + planting_tx: str + observation_block: int + subtype: str + evidence_summary: str + coverage_limitations: str + source_labels: tuple[str, ...] + + +class ReviewDecision(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-review/1"] = "poisoning-review/1" + victim_event_id: str + decision: Decision + rationale: str + reviewer: str # pseudonym + reviewed_at: str # ISO timestamp + + +class ReviewImportError(ValueError): + pass + + +def packet(event: PoisoningEvent, source_labels: Sequence[str], evidence: str) -> ReviewPacket: + limits = { + "complete": "wallet window fully observed", + "partial": "wallet history incomplete: unobserved events may exist", + "unavailable": "no wallet history observed", + }[event.coverage] + return ReviewPacket( + victim_event_id=event.victim_event_id, + victim=event.victim, + lookalike=event.lookalike, + imitated=event.imitated, + planting_tx=event.planting_tx, + observation_block=event.planting_block, + subtype=event.subtype, + evidence_summary=evidence, + coverage_limitations=limits, + source_labels=tuple(source_labels), + ) + + +def export_packets(packets: Iterable[ReviewPacket], path: Path) -> int: + lines = [p.model_dump_json() for p in sorted(packets, key=lambda p: p.victim_event_id)] + path.write_text("".join(line + "\n" for line in lines), encoding="utf-8", newline="\n") + return len(lines) + + +def import_reviews( + path: Path, known_events: set[str], history: list[LabelRecord] +) -> list[LabelRecord]: + """Validate every decision first (all or nothing), then append to ``history``.""" + new: list[LabelRecord] = [] + for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + if not line.strip(): + continue + try: + d = ReviewDecision.model_validate(json.loads(line)) + except (json.JSONDecodeError, ValidationError) as exc: + raise ReviewImportError(f"{path}: line {i}: {exc}") from None + if d.victim_event_id not in known_events: + raise ReviewImportError(f"{path}: line {i}: unknown event {d.victim_event_id}") + new.append( + LabelRecord( + victim_event_id=d.victim_event_id, + tier=DECISION_TIER[d.decision], + source=f"review:{d.reviewer}", + available_at=d.reviewed_at, + rationale=d.rationale, + ) + ) + return [*history, *new] diff --git a/tests/unit/test_ml_poisoning.py b/tests/unit/test_ml_poisoning.py new file mode 100644 index 0000000..18aa954 --- /dev/null +++ b/tests/unit/test_ml_poisoning.py @@ -0,0 +1,613 @@ +# ruff: noqa: E501 (tabular test cases are kept on one line each) +"""Phase 11.2: poisoning research data model, parser, pilot records, payment verification, +candidate generation, point-in-time features, review workflow, planner and monitoring. + +Synthetic data only (no RPC, no third-party files). Each test states the invariant it guards. +""" + +from __future__ import annotations + +import csv +import json +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import candidates as cand +from cryptoguard.ml.events import ( + LabelRecord, + PoisoningEvent, + campaign_groups, + deduplicate, + grouped_temporal_split, + manifest, + quality_gates, + resolve_labels, +) +from cryptoguard.ml.history import events_from_fixture +from cryptoguard.ml.monitoring import missing_share, psi, reference_bins +from cryptoguard.ml.payments import verify_payment +from cryptoguard.ml.pilot import ( + PilotRecordError, + YieldRecord, + cost_record, + read_jsonl, + reconstruct, + render_markdown, + summarize_fixture, + summarize_fixture_json, + yield_record, +) +from cryptoguard.ml.planner import CollectionJob, PlanRejected, plan +from cryptoguard.ml.poison_hunter import ( + EXPECTED_HEADER, + SchemaMismatchError, + parse_sample, + profile, +) +from cryptoguard.ml.review import ReviewImportError, export_packets, import_reviews, packet +from cryptoguard.replay.models import RecordedTransaction, RecordedTransfer, ReplayFixture + +WALLET = "0x" + "11" * 20 +FRIEND = "0xd296222fb44f5ec8d9600a8c91ed70ed5657d7d5" +LOOKALIKE = "0xd296261b103d698c272887274f38d7ea8097d7d5" +STRANGER = "0x" + "3c" * 20 +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +FAKE = "0x" + "fa" * 20 +TX = "0x" + "ab" * 32 + + +def h(n: int) -> str: + return "0x" + f"{n:064x}" + + +# --- Poison-Hunter parser ------------------------------------------------------------- + + +def ph_row(**over: str) -> list[str]: + row = { + 0: LOOKALIKE, 1: WALLET, 2: FRIEND, 3: h(1), 4: "usdt", 5: "dust", 6: USDT, 7: "", + 8: LOOKALIKE, 9: USDT, 10: "0.001", 11: "1.0", 12: "", 13: "16000000", 14: "12", + 15: "from", 16: "10", + } # fmt: skip + for k, v in over.items(): + row[int(k[1:])] = v + return [row[i] for i in range(17)] + + +def write_ph(path: Path, rows: list[list[str]], header: list[str] = EXPECTED_HEADER) -> Path: + with path.open("w", newline="", encoding="utf-8") as fh: + w = csv.writer(fh) + w.writerow(header) + w.writerows(rows) + return path + + +def test_parser_maps_fields_and_keeps_provenance(tmp_path: Path) -> None: + res = parse_sample(write_ph(tmp_path / "s.csv", [ph_row()])) + (r,) = res.records + assert r.status == "valid" + assert (r.lookalike, r.victim, r.imitated) == (LOOKALIKE, WALLET, FRIEND) + assert r.source_line == 2 # traceable to the original row + assert (r.prefix_match, r.suffix_match) == (5, 5) + assert len(res.source_sha256) == 64 + + +def test_header_or_width_changes_are_refused(tmp_path: Path) -> None: + with pytest.raises(SchemaMismatchError): + parse_sample(write_ph(tmp_path / "a.csv", [ph_row()], header=EXPECTED_HEADER[1:])) + with pytest.raises(SchemaMismatchError): + parse_sample(write_ph(tmp_path / "b.csv", [ph_row()[:16]])) + + +def test_bad_rows_are_quarantined_with_reasons_not_dropped(tmp_path: Path) -> None: + rows = [ + ph_row(c3="0x123"), # malformed hash + ph_row(c2="0x" + "99" * 20), # imitated address not similar at all + ph_row(c15="to"), # the unverified direction + ph_row(c13="", c0="0xZZ"), # missing block, malformed address + ] + res = parse_sample(write_ph(tmp_path / "s.csv", rows)) + assert len(res.records) == 4 + assert all(r.status == "quarantined" and r.issues for r in res.records) + assert any("below any published lookalike" in i for i in res.records[1].issues) + + +def test_batch_planting_and_duplicates_are_profiled(tmp_path: Path) -> None: + other = "0x" + "22" * 20 + batch = dict(c5="zero", c8=STRANGER, c9=FAKE, c11="2.0", c12=STRANGER) + rows = [ph_row(**batch), ph_row(**batch, c1=other), ph_row(**batch)] + p = profile(parse_sample(write_ph(tmp_path / "s.csv", rows))) + assert p["distinct_planting_txs"] == 1 + assert p["planting_txs_with_several_rows"] == 1 + assert p["duplicate_victim_events"] == 1 # the third row repeats the first victim-event + + +# --- pilot records: the lost-data bug and its migration --------------------------------- + + +def fixture( + transfers: list[RecordedTransfer], txs: list[RecordedTransaction], **kw: Any +) -> ReplayFixture: + base: dict[str, Any] = dict( + case_id="t", chain_id=1, wallet=WALLET, from_block=100, to_block=10_000, + recorded_at=datetime(2026, 1, 1, tzinfo=UTC), recorded_with="test", rpc_requests=0, + transfer_scan_complete=True, sender_lookups_skipped=0, method=[], wallet_code_hex={}, + block_timestamps={}, + ) # fmt: skip + base.update(kw) + return ReplayFixture(**base, transfers=transfers, wallet_transactions=txs) + + +def transfer(block: int, sender: str, recipient: str, value: int, *, token: str = USDT, + tx_sender: str | None = None, idx: int = 0, log: int = 0) -> RecordedTransfer: # fmt: skip + return RecordedTransfer( + token=token, sender=sender, recipient=recipient, value=str(value), block_number=block, + block_hash=h(block), transaction_hash=h(block * 1000 + idx * 10 + log), + transaction_index=idx, log_index=log, tx_sender=tx_sender, + ) # fmt: skip + + +def eth_tx(block: int, to: str, value: int, *, succeeded: bool | None = True, idx: int = 0) -> RecordedTransaction: # fmt: skip + return RecordedTransaction( + transaction_hash=h(block * 7 + idx), block_number=block, transaction_index=idx, nonce=block, + to=to, value=str(value), succeeded=succeeded, + ) # fmt: skip + + +def test_summary_reads_wallet_transactions_and_counts_payments() -> None: + fx = fixture( + [ + transfer(200, WALLET, FRIEND, 5, tx_sender=WALLET), # a payment + transfer(210, WALLET, LOOKALIKE, 0, tx_sender=LOOKALIKE), # spoofed, not a payment + ], + [eth_tx(300, FRIEND, 10**18), eth_tx(310, FRIEND, 10**18, succeeded=False)], + ) + s = summarize_fixture(fx) + assert (s.wallet_transactions, s.outgoing_payments, s.transfers) == (2, 2, 2) + + +def test_empty_valid_history_is_a_real_zero() -> None: + s = summarize_fixture(fixture([], [])) + assert (s.wallet_transactions, s.outgoing_payments, s.scan_complete) == (0, 0, True) + + +def test_old_field_name_or_missing_field_raises_instead_of_reading_zero() -> None: + good = json.loads(fixture([], [eth_tx(300, FRIEND, 1)]).model_dump_json()) + renamed = dict(good) + renamed["transactions"] = renamed.pop("wallet_transactions") # the pilot's misreading + with pytest.raises(PilotRecordError): + summarize_fixture_json(renamed) + missing = {k: v for k, v in good.items() if k != "wallet_transactions"} + with pytest.raises(PilotRecordError): + summarize_fixture_json(missing) + wrong_type = dict(good, wallet_transactions="none") + with pytest.raises(PilotRecordError): + summarize_fixture_json(wrong_type) + assert summarize_fixture_json(good).wallet_transactions == 1 + + +def test_lost_recordings_migrate_to_unknown_not_zero() -> None: + legacy = { + "block": 5, "draw": 7, "has_code": False, "nonce_end": 176, "requests": 228, + "result": "error", "sends": 6, "wallet_sha": "ee", + "error": "AttributeError: 'ReplayFixture' object has no attribute 'transactions'", + } # fmt: skip + rec = cost_record(legacy) + assert rec.result == "recorded_contents_lost" + assert rec.outgoing_payments is None and rec.wallet_transactions is None # noqa: PT018 + assert rec.signed_in_window == 6 # recoverable: the nonce difference was logged + assert rec.record_requests == 224 + assert rec.migrated_from == "pilot-cost/legacy-1" + + +def test_unknown_schema_versions_and_fields_are_rejected() -> None: + with pytest.raises(PilotRecordError): + yield_record({"schema_version": "pilot-yield/9"}) + with pytest.raises(PilotRecordError): + yield_record({"victim": WALLET, "attacker": LOOKALIKE, "type": "dust", "lo": 1, "hi": 2, + "requests": 2, "surprise": 1}) # fmt: skip + with pytest.raises(PilotRecordError): + cost_record({"draw": 1}) + + +def _legacy_yield(**kw: Any) -> dict[str, Any]: + base = {"victim": WALLET, "attacker": LOOKALIKE, "type": "dust", "lo": 101, "hi": 50_500, + "n0": 3, "requests": 2} # fmt: skip + base.update(kw) + return base + + +@pytest.mark.parametrize( + ("kw", "outcome"), + [ + (dict(sent_in_window=0, resolved=True), "no_direct_payment_observed_with_complete_declared_coverage"), + (dict(sent_in_window=2, resolved=True, paid_attacker=[]), "no_direct_payment_observed_with_complete_declared_coverage"), + (dict(sent_in_window=2, resolved=False, paid_attacker=[]), "partial_coverage"), + (dict(sent_in_window=40, resolved=False), "unresolved"), + (dict(sent_in_window=3, resolved=False, skipped="phase_cap"), "not_evaluated"), + (dict(error="RpcTimeoutError", resolved=False), "unresolved"), + (dict(sent_in_window=1, resolved=True, + paid_attacker=[{"tx": TX, "kind": "eth", "succeeded": True}]), "confirmed_direct_payment"), + (dict(sent_in_window=1, resolved=True, + paid_attacker=[{"tx": TX, "kind": "eth", "succeeded": False}]), + "no_direct_payment_observed_with_complete_declared_coverage"), + ], +) # fmt: skip +def test_outcomes_never_call_an_unobserved_victim_benign(kw: dict[str, Any], outcome: str) -> None: + assert yield_record(_legacy_yield(**kw)).outcome == outcome + + +def test_jsonl_cut_off_tail_is_skipped_and_middle_corruption_raises(tmp_path: Path) -> None: + p = tmp_path / "y.jsonl" + p.write_text('{"a": 1}\n{"a": 2}\n{"a": 3', encoding="utf-8") + rows, truncated = read_jsonl(p) + assert rows == [{"a": 1}, {"a": 2}] + assert truncated + p.write_text('{"a": 1}\n{broken\n{"a": 3}\n', encoding="utf-8") + with pytest.raises(PilotRecordError, match="corrupt line 2"): + read_jsonl(p) + + +def _pilot_dir(tmp_path: Path) -> Path: + d = tmp_path / "pilot" + d.mkdir() + ys = [_legacy_yield(sent_in_window=0, resolved=True), + _legacy_yield(victim="0x" + "22" * 20, sent_in_window=200, resolved=False, requests=2)] # fmt: skip + (d / "yield.jsonl").write_text("".join(json.dumps(y) + "\n" for y in ys), encoding="utf-8") + (d / "cost.jsonl").write_text( + json.dumps({"draw": 1, "block": 9, "requests": 3, "result": "ineligible", + "has_code": False, "nonce_end": 4}) + "\n", encoding="utf-8") # fmt: skip + (d / "budget.json").write_text(json.dumps({"requests": 10}), encoding="utf-8") + (d / "summary.json").write_text( + json.dumps({"started_used": 2, "ended_used": 10, "seconds": 1.0}), encoding="utf-8" + ) + (d / "plan.json").write_text("{}", encoding="utf-8") + return d + + +def test_reconstruction_is_deterministic_and_bounds_are_conditional(tmp_path: Path) -> None: + d = _pilot_dir(tmp_path) + cands = [(2, WALLET, LOOKALIKE), (3, "0x" + "22" * 20, LOOKALIKE)] + a, b = reconstruct(d, cands), reconstruct(d, cands) + assert a == b + assert render_markdown(a) == render_markdown(b) + assert a["requests"]["run_overhead"] == 1 # 10 - 2 - (2 + 2) - 3 + assert a["yield"]["outcomes"]["unresolved"] == 1 + assert a["yield"]["observed_complete"] == 1 + assert "not a random sample" in a["yield"]["conditional_on"] + + +def test_reconstruction_refuses_misaligned_candidates(tmp_path: Path) -> None: + d = _pilot_dir(tmp_path) + with pytest.raises(PilotRecordError): + reconstruct(d, [(2, LOOKALIKE, WALLET), (3, WALLET, LOOKALIKE)]) + with pytest.raises(PilotRecordError): + reconstruct(d, [(2, WALLET, LOOKALIKE)]) + + +def test_new_records_round_trip_through_the_versioned_schema() -> None: + rec = yield_record(_legacy_yield(sent_in_window=0, resolved=True), source_line=4) + again = yield_record(json.loads(rec.model_dump_json())) + assert again == rec + assert isinstance(again, YieldRecord) + + +# --- payment verification --------------------------------------------------------------- + + +def _topic(a: str) -> str: + return "0x" + "0" * 24 + a[2:] + + +def tok_transfer(token: str, to: str, amount: int) -> dict[str, Any]: + data = "0xa9059cbb" + "0" * 24 + to[2:] + f"{amount:064x}" + return {"hash": TX, "from": WALLET, "to": token, "value": "0x0", "input": data} + + +def tlog(token: str, frm: str, to: str, amount: int) -> dict[str, Any]: + from cryptoguard.blockchain.abi import TRANSFER_TOPIC + + return {"address": token, "topics": [TRANSFER_TOPIC, _topic(frm), _topic(to)], + "data": f"0x{amount:064x}"} # fmt: skip + + +OK = {"status": "0x1", "logs": []} + + +def test_native_transfer_needs_signer_destination_value_and_success() -> None: + tx = {"hash": TX, "from": WALLET, "to": LOOKALIKE, "value": hex(10**18), "input": "0x"} + assert verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt=OK).status == ( + "confirmed_direct_payment" + ) + rev = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt={"status": "0x0"}) + assert rev.status == "reverted" + assert ( + verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt=None).status + == "unresolved" + ) + other = verify_payment(victim=WALLET, candidate=STRANGER, tx=tx, receipt=OK) + assert other.status == "not_a_payment" + assert other.ownership_claim is None + + +def test_trusted_token_transfer_needs_a_matching_log() -> None: + tx = tok_transfer(USDT, LOOKALIKE, 5_000_000) + good = {"status": "0x1", "logs": [tlog(USDT, WALLET, LOOKALIKE, 5_000_000)]} + r = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt=good) + assert (r.status, r.asset, r.amount) == ("confirmed_direct_payment", "USDT", 5_000_000) + no_log = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt=OK) + assert no_log.status == "unresolved" + wrong_amount = {"status": "0x1", "logs": [tlog(USDT, WALLET, LOOKALIKE, 1)]} + assert ( + verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, receipt=wrong_amount).status + == "unresolved" + ) + + +def test_fake_tokens_zero_amounts_and_forged_logs_are_not_losses() -> None: + fake = tok_transfer(FAKE, LOOKALIKE, 9) + fake_receipt = {"status": "0x1", "logs": [tlog(FAKE, WALLET, LOOKALIKE, 9)]} + r = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=fake, receipt=fake_receipt) + assert r.status == "unresolved" + assert "untrusted_token" in r.evidence + zero = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tok_transfer(USDT, LOOKALIKE, 0), + receipt={"status": "0x1", "logs": [tlog(USDT, WALLET, LOOKALIKE, 0)]}) # fmt: skip + assert zero.status == "not_a_payment" + # The attacker's own transferFrom(victim, lookalike, 0): a genuine-token log, not victim-signed. + spoof = {"hash": TX, "from": LOOKALIKE, "to": USDT, "value": "0x0", "input": "0x23b872dd"} + s = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=spoof, + receipt={"status": "0x1", "logs": [tlog(USDT, WALLET, LOOKALIKE, 0)]}) # fmt: skip + assert s.status == "unresolved" + assert "spender_mediated_transfer_from" in s.evidence + + +def test_router_and_contract_calls_stay_unresolved() -> None: + tx = { + "hash": TX, + "from": WALLET, + "to": STRANGER, + "value": "0x0", + "input": "0x5ae401dc" + "00" * 64, + } + r = verify_payment(victim=WALLET, candidate=LOOKALIKE, tx=tx, + receipt={"status": "0x1", "logs": [tlog(USDT, WALLET, LOOKALIKE, 7)]}) # fmt: skip + assert r.status == "unresolved" + + +# --- events, labels, groups, splits, gates ---------------------------------------------- + + +def event(victim: str = WALLET, lookalike: str = LOOKALIKE, tx: str = TX, block: int = 1_000, + signer: str | None = None, log: int | None = 0) -> PoisoningEvent: # fmt: skip + return PoisoningEvent( + chain_id=1, victim=victim, lookalike=lookalike, imitated=FRIEND, planting_tx=tx, + planting_block=block, planting_tx_index=0, planting_log_index=log, + observation_timestamp=None, subtype="zero_value", tx_signer=signer, log_contract=USDT, + token_contract=USDT, candidate_method="test", + ) # fmt: skip + + +def test_one_batch_transaction_gives_separate_victim_events_and_one_group() -> None: + a, b = event(victim=WALLET, log=0), event(victim="0x" + "22" * 20, log=1) + assert a.planting_tx_id == b.planting_tx_id + assert a.victim_event_id != b.victim_event_id + kept, dropped = deduplicate([a, b, a]) + assert (len(kept), dropped) == (2, 1) + groups = campaign_groups([a, b]) + assert groups[a.victim_event_id] == groups[b.victim_event_id] # one campaign + + +def test_public_infrastructure_does_not_merge_campaigns() -> None: + a = event(victim=WALLET, lookalike=LOOKALIKE, tx=h(1), signer=USDT) + b = event(victim="0x" + "22" * 20, lookalike=STRANGER, tx=h(2), signer=USDT) + groups = campaign_groups([a, b]) + assert groups[a.victim_event_id] != groups[b.victim_event_id] + + +def test_grouped_split_keeps_campaigns_whole_and_test_later() -> None: + evs = [event(victim="0x" + f"{i:040x}", lookalike="0x" + f"{i + 900:040x}", tx=h(i), block=i * 10) + for i in range(1, 21)] # fmt: skip + evs.append(event(victim="0x" + f"{20:040x}", lookalike="0x" + f"{999:040x}", tx=h(99), block=5)) + groups = campaign_groups(evs) + split = grouped_temporal_split(evs, groups, test_fraction=0.3) + for g in set(groups.values()): + assert len({split[e] for e, gg in groups.items() if gg == g}) == 1 + train_max = max(e.planting_block for e in evs if split[e.victim_event_id] == "train" + and groups[e.victim_event_id] != groups[evs[-1].victim_event_id]) # fmt: skip + test_min = min(e.planting_block for e in evs if split[e.victim_event_id] == "test" + and groups[e.victim_event_id] != groups[evs[-1].victim_event_id]) # fmt: skip + assert train_max < test_min + # The early event shares a victim with the latest group: it follows its group to test. + assert split[evs[-1].victim_event_id] == split[evs[19].victim_event_id] + + +def test_labels_keep_weak_verified_and_conflicts_apart() -> None: + labs = [ + LabelRecord(victim_event_id="a", tier="weak_attempt", source="ph", available_at=None), + LabelRecord(victim_event_id="b", tier="weak_attempt", source="ph", available_at=None), + LabelRecord(victim_event_id="b", tier="verified_attempt", source="review:x", available_at=None), + LabelRecord(victim_event_id="c", tier="verified_attempt", source="review:x", available_at=None), + LabelRecord(victim_event_id="c", tier="verified_legitimate", source="review:y", available_at=None), + ] # fmt: skip + assert resolve_labels(labs) == { + "a": "weak_attempt", + "b": "verified_attempt", + "c": "conflicting", + } + + +def test_gates_block_training_on_weak_positives_without_verified_negatives() -> None: + evs = [event(victim="0x" + f"{i:040x}", tx=h(i)) for i in range(40)] + labels = {e.victim_event_id: "weak_attempt" for e in evs} + gates = {g.gate: g for g in quality_gates(evs, labels, license_ok=False)} # type: ignore[arg-type] + assert not gates["B_label_validity"].passed + assert not gates["license"].passed + assert gates["A_data_validity"].passed + + +def test_manifest_hash_is_order_independent() -> None: + a, b = event(tx=h(1)), event(tx=h(2)) + assert manifest([a, b], [])["sha256"] == manifest([b, a], [])["sha256"] + assert manifest([a], [])["sha256"] != manifest([a, b], [])["sha256"] + + +# --- candidates and point-in-time features ---------------------------------------------- + + +def _history() -> list[RecordedTransfer]: + return [ + transfer(500, WALLET, FRIEND, 100, tx_sender=WALLET, idx=1), # the wallet pays FRIEND + transfer(900, LOOKALIKE, WALLET, 0, idx=2), # zero-value planting from a lookalike + transfer(950, WALLET, LOOKALIKE, 0, tx_sender=LOOKALIKE, idx=3), # spoofed transferFrom + ] + + +def test_generator_finds_each_planting_shape_independently_of_the_detector() -> None: + fx = fixture([*_history(), transfer(960, STRANGER, WALLET, 5_000, idx=1), + transfer(970, LOOKALIKE, WALLET, 3, token=FAKE, idx=1)], []) # fmt: skip + cs = cand.generate(fx) + methods = {c.event.planting_block: set(c.methods) for c in cs} + assert methods[900] == {"zero_value_in", "lookalike_in"} + assert methods[950] == {"spoofed_out"} + assert methods[960] == {"dust_in"} + assert methods[970] == {"lookalike_in", "untrusted_token_in"} + assert 500 not in methods # an ordinary payment is not a candidate + assert cs[0].event.imitated == FRIEND + + +def test_lookalike_is_relative_to_counterparties_chosen_before_the_event() -> None: + # The planting comes before the wallet ever pays FRIEND: no imitated counterparty yet. + fx = fixture([transfer(400, LOOKALIKE, WALLET, 5_000_000, idx=1), + transfer(500, WALLET, FRIEND, 100, tx_sender=WALLET, idx=1)], []) # fmt: skip + assert cand.generate(fx) == [] + + +def _features_at(fx: ReplayFixture, block: int) -> cand.EventFeatures: + events, coverage = events_from_fixture(fx) + c = next(c for c in cand.generate(fx) if c.event.planting_block == block) + return cand.event_features(c, events, coverage) + + +def test_future_events_and_losses_do_not_change_past_features() -> None: + base = fixture(_history(), []) + later = fixture([*_history(), transfer(5_000, WALLET, LOOKALIKE, 10**9, tx_sender=WALLET)], + [eth_tx(6_000, LOOKALIKE, 10**18)]) # fmt: skip + assert _features_at(base, 900) == _features_at(later, 900) + + +def test_input_order_does_not_change_features() -> None: + fx = fixture(_history(), []) + shuffled = fixture(list(reversed(_history())), []) + assert _features_at(fx, 950) == _features_at(shuffled, 950) + + +def test_later_transactions_in_the_same_block_are_invisible() -> None: + same_block_later = transfer(900, WALLET, FRIEND, 100, tx_sender=WALLET, idx=9) + a = _features_at(fixture(_history(), []), 900) + b = _features_at(fixture([*_history(), same_block_later], []), 900) + assert a == b + + +def test_unknown_history_is_not_safe_history() -> None: + partial = fixture(_history(), [], transfer_scan_complete=False) + f = _features_at(partial, 900) + assert f.history.history_status == "partial" + assert f.history.prior_payments_to_recipient is None + assert f.plausible_impersonated is None + assert f.as_model_row()["prior_payments_to_recipient"] == -1.0 + + +def test_known_empty_history_gives_zeros() -> None: + fx = fixture([transfer(500, WALLET, FRIEND, 1, tx_sender=WALLET, idx=1), + transfer(900, LOOKALIKE, WALLET, 0, idx=2)], []) # fmt: skip + f = _features_at(fx, 900) + assert f.history.prior_payments_to_recipient == 0 + assert f.plausible_impersonated == 1 + assert f.blocks_since_imitated_chosen == 400 + + +def test_cross_wallet_index_sees_only_earlier_blocks() -> None: + idx = cand.PriorIndex() + idx.add(event(victim="0x" + "22" * 20, block=800)) + idx.add(event(victim="0x" + "33" * 20, block=900)) # same block as the query: invisible + idx.add(event(victim="0x" + "44" * 20, block=2_000)) # future + assert idx.distinct_victims_before("lookalike", LOOKALIKE, 900) == 1 + assert idx.distinct_victims_before("signer", None, 900) is None + + +# --- review workflow -------------------------------------------------------------------- + + +def test_review_export_has_no_score_and_imports_preserve_disagreement(tmp_path: Path) -> None: + e = event() + out = tmp_path / "packets.jsonl" + export_packets([packet(e, ["poison-hunter:weak_attempt"], "zero-value transfer")], out) + line = json.loads(out.read_text().splitlines()[0]) + assert not any("score" in k for k in line) + decisions = tmp_path / "d.jsonl" + rows = [ + {"victim_event_id": e.victim_event_id, "decision": "confirmed_poisoning_attempt", + "rationale": "r", "reviewer": "a", "reviewed_at": "2026-11-02T00:00:00Z"}, + {"victim_event_id": e.victim_event_id, "decision": "confirmed_legitimate_interaction", + "rationale": "r", "reviewer": "b", "reviewed_at": "2026-11-02T01:00:00Z"}, + ] # fmt: skip + decisions.write_text("".join(json.dumps(r) + "\n" for r in rows)) + prior = [LabelRecord(victim_event_id=e.victim_event_id, tier="weak_attempt", source="ph", + available_at=None)] # fmt: skip + history = import_reviews(decisions, {e.victim_event_id}, prior) + assert len(history) == 3 # nothing overwritten + assert resolve_labels(history)[e.victim_event_id] == "conflicting" + + +def test_review_import_is_all_or_nothing(tmp_path: Path) -> None: + bad = tmp_path / "d.jsonl" + bad.write_text(json.dumps({"victim_event_id": "x", "decision": "benign", "rationale": "", + "reviewer": "a", "reviewed_at": "t"}) + "\n") # fmt: skip + with pytest.raises(ReviewImportError): + import_reviews(bad, {"x"}, []) + + +# --- planner ---------------------------------------------------------------------------- + + +def test_planner_estimates_conservatively_and_rejects_over_cap() -> None: + small = plan(CollectionJob(wallets=2, window_blocks=7_200, request_cap=10_000)) + assert small["executes"] is False + assert small["estimate"]["log_requests_per_wallet"] == 144 + with pytest.raises(PlanRejected): + plan(CollectionJob(wallets=120, window_blocks=50_400, request_cap=200_000)) + assert plan(CollectionJob(wallets=2, window_blocks=7_200, request_cap=10_000)) == small + + +# --- monitoring ------------------------------------------------------------------------- + + +def test_psi_edge_cases() -> None: + ref = reference_bins([float(i % 10) for i in range(200)]) + assert psi(ref, []) is None # empty batch: no PSI, not 0 + assert psi(ref, [None, float("nan")]) is None # only missing values + assert missing_share([1.0, None, float("nan"), 2.0]) == 0.5 + assert missing_share([]) is None + constant = reference_bins([3.0] * 100) + assert psi(constant, [3.0] * 10) == pytest.approx(0.0, abs=1e-9) + sparse = reference_bins([0.0] * 95 + [1.0, 2.0, 5.0, 9.0, 40.0]) + stable = psi(sparse, [0.0] * 95 + [1.0, 2.0, 5.0, 9.0, 40.0]) + assert stable is not None + assert stable < 0.01 + shifted = psi(sparse, [40.0] * 20) + assert shifted is not None + assert shifted > 1.0 # zero-frequency bins handled by the floor, no division by zero + + +def test_phase11_reference_bins_keep_their_original_semantics() -> None: + # A Phase 11 card stores shares counted with bisect_right and has no "closed" key. + old = {"edges": [0.0], "expected": [0.0, 1.0]} + assert psi(old, [0.0] * 50) == pytest.approx(0.0, abs=1e-9) # no false drift on old cards + + +def test_option_b_estimate_under_pilot_assumptions() -> None: + p = plan(CollectionJob(wallets=120, window_blocks=50_400, request_cap=240_000)) + assert p["estimate"]["total_requests_conservative"] == 237_360 From 2a69f028d39e12dfa1702766dd3c2c5301158a8c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:01:42 +0300 Subject: [PATCH 11/92] docs(ml): pilot audit, poisoning dataset card and research plan - ML_PILOT_AUDIT.md: the pilot reconstructed from its raw outputs. The request accounting matches the ledger exactly (2,636). The 0.069 payment bound is corrected to a conditional bound on the 52 least active rows. The data-loss root cause is recorded, with what was recovered and what was lost. - ML_POISONING_DATASET.md: task definition, event schema, label tiers, Poison-Hunter field provenance, and the quarantined row. - ML_RESEARCH_PLAN.md: issue register, candidate-generation results, collection cost model, external sources (none downloaded) and the next experiment. - ML_POISONING_TABLES.md: generated by `ml poisoning-report`. - The proposal, ML.md and CHANGELOG are corrected and updated. Verification: - ruff, format and mypy (107 files) clean; - ML suites: 97 passed; - full backend suite: 527 passed and 1 failed. The failure was a thread-starvation timeout in the ledger test, fixed in 4928030; that file then passed 19/19. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 +++++ ML.md | 27 ++++++ ML_PILOT_AUDIT.md | 143 ++++++++++++++++++++++++++++ ML_POISONING_DATASET.md | 156 +++++++++++++++++++++++++++++++ ML_POISONING_TABLES.md | 66 +++++++++++++ ML_RESEARCH_PLAN.md | 124 ++++++++++++++++++++++++ docs/ml/proposal-next-dataset.md | 25 +++-- 7 files changed, 556 insertions(+), 9 deletions(-) create mode 100644 ML_PILOT_AUDIT.md create mode 100644 ML_POISONING_DATASET.md create mode 100644 ML_POISONING_TABLES.md create mode 100644 ML_RESEARCH_PLAN.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 20f6f95..428c7bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,30 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Wallet-centric poisoning research platform (Phase 11.2) +- Fixed: the option A pilot lost three wallet recordings because its post-processing read a + non-existent field (`transactions`, not `wallet_transactions`) inside a broad exception + handler. Pilot records are now typed and versioned (`ml/pilot.py`). Schema mismatches + raise instead of reading as zero, and lost values are migrated as unknown. +- Corrected: the pilot's 0.069 payment-rate bound applies only to the 52 least active, + completely checked rows, not to all candidates (ML_PILOT_AUDIT.md). +- Fixed: the request ledger used a lock file broken after 60 s, which two processes could + both break; it now uses an OS file lock with fsynced writes, tested across processes. +- Fixed: PSI hid shifts of mostly-constant features (new references only), returned a large + value for empty batches, and binned NaN silently. +- Added: + - a typed Poison-Hunter parser with provenance and quarantine; + - the poisoning event schema, with identity, campaign groups, grouped temporal splits, + label tiers and quality gates; + - an offline payment verifier; + - a structural candidate generator and point-in-time event features; + - a label review export and import; + - a collection cost planner; + - `cryptoguard ml poisoning-report` and `ml plan-collection`; + - a task identifier on model cards. +- Docs: ML_POISONING_DATASET.md, ML_PILOT_AUDIT.md, ML_RESEARCH_PLAN.md, + ML_POISONING_TABLES.md. + ## 0.1.0 — 2026-10-28 (first release candidate, not independently audited) ### Detection and monitoring diff --git a/ML.md b/ML.md index afb67ed..16bf0e1 100644 --- a/ML.md +++ b/ML.md @@ -20,6 +20,33 @@ Generated results: [ML_EVALUATION.md](ML_EVALUATION.md) (Phase 11, historical) a [ML_AUDIT_TABLES.md](ML_AUDIT_TABLES.md) (Phase 11.1 audit). This page is the data card, method and decision log. +## Two separate tasks (Phase 11.2) + +| Task | Question | Status | +|---|---|---| +| `ptxphish-transaction-phishing/1` (this page) | Is a mined transaction part of a phishing operation? | Model trained, research-only | +| `poisoning-attempt/1` ([ML_POISONING_DATASET.md](ML_POISONING_DATASET.md)) | At a cutoff, is a candidate event an address-poisoning attempt against this wallet? | Data model, candidates, features, review and gates built; **no verified labels, no model** | + +- **Isolation.** Model cards carry `task`, and the shadow scorer refuses any task other than + the first. Cards without the field predate it and belong to the first task. +- **Modules for the poisoning task:** + - `ml/events.py`: schema, identity, groups, splits and gates; + - `ml/poison_hunter.py`: typed parser with provenance; + - `ml/pilot.py`: typed pilot records and reconstruction; + - `ml/payments.py`: offline payment verification; + - `ml/candidates.py`: candidate generation and point-in-time event features; + - `ml/review.py`: label review export and import; + - `ml/planner.py`: collection cost planning, which never collects; + - `ml/poisoning_report.py`: the offline report (`cryptoguard ml poisoning-report`). +- **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot + reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the + issue register, the collection design and the next experiment. +- **Monitoring correction.** PSI reference bins created from now on keep a tied decile in + its own bin (`closed="left"`). The Phase 11 card's bins use the original binning, under + which a feature that is mostly one value sits in one bin and its shifts are invisible. + That stays until the model is retrained. Empty or all-missing batches now give no PSI, + and missing values are reported separately (`missing_share`). + ## Data card ### Sources (pinned) diff --git a/ML_PILOT_AUDIT.md b/ML_PILOT_AUDIT.md new file mode 100644 index 0000000..cb4364a --- /dev/null +++ b/ML_PILOT_AUDIT.md @@ -0,0 +1,143 @@ +# Audit of the option A pilot (2026-11-01) + +Status: **reconstructed offline from the pilot's raw outputs (0 new RPC requests).** The +approved cap was 3,000 requests on `eth.drpc.org`. The remaining 364 are not used and are not +authorization for further collection. Regenerate the numbers with +`cryptoguard ml poisoning-report`; the tables are in [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). +Raw files stay in the git-ignored `data/ml/pilot/`. + +## 1. What the pilot measured + +- **Yield phase.** For each of the 149 valid Poison-Hunter rows, the pilot compared the + victim's nonce at the start and end of the 7 days after the planting. For victims who + signed 1–8 transactions, it located each one by nonce bisection and decoded it. +- **Cost phase.** It recorded random wallets over one day with `replay.record_window` and + measured the requests used. +- The plan was frozen before the run (`plan.json`, SHA-256 `82ae27e0…`). + +## 2. Reconstructed request accounting + +| Item | Requests | Source | +|---|---|---| +| Smoke tests and range probes before the final run | 70 | `summary.json` (`started_used`) | +| Yield phase | 1,521 | sum of `requests` in `yield.jsonl` | +| Cost phase | 1,044 | sum of `requests` in `cost.jsonl` | +| Chain check at the start of the run | 1 | difference | +| **Ledger total** | **2,636** | `budget.json` | + +The sum matches the ledger exactly. The ledger counts reservations, so a request cut off in +flight is counted whether or not the provider received it. Provider-side billing is not +reconstructed. Provider failures in the final run: 1 rate-limit error (cost phase, draw 14) +and 0 yield-phase errors. + +## 3. Yield phase: corrected interpretation + +| Outcome | Rows | +|---|---| +| `confirmed_direct_payment` | 0 | +| `no_direct_payment_observed_with_complete_declared_coverage` | 52 (35 signed nothing; 17 located and decoded) | +| `partial_coverage` | 0 | +| `unresolved` (signed more than 8 transactions; not inspected) | 46 (33 signed 9–100, 13 more than 100) | +| `not_evaluated` (signed 1–8 but the phase cap was reached) | 51 | + +- **Declared coverage** is limited to transactions the victim signed: native ETH sends and + `transfer(recipient, amount)` calls in blocks [planting + 1, planting + 50,400]. +- **Not covered:** + - `transferFrom` by a spender; + - router and aggregator payments; + - contract-wallet (relayed) payments; + - permit-based transfers; + - payments after the window. +- **The pilot's calldata check is weaker than the new verifier.** It did not check the + receipt log or whether the token was genuine. `ml/payments.py` now requires a reviewed + token, a successful receipt and a matching Transfer log. No pilot row would have been + affected, because none matched at all. +- **Rows versus events.** The 149 rows contain 6 duplicate victim-events, so there are 143 + distinct ones. Rows are not independent observations. + +**Correction to the earlier report.** +- `docs/ml/proposal-next-dataset.md` §11.2 gave a Wilson 95% upper bound of **0.069** on + "the share of candidate rows that end in a payment". +- That bound is valid only **conditional on** the 52 complete rows being representative. + They are not: + - they are the victims who signed nothing or very little; + - the 97 rows that were not checked are systematically the more active victims; + - the 52 include duplicate events. +- The 0.069 bound therefore **does not apply to all 149 rows or to Poison-Hunter victims in + general**. The supported statement: *0 confirmed direct payments in 52 rows checked with + complete declared coverage; outcomes of the other 97 rows are unknown.* The proposal has + been corrected. + +## 4. Cost phase and the lost-data defect + +- **Draws.** + - 25 draws, of which 11 were eligible (an externally owned account with a nonce of + 20–2,000). + - 6 eligible wallets signed more than 12 transactions in the day and were not recorded. + - 1 eligible wallet was rate-limited after 170 requests. + - 1 was skipped for budget. +- **Recordings.** 3 wallet-days were recorded completely, using **216, 224 and 351 + requests** inside `record_window`. + +**The defect.** +- The pilot script (outside the package, untyped) read `fixture.transactions`. The replay + model's field is `wallet_transactions`. +- The resulting `AttributeError` was caught by a broad `except Exception`, so the three + completed recordings were logged as `error` and their fixtures were never written. +- No raw RPC responses, checkpoints or temporary files were kept, so the search for + recoverable data found none. + +**Recovered and lost.** +- **Recovered from the log:** request counts (exact) and transactions signed in the window + (3, 6 and 12, from the logged nonce difference). +- **Irrecoverable:** transfer counts, payment counts and scan completeness. They are now + explicitly `None` (`recorded_contents_lost`), never zero. + +**Did it change the conclusions?** The cost numbers came from the request ledger, which is +intact. The lost payment counts were never used in a reported number, so no published figure +changes. The "1,500–2,500 requests per wallet-week" extrapolation stays an estimate, from +three wallet-days and biased low (busier wallets were excluded). + +**Fix (`ml/pilot.py`).** +- Versioned pydantic records (`pilot-yield/2`, `pilot-cost/2`, `extra="forbid"`). +- `summarize_fixture` reads typed attributes that mypy checks. +- A stored fixture whose fields do not match `ReplayFixture` raises `PilotRecordError` + instead of being read as zero. +- Legacy lines are migrated explicitly (`migrated_from`), and unknown versions or fields + are rejected. +- A cut-off final JSONL line is reported and skipped; a corrupt middle line is an error. +- Regression tests: `tests/unit/test_ml_poisoning.py`. They cover the correct field, the + old field, a missing field, a wrong type, an empty valid list, a truncated JSONL, schema + versions, migration and deterministic reconstruction. + +## 5. Provider observations (one free endpoint, not general) + +- `eth.drpc.org` on its free plan rejected `eth_getLogs` ranges of 250 blocks or more and + accepted 100. The error text claimed a 10,000-block limit, which is wrong. +- Throughput was about 4 requests/s (2,566 requests in 646 s). +- These describe one endpoint on one day. Providers with larger log ranges, or an indexed + source, change the cost model (ML_RESEARCH_PLAN.md §4). + +## 6. Request-budget hardening done in this phase + +- `RequestLedger` now uses an OS file lock (`msvcrt`/`flock`), which the OS releases if the + holder dies. +- **The P1 race this removes:** the previous lock file was broken after 60 s. Two waiting + processes could both break a crashed holder's lock, and then both would hold it. +- Writes are fsynced before the atomic replace. That costs about 56 ms per reservation on + this machine, capping one ledger at roughly 18 reservations/s, far above the free + endpoint's 4 requests/s. +- Threads of one process queue on a blocking in-process lock before taking the OS lock. + Without it, polling threads could starve under load: the full test suite showed one + starved thread in a five-thread test. A lock timeout is fail-safe, because nothing is sent. +- New tests: + - two separate processes sharing a cap; + - a process killed while holding the lock; + - a live holder (times out; the lock is not broken); + - a zero budget (sends nothing); + - rate limits and timeouts (counted as attempts); + - the cap reached during retries; + - five async workers on one client; + - a truncated ledger file (fails closed). +- **Guarantee:** the recorded count is never below the attempts sent by budgeted clients. It + exceeds them only by attempts reserved but never sent, for example after a crash. diff --git a/ML_POISONING_DATASET.md b/ML_POISONING_DATASET.md new file mode 100644 index 0000000..5ed6800 --- /dev/null +++ b/ML_POISONING_DATASET.md @@ -0,0 +1,156 @@ +# Wallet-centric poisoning dataset (task `poisoning-attempt/1`) + +Status: **data model, parser, label protocol and quality gates are implemented; no dataset that +passes the gates exists yet.** No model is trained for this task. Numbers below come from +`cryptoguard ml poisoning-report` (tables: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md)). + +This task is separate from the Phase 11 PTXPhish classifier (`ptxphish-transaction-phishing/1`, +[ML_EVALUATION.md](ML_EVALUATION.md)). That model asks whether a mined transaction belongs to +a phishing operation. Its labels are not poisoning-attempt labels and are not reused here. + +## 1. Events that must not be confused + +| Category | Meaning | Where it lives | +|---|---|---| +| Poisoning attempt | A planting transfer meant to put a lookalike into a victim's history | `PoisoningEvent` with a `LabelRecord` | +| Confirmed victim loss | Recorded evidence that the victim moved value to the lookalike | `OutcomeRecord.status = confirmed_direct_payment`, verified by `ml/payments.py` | +| Unresolved outcome | What happened next is unknown or incompletely observed | `OutcomeRecord.status` `unresolved` / `partial_coverage` / `not_evaluated` | +| Confirmed legitimate activity | Independent review found a legitimate interaction | `LabelRecord.tier = verified_legitimate` | +| Unlabelled background | Chain data without ground truth | no label, or tier `unknown` | + +An attempt can be real when nobody loses money. An unobserved payment is not proof that no +payment happened. A victim who did not pay is never called "benign". + +## 2. Prediction unit, target and cutoff + +- **Unit:** `(chain_id, victim, candidate_event_id, observation_cutoff)`. A candidate event is + one suspicious transfer seen by one wallet. +- **Target:** the poisoning-attempt status of that event (label tiers below). Whether the + victim later lost money is a secondary outcome, stored apart, and never a feature. +- **Cutoff:** after the planting transaction executes, before any later transaction in the + same block (`history` boundary `pre_execution`, with the event's own transaction + excluded). When the transaction index is unknown, only earlier blocks are visible. The + cross-wallet index (`PriorIndex`) sees only earlier blocks. +- **Output:** an experimental ranking or priority score with evidence and coverage. It is + not a probability of theft, and it never creates or changes a finding. + +## 3. Schema (`ml/events.py`, `poisoning-event/1`) + +`PoisoningEvent` records: +- chain ID, victim, lookalike and imitated address; +- planting transaction, block, transaction index and log index; +- subtype, verified signer, log-emitting contract and token contract; +- candidate-generation method, evidence references, coverage status and dataset version. + +Unknown values are `None`, never guessed. `LabelRecord` and `OutcomeRecord` are separate +models, each with its own source and availability time. + +**Identity.** +- `planting_tx_id` = `chain:tx_hash`. One batched transaction can plant many victims. +- `victim_event_id` = hash of chain, victim, planting tx, lookalike and log index. Repeated + victim-events are duplicates and are dropped (`deduplicate`). +- `campaign_groups` is a union-find over victims, lookalikes, planting transactions and + signers. Reviewed public infrastructure (`ml/dataset.py: PUBLIC_INFRASTRUCTURE`, 15 + contracts) is exempt. High degree alone does not exempt an address. +- `grouped_temporal_split` keeps whole groups on one side, and the latest-starting groups + form the test set. + +## 4. Label tiers and protocol + +| Tier | Use | +|---|---| +| `verified_attempt` | Trainable positive: independent review confirmed an attempt | +| `verified_legitimate` | Trainable negative: independent review confirmed a legitimate interaction | +| `weak_attempt` | A source pipeline says attempt. Positive-case reproduction and candidate recall only | +| `likely_legitimate` | Limited evidence. Not a training negative | +| `conflicting` | Verified disagreement, or weak versus likely | +| `unknown` | No usable evidence | + +`resolve_labels` lets verified labels win over weak ones. Verified disagreement becomes +`conflicting`, and nothing is overwritten. + +**Review workflow (`ml/review.py`).** Packets carry the evidence, the coverage limits and the +source labels, but **no model score**. Decisions are `confirmed_poisoning_attempt`, +`likely_poisoning_attempt`, `confirmed_legitimate_interaction`, `insufficient_evidence` or +`conflicting_evidence`. They are validated all-or-nothing and appended to the label history. + +**Negatives.** +- Random unlabelled wallets are not confirmed benign. A verified negative needs a reviewed + legitimate interaction that resembles a planting. Examples: + - a first payment to a new counterparty that independent evidence ties to the wallet's + owner; + - a similar-looking address that turns out to be legitimate; + - an unsolicited dust transfer from a known airdrop. +- Negatives should be matched to positives by period, transfer type, token, amount, wallet + activity, coverage and candidate rule. Otherwise the source itself becomes a shortcut. +- None exist yet. + +## 5. Poison-Hunter sample (`ml/poison_hunter.py`) + +**Source.** `DS2L/Poison-Hunter` at commit `74ff6f7d`, file `phishing_transfers_sample.csv` +(SHA-256 `1de4bf2a…`, pinned in `ml/sources.py`). Guan and Li, CCS 2024. **No license:** +the raw file stays local and is never redistributed. + +**Field identification.** Checked on all 150 rows; the full table is in the module +docstring. +- The 15-name header is aligned with fields 0–14, and each row carries 2 extra unnamed + fields. An earlier note called the columns "shifted"; that was imprecise. +- Two names misdescribe their content: + - `fake_token_address` holds the genuine USDC/USDT contract for `dust` and `zero` rows; + - `is_batching` holds a batch size, not a flag. +- Field 15 (`from`/`to`) is read as the direction of the imitated transfer. +- Field 16 equals our prefix+suffix match count in 135 of 149 rows, so it is probably the + source's own similarity count. This is inferred, not documented. +- Signers match the subtype: `dust` rows are signed by the lookalike itself, while `zero` + and `fake` rows are signed by batch operators. + +**Validation.** +- 149 rows are valid and 1 is quarantined. +- 123 victims, 128 lookalikes, 116 planting transactions (7 batched), 6 duplicate + victim-events. +- Blocks 15,861,385–17,965,129. +- The similarity definition matters: + - CryptoGuard's detector predicate accepts 139 rows; + - Tsuchiya et al.'s definition (at least 3 leading and 4 trailing hex characters) + accepts 105, because 31 `dust` rows share only 2 leading characters. + +**Quarantined row (CSV line 3).** +- It is the only row with direction `to`. +- Its lookalike shares 2 leading and 1 trailing hex characters with the imitated address, + below every published definition. +- Possible explanations: + - the imitated address for direction `to` is recorded differently; + - the row is a source error; + - it is a non-lookalike subtype. +- None of these can be decided offline. The row is kept, marked quarantined, and is not + called benign. + +**Label status.** All 143 distinct victim-events are `weak_attempt`. They are useful for +positive-case reproduction, candidate recall and feature testing, not for binary training. + +## 6. Quality gates (`quality_gates`) + +| Gate | Current state | +|---|---| +| A: data validity | Passes. Events parse reproducibly, with no duplicate identities | +| B: label validity | **Fails.** 0 verified positives, 0 verified negatives (30 each needed) | +| C: temporal validity | Passes. Every event has a planting block; the cutoff is defined | +| D: split validity | **Fails.** No verified groups to split | +| License | **Fails** for redistribution. Raw rows stay local | +| E: baseline comparability | Not reached: needs a labelled population shared by the detector and a model | +| F: statistical adequacy | Not reached | +| G: deployment isolation | Passes. The shadow scorer serves only `ptxphish-transaction-phishing/1` cards; findings are unchanged with ML on or off (integration test) | + +Training for this task is blocked until gates B and D pass. + +## 7. External sources reviewed (no data downloaded) + +These were checked from the source pages on 2026-11-02 by a research agent; details are in +ML_RESEARCH_PLAN.md §5. + +| Source | What it offers | Blocker | +|---|---|---| +| Tsuchiya et al., USENIX Security 2025 (KiltHub DOI 10.1184/R1/29212703.v1) | Ethereum attempts (2.3 GB SQL dump) plus payoff-transfer CSVs (under 2 MB) | Licence CC BY-NC-ND 4.0; download needs your approval | +| Poison-Hunter full data | Withheld; "contact us", with no address published | Request needed | +| Forta labelled datasets | MIT, Etherscan-derived address labels | No poisoning category, no loss transactions | +| Etherscan labels | Underlie Forta and Poison-Hunter ground truth | Terms require written permission for ML or dataset use | diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md new file mode 100644 index 0000000..a13bf17 --- /dev/null +++ b/ML_POISONING_TABLES.md @@ -0,0 +1,66 @@ +# ML Phase 11.2 tables + +Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). +Git `3411c6d3cc5f596b1044f430e616a20ae24a4cbd`; runtime 7.03 s; peak Python heap 0.0 MiB. + +## Poison-Hunter sample + +| Quantity | Value | +|---|---| +| Source SHA-256 | `1de4bf2aa0bdc02e…` (matches the pinned hash) | +| Rows / valid / quarantined | 150 / 149 / 1 | +| Subtypes | dust 50, zero 50, fake 50 | +| Distinct victims / lookalikes / planting txs | 123 / 128 / 116 | +| Planting txs with several rows (batches) | 7 | +| Duplicate victim-events | 6 | +| Victims / lookalikes in several rows | 15 / 12 | +| Block range | 15,861,385-17,965,129 | +| Lookalike by CryptoGuard's detector predicate | 139 of 149 | +| Lookalike by Tsuchiya et al. (≥3 leading, ≥4 trailing) | 105 of 149 | +| Source field 16 equals prefix+suffix match | 135 of 149 | + +Quarantined line 3: only direction 'to' row: imitation mapping for this direction unverified; lookalike shares 2+1 hex characters with the imitated address, below any published lookalike definition. + +## Event dataset and gates + +143 victim-events after dropping 6 duplicates; 65 campaign groups (largest 26 events); labels: {'weak_attempt': 143}; manifest `dbcad6907b4a2fb1…`. + +| Gate | Passed | Detail | +|---|---|---| +| A_data_validity | yes | 143 events, 0 duplicate identities | +| B_label_validity | **no** | verified positives 0, verified negatives 0 (need 30 each); weak 143, unknown 0, conflicting 0 | +| C_temporal_validity | yes | every event has a planting block; cutoff = after the planting transaction | +| D_split_validity | **no** | 0 positive and 0 negative campaign groups | +| license | **no** | raw rows stay local | + +## Pilot reconstruction + +| Quantity | Value | Source | +|---|---|---| +| Ledger total (cap 3000) | 2636 | `budget.json` | +| Before the final run (smoke tests, probes) | 70 | `summary.json` | +| Yield phase | 1521 | sum over `yield.jsonl` | +| Cost phase | 1044 | sum over `cost.jsonl` | +| Run overhead (chain check) | 1 | difference | +| Candidate rows / distinct victim-events | 149 / 143 | `yield.jsonl` | +| Outcome `confirmed_direct_payment` | 0 | derived | +| Outcome `no_direct_payment_observed_with_complete_declared_coverage` | 52 | derived | +| Outcome `partial_coverage` | 0 | derived | +| Outcome `unresolved` | 46 | derived | +| Outcome `not_evaluated` | 51 | derived | +| Signed 0 / 1-8 / 9-100 / >100 in window | 35 / 68 / 33 / 13 | nonce differences | +| Cost draws / eligible / recorded wallet-days | 25 / 11 / 3 | `cost.jsonl` | +| Requests per recorded wallet-day | 216, 224, 351 | `cost.jsonl` (minus 4 eligibility requests) | +| Recordings whose contents were lost | 3 | migration | +| Conditional Wilson 95% upper bound | 0.069 | 0 of 52 complete rows; not a population bound | + +## Candidate generation (recorded replay fixtures) + +| Incident | Candidates | Harmful lookalike found | Candidate lead (blocks) | Detector lead (blocks) | First-hit rules | +|---|---|---|---|---|---| +| eth-140-poisoning-2025-08-14 | 4 | yes | 21523 | 42 | spoofed_out | +| eth-4556-poisoning-2026-01-30 | 38 | yes | 13063 | 13057 | spoofed_out | +| usdt-50m-poisoning-2025-12-19 | 7 | yes | 113 | 113 | spoofed_out | +| wbtc-1155-poisoning-2024-05-03 | 169 | yes | 367 | 367 | spoofed_out | + +Background wallets: 9 recorded windows, 8 candidates, 0.296 per wallet-day (unlabelled). Incidents were used during detector development; background candidates are unlabelled (not false positives). diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md new file mode 100644 index 0000000..47fda8f --- /dev/null +++ b/ML_RESEARCH_PLAN.md @@ -0,0 +1,124 @@ +# ML research plan: wallet-centric poisoning detection (Phase 11.2) + +Status: infrastructure done, gates B and D fail (no verified labels), and no model is trained +for this task. Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). +Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: +[ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). + +## 1. Issue register (Phase 11.2 audit) + +| ID | Pri | Issue | Status | +|---|---|---|---| +| 1 | P0 | **Pilot data loss.** The pilot post-processing read `fixture.transactions` (the field is `wallet_transactions`). A broad `except` turned three completed recordings into "errors", and their contents were lost | Fixed: typed versioned records, schema errors raise, legacy migration marks lost values `None` (ML_PILOT_AUDIT.md §4) | +| 2 | P0 | **Invalid conclusion.** "At most 7% of candidate rows end in a payment" generalized a bound computed on a non-random subset (the least active victims) | Corrected in the proposal and the audit: the bound is conditional only | +| 3 | P1 | **Ledger lock race.** The stale-lock break (after 60 s) could let two processes hold the lock after a holder crashed | Fixed: OS file lock, fsync; process-level tests | +| 4 | P1 | **PSI blind spot.** `bisect_right` binning put a mostly-constant feature into one bin, so its shifts were invisible (PSI 0 for a 0→40 shift) | Fixed for new references (`closed="left"`). Phase 11 cards keep the old semantics so they show no false drift; the limitation is documented | +| 5 | P1 | **PSI on empty or missing input.** An empty batch gave a large number, and NaN fell silently into the first bin | Fixed: `None` for empty or all-missing; missing values excluded and reported (`missing_share`) | +| 6 | P1 | **Untyped pilot outside the package.** The pilot script was not under tests, mypy or review | Fixed: the pilot logic now lives in `ml/pilot.py`, tested. The scratch script stays out of the repository | +| 7 | P1 | **Payment check too weak.** The pilot accepted victim-signed `transfer()` calldata without checking the token or the receipt log | Fixed: `ml/payments.py` requires a reviewed token, success and a matching log; otherwise `unresolved` | +| 8 | P1 | **Task confusion risk.** A future poisoning model could be loaded by the transaction scorer | Fixed: cards carry `task`, and the registry refuses a task other than `ptxphish-transaction-phishing/1` | +| 9 | P2 | **Imprecise description of the CSV.** The Poison-Hunter header was described as "shifted"; it is aligned, with 2 unnamed trailing fields | Corrected in docs and the parser docstring | +| 10 | P2 | **Rows counted as events.** The pilot treated duplicate victim-events as separate observations | Reported (149 rows, 143 events); the event model deduplicates | +| 11 | P2 | **Phase 11 monitoring on sparse features** keeps the old binning until the model is retrained | Open (the model is research-only, so no live impact) | + +## 2. Task definition + +See ML_POISONING_DATASET.md §2: +- **Unit:** `(chain_id, victim, candidate_event_id, observation_cutoff)`. +- **Target:** poisoning-attempt status. +- **Cutoff:** after the planting transaction, before later transactions in the same block. +- **Losses** are a separate outcome, never a feature. +- **Output:** an experimental ranking with coverage, not a theft probability, never a + finding. + +## 3. Candidate generation (`ml/candidates.py`, `candidates/1`) + +**Rules.** The rules are structural and independent of the production detector and of any +model: +- `zero_value_in`; +- `spoofed_out` (a transfer out of the wallet that the wallet did not sign); +- `lookalike_in` (at least 6 matching affix characters, at least 3 trailing, against a + counterparty the wallet chose before the event); +- `untrusted_token_in`; +- `dust_in` (a stablecoin transfer of at most 0.01). + +**Results on recorded data (0 RPC requests).** +- **Incidents:** the harmful lookalike is a candidate before the theft in **4 of 4** + incidents. + + | Incident | Candidate lead | Detector lead | Candidates in the 3-day window | + |---|---|---|---| + | eth-140 | 21,523 | 42 | 4 | + | eth-4556 | 13,063 | 13,057 | 38 | + | usdt-50m | 113 | 113 | 7 | + | wbtc-1155 | 367 | 367 | 169 | + + (Leads are in blocks.) +- **Background:** 9 recorded background windows (27 wallet-days) produced 8 candidates, + about 0.30 per wallet-day. They are unlabelled, so they are not false positives. +- **Resources:** generation takes milliseconds per window (at most 128 ms, 403 KiB peak), + and the whole report takes under a minute. + +**Limits on what this shows.** +- The incidents were used while developing the detector, so they are not untouched. +- The generator is loose by design: 169 candidates for one heavily targeted wallet. A + longer lead time in eth-140 is not a better detector; it reflects a structural rule that + fires on every spoofed transfer. +- Candidate recall on Poison-Hunter rows cannot be measured without the victims' histories. + +## 4. Future collection architecture + +`cryptoguard ml plan-collection` estimates a job and never collects. Its defaults are taken +from the pilot and are conservative: 90th-percentile 30 signed transactions per wallet-week +at 26 requests each, 10% retries, 4 requests/s. + +| Scenario (120 wallets × 7 days) | Requests per wallet | Total | Hours | +|---|---|---|---| +| Free endpoint, 100-block logs | 1,978 | 237,360 | 16.5 | +| Provider with 2,000-block logs | 927 | 111,240 | 7.7 | + +**What dominates the cost.** +- With larger log ranges, the cost is dominated by nonce bisection (about 26 requests per + signed transaction), not by log scans. +- **Cheaper designs:** + - **Event-first discovery.** Start from attempts already listed by a dataset (for + example Tsuchiya et al.), so only the planting transaction and the following window + are needed. + - **Receipt reuse.** One planting transaction covers all victims of its batch. + - **An indexed source.** An address-indexed source, which a paid service or a self-run + archive indexer would provide, replaces bisection. +- None of this has been run, and none is authorized. + +## 5. External data (checked on 2026-11-02; nothing downloaded) + +| Source | Verified facts | Fit | Blocker | +|---|---|---|---| +| Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. KiltHub DOI 10.1184/R1/29212703.v1 | Files: `payoff_transfers_ethereum.csv` (482 KB), `payoff_transfers_bsc.csv` (1.33 MB), `address_poisoning_ethereum.sql.gz` (2.32 GB). Licence CC BY-NC-ND 4.0 | Payoffs give independent confirmed-loss transfers (stablecoin, Ethereum, 2022-07 to 2024-06) | Download needs your approval; NC-ND allows local research use only, with no redistributed derivatives; columns not yet inspected | +| Poison-Hunter (Guan and Li, CCS 2024), `DS2L/Poison-Hunter` | 5 files in the repository, no licence; full data "available on request", with no contact address published | Weak attempt labels | A request is needed; a draft request exists, not sent | +| RMIT arXiv 2609.23405 | Claims 4,209 victim transfers; its artifact link showed no files | — | Unverified | +| Forta labelled datasets | MIT; Etherscan phish-hack/exploit/heist labels | Contamination checks only | No poisoning category | +| Etherscan labels | Terms require written permission for ML or dataset creation | — | Affects Forta and Poison-Hunter ground truth | + +## 6. Next experiment (highest value, 0 RPC requests) + +**Cross-check the Poison-Hunter rows against Tsuchiya et al.'s independent payoff list.** + +- **Needs:** your approval to download `payoff_transfers_ethereum.csv` (482 KB, CC BY-NC-ND + 4.0, kept local under `data/external/`, never committed). It is a file download, so your + standing rule requires an explicit yes. +- **Method.** Pin its hash in `ml/sources.py`, then parse it with a typed schema after + inspecting the columns. Join it on victim and lookalike with the 143 Poison-Hunter + victim-events and the 4 replay incidents. +- **What it gives.** + 1. Independent outcome evidence for the 97 rows the pilot could not resolve, at no RPC + cost. + 2. Agreement between two independent pipelines on attempts, giving a first estimate of + label noise. + 3. A list of confirmed-loss victims whose preceding attempts could become + `verified_attempt` positives after review. +- **Success criterion, stated now.** Report the overlap counts and the disagreements as + they are. Do not change the Poison-Hunter labels on the basis of the overlap alone; + changes go through the review workflow. +- **Still missing afterwards:** verified negatives (gate B). They need a reviewed sample of + legitimate lookalike-shaped interactions, which no public source provides. That is the + real blocker for supervised learning on this task. diff --git a/docs/ml/proposal-next-dataset.md b/docs/ml/proposal-next-dataset.md index 8ac95df..7a6be7c 100644 --- a/docs/ml/proposal-next-dataset.md +++ b/docs/ml/proposal-next-dataset.md @@ -5,6 +5,10 @@ are not approved.** The Phase 11 authorization (12,000 requests) is exhausted (1 the pilot used 2,636 of its separate 3,000-request cap. Background: ML_GENERALIZATION_AUDIT.md §16–17. +**Phase 11.2 audit (2026-11-02):** the pilot was reconstructed from its raw outputs and two +claims below were corrected: the 0.069 bound (§11.2) is conditional, not a population bound, +and the CSV header is aligned, not shifted. See ML_PILOT_AUDIT.md and ML_RESEARCH_PLAN.md. + **Pilot verdict: option B as costed here is not viable.** Cost per wallet is about twice the §7 estimate, the free endpoint's throughput is about a third of the Phase 11 figure, and no positive was confirmed. See §11 before deciding on B, C or stopping. @@ -89,7 +93,7 @@ promotion record then gets the `holdout` entry that `shadow_approved` requires. | Stage | Work | Request cap | Stop rule | |---|---|---|---| -| 0 (offline) | Repair the column-shifted Poison-Hunter sample (verify the field mapping on rows with known structure; reject if ambiguous); freeze the sampling plan and holdout hash | 0 | If the sample cannot be repaired unambiguously, positives fall back to the 4 incidents plus manually curated public reports | +| 0 (offline) | Validate the Poison-Hunter sample (aligned header, 2 unnamed trailing fields) (verify the field mapping on rows with known structure; reject if ambiguous); freeze the sampling plan and holdout hash | 0 | If the sample cannot be repaired unambiguously, positives fall back to the 4 incidents plus manually curated public reports | | 1 = Option A (pilot) | As run (§11): payment check for all 149 candidate rows; 1-day recordings of random wallets. The original design (10 + 10 wallets, 7-day windows) needed ~25,000 requests and was replaced before collection | 3,000 | Report: requests per wallet, eligibility rate, positive yield. Stop for your decision | | 2 = B or C | Remaining negatives and candidates | 240,000 (B) or 30,000 (C) | Stop at the cap; report what was reached | @@ -174,8 +178,8 @@ the git-ignored `data/ml/pilot/`, and only aggregates appear here. - **"Zero" and "fake" plantings forge `Transfer(victim → attacker)` logs.** A log match would therefore confirm every such victim. Only transactions the victim signed are counted. -- **Stage 0 repaired the Poison-Hunter sample.** Every row has 17 fields against a 15-name - header. Field types identify the mapping: [0] lookalike, [1] victim, [2] imitated address, +- **Stage 0 validated the Poison-Hunter sample.** Every row has 17 fields; the 15-name header + is aligned with the first 15, and 2 trailing fields are unnamed (ML_POISONING_DATASET.md §5). Field types identify the mapping: [0] lookalike, [1] victim, [2] imitated address, [13] block. In 100 rows (types "zero" and "fake") the transaction sender is a batch operator, as expected for those attacks. 149 of 150 rows validate: 123 victims, blocks 15.86M–17.97M. One row was rejected (no address similarity). @@ -193,18 +197,21 @@ the git-ignored `data/ml/pilot/`, and only aggregates appear here. | Signed more than 100 (bot- or exchange-like) | 13 | — | | **Confirmed payment to the labelled attacker** | **0** | **0** | -- **Confirmed: 0 of 52 resolved rows.** - - Upper bound (Wilson 95%) on the share of candidate rows that end in a payment: - **0.069**. - - Among rows where the victim was active: 0 of 17, upper bound 0.18. +- **Confirmed: 0 of 52 rows checked with complete declared coverage.** + - *Corrected 2026-11-02 (ML_PILOT_AUDIT.md §3):* an earlier version gave a Wilson 95% upper + bound of 0.069 "on the share of candidate rows that end in a payment". That bound holds + only if the 52 checked rows were representative. They are not: they are the least active + victims, and they include duplicate victim-events. It says nothing about the other 97 + rows or about Poison-Hunter victims in general. - **Not covered:** - `transferFrom`, permit and router payments; - payments made after 7 days; - the 97 unresolved rows, which are the more active victims. - 90 of 123 "victims" were active. 13 rows belong to addresses that signed more than 100 transactions in a week, so the sample's victim list includes automated accounts. -- **Consequence:** under the full design, the 149 candidate rows would yield at most about - 10 positives, and plausibly 0. The positive class cannot come from this sample alone. +- **Consequence:** the pilot cannot estimate how many of the 149 rows ended in a payment. + Outcomes for the more active victims are unknown. The positive class cannot be built from + this sample by on-chain checks at this cost. ### 11.3 Cost per wallet and eligibility (random wallets, blocks 18.0M–19.3M) From 993806f0b4f0af37a7c93eef739490366f67fa38 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:02:12 +0300 Subject: [PATCH 12/92] fix(ml): drop a misleading memory figure from the poisoning report The outer tracemalloc measurement in build() was reset by the nested measurements in candidate generation and replay(), so the report showed 0.0 MiB. Per-window generation memory, measured correctly, stays in the JSON report. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/poisoning_report.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/cryptoguard/ml/poisoning_report.py b/src/cryptoguard/ml/poisoning_report.py index 4f56e11..1639e2e 100644 --- a/src/cryptoguard/ml/poisoning_report.py +++ b/src/cryptoguard/ml/poisoning_report.py @@ -12,7 +12,6 @@ import platform import subprocess import time -import tracemalloc from pathlib import Path from typing import Any @@ -155,7 +154,6 @@ def candidate_evaluation() -> dict[str, Any]: def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: - tracemalloc.start() t0 = time.perf_counter() sample = data_dir / "poison-hunter" / "phishing_transfers_sample.csv" parsed = parse_sample(sample) @@ -177,8 +175,6 @@ def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: pilot = reconstruct(pilot_dir, candidates) if (pilot_dir / "yield.jsonl").exists() else None cand_eval = candidate_evaluation() runtime = time.perf_counter() - t0 - _, peak = tracemalloc.get_traced_memory() - tracemalloc.stop() return { "task": TASK_ID, "git": _git_sha(), @@ -201,7 +197,6 @@ def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: "pilot": pilot, "candidates": cand_eval, "runtime_seconds": round(runtime, 2), - "peak_python_mib": round(peak / 2**20, 1), "rpc_requests": 0, } @@ -212,8 +207,8 @@ def render(report: dict[str, Any]) -> str: "# ML Phase 11.2 tables", "", "Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests).", - f"Git `{report['git']}`; runtime {report['runtime_seconds']} s; peak Python heap " - f"{report['peak_python_mib']} MiB.", + f"Git `{report['git']}`; runtime {report['runtime_seconds']} s (per-window generation " + "memory is in the JSON report).", "", "## Poison-Hunter sample", "", From 46c27f7199222697ea8ac65fb8c62ef5e05c1b5a Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 02:02:23 +0300 Subject: [PATCH 13/92] docs(ml): regenerate poisoning tables Co-Authored-By: Claude Opus 5.5 --- ML_POISONING_TABLES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md index a13bf17..7314648 100644 --- a/ML_POISONING_TABLES.md +++ b/ML_POISONING_TABLES.md @@ -1,7 +1,7 @@ # ML Phase 11.2 tables Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). -Git `3411c6d3cc5f596b1044f430e616a20ae24a4cbd`; runtime 7.03 s; peak Python heap 0.0 MiB. +Git `993806f0b4f0af37a7c93eef739490366f67fa38`; runtime 7.02 s (per-window generation memory is in the JSON report). ## Poison-Hunter sample From 2a783978ce7b03aa018a6b01b5427df67a845e36 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 03:42:02 +0300 Subject: [PATCH 14/92] feat(ml): offline cross-check with Tsuchiya et al. payoff transfers Parse Tsuchiya et al.'s payoff_transfers_ethereum.csv (KiltHub DOI 10.1184/R1/29212703.v1, CC BY-NC-ND 4.0) with a typed, quarantining schema and join it against the Poison-Hunter rows, their pilot outcomes and the replay incidents. The file stays local and is pinned by hash in ml/tsuchiya.py rather than ml/sources.py, so fetch-sources never downloads it unasked. Only aggregates and line numbers are reported. Results (0 RPC requests): no complete-coverage pilot row is contradicted; 76 of the 97 unchecked rows fall in the file's coverage with no payoff to their lookalike; one victim (line 74) paid a competing lookalike of the same address; one row's lookalike (line 87) was paid by another victim. Labels are unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + ML_PILOT_AUDIT.md | 32 +++ ML_POISONING_DATASET.md | 42 ++- ML_POISONING_TABLES.md | 37 ++- ML_RESEARCH_PLAN.md | 87 ++++-- src/cryptoguard/ml/pilot.py | 19 +- src/cryptoguard/ml/poisoning_report.py | 134 +++++++++- src/cryptoguard/ml/tsuchiya.py | 356 +++++++++++++++++++++++++ tests/unit/test_ml_tsuchiya.py | 220 +++++++++++++++ 9 files changed, 897 insertions(+), 34 deletions(-) create mode 100644 src/cryptoguard/ml/tsuchiya.py create mode 100644 tests/unit/test_ml_tsuchiya.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 428c7bd..0c50d3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,10 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m - a task identifier on model cards. - Docs: ML_POISONING_DATASET.md, ML_PILOT_AUDIT.md, ML_RESEARCH_PLAN.md, ML_POISONING_TABLES.md. +- Added: an offline cross-check with Tsuchiya et al.'s payoff transfers + (`ml/tsuchiya.py`; the file stays local under CC BY-NC-ND). No complete-coverage pilot + row is contradicted. One victim the pilot did not evaluate paid a competing lookalike + (ML_PILOT_AUDIT.md §7). ## 0.1.0 — 2026-10-28 (first release candidate, not independently audited) diff --git a/ML_PILOT_AUDIT.md b/ML_PILOT_AUDIT.md index cb4364a..b4349fa 100644 --- a/ML_PILOT_AUDIT.md +++ b/ML_PILOT_AUDIT.md @@ -141,3 +141,35 @@ three wallet-days and biased low (busier wallets were excluded). - a truncated ledger file (fails closed). - **Guarantee:** the recorded count is never below the attempts sent by budgeted clients. It exceeds them only by attempts reserved but never sent, for example after a crash. + +## 7. Independent cross-check with Tsuchiya et al. (2026-11-02, 0 RPC requests) + +- **Source.** Tsuchiya et al.'s `payoff_transfers_ethereum.csv` was downloaded with your + approval: KiltHub DOI 10.1184/R1/29212703.v1, CC BY-NC-ND 4.0. It is kept local in + `data/external/tsuchiya2025/` and its MD5 matches KiltHub's. + - It lists 1,738 victim-to-lookalike token payoffs in blocks 16,060,625–20,207,365: 1,733 + in USDT, USDC or DAI, 5 in other tokens, and none in native ETH. + - Parser and join: `ml/tsuchiya.py`. Tables: ML_POISONING_TABLES.md. +- **No contradiction.** None of the 52 complete-coverage rows has a payoff in the file, to + any lookalike, at any time. +- **The 97 rows the pilot could not check:** + - 76 of them fall inside the study period and its 3+4 lookalike definition (34 + unresolved, 42 not evaluated). The file has no payoff to the row's own lookalike for any + of them. + - **Line 74** (not evaluated): 11,653 blocks (about 1.6 days) after the planting, the + victim paid about $5,032 to a *different* lookalike of the same address. That lookalike + matched 3+6 characters; the row's own lookalike matched 7+6. +- **Line 87** (not evaluated): the row's lookalike had received about $5,973 from *another* + victim, who meant to pay the same address, 12,053 blocks *before* this planting. That is + independent evidence that this lookalike belongs to an attacker. +- **What this does and does not show.** + - Missing from the file is weaker evidence than "no payment". The file lists only token + payoffs to lookalikes that Tsuchiya et al.'s own pipeline detected, and only up to block + 20,207,365. + - Whether their pipeline detected each Poison-Hunter lookalike can't be checked from the + payoff file; that needs their attempt table (the 2.3 GB dump). + - The result is consistent with a low success rate for each event, but it isn't a rate + estimate: the rows are not a random sample, and 6 are duplicates. +- **Effect on the pilot outcomes: none.** Pilot outcomes record only payments the pilot + observed itself. Line 74 shows that a *victim's* loss and a *given event's* outcome can + differ: the payment went to a competing lookalike. diff --git a/ML_POISONING_DATASET.md b/ML_POISONING_DATASET.md index 5ed6800..1385a0f 100644 --- a/ML_POISONING_DATASET.md +++ b/ML_POISONING_DATASET.md @@ -143,14 +143,52 @@ positive-case reproduction, candidate recall and feature testing, not for binary Training for this task is blocked until gates B and D pass. -## 7. External sources reviewed (no data downloaded) +## 7. External sources reviewed These were checked from the source pages on 2026-11-02 by a research agent; details are in ML_RESEARCH_PLAN.md §5. | Source | What it offers | Blocker | |---|---|---| -| Tsuchiya et al., USENIX Security 2025 (KiltHub DOI 10.1184/R1/29212703.v1) | Ethereum attempts (2.3 GB SQL dump) plus payoff-transfer CSVs (under 2 MB) | Licence CC BY-NC-ND 4.0; download needs your approval | +| Tsuchiya et al., USENIX Security 2025 (KiltHub DOI 10.1184/R1/29212703.v1) | Ethereum attempts (2.3 GB SQL dump) plus payoff-transfer CSVs (under 2 MB) | Licence CC BY-NC-ND 4.0. The Ethereum payoff CSV is downloaded (§8); every other file needs your approval | | Poison-Hunter full data | Withheld; "contact us", with no address published | Request needed | | Forta labelled datasets | MIT, Etherscan-derived address labels | No poisoning category, no loss transactions | | Etherscan labels | Underlie Forta and Poison-Hunter ground truth | Terms require written permission for ML or dataset use | + +## 8. Tsuchiya et al. payoff transfers (`ml/tsuchiya.py`, `tsuchiya-payoff/1`) + +**Source.** +- `payoff_transfers_ethereum.csv` from KiltHub DOI 10.1184/R1/29212703.v1, CC BY-NC-ND 4.0. +- Downloaded once with your approval on 2026-11-02 into the git-ignored + `data/external/tsuchiya2025/`. 482,397 bytes; the MD5 matches KiltHub's; the SHA-256 is + pinned in the module. +- Not listed in `ml/sources.py`, because `fetch-sources` would download it unasked. +- The licence permits local non-commercial research use but no redistributed adaptations. + Only aggregate counts and Poison-Hunter line numbers leave the module. + +**Columns.** 11 named columns, each identified on all 1,738 rows: +- block and transaction; +- token contract (`addr`); +- payer, the victim (`topics_from_addr`); +- recipient, the lookalike (`topics_to_addr`); +- amount (float-encoded base units, plus USD); +- `is_sender_victim` (always `True`); +- leading and trailing matched digits; +- the intended address. + +**Validation.** +- 1,738 rows are valid and 0 are quarantined. +- Every row's declared affix counts equal `affix_match` on its addresses. +- One row per transaction: 1,502 payers and 1,551 lookalikes. +- Blocks 16,060,625–20,207,365. +- Tokens: USDT 1,154, USDC 543, DAI 36, other 5. None are native ETH. +- 41 amounts cannot be represented exactly as stored, so only `value_usd` is used. + +**How it is used.** +- **As outcome evidence only: a victim paid a lookalike.** It contains no planting + transactions, so it creates no `PoisoningEvent` and no label. +- **Absence is not a negative.** A victim missing from the file has not been shown to + have avoided a loss. The file has no ETH, covers only lookalikes the study detected with + at least 3 leading and 4 trailing matches, and ends in mid-2024. +- **Per-event attribution.** A payoff to a different lookalike of the same address (one + case, line 74) is a loss for the victim, not an outcome of that Poison-Hunter event. diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md index 7314648..29d26d4 100644 --- a/ML_POISONING_TABLES.md +++ b/ML_POISONING_TABLES.md @@ -1,7 +1,7 @@ # ML Phase 11.2 tables Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). -Git `993806f0b4f0af37a7c93eef739490366f67fa38`; runtime 7.02 s (per-window generation memory is in the JSON report). +Git `46c27f7199222697ea8ac65fb8c62ef5e05c1b5a`; runtime 5.76 s (per-window generation memory is in the JSON report). ## Poison-Hunter sample @@ -54,6 +54,41 @@ Quarantined line 3: only direction 'to' row: imitation mapping for this directio | Recordings whose contents were lost | 3 | migration | | Conditional Wilson 95% upper bound | 0.069 | 0 of 52 complete rows; not a population bound | +## Cross-check with Tsuchiya et al. payoff transfers + +Source: KiltHub DOI 10.1184/R1/29212703.v1 (CC BY-NC-ND 4.0), kept local. SHA-256 `7851f9f9edcf0418…` (matches the pinned hash); MD5 matches the value KiltHub publishes. + +| Quantity | Value | +|---|---| +| Rows / valid / quarantined | 1738 / 1738 / 0 | +| Payoff block range | 16,060,625-20,207,365 | +| Tokens | USDT 1154, USDC 543, DAI 36, other 5 | +| Distinct payers / lookalikes | 1502 / 1551 | +| Amounts not exactly representable (float-encoded) | 41 | +| Accepted by the detector predicate / candidate rule | 1738 / 1738 (implied by the study's 3+4 selection: a consistency check, not recall) | + +Poison-Hunter rows by pilot outcome (window: 50,400 blocks after the planting): + +| Pilot outcome | Rows | In payoff period | In 3+4 definition | Paid this lookalike (in window) | Paid another lookalike of the same address | Lookalike paid by another victim | +|---|---|---|---|---|---|---| +| complete, none seen | 52 | 52 | 29 | 0 (0) | 0 | 0 | +| not evaluated | 51 | 51 | 42 | 0 (0) | 1 | 1 | +| unresolved | 46 | 45 | 34 | 0 (0) | 0 | 0 | + +Complete-coverage rows contradicted by a payoff to the same lookalike in the window: 0. + +- Line 74 (not evaluated): paid another lookalike of the same address, 11,653 blocks after the planting, about $5,032, meaning to pay the same address; affix 3+6 (row lookalike 7+6). +- Line 87 (not evaluated): paid this lookalike, by another victim, 12,053 blocks before the planting, about $5,973, meaning to pay the same address; affix 9+6 (row lookalike 9+6). + +| Incident | In payoff period | Token in file | Harmful tx listed | Victim listed | +|---|---|---|---|---| +| eth-140-poisoning-2025-08-14 | no | no | no | no | +| eth-4556-poisoning-2026-01-30 | no | no | no | no | +| usdt-50m-poisoning-2025-12-19 | no | yes | no | no | +| wbtc-1155-poisoning-2024-05-03 | yes | no | no | no | + +Absence from the payoff file is not evidence of no payment: it has no native-ETH payoffs, covers only lookalikes the study itself detected (at least 3 leading and 4 trailing matching characters), and ends at the block above. + ## Candidate generation (recorded replay fixtures) | Incident | Candidates | Harmful lookalike found | Candidate lead (blocks) | Detector lead (blocks) | First-hit rules | diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 47fda8f..b30855f 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -1,7 +1,7 @@ # ML research plan: wallet-centric poisoning detection (Phase 11.2) Status: infrastructure done, gates B and D fail (no verified labels), and no model is trained -for this task. Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). +for this task. The Tsuchiya et al. payoff cross-check is done (§6). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). @@ -20,6 +20,7 @@ Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: | 9 | P2 | **Imprecise description of the CSV.** The Poison-Hunter header was described as "shifted"; it is aligned, with 2 unnamed trailing fields | Corrected in docs and the parser docstring | | 10 | P2 | **Rows counted as events.** The pilot treated duplicate victim-events as separate observations | Reported (149 rows, 143 events); the event model deduplicates | | 11 | P2 | **Phase 11 monitoring on sparse features** keeps the old binning until the model is retrained | Open (the model is research-only, so no live impact) | +| 12 | P2 | **A victim's loss is not the event's outcome.** In the Tsuchiya cross-check, a Poison-Hunter victim paid a *competing* lookalike of the same address (line 74) | Documented: `OutcomeRecord` is per event, and a loss to another lookalike is never credited to this event (ML_PILOT_AUDIT.md §7) | ## 2. Task definition @@ -89,36 +90,74 @@ at 26 requests each, 10% retries, 4 requests/s. archive indexer would provide, replaces bisection. - None of this has been run, and none is authorized. -## 5. External data (checked on 2026-11-02; nothing downloaded) +## 5. External data (checked on 2026-11-02; only the Ethereum payoff CSV downloaded) | Source | Verified facts | Fit | Blocker | |---|---|---|---| -| Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. KiltHub DOI 10.1184/R1/29212703.v1 | Files: `payoff_transfers_ethereum.csv` (482 KB), `payoff_transfers_bsc.csv` (1.33 MB), `address_poisoning_ethereum.sql.gz` (2.32 GB). Licence CC BY-NC-ND 4.0 | Payoffs give independent confirmed-loss transfers (stablecoin, Ethereum, 2022-07 to 2024-06) | Download needs your approval; NC-ND allows local research use only, with no redistributed derivatives; columns not yet inspected | +| Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. KiltHub DOI 10.1184/R1/29212703.v1 | Files: `payoff_transfers_ethereum.csv` (482 KB, **downloaded with approval, parsed**: 1,738 token payoffs, no ETH), `payoff_transfers_bsc.csv` (1.33 MB), `address_poisoning_ethereum.sql.gz` (2.32 GB, the attempt table). Licence CC BY-NC-ND 4.0 | Payoffs: independent confirmed losses. The dump: the attempts behind them | NC-ND allows local research use only, with no redistributed derivatives. Each further file needs your approval | | Poison-Hunter (Guan and Li, CCS 2024), `DS2L/Poison-Hunter` | 5 files in the repository, no licence; full data "available on request", with no contact address published | Weak attempt labels | A request is needed; a draft request exists, not sent | | RMIT arXiv 2609.23405 | Claims 4,209 victim transfers; its artifact link showed no files | — | Unverified | | Forta labelled datasets | MIT; Etherscan phish-hack/exploit/heist labels | Contamination checks only | No poisoning category | | Etherscan labels | Terms require written permission for ML or dataset creation | — | Affects Forta and Poison-Hunter ground truth | -## 6. Next experiment (highest value, 0 RPC requests) - -**Cross-check the Poison-Hunter rows against Tsuchiya et al.'s independent payoff list.** - -- **Needs:** your approval to download `payoff_transfers_ethereum.csv` (482 KB, CC BY-NC-ND - 4.0, kept local under `data/external/`, never committed). It is a file download, so your - standing rule requires an explicit yes. -- **Method.** Pin its hash in `ml/sources.py`, then parse it with a typed schema after - inspecting the columns. Join it on victim and lookalike with the 143 Poison-Hunter - victim-events and the 4 replay incidents. +## 6. Done: cross-check with Tsuchiya et al.'s payoff list (0 RPC requests) + +Details: ML_PILOT_AUDIT.md §7. Code: `ml/tsuchiya.py`, run by `cryptoguard ml poisoning-report` +whenever the file is present. + +- **Deviation from the plan.** The hash is pinned in `ml/tsuchiya.py`, not `ml/sources.py`. + `fetch-sources` downloads every source in that registry unasked, and this file needs a + download decision each time. +- **Results against the three expected outcomes.** + 1. **Outcome evidence for the 97 unknown rows.** + - The file has no payoff to the row's own lookalike for any of them. 76 of the 97 lie + inside its definition and period. + - One victim (line 74) paid a competing lookalike of the same address within 1.6 days. + - None of the 52 complete-coverage rows is contradicted. + - These absences rest on the file's coverage; they are not proof of no payment. + 2. **Label agreement on attempts: not measurable from the payoff file.** Attempts are in + the 2.3 GB dump. One Poison-Hunter lookalike (line 87) appears as a payoff recipient + from another victim, which independently corroborates that row. + 3. **Confirmed losses: 1,738 payoffs** (1,502 payers, 1,551 lookalikes). The planting + transactions that preceded them are not in the CSV, so none is an event yet. +- **Labels unchanged, as stated in advance.** Line 87 is a candidate for the review + workflow, not an automatic upgrade. +- **Consistency checks.** + - The source's declared affix counts equal `affix_match` on all 1,738 rows. + - Both CryptoGuard predicates accept all 1,738 lookalikes. The study's 3+4 selection + implies this, so it is not recall. + - 41 amounts are float-encoded beyond exact precision. Only `value_usd` is used. +- **Incidents.** + - Three of the four are after the file's last block. + - wbtc-1155 is inside the period but was paid in WBTC, and the file has no WBTC payoffs. + - None appears in the file. + +## 7. Next experiment (highest value, 0 RPC requests) + +**Turn confirmed payoffs into reviewable attempt events using Tsuchiya et al.'s attempt +table.** + +- **Needs:** + - your approval to download `address_poisoning_ethereum.sql.gz` (2.32 GB, CC BY-NC-ND + 4.0, kept local and never committed); + - about 2.4 GB of free disk. +- **Method.** + - Stream-parse the dump (gzip, line by line, constant memory: no import into a database + and no full decompression). + - For each payoff, take the latest attempt by that lookalike against that victim before + the payoff block: the planting transaction, its subtype and its block. + - Build `PoisoningEvent`s for them, and for the Poison-Hunter rows that the dump also + lists. - **What it gives.** - 1. Independent outcome evidence for the 97 rows the pilot could not resolve, at no RPC - cost. - 2. Agreement between two independent pipelines on attempts, giving a first estimate of - label noise. - 3. A list of confirmed-loss victims whose preceding attempts could become - `verified_attempt` positives after review. -- **Success criterion, stated now.** Report the overlap counts and the disagreements as - they are. Do not change the Poison-Hunter labels on the basis of the overlap alone; - changes go through the review workflow. + 1. Attempt-level agreement between Poison-Hunter and Tsuchiya et al.: the first measured + label-noise estimate. + 2. A pool of attempt events with an independently confirmed loss, ready for the review + workflow (`verified_attempt` only after review). + 3. Whether Tsuchiya et al.'s pipeline detected each Poison-Hunter lookalike, which turns + the absences above into evidence that rests on known coverage. +- **The RPC alternative is far costlier.** Finding each planting transaction on the free + endpoint means scanning 7 days of logs per payoff: about 1,000 requests each at 100 + blocks per query, so about 100,000 requests per 100 payoffs. - **Still missing afterwards:** verified negatives (gate B). They need a reviewed sample of - legitimate lookalike-shaped interactions, which no public source provides. That is the - real blocker for supervised learning on this task. + legitimate lookalike-shaped interactions, which no public source provides. That remains + the real blocker for supervised learning on this task. diff --git a/src/cryptoguard/ml/pilot.py b/src/cryptoguard/ml/pilot.py index 9a0c14c..c5a7301 100644 --- a/src/cryptoguard/ml/pilot.py +++ b/src/cryptoguard/ml/pilot.py @@ -288,15 +288,14 @@ def wilson_upper(k: int, n: int, z: float = 1.959964) -> float | None: return (centre + spread) / (1 + z * z / n) -def reconstruct( +def load_yield( pilot_dir: Path, candidates: list[tuple[int, str, str]] | None = None -) -> dict[str, Any]: - """Recompute the pilot report from its raw outputs. +) -> tuple[list[YieldRecord], bool]: + """Typed yield records (and whether a truncated tail was skipped). ``candidates``: ``(source_line, victim, lookalike)`` of the parser's valid rows in file order; the yield file is checked against it row by row.""" - yield_raw, y_trunc = read_jsonl(pilot_dir / "yield.jsonl") - cost_raw, c_trunc = read_jsonl(pilot_dir / "cost.jsonl") + yield_raw, truncated = read_jsonl(pilot_dir / "yield.jsonl") if candidates is not None: if len(candidates) != len(yield_raw): raise PilotRecordError( @@ -309,7 +308,15 @@ def reconstruct( ): raise PilotRecordError("yield lines are not in candidate order") lines = [c[0] for c in candidates] if candidates else [None] * len(yield_raw) - ys = [yield_record(o, line) for o, line in zip(yield_raw, lines, strict=True)] + return [yield_record(o, line) for o, line in zip(yield_raw, lines, strict=True)], truncated + + +def reconstruct( + pilot_dir: Path, candidates: list[tuple[int, str, str]] | None = None +) -> dict[str, Any]: + """Recompute the pilot report from its raw outputs (``candidates`` as in ``load_yield``).""" + ys, y_trunc = load_yield(pilot_dir, candidates) + cost_raw, c_trunc = read_jsonl(pilot_dir / "cost.jsonl") cs = [cost_record(o) for o in cost_raw] budget = json.loads((pilot_dir / "budget.json").read_text(encoding="utf-8")) summary = json.loads((pilot_dir / "summary.json").read_text(encoding="utf-8")) diff --git a/src/cryptoguard/ml/poisoning_report.py b/src/cryptoguard/ml/poisoning_report.py index 1639e2e..cb01079 100644 --- a/src/cryptoguard/ml/poisoning_report.py +++ b/src/cryptoguard/ml/poisoning_report.py @@ -33,8 +33,11 @@ resolve_labels, ) from cryptoguard.ml.history import events_from_fixture -from cryptoguard.ml.pilot import reconstruct, render_markdown +from cryptoguard.ml.pilot import load_yield, reconstruct, render_markdown from cryptoguard.ml.poison_hunter import PoisonHunterRecord, parse_sample, profile +from cryptoguard.ml.tsuchiya import SOURCE_FILE as PAYOFF_FILE +from cryptoguard.ml.tsuchiya import cross_check, parse_payoffs +from cryptoguard.ml.tsuchiya import profile as payoff_profile _SUBTYPE = {"dust": "dust", "zero": "zero_value", "fake": "fake_token"} @@ -153,6 +156,36 @@ def candidate_evaluation() -> dict[str, Any]: } +def payoff_cross_check( + path: Path, + rows: list[PoisonHunterRecord], + pilot_dir: Path, + candidates: list[tuple[int, str, str]], +) -> dict[str, Any]: + """Tsuchiya et al.'s payoff transfers against Poison-Hunter rows, pilot outcomes and + the recorded incidents. Aggregates and Poison-Hunter line numbers only (CC BY-NC-ND).""" + from cryptoguard.replay.models import load_cases + + parsed = parse_payoffs(path) + outcomes = None + if (pilot_dir / "yield.jsonl").exists(): + outcomes = [y.outcome for y in load_yield(pilot_dir, candidates)[0]] + incidents = [ + { + "case": m.case_id, + "victim": m.victim, + "block": m.harm.block_number, + "tx": m.harm.transaction_hash, + "token": m.harm.token, + } + for m in (case.manifest for case in load_cases()) + ] + return { + "source": payoff_profile(parsed), + **cross_check(parsed.valid, rows, outcomes, incidents), + } + + def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: t0 = time.perf_counter() sample = data_dir / "poison-hunter" / "phishing_transfers_sample.csv" @@ -173,6 +206,12 @@ def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: gates = quality_gates(events, resolved, license_ok=False) candidates = [(r.source_line, r.victim, r.lookalike) for r in parsed.valid] pilot = reconstruct(pilot_dir, candidates) if (pilot_dir / "yield.jsonl").exists() else None + payoff_path = data_dir / "tsuchiya2025" / PAYOFF_FILE + payoffs = ( + payoff_cross_check(payoff_path, parsed.valid, pilot_dir, candidates) + if payoff_path.exists() + else None + ) cand_eval = candidate_evaluation() runtime = time.perf_counter() - t0 return { @@ -195,12 +234,103 @@ def build(data_dir: Path, pilot_dir: Path) -> dict[str, Any]: }, "gates": [g.model_dump() for g in gates], "pilot": pilot, + "payoff_cross_check": payoffs, "candidates": cand_eval, "runtime_seconds": round(runtime, 2), "rpc_requests": 0, } +_OUTCOME_SHORT = { + "confirmed_direct_payment": "confirmed", + "no_direct_payment_observed_with_complete_declared_coverage": "complete, none seen", + "partial_coverage": "partial", + "unresolved": "unresolved", + "not_evaluated": "not evaluated", + "no_pilot_record": "no pilot record", +} + + +def render_payoffs(x: dict[str, Any]) -> list[str]: + src = x["source"] + lo, hi = x["payoff_block_range"] + sha = "matches" if src["source_sha256_matches_pinned"] else "**differs from**" + md5 = "matches" if src["source_md5_matches_published"] else "**differs from**" + lines = [ + "## Cross-check with Tsuchiya et al. payoff transfers", + "", + "Source: KiltHub DOI 10.1184/R1/29212703.v1 (CC BY-NC-ND 4.0), kept local. " + f"SHA-256 `{src['source_sha256'][:16]}…` ({sha} the pinned hash); MD5 {md5} the " + "value KiltHub publishes.", + "", + "| Quantity | Value |", + "|---|---|", + f"| Rows / valid / quarantined | {src['rows']} / {src['valid']} / " + f"{len(src['quarantined'])} |", + f"| Payoff block range | {lo:,}-{hi:,} |", + f"| Tokens | {', '.join(f'{k} {v}' for k, v in src['tokens'].items())} |", + f"| Distinct payers / lookalikes | {src['distinct_payers']} / " + f"{src['distinct_lookalikes']} |", + f"| Amounts not exactly representable (float-encoded) | {src['inexact_values']} |", + f"| Accepted by the detector predicate / candidate rule | " + f"{src['detector_predicate_accepts']} / {src['candidate_rule_accepts']} (implied by " + "the study's 3+4 selection: a consistency check, not recall) |", + "", + f"Poison-Hunter rows by pilot outcome (window: {x['window_blocks']:,} blocks after " + "the planting):", + "", + "| Pilot outcome | Rows | In payoff period | In 3+4 definition | Paid this lookalike " + "(in window) | Paid another lookalike of the same address | Lookalike paid by " + "another victim |", + "|---|---|---|---|---|---|---|", + ] + for outcome, b in x["by_outcome"].items(): + lines.append( + f"| {_OUTCOME_SHORT.get(outcome, outcome)} | {b['rows']} | {b['in_period']} | " + f"{b['in_definition']} | {b['victim_paid_this_lookalike']} " + f"({b['victim_paid_this_lookalike_in_window']}) | " + f"{b['victim_paid_other_lookalike_of_same_address']} | " + f"{b['lookalike_paid_by_another_victim']} |" + ) + lines += [ + "", + "Complete-coverage rows contradicted by a payoff to the same lookalike in the window: " + f"{len(x['contradicted_complete_rows'])}.", + "", + ] + for f in x["findings"]: + d = f["blocks_after_planting"] + when = ( + "at an unknown block" + if d is None + else f"{abs(d):,} blocks {'after' if d > 0 else 'before'} the planting" + ) + intended = "the same" if f["same_intended_address"] else "a different" + lines.append( + f"- Line {f['line']} ({_OUTCOME_SHORT.get(f['outcome'], f['outcome'])}): paid " + f"{f['paid']}, {when}, about ${f['value_usd']:,}, meaning to pay {intended} " + f"address; affix {f['paid_affix'][0]}+{f['paid_affix'][1]} (row lookalike " + f"{f['row_affix'][0]}+{f['row_affix'][1]})." + ) + lines += [ + "", + "| Incident | In payoff period | Token in file | Harmful tx listed | Victim listed |", + "|---|---|---|---|---|", + *( + f"| {i['case']} | {'yes' if i['in_period'] else 'no'} | " + f"{'yes' if i['token_in_file'] else 'no'} | {'yes' if i['harm_tx_listed'] else 'no'}" + f" | {'yes' if i['victim_listed'] else 'no'} |" + for i in x["incidents"] + ), + "", + "Absence from the payoff file is not evidence of no payment: it has no native-ETH " + "payoffs, covers only lookalikes the study itself detected (at least 3 leading and " + "4 trailing matching characters), and ends at the block above.", + "", + ] + return lines + + def render(report: dict[str, Any]) -> str: ph, ev, cand = report["poison_hunter"], report["events"], report["candidates"] lines = [ @@ -252,6 +382,8 @@ def render(report: dict[str, Any]) -> str: ] if report["pilot"] is not None: lines += ["## Pilot reconstruction", "", render_markdown(report["pilot"])] + if report.get("payoff_cross_check") is not None: + lines += render_payoffs(report["payoff_cross_check"]) lines += [ "## Candidate generation (recorded replay fixtures)", "", diff --git a/src/cryptoguard/ml/tsuchiya.py b/src/cryptoguard/ml/tsuchiya.py new file mode 100644 index 0000000..a1bbde9 --- /dev/null +++ b/src/cryptoguard/ml/tsuchiya.py @@ -0,0 +1,356 @@ +"""Typed parser and offline cross-check for Tsuchiya et al.'s ``payoff_transfers_ethereum.csv``. + +Source: Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. Companion +dataset on KiltHub, DOI 10.1184/R1/29212703.v1, licensed CC BY-NC-ND 4.0. Each row is one +token transfer in which a victim paid a lookalike address (a *payoff*). The file stays local +(``data/`` is git-ignored) because the licence forbids redistributing adaptations, so only +aggregate counts and Poison-Hunter line numbers leave this module. + +Columns (checked on all 1,738 rows of the pinned file; see ML_POISONING_DATASET.md): + +========================== =========================================================== +column content +========================== =========================================================== +block_number payoff block +tx_hash payoff transaction (one row per transaction) +addr token contract (USDT, USDC or DAI in all but 5 rows) +topics_from_addr payer: the victim +topics_to_addr recipient: the lookalike +value amount in base units, float-encoded (some rows use + scientific notation, so values above 2**53 are rounded) +value_usd amount in USD, as computed by the source +is_sender_victim ``True`` in every row +num_first_matched_digits leading hex characters shared with ``intended_addr`` +num_last_matched_digits trailing hex characters shared with ``intended_addr`` +intended_addr the address the victim presumably meant to pay +========================== =========================================================== + +The file has no native-ETH payoffs, and the study selected lookalikes sharing at least 3 +leading and 4 trailing hex characters. Absence of a victim from this file is therefore not +evidence that no payment happened: ETH payments, other tokens, lookalikes outside that +definition and payments after the study period are not in it. +""" + +from __future__ import annotations + +import csv +import hashlib +import re +from collections import Counter +from collections.abc import Sequence +from decimal import Decimal, InvalidOperation +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict + +from cryptoguard.detectors.poisoning import PoisoningConfig, affix_match, is_lookalike +from cryptoguard.ml.candidates import MIN_AFFIX, MIN_SUFFIX +from cryptoguard.ml.poison_hunter import PoisonHunterRecord, SchemaMismatchError + +PARSER_VERSION = "tsuchiya-payoff/1" +SOURCE_DOI = "10.1184/R1/29212703.v1" +SOURCE_LICENSE = "CC BY-NC-ND 4.0" +SOURCE_FILE = "payoff_transfers_ethereum.csv" +# Not in ml/sources.py: `fetch-sources` downloads every listed source unasked, and this +# file needs an explicit download decision. Fetched once on 2026-11-02 (482,397 bytes). +SOURCE_URL = "https://ndownloader.figshare.com/files/55053137" +SOURCE_MD5 = "a42bda4339981d31a7e31b66c2d92297" # published by KiltHub for version 1 +SOURCE_SHA256 = "7851f9f9edcf04189137894e16dd228a544d13f4a0799548ece79c69762f2f78" +EXPECTED_HEADER = [ + "block_number", + "tx_hash", + "addr", + "topics_from_addr", + "topics_to_addr", + "value", + "value_usd", + "is_sender_victim", + "num_first_matched_digits", + "num_last_matched_digits", + "intended_addr", +] +TOKENS = { + "0xdac17f958d2ee523a2206206994597c13d831ec7": "USDT", + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": "USDC", + "0x6b175474e89094c44da98b954eedeac495271d0f": "DAI", +} +WINDOW_BLOCKS = 50_400 # the pilot's 7-day payment window +_EXACT_FLOAT = 2**53 + +_ADDR = re.compile(r"^0x[0-9a-fA-F]{40}$") +_HASH = re.compile(r"^0x[0-9a-fA-F]{64}$") + +Status = Literal["valid", "quarantined"] + + +class PayoffTransfer(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + source_line: int # 1-based line in the CSV (header = line 1) + status: Status + issues: tuple[str, ...] + block_number: int | None + tx_hash: str + token: str + payer: str + lookalike: str + intended: str + value_usd: float | None + value_exact: bool # False when the float encoding cannot hold the base-unit amount + prefix_match: int + suffix_match: int + + +class PayoffParse(BaseModel): + model_config = ConfigDict(extra="forbid") + + parser_version: str + source_sha256: str + source_md5: str + records: list[PayoffTransfer] + + @property + def valid(self) -> list[PayoffTransfer]: + return [r for r in self.records if r.status == "valid"] + + +def _int(text: str) -> int | None: + try: + return int(text) + except ValueError: + return None + + +def _float(text: str) -> float | None: + try: + return float(text) + except ValueError: + return None + + +def _exact(text: str) -> bool: + try: + value = Decimal(text) + except InvalidOperation: + return False + return value == value.to_integral_value() and abs(value) < _EXACT_FLOAT + + +def _parse_row(line: int, r: dict[str, str]) -> PayoffTransfer: + issues: list[str] = [] + addresses = ("addr", "topics_from_addr", "topics_to_addr", "intended_addr") + for name in addresses: + if not _ADDR.match(r[name]): + issues.append(f"{name} is not an address") + if not _HASH.match(r["tx_hash"]): + issues.append("tx_hash is not a 32-byte hash") + block = _int(r["block_number"]) + if block is None: + issues.append("block_number is not an integer") + if r["is_sender_victim"] != "True": + issues.append(f"is_sender_victim is {r['is_sender_victim']!r}") + usd = _float(r["value_usd"]) + if usd is None or usd < 0: + issues.append("value_usd is not a non-negative number") + valid_pair = all(_ADDR.match(r[n]) for n in ("topics_to_addr", "intended_addr")) + prefix, suffix = affix_match(r["topics_to_addr"], r["intended_addr"]) if valid_pair else (0, 0) + declared = (_int(r["num_first_matched_digits"]), _int(r["num_last_matched_digits"])) + if valid_pair and declared != (prefix, suffix): + issues.append(f"declared affix {declared} differs from the addresses ({prefix}, {suffix})") + return PayoffTransfer( + source_line=line, + status="quarantined" if issues else "valid", + issues=tuple(issues), + block_number=block, + tx_hash=r["tx_hash"].lower(), + token=r["addr"].lower(), + payer=r["topics_from_addr"].lower(), + lookalike=r["topics_to_addr"].lower(), + intended=r["intended_addr"].lower(), + value_usd=usd, + value_exact=_exact(r["value"]), + prefix_match=prefix, + suffix_match=suffix, + ) + + +def parse_payoffs(path: Path) -> PayoffParse: + """Parse every row; rows failing a check are quarantined with reasons, never dropped.""" + raw = path.read_bytes() + with path.open(newline="", encoding="utf-8") as fh: + reader = csv.DictReader(fh) + if reader.fieldnames != EXPECTED_HEADER: + raise SchemaMismatchError(f"{path}: header differs from the identified layout") + rows = list(reader) + if any(None in r or None in r.values() for r in rows): + raise SchemaMismatchError(f"{path}: a row's width differs from the header") + return PayoffParse( + parser_version=PARSER_VERSION, + source_sha256=hashlib.sha256(raw).hexdigest(), + source_md5=hashlib.md5(raw, usedforsecurity=False).hexdigest(), + records=[_parse_row(i + 2, r) for i, r in enumerate(rows)], + ) + + +def block_range(payoffs: list[PayoffTransfer]) -> tuple[int, int] | None: + blocks = [p.block_number for p in payoffs if p.block_number is not None] + return (min(blocks), max(blocks)) if blocks else None + + +def profile(result: PayoffParse, config: PoisoningConfig | None = None) -> dict[str, Any]: + """Aggregate validation report (no addresses).""" + config = config or PoisoningConfig() + valid = result.valid + usd = sorted(p.value_usd for p in valid if p.value_usd is not None) + return { + "parser_version": result.parser_version, + "source_sha256": result.source_sha256, + "source_md5_matches_published": result.source_md5 == SOURCE_MD5, + "source_sha256_matches_pinned": result.source_sha256 == SOURCE_SHA256, + "rows": len(result.records), + "valid": len(valid), + "quarantined": [ + {"line": r.source_line, "issues": list(r.issues)} + for r in result.records + if r.status == "quarantined" + ], + "block_range": block_range(valid), + "tokens": dict(Counter(TOKENS.get(p.token, "other") for p in valid).most_common()), + "distinct_txs": len({p.tx_hash for p in valid}), + "distinct_payers": len({p.payer for p in valid}), + "distinct_lookalikes": len({p.lookalike for p in valid}), + "inexact_values": sum(1 for p in valid if not p.value_exact), + "usd_total": round(sum(usd)), + "usd_median": round(usd[len(usd) // 2], 2) if usd else None, + # The study's 3+4 selection implies both predicates, so these are consistency + # checks of the shared affix arithmetic, not recall measurements. + "detector_predicate_accepts": sum( + 1 for p in valid if is_lookalike(p.lookalike, p.intended, config) + ), + "candidate_rule_accepts": sum( + 1 + for p in valid + if p.prefix_match + p.suffix_match >= MIN_AFFIX and p.suffix_match >= MIN_SUFFIX + ), + } + + +def _bucket() -> dict[str, int]: + return dict.fromkeys( + ( + "rows", + "in_period", + "in_definition", + "victim_paid_this_lookalike", + "victim_paid_this_lookalike_in_window", + "victim_paid_other_lookalike_of_same_address", + "victim_paid_any_lookalike", + "lookalike_paid_by_another_victim", + ), + 0, + ) + + +def _finding(r: PoisonHunterRecord, outcome: str, p: PayoffTransfer, kind: str) -> dict[str, Any]: + return { + "line": r.source_line, + "outcome": outcome, + "paid": kind, + "blocks_after_planting": ( + p.block_number - r.block_number + if p.block_number is not None and r.block_number is not None + else None + ), + "value_usd": round(p.value_usd) if p.value_usd is not None else None, + "same_intended_address": p.intended == r.imitated, + "paid_affix": [p.prefix_match, p.suffix_match], + "row_affix": [r.prefix_match, r.suffix_match], + } + + +def cross_check( + payoffs: list[PayoffTransfer], + rows: list[PoisonHunterRecord], + outcomes: Sequence[str] | None, + incidents: list[dict[str, Any]], + window_blocks: int = WINDOW_BLOCKS, +) -> dict[str, Any]: + """Match payoffs against Poison-Hunter rows (with their pilot outcomes) and incidents. + + ``outcomes`` is aligned with ``rows``; ``incidents`` items carry ``case``, ``victim``, + ``block``, ``tx`` and ``token``. A payoff counts *in window* when it lands in blocks + (planting, planting + window]. Rows are reported by Poison-Hunter line, never address.""" + if outcomes is not None and len(outcomes) != len(rows): + raise ValueError(f"{len(outcomes)} outcomes for {len(rows)} rows") + span = block_range(payoffs) + by_payer: dict[str, list[PayoffTransfer]] = {} + by_lookalike: dict[str, list[PayoffTransfer]] = {} + for p in payoffs: + by_payer.setdefault(p.payer, []).append(p) + by_lookalike.setdefault(p.lookalike, []).append(p) + + buckets: dict[str, dict[str, int]] = {} + findings: list[dict[str, Any]] = [] + contradictions: list[int] = [] + for i, r in enumerate(rows): + outcome = outcomes[i] if outcomes is not None else "no_pilot_record" + b = buckets.setdefault(outcome, _bucket()) + b["rows"] += 1 + planted = r.block_number + in_period = span is not None and planted is not None and span[0] <= planted <= span[1] + b["in_period"] += in_period + b["in_definition"] += in_period and r.tsuchiya_lookalike + paid = by_payer.get(r.victim, []) + same = [p for p in paid if p.lookalike == r.lookalike] + in_window = [ + p + for p in same + if planted is not None + and p.block_number is not None + and 0 < p.block_number - planted <= window_blocks + ] + other = [p for p in paid if p.lookalike != r.lookalike and p.intended == r.imitated] + b["victim_paid_this_lookalike"] += bool(same) + b["victim_paid_this_lookalike_in_window"] += bool(in_window) + b["victim_paid_other_lookalike_of_same_address"] += bool(other) + b["victim_paid_any_lookalike"] += bool(paid) + b["lookalike_paid_by_another_victim"] += any( + p.payer != r.victim for p in by_lookalike.get(r.lookalike, []) + ) + if in_window and outcome == "no_direct_payment_observed_with_complete_declared_coverage": + contradictions.append(r.source_line) + for p in paid: + if p.lookalike == r.lookalike: + kind = "this lookalike" + elif p.intended == r.imitated: + kind = "another lookalike of the same address" + else: + kind = "a lookalike of another address" + findings.append(_finding(r, outcome, p, kind)) + findings += [ + _finding(r, outcome, p, "this lookalike, by another victim") + for p in by_lookalike.get(r.lookalike, []) + if p.payer != r.victim + ] + + tokens = {p.token for p in payoffs} + txs = {p.tx_hash for p in payoffs} + incident_rows = [ + { + "case": inc["case"], + "in_period": span is not None and span[0] <= inc["block"] <= span[1], + "token_in_file": inc["token"].lower() in tokens, + "harm_tx_listed": inc["tx"].lower() in txs, + "victim_listed": inc["victim"].lower() in by_payer, + } + for inc in incidents + ] + return { + "window_blocks": window_blocks, + "payoff_block_range": span, + "by_outcome": dict(sorted(buckets.items())), + "contradicted_complete_rows": contradictions, + "findings": sorted(findings, key=lambda f: (f["line"], f["paid"])), + "incidents": incident_rows, + } diff --git a/tests/unit/test_ml_tsuchiya.py b/tests/unit/test_ml_tsuchiya.py new file mode 100644 index 0000000..aad3c6b --- /dev/null +++ b/tests/unit/test_ml_tsuchiya.py @@ -0,0 +1,220 @@ +"""Tsuchiya et al. payoff parser and the offline cross-check with Poison-Hunter rows. + +Synthetic data only (no RPC, no third-party files). Each test states the invariant it guards. +""" + +from __future__ import annotations + +import csv +import json +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml.poison_hunter import PoisonHunterRecord, SchemaMismatchError +from cryptoguard.ml.tsuchiya import EXPECTED_HEADER, cross_check, parse_payoffs, profile + +VICTIM = "0x" + "11" * 20 +OTHER_VICTIM = "0x" + "22" * 20 +FRIEND = "0xd296222fb44f5ec8d9600a8c91ed70ed5657d7d5" +LOOKALIKE = "0xd296261b103d698c272887274f38d7ea8097d7d5" # 5+5 with FRIEND +OTHER_LOOKALIKE = "0xd29" + "0" * 33 + "d7d5" # 3+4 with FRIEND +USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7" +WBTC = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599" +COMPLETE = "no_direct_payment_observed_with_complete_declared_coverage" + + +def h(n: int) -> str: + return "0x" + f"{n:064x}" + + +def payoff(**over: str) -> dict[str, str]: + row = { + "block_number": "16100000", "tx_hash": h(1), "addr": USDT, "topics_from_addr": VICTIM, + "topics_to_addr": LOOKALIKE, "value": "5000000000.0", "value_usd": "5000.0", + "is_sender_victim": "True", "num_first_matched_digits": "5", + "num_last_matched_digits": "5", "intended_addr": FRIEND, + } # fmt: skip + return {**row, **over} + + +def write_payoffs( + path: Path, rows: list[dict[str, str]], header: list[str] = EXPECTED_HEADER +) -> Path: + with path.open("w", newline="", encoding="utf-8") as fh: + w = csv.DictWriter(fh, fieldnames=header, extrasaction="ignore") + w.writeheader() + w.writerows(rows) + return path + + +def ph( + line: int = 2, + *, + victim: str = VICTIM, + lookalike: str = LOOKALIKE, + block: int | None = 16_090_000, +) -> PoisonHunterRecord: + return PoisonHunterRecord( + source_line=line, status="valid", issues=(), lookalike=lookalike, victim=victim, + imitated=FRIEND, planting_tx=h(99), token_symbol="usdt", subtype="dust", + log_contract=USDT.lower(), fake_token_deployer=None, tx_signer=lookalike, + tx_target=USDT.lower(), batch_size=1, block_number=block, block_distance=12, + imitated_direction="from", source_similarity=10, prefix_match=5, suffix_match=5, + cryptoguard_lookalike=True, tsuchiya_lookalike=True, + ) # fmt: skip + + +def test_parser_lowercases_checks_affixes_and_keeps_provenance(tmp_path: Path) -> None: + """Addresses are normalised, the declared affix counts are re-derived from the addresses, + and the file hash is recorded.""" + parsed = parse_payoffs(write_payoffs(tmp_path / "p.csv", [payoff()])) + (r,) = parsed.records + assert (r.status, r.source_line) == ("valid", 2) + assert (r.payer, r.lookalike, r.token) == (VICTIM, LOOKALIKE, USDT.lower()) + assert (r.prefix_match, r.suffix_match) == (5, 5) + assert len(parsed.source_sha256) == 64 + + +def test_header_or_width_changes_are_refused(tmp_path: Path) -> None: + """A reordered header or a row of the wrong width is a schema change: refuse to guess.""" + swapped = [EXPECTED_HEADER[1], EXPECTED_HEADER[0], *EXPECTED_HEADER[2:]] + with pytest.raises(SchemaMismatchError): + parse_payoffs(write_payoffs(tmp_path / "a.csv", [payoff()], swapped)) + path = write_payoffs(tmp_path / "b.csv", [payoff()]) + path.write_text(path.read_text() + "1,2,3\n", encoding="utf-8") + with pytest.raises(SchemaMismatchError): + parse_payoffs(path) + + +@pytest.mark.parametrize( + ("over", "issue"), + [ + ({"num_first_matched_digits": "6"}, "declared affix"), + ({"is_sender_victim": "False"}, "is_sender_victim"), + ({"tx_hash": "0x12"}, "tx_hash"), + ({"topics_to_addr": "0xnothex"}, "topics_to_addr"), + ({"block_number": "16.1e6"}, "block_number"), + ({"value_usd": "-1"}, "value_usd"), + ], +) +def test_inconsistent_rows_are_quarantined_with_reasons( + tmp_path: Path, over: dict[str, str], issue: str +) -> None: + """A row that contradicts itself or the layout is kept, marked and explained.""" + (r,) = parse_payoffs(write_payoffs(tmp_path / "p.csv", [payoff(**over)])).records + assert r.status == "quarantined" + assert any(issue in i for i in r.issues) + + +def test_float_encoded_amounts_beyond_double_precision_are_flagged(tmp_path: Path) -> None: + """Base-unit amounts above 2**53 or in scientific notation cannot be trusted exactly.""" + rows = [ + payoff(value="5000000000.0"), + payoff(tx_hash=h(2), value="1.2345e+22"), + payoff(tx_hash=h(3), value="12345678901234567890.0"), + ] + parsed = parse_payoffs(write_payoffs(tmp_path / "p.csv", rows)) + assert [r.value_exact for r in parsed.records] == [True, False, False] + assert profile(parsed)["inexact_values"] == 2 + + +def _check( + payoffs: list[dict[str, str]], + rows: list[PoisonHunterRecord], + outcomes: list[str] | None, + tmp_path: Path, + incidents: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + parsed = parse_payoffs(write_payoffs(tmp_path / "p.csv", payoffs)) + return cross_check(parsed.valid, rows, outcomes, incidents or []) + + +def test_payoff_to_the_same_lookalike_in_window_contradicts_complete_coverage( + tmp_path: Path, +) -> None: + """A complete-coverage pilot row whose victim paid that lookalike inside the window is a + contradiction and is listed by Poison-Hunter line.""" + x = _check([payoff(block_number="16100000")], [ph(7)], [COMPLETE], tmp_path) + b = x["by_outcome"][COMPLETE] + assert b["victim_paid_this_lookalike"] == b["victim_paid_this_lookalike_in_window"] == 1 + assert x["contradicted_complete_rows"] == [7] + + +@pytest.mark.parametrize("block", ["16090000", "16080000", "16140401"]) +def test_payoffs_at_before_or_after_the_window_are_not_in_window( + tmp_path: Path, block: str +) -> None: + """The window is (planting, planting + 50,400]: the planting block itself, earlier blocks + and later blocks do not count as a payment caused within the window.""" + x = _check([payoff(block_number=block)], [ph(7)], [COMPLETE], tmp_path) + b = x["by_outcome"][COMPLETE] + assert (b["victim_paid_this_lookalike"], b["victim_paid_this_lookalike_in_window"]) == (1, 0) + assert x["contradicted_complete_rows"] == [] + + +def test_other_lookalikes_and_other_victims_are_reported_separately(tmp_path: Path) -> None: + """Paying a different lookalike of the same address, and the row's lookalike being paid + by someone else, are separate findings: neither is a payment for this event.""" + rows = [ + payoff( + topics_to_addr=OTHER_LOOKALIKE, + num_first_matched_digits="3", + num_last_matched_digits="4", + ), + payoff(tx_hash=h(2), topics_from_addr=OTHER_VICTIM, block_number="16000000"), + ] + x = _check(rows, [ph(9)], ["not_evaluated"], tmp_path) + b = x["by_outcome"]["not_evaluated"] + assert b["victim_paid_this_lookalike"] == 0 + assert b["victim_paid_other_lookalike_of_same_address"] == 1 + assert b["lookalike_paid_by_another_victim"] == 1 + kinds = {(f["paid"], f["blocks_after_planting"]) for f in x["findings"]} + assert kinds == { + ("another lookalike of the same address", 10_000), + ("this lookalike, by another victim", -90_000), + } + + +def test_output_has_no_addresses_and_rows_without_outcomes_are_grouped(tmp_path: Path) -> None: + """Only aggregates and line numbers leave the cross-check (licence and privacy).""" + incident = {"case": "case-1", "victim": VICTIM, "block": 16_100_000, "tx": h(1), "token": WBTC} + x = _check([payoff()], [ph(3)], None, tmp_path, [incident]) + assert "no_pilot_record" in x["by_outcome"] + assert "0x" not in json.dumps(x["by_outcome"]) + json.dumps(x["findings"]) + json.dumps( + x["incidents"] + ) + assert x["incidents"] == [ + { + "case": "case-1", + "in_period": True, + "token_in_file": False, + "harm_tx_listed": True, + "victim_listed": True, + } + ] + + +def test_period_and_definition_coverage(tmp_path: Path) -> None: + """Rows outside the payoff block range, or with lookalikes outside 3+4, cannot appear in + the file by construction and are counted as outside its coverage.""" + rows = [ph(2, block=15_000_000), ph(3), ph(4).model_copy(update={"tsuchiya_lookalike": False})] + span = [payoff(block_number="16000000"), payoff(tx_hash=h(2), block_number="16200000")] + x = _check(span, rows, None, tmp_path) + b = x["by_outcome"]["no_pilot_record"] + assert (b["rows"], b["in_period"], b["in_definition"]) == (3, 2, 1) + + +def test_misaligned_outcomes_raise(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="outcomes"): + _check([payoff()], [ph(2), ph(3)], [COMPLETE], tmp_path) + + +def test_profile_counts_predicates_and_tokens(tmp_path: Path) -> None: + rows = [payoff(), payoff(tx_hash=h(2), addr=WBTC)] + p = profile(parse_payoffs(write_payoffs(tmp_path / "p.csv", rows))) + assert p["tokens"] == {"USDT": 1, "other": 1} + assert p["detector_predicate_accepts"] == p["candidate_rule_accepts"] == 2 + assert p["source_md5_matches_published"] is False # synthetic file + assert p["source_sha256_matches_pinned"] is False From 800e6823696f1a241e60f636ed5f2b1f06273e46 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 09:02:42 +0300 Subject: [PATCH 15/92] fix(ml): payoff amounts are float4 approximations; payoff identity Tsuchiya et al.'s payoff amounts come from a PostgreSQL real (float4), which holds integers exactly only up to 2^24 base units (about 16.8 USDT). Phase 11.2 used the float64 limit and reported 41 inexact amounts; 1,644 of 1,738 are approximations. Each payoff now keeps the verbatim source text, a precision class, a human amount only for tokens with known decimals, the source's USD valuation unchanged, a stable payoff_id (chain, tx, token, payer, recipient) and file provenance (tsuchiya-payoff/2). Co-Authored-By: Claude Opus 5.5 --- ML_POISONING_TABLES.md | 5 ++- src/cryptoguard/ml/poisoning_report.py | 4 +- src/cryptoguard/ml/tsuchiya.py | 55 ++++++++++++++++++++------ tests/unit/test_ml_tsuchiya.py | 38 ++++++++++++++---- 4 files changed, 79 insertions(+), 23 deletions(-) diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md index 29d26d4..bed0f42 100644 --- a/ML_POISONING_TABLES.md +++ b/ML_POISONING_TABLES.md @@ -1,7 +1,7 @@ # ML Phase 11.2 tables Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). -Git `46c27f7199222697ea8ac65fb8c62ef5e05c1b5a`; runtime 5.76 s (per-window generation memory is in the JSON report). +Git `2a783978ce7b03aa018a6b01b5427df67a845e36`; runtime 12.16 s (per-window generation memory is in the JSON report). ## Poison-Hunter sample @@ -64,7 +64,8 @@ Source: KiltHub DOI 10.1184/R1/29212703.v1 (CC BY-NC-ND 4.0), kept local. SHA-25 | Payoff block range | 16,060,625-20,207,365 | | Tokens | USDT 1154, USDC 543, DAI 36, other 5 | | Distinct payers / lookalikes | 1502 / 1551 | -| Amounts not exactly representable (float-encoded) | 41 | +| Amount precision (float4 source: exact only up to 2^24 base units) | exact 94, float4_approximate 1644 | +| Duplicate payoff identities | 0 | | Accepted by the detector predicate / candidate rule | 1738 / 1738 (implied by the study's 3+4 selection: a consistency check, not recall) | Poison-Hunter rows by pilot outcome (window: 50,400 blocks after the planting): diff --git a/src/cryptoguard/ml/poisoning_report.py b/src/cryptoguard/ml/poisoning_report.py index cb01079..f06c301 100644 --- a/src/cryptoguard/ml/poisoning_report.py +++ b/src/cryptoguard/ml/poisoning_report.py @@ -271,7 +271,9 @@ def render_payoffs(x: dict[str, Any]) -> list[str]: f"| Tokens | {', '.join(f'{k} {v}' for k, v in src['tokens'].items())} |", f"| Distinct payers / lookalikes | {src['distinct_payers']} / " f"{src['distinct_lookalikes']} |", - f"| Amounts not exactly representable (float-encoded) | {src['inexact_values']} |", + f"| Amount precision (float4 source: exact only up to 2^24 base units) | " + f"{', '.join(f'{k} {v}' for k, v in sorted(src['amount_precision'].items()))} |", + f"| Duplicate payoff identities | {src['duplicate_payoff_ids']} |", f"| Accepted by the detector predicate / candidate rule | " f"{src['detector_predicate_accepts']} / {src['candidate_rule_accepts']} (implied by " "the study's 3+4 selection: a consistency check, not recall) |", diff --git a/src/cryptoguard/ml/tsuchiya.py b/src/cryptoguard/ml/tsuchiya.py index a1bbde9..fd416df 100644 --- a/src/cryptoguard/ml/tsuchiya.py +++ b/src/cryptoguard/ml/tsuchiya.py @@ -16,9 +16,10 @@ addr token contract (USDT, USDC or DAI in all but 5 rows) topics_from_addr payer: the victim topics_to_addr recipient: the lookalike -value amount in base units, float-encoded (some rows use - scientific notation, so values above 2**53 are rounded) -value_usd amount in USD, as computed by the source +value amount in token base units, printed from a PostgreSQL + ``real`` (float4): exact only up to 2**24 base units, so + most amounts are approximations (about 7 digits) +value_usd historical USD valuation computed by the source is_sender_victim ``True`` in every row num_first_matched_digits leading hex characters shared with ``intended_addr`` num_last_matched_digits trailing hex characters shared with ``intended_addr`` @@ -48,7 +49,9 @@ from cryptoguard.ml.candidates import MIN_AFFIX, MIN_SUFFIX from cryptoguard.ml.poison_hunter import PoisonHunterRecord, SchemaMismatchError -PARSER_VERSION = "tsuchiya-payoff/1" +PARSER_VERSION = "tsuchiya-payoff/2" +SOURCE_VERSION = "KiltHub v1 (2025-06-03)" +CHAIN_ID = 1 SOURCE_DOI = "10.1184/R1/29212703.v1" SOURCE_LICENSE = "CC BY-NC-ND 4.0" SOURCE_FILE = "payoff_transfers_ethereum.csv" @@ -75,13 +78,15 @@ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": "USDC", "0x6b175474e89094c44da98b954eedeac495271d0f": "DAI", } +DECIMALS = {"USDT": 6, "USDC": 6, "DAI": 18} WINDOW_BLOCKS = 50_400 # the pilot's 7-day payment window -_EXACT_FLOAT = 2**53 +FLOAT4_EXACT = 2**24 # largest integer range a PostgreSQL real holds exactly _ADDR = re.compile(r"^0x[0-9a-fA-F]{40}$") _HASH = re.compile(r"^0x[0-9a-fA-F]{64}$") Status = Literal["valid", "quarantined"] +Precision = Literal["exact", "float4_approximate", "unparseable"] class PayoffTransfer(BaseModel): @@ -90,22 +95,33 @@ class PayoffTransfer(BaseModel): source_line: int # 1-based line in the CSV (header = line 1) status: Status issues: tuple[str, ...] + chain_id: int = CHAIN_ID block_number: int | None tx_hash: str token: str payer: str lookalike: str intended: str - value_usd: float | None - value_exact: bool # False when the float encoding cannot hold the base-unit amount + value_usd: float | None # the source's historical valuation, not a token amount + value_text: str = "" # the amount exactly as printed in the source + amount_precision: Precision = "unparseable" + human_amount: Decimal | None = None # base units / 10**decimals, known tokens only prefix_match: int suffix_match: int + @property + def payoff_id(self) -> str: + """Stable identity. The source has one row per transaction and no log index, so + (chain, tx, token, payer, recipient) identifies a payoff row.""" + return f"{self.chain_id}:{self.tx_hash}:{self.token}:{self.payer}:{self.lookalike}" + class PayoffParse(BaseModel): model_config = ConfigDict(extra="forbid") parser_version: str + source_file: str + source_version: str source_sha256: str source_md5: str records: list[PayoffTransfer] @@ -129,12 +145,19 @@ def _float(text: str) -> float | None: return None -def _exact(text: str) -> bool: +def _amount(text: str, token: str) -> tuple[Precision, Decimal | None]: + """Precision class of a float4-printed base-unit amount, and the human-readable amount + for tokens with known decimals (as approximate as the base-unit value).""" try: value = Decimal(text) except InvalidOperation: - return False - return value == value.to_integral_value() and abs(value) < _EXACT_FLOAT + return "unparseable", None + if not value.is_finite() or value < 0: + return "unparseable", None + exact = value == value.to_integral_value() and value <= FLOAT4_EXACT + decimals = DECIMALS.get(TOKENS.get(token.lower(), "")) + human = value.scaleb(-decimals) if decimals is not None else None + return ("exact" if exact else "float4_approximate"), human def _parse_row(line: int, r: dict[str, str]) -> PayoffTransfer: @@ -156,6 +179,9 @@ def _parse_row(line: int, r: dict[str, str]) -> PayoffTransfer: valid_pair = all(_ADDR.match(r[n]) for n in ("topics_to_addr", "intended_addr")) prefix, suffix = affix_match(r["topics_to_addr"], r["intended_addr"]) if valid_pair else (0, 0) declared = (_int(r["num_first_matched_digits"]), _int(r["num_last_matched_digits"])) + precision, human = _amount(r["value"], r["addr"]) + if precision == "unparseable": + issues.append("value is not a non-negative number") if valid_pair and declared != (prefix, suffix): issues.append(f"declared affix {declared} differs from the addresses ({prefix}, {suffix})") return PayoffTransfer( @@ -169,7 +195,9 @@ def _parse_row(line: int, r: dict[str, str]) -> PayoffTransfer: lookalike=r["topics_to_addr"].lower(), intended=r["intended_addr"].lower(), value_usd=usd, - value_exact=_exact(r["value"]), + value_text=r["value"], + amount_precision=precision, + human_amount=human, prefix_match=prefix, suffix_match=suffix, ) @@ -187,6 +215,8 @@ def parse_payoffs(path: Path) -> PayoffParse: raise SchemaMismatchError(f"{path}: a row's width differs from the header") return PayoffParse( parser_version=PARSER_VERSION, + source_file=path.name, + source_version=SOURCE_VERSION, source_sha256=hashlib.sha256(raw).hexdigest(), source_md5=hashlib.md5(raw, usedforsecurity=False).hexdigest(), records=[_parse_row(i + 2, r) for i, r in enumerate(rows)], @@ -220,7 +250,8 @@ def profile(result: PayoffParse, config: PoisoningConfig | None = None) -> dict[ "distinct_txs": len({p.tx_hash for p in valid}), "distinct_payers": len({p.payer for p in valid}), "distinct_lookalikes": len({p.lookalike for p in valid}), - "inexact_values": sum(1 for p in valid if not p.value_exact), + "amount_precision": dict(Counter(p.amount_precision for p in valid)), + "duplicate_payoff_ids": len(valid) - len({p.payoff_id for p in valid}), "usd_total": round(sum(usd)), "usd_median": round(usd[len(usd) // 2], 2) if usd else None, # The study's 3+4 selection implies both predicates, so these are consistency diff --git a/tests/unit/test_ml_tsuchiya.py b/tests/unit/test_ml_tsuchiya.py index aad3c6b..2489a32 100644 --- a/tests/unit/test_ml_tsuchiya.py +++ b/tests/unit/test_ml_tsuchiya.py @@ -7,6 +7,7 @@ import csv import json +from decimal import Decimal from pathlib import Path from typing import Any @@ -108,16 +109,37 @@ def test_inconsistent_rows_are_quarantined_with_reasons( assert any(issue in i for i in r.issues) -def test_float_encoded_amounts_beyond_double_precision_are_flagged(tmp_path: Path) -> None: - """Base-unit amounts above 2**53 or in scientific notation cannot be trusted exactly.""" +def test_float4_amounts_are_marked_approximate_beyond_2_pow_24(tmp_path: Path) -> None: + """The source column is a PostgreSQL real: integers above 2**24 base units (about 16.8 + USDT) are rounded, so only small integral amounts count as exact. Human amounts use + the token's decimals and stay separate from the source's USD valuation.""" rows = [ - payoff(value="5000000000.0"), - payoff(tx_hash=h(2), value="1.2345e+22"), - payoff(tx_hash=h(3), value="12345678901234567890.0"), + payoff(value="16777216.0"), # 2**24: still exact + payoff(tx_hash=h(2), value="16777217.0"), + payoff(tx_hash=h(3), value="5e+09", value_usd="4999.5"), + payoff(tx_hash=h(4), value="1.5", addr=WBTC), + payoff(tx_hash=h(5), value="lots"), ] - parsed = parse_payoffs(write_payoffs(tmp_path / "p.csv", rows)) - assert [r.value_exact for r in parsed.records] == [True, False, False] - assert profile(parsed)["inexact_values"] == 2 + recs = parse_payoffs(write_payoffs(tmp_path / "p.csv", rows)).records + assert [r.amount_precision for r in recs] == [ + "exact", + "float4_approximate", + "float4_approximate", + "float4_approximate", + "unparseable", + ] + assert recs[2].human_amount == Decimal("5000") # 5e9 base units of a 6-decimal token + assert recs[2].value_usd == 4999.5 # the source's valuation is kept, not recomputed + assert recs[3].human_amount is None # unknown decimals: no human amount is invented + assert recs[4].status == "quarantined" + + +def test_payoff_identity_and_provenance(tmp_path: Path) -> None: + parsed = parse_payoffs(write_payoffs(tmp_path / "p.csv", [payoff(), payoff()])) + assert parsed.source_file == "p.csv" + assert parsed.source_version.startswith("KiltHub v1") + assert parsed.records[0].payoff_id == f"1:{h(1)}:{USDT.lower()}:{VICTIM}:{LOOKALIKE}" + assert profile(parsed)["duplicate_payoff_ids"] == 1 # a repeated row is not two payoffs def _check( From e367f7c4a43380dfa19aefdaa43547440a39d858 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 09:02:44 +0300 Subject: [PATCH 16/92] feat(ml): safe archive ingestion and cross-dataset reconciliation - ml fetch-file: verified, resumable download of one approved, pinned file (206 + matching Content-Range to resume, 200 restarts, size/MD5/ SHA-256/gzip checks before rename, disk reserve). No default caller. - ml scan-archive: streaming reader for Tsuchiya et al.'s PostgreSQL dump. Never executes SQL; whitelisted statements, schema and COPY column checks, bounded lines, typed rows with counted rejections, exact distinct counts with bounded memory (spill buckets), a target subset in SQLite renamed only after a complete pass; killed-run leftovers (including the SQLite journal) are cleared first. Real archive: 34,905,969 rows, 0 malformed, all ten publisher counts reproduced, peak RSS 287 MiB, two passes identical. - ml cross-dataset-report: match levels for Poison-Hunter rows, payoff-to-attempt linkage, separate attempt/victim/address/campaign outcomes, temporal categories, tie-aware competing-lookalike comparison, decision gates, and a local review queue (packets v2 with competing lookalikes and payment evidence; no labels assigned). - Candidate rules are shared through candidates.transfer_methods so the archive evaluation uses the generator's own logic. - ml bench-archive: seeded synthetic scaling benchmark. 0 RPC requests. Third-party data stays in the git-ignored data/. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/bench_archive.py | 135 ++++ src/cryptoguard/ml/candidates.py | 54 +- src/cryptoguard/ml/cli.py | 108 ++++ src/cryptoguard/ml/cross_dataset.py | 523 +++++++++++++++ src/cryptoguard/ml/fetch.py | 258 ++++++++ src/cryptoguard/ml/reconcile.py | 503 +++++++++++++++ src/cryptoguard/ml/review.py | 17 +- src/cryptoguard/ml/tsuchiya_archive.py | 858 +++++++++++++++++++++++++ tests/unit/test_ml_fetch.py | 171 +++++ tests/unit/test_ml_reconcile.py | 468 ++++++++++++++ tests/unit/test_ml_tsuchiya_archive.py | 469 ++++++++++++++ 11 files changed, 3546 insertions(+), 18 deletions(-) create mode 100644 src/cryptoguard/ml/bench_archive.py create mode 100644 src/cryptoguard/ml/cross_dataset.py create mode 100644 src/cryptoguard/ml/fetch.py create mode 100644 src/cryptoguard/ml/reconcile.py create mode 100644 src/cryptoguard/ml/tsuchiya_archive.py create mode 100644 tests/unit/test_ml_fetch.py create mode 100644 tests/unit/test_ml_reconcile.py create mode 100644 tests/unit/test_ml_tsuchiya_archive.py diff --git a/src/cryptoguard/ml/bench_archive.py b/src/cryptoguard/ml/bench_archive.py new file mode 100644 index 0000000..e8f1911 --- /dev/null +++ b/src/cryptoguard/ml/bench_archive.py @@ -0,0 +1,135 @@ +"""Scaling benchmark for the archive scanner on seeded synthetic dumps (Stage Q). + +Each size runs in a fresh process, so peak RSS is per size rather than cumulative. +Synthetic rows mimic the real dump's shape (subtype mix, victims receiving most plantings, +lookalikes matching their target's ends); they carry no real addresses and are never +accuracy evidence. +""" + +from __future__ import annotations + +import gzip +import hashlib +import json +import random +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +from cryptoguard.ml import tsuchiya_archive as ta + +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" + + +def _addr(rng: random.Random) -> str: + return "0x" + "".join(rng.choice("0123456789abcdef") for _ in range(40)) + + +def _lookalike(rng: random.Random, target: str) -> str: + middle = "".join(rng.choice("0123456789abcdef") for _ in range(30)) + return target[:6] + middle + target[-6:] + + +def synthetic_dump(path: Path, rows: int, *, seed: int = 0) -> Path: + """A gzip PostgreSQL dump in the real archive's layout with ``rows`` data rows.""" + rng = random.Random(seed) # noqa: S311 - seeded synthetic fixtures, not cryptography + victims = [_addr(rng) for _ in range(max(10, rows // 20))] + friends = [_addr(rng) for _ in range(max(10, rows // 50))] + order = list(ta.COLUMNS) + header = [ + "--", + "SET statement_timeout = 0;", + f"CREATE TABLE public.{ta.TABLE} (", + *[f" {n} {t}," for n, t in list(ta.COLUMNS.items())[:-1]], + f" {order[-1]} {ta.COLUMNS[order[-1]]}", + ");", + f"COPY public.{ta.TABLE} ({', '.join(order)}) FROM stdin;", + ] + with gzip.open(path, "wt", encoding="utf-8", compresslevel=1, newline="\n") as fh: + fh.write("\n".join(header) + "\n") + for i in range(rows): + victim, friend = rng.choice(victims), rng.choice(friends) + lookalike = _lookalike(rng, friend) + kind = rng.choices(("zero", "counterfeit", "tiny", "intended"), (41, 56, 2, 1))[0] + sends = kind != "tiny" and rng.random() < 0.3 + flags = {k: "f" for k in ta.FLAG_COLUMNS} + flags[ + { + "zero": "zero_value_transfer", + "counterfeit": "counterfeit_token_transfer", + "tiny": "tiny_transfer", + "intended": "intended_transfer", + }[kind] + ] = "t" + value = {"zero": "0", "tiny": "5000", "counterfeit": "1e+06", "intended": "5e+09"} + sender, receiver = (victim, lookalike) if sends else (lookalike, victim) + if kind == "intended": + sender, receiver, sends = victim, friend, True + row = { + "block_number": str(16_000_000 + i), + "tx_hash": "0x" + hashlib.sha256(f"{seed}:{i}".encode()).hexdigest(), + "addr": USDT if kind != "counterfeit" else _lookalike(rng, USDT), + "topics_from_addr": sender, + "topics_to_addr": receiver, + "is_sender_victim": "t" if sends else "f", + "value": value[kind], + "value_usd": "NaN" if kind == "counterfeit" else "0", + **flags, + "intended_addr": friend, + "num_first_matched_digits": "20" if kind == "intended" else "4", + "num_last_matched_digits": "20" if kind == "intended" else "4", + } + fh.write("\t".join(row[c] for c in order) + "\n") + fh.write("\\.\n") + return path + + +def run_one(rows: int, work: Path) -> dict[str, Any]: + """Generate, scan twice (determinism), and measure one size in this process.""" + work.mkdir(parents=True, exist_ok=True) + dump = synthetic_dump(work / f"syn{rows}.sql.gz", rows) + manifest = work / "targets.json" + rng = random.Random(1) # noqa: S311 - seeded synthetic fixtures, not cryptography + targets = ta.build_targets({"bench_victims": [_addr(rng) for _ in range(100)]}) + manifest.write_text(json.dumps(targets), encoding="utf-8") + t = ta.load_targets(manifest) + t0 = time.perf_counter() + first = ta.scan(dump, t, work / "a.sqlite", work_dir=work / "spill") + elapsed = time.perf_counter() - t0 + second = ta.scan(dump, t, work / "b.sqlite", work_dir=work / "spill") + volatile = ("runtime_seconds", "peak_rss_bytes", "output_bytes") + same = {k: v for k, v in first.items() if k not in volatile} == { + k: v for k, v in second.items() if k not in volatile + } + return { + "rows": rows, + "compressed_bytes": dump.stat().st_size, + "decompressed_bytes": first["reader"]["decompressed_bytes"], + "scan_seconds": round(elapsed, 2), + "rows_per_second": round(rows / elapsed), + "peak_rss_mib": round((ta.peak_rss_bytes() or 0) / 2**20, 1), + "peak_spill_mib": round(first["peak_spill_bytes"] / 2**20, 2), + "subset_bytes": first["output_bytes"], + "distinct_lookalikes": first["distinct"]["lookalikes"], + "deterministic": same, + } + + +def bench(sizes: list[int], work: Path) -> list[dict[str, Any]]: + """One subprocess per size, so each peak RSS is measured in isolation.""" + out = [] + for n in sizes: + proc = subprocess.run( # noqa: S603 - our own module, integer arguments + [sys.executable, "-m", "cryptoguard.ml.bench_archive", str(n), str(work / str(n))], + capture_output=True, + text=True, + check=True, + ) + out.append(json.loads(proc.stdout.strip().splitlines()[-1])) + return out + + +if __name__ == "__main__": + print(json.dumps(run_one(int(sys.argv[1]), Path(sys.argv[2])))) diff --git a/src/cryptoguard/ml/candidates.py b/src/cryptoguard/ml/candidates.py index a0b639a..f65b5bb 100644 --- a/src/cryptoguard/ml/candidates.py +++ b/src/cryptoguard/ml/candidates.py @@ -53,13 +53,40 @@ RECENT_BLOCKS = 7_200 # about one day -def _similar(a: str, b: str) -> tuple[int, int] | None: +def similar(a: str, b: str) -> tuple[int, int] | None: + """The ``lookalike_in`` similarity rule: (prefix, suffix) when it matches, else None.""" if a == b: return None prefix, suffix = affix_match(a, b) return (prefix, suffix) if prefix + suffix >= MIN_AFFIX and suffix >= MIN_SUFFIX else None +def transfer_methods( + *, + incoming: bool, + outgoing: bool, + value: int, + token: str, + wallet_signed: bool | None, + matched: bool, +) -> list[str]: + """The candidate rules that fire for one transfer seen from the wallet (see the module + docstring). ``wallet_signed`` is None when the transaction signer is unknown; ``matched`` is + whether the counterparty passes ``similar`` against a counterparty chosen earlier.""" + methods: list[str] = [] + if incoming and value == 0: + methods.append("zero_value_in") + if outgoing and wallet_signed is False: + methods.append("spoofed_out") + if incoming and matched: + methods.append("lookalike_in") + if token not in TRUSTED_TOKENS: + methods.append("untrusted_token_in") + if incoming and token in STABLECOINS and 0 < value <= DUST_MAX_BASE_UNITS: + methods.append("dust_in") + return methods + + @dataclass(frozen=True) class Candidate: event: PoisoningEvent @@ -95,24 +122,21 @@ def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: position = (t.block_number, t.transaction_index, t.log_index) token = t.token.lower() value = int(t.value) - methods: list[str] = [] party = (t.sender if incoming else t.recipient).lower() chosen = _chosen_before(events, position) match = max( - ((k, m) for k in chosen if (m := _similar(party, k)) is not None), + ((k, m) for k in chosen if (m := similar(party, k)) is not None), key=lambda km: (sum(km[1]), km[1][1], km[0]), default=None, ) - if incoming and value == 0: - methods.append("zero_value_in") - if outgoing and t.tx_sender is not None and t.tx_sender.lower() != wallet: - methods.append("spoofed_out") - if incoming and match is not None: - methods.append("lookalike_in") - if token not in TRUSTED_TOKENS: - methods.append("untrusted_token_in") - if incoming and token in STABLECOINS and 0 < value <= DUST_MAX_BASE_UNITS: - methods.append("dust_in") + methods = transfer_methods( + incoming=incoming, + outgoing=outgoing, + value=value, + token=token, + wallet_signed=None if t.tx_sender is None else t.tx_sender.lower() == wallet, + matched=match is not None, + ) if not methods: continue out.append( @@ -239,9 +263,7 @@ def event_features( token_trusted=(e.log_contract or "") in TRUSTED_TOKENS, prefix_to_imitated=c.best_match[0] if c.best_match else None, suffix_to_imitated=c.best_match[1] if c.best_match else None, - plausible_impersonated=sum(1 for k in chosen if _similar(e.lookalike, k)) - if known - else None, + plausible_impersonated=sum(1 for k in chosen if similar(e.lookalike, k)) if known else None, blocks_since_imitated_chosen=( e.planting_block - chosen[e.imitated] if known and e.imitated in chosen else None ), diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index e2dd07e..81ded20 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -63,6 +63,30 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None pc.add_argument("--window-blocks", type=int, required=True) pc.add_argument("--request-cap", type=int, required=True) pc.add_argument("--log-range-blocks", type=int, default=100) + ff = ml.add_parser( + "fetch-file", + help="download ONE named, pinned research file after explicit approval (verified)", + ) + ff.add_argument("name", help="pinned file name, e.g. address_poisoning_ethereum.sql.gz") + ff.add_argument("--dest", type=Path, default=DEFAULT_DATA_DIR / "tsuchiya2025") + ff.add_argument("--reserve-gib", type=float, default=10.0) + sa = ml.add_parser( + "scan-archive", + help="one offline pass over the local Tsuchiya archive (verified; never downloads)", + ) + sa.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + sa.add_argument("--out", type=Path, default=ML_DIR / "poisoning") + sa.add_argument("--force", action="store_true", help="rescan even if a cached scan matches") + cr = ml.add_parser( + "cross-dataset-report", + help="reconcile the scanned archive with Poison-Hunter, payoffs and incidents (no RPC)", + ) + cr.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + cr.add_argument("--out", type=Path, default=ML_DIR / "poisoning") + cr.add_argument("--tables", type=Path, default=Path("ML_CROSS_DATASET_TABLES.md")) + bz = ml.add_parser("bench-archive", help="archive-scanner scaling on synthetic dumps") + bz.add_argument("sizes", type=int, nargs="+") + bz.add_argument("--work", type=Path, default=ML_DIR / "bench") def run(args: argparse.Namespace) -> int: @@ -95,6 +119,19 @@ def run(args: argparse.Namespace) -> int: return 2 print(json.dumps(body, indent=1)) return 0 + if args.ml_command == "fetch-file": + return _fetch_file(args) + if args.ml_command == "scan-archive": + return _scan_archive(args) + if args.ml_command == "cross-dataset-report": + return _cross_dataset_report(args) + if args.ml_command == "bench-archive": + import json + + from cryptoguard.ml.bench_archive import bench + + print(json.dumps(bench(args.sizes, args.work), indent=1)) + return 0 if not ml_available(): print("error [ml_unavailable]: install the ml extra (uv sync --extra ml)") return 1 @@ -153,6 +190,77 @@ def run(args: argparse.Namespace) -> int: raise AssertionError(args.ml_command) +def _fetch_file(args: argparse.Namespace) -> int: + import json + + from cryptoguard.ml.fetch import TSUCHIYA_FILES, DownloadError, download + + pinned = TSUCHIYA_FILES.get(args.name) + if pinned is None: + print(f"error: {args.name!r} is not pinned; known: {', '.join(TSUCHIYA_FILES)}") + return 2 + last = [-1] + + def progress(done: int, total: int) -> None: + pct = done * 100 // total + if pct >= last[0] + 5: + last[0] = pct + print(f"{pct:3d}% {done:,}/{total:,} bytes", flush=True) + + try: + record = download( + pinned, args.dest, reserve_bytes=int(args.reserve_gib * (1 << 30)), progress=progress + ) + except DownloadError as exc: + print(f"error [{type(exc).__name__}]: {exc}") + return 1 + print(json.dumps(record, indent=1)) + return 0 + + +def _scan_archive(args: argparse.Namespace) -> int: + import time + + from cryptoguard.ml.cross_dataset import run_scan + from cryptoguard.ml.fetch import IntegrityError + from cryptoguard.ml.tsuchiya_archive import ArchiveError, ReaderStats + + t0 = time.perf_counter() + + def progress(stats: ReaderStats) -> None: + print( + f"{stats.data_rows:>12,} rows {stats.decompressed_bytes / 1e9:6.2f} GB " + f"{time.perf_counter() - t0:7.0f} s", + flush=True, + ) + + try: + s = run_scan(args.data_dir, args.out, force=args.force, progress=progress) + except (FileNotFoundError, IntegrityError, ArchiveError) as exc: + print(f"error [{type(exc).__name__}]: {exc}") + return 1 + print( + f"{'cached' if s['cached'] else 'scanned'}: {s['reader']['valid_rows']:,} valid rows, " + f"{s['reader']['malformed_rows']:,} malformed, {s['stored_target_rows']:,} stored; " + f"{s['runtime_seconds']} s, peak RSS {s['peak_rss_bytes']} bytes (0 RPC requests)." + ) + return 0 + + +def _cross_dataset_report(args: argparse.Namespace) -> int: + from cryptoguard.ml.cross_dataset import build_report, write_report + from cryptoguard.ml.tsuchiya_archive import ArchiveError + + try: + report = build_report(args.data_dir, args.out) + except (FileNotFoundError, ArchiveError) as exc: + print(f"error [{type(exc).__name__}]: {exc} (run `cryptoguard ml scan-archive` first)") + return 1 + written = write_report(report, args.out, args.tables) + print(f"Wrote {written} and {args.tables} (0 RPC requests).") + return 0 + + def _shadow(args: argparse.Namespace) -> int: import json diff --git a/src/cryptoguard/ml/cross_dataset.py b/src/cryptoguard/ml/cross_dataset.py new file mode 100644 index 0000000..29e4e89 --- /dev/null +++ b/src/cryptoguard/ml/cross_dataset.py @@ -0,0 +1,523 @@ +"""Cross-dataset validation: Poison-Hunter sample, Tsuchiya et al. attempt archive and +payoff list, with the recorded incidents kept as a separate case-study source. + +Stages (all offline, 0 RPC requests): + +1. ``build_target_manifest`` - deterministic list of addresses and transactions to keep. +2. ``run_scan`` - one verified pass over the archive (``tsuchiya_archive.scan``). +3. ``reconcile`` - match levels, attempt/victim/address outcomes, temporal categories, + competing lookalikes and source overlap, from the stored subset. + +Everything that leaves this module is aggregate or keyed by Poison-Hunter line number; +address-level tables stay in the git-ignored data directory (CC BY-NC-ND 4.0). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from cryptoguard.ml.fetch import TSUCHIYA_FILES, verify_local +from cryptoguard.ml.poison_hunter import PoisonHunterRecord, parse_sample +from cryptoguard.ml.tsuchiya import PayoffTransfer, parse_payoffs +from cryptoguard.ml.tsuchiya_archive import ( + PARSER_VERSION, + ArchiveError, + build_targets, + load_subset, + load_targets, + scan, +) + +ARCHIVE = "address_poisoning_ethereum.sql.gz" +PAYOFFS = "payoff_transfers_ethereum.csv" + + +def git_state() -> dict[str, Any]: + """HEAD commit and whether tracked files differ from it (a run on a dirty tree is + reproducible only with that diff).""" + import subprocess + + def git(*args: str) -> str | None: + try: + out = subprocess.run( # noqa: S603 - fixed git arguments + ["git", *args], # noqa: S607 + capture_output=True, + text=True, + timeout=10, + check=False, + ) + except OSError: + return None + return out.stdout.strip() if out.returncode == 0 else None + + status = git("status", "--porcelain", "--untracked-files=no") + return {"commit": git("rev-parse", "HEAD"), "dirty": None if status is None else bool(status)} + + +def incident_refs() -> list[dict[str, Any]]: + from cryptoguard.replay.models import load_cases + + return [ + { + "case": m.case_id, + "victim": m.victim.lower(), + "recipient": m.harm.recipient.lower(), + "block": m.harm.block_number, + "tx": m.harm.transaction_hash.lower(), + "token": m.harm.token.lower(), + } + for m in (case.manifest for case in load_cases()) + ] + + +def build_target_manifest( + ph: list[PoisonHunterRecord], payoffs: list[PayoffTransfer], incidents: list[dict[str, Any]] +) -> dict[str, Any]: + """Addresses whose archive rows (as sender or receiver) and transactions to keep. + + Imitated/intended addresses are deliberately not targets: they can be exchange wallets + with millions of rows, and every row a victim takes part in already carries them.""" + return build_targets( + { + "ph_victims": [r.victim for r in ph], + "ph_lookalikes": [r.lookalike for r in ph], + "ph_txs": [r.planting_tx for r in ph], + "payoff_victims": [p.payer for p in payoffs], + "payoff_lookalikes": [p.lookalike for p in payoffs], + "payoff_txs": [p.tx_hash for p in payoffs], + "incident_victims": [i["victim"] for i in incidents], + "incident_recipients": [i["recipient"] for i in incidents], + "incident_txs": [i["tx"] for i in incidents], + } + ) + + +def run_scan( + data_dir: Path, out_dir: Path, *, force: bool = False, progress: Any = None +) -> dict[str, Any]: + """Verify the local archive, build the target manifest and scan once (cached when the + archive, manifest and parser are unchanged). Raises if a source file is missing: + nothing is downloaded here.""" + src = data_dir / "tsuchiya2025" + archive = src / ARCHIVE + if not archive.exists(): + raise FileNotFoundError( + f"{archive} is missing. It is never fetched automatically; after approval run " + f"`cryptoguard ml fetch-file {ARCHIVE}`." + ) + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + ph = parse_sample(data_dir / "poison-hunter" / "phishing_transfers_sample.csv").valid + payoffs = parse_payoffs(src / PAYOFFS).valid + out_dir.mkdir(parents=True, exist_ok=True) + manifest_path = out_dir / "archive_targets.json" + manifest = build_target_manifest(ph, payoffs, incident_refs()) + manifest_path.write_text(json.dumps(manifest, indent=0), encoding="utf-8") + targets = load_targets(manifest_path) + db = out_dir / "archive_subset.sqlite" + if db.exists() and not force: + try: + _, summary = load_subset(db) + except ArchiveError: + summary = None + if ( + summary is not None + and summary.get("source_sha256") == source["sha256"] + and summary.get("target_manifest_sha256") == targets.sha256 + and summary.get("parser_version") == PARSER_VERSION + ): + return {**summary, "cached": True} + summary = scan( + archive, + targets, + db, + work_dir=out_dir / "spill", + source_sha256=source["sha256"], + progress=progress, + ) + summary["source"] = { + **source, + "url": TSUCHIYA_FILES[ARCHIVE].url, + "record": TSUCHIYA_FILES[ARCHIVE].source, + "license": TSUCHIYA_FILES[ARCHIVE].license, + } + summary["target_groups"] = {k: len(v) for k, v in manifest["groups"].items()} + summary["git"] = git_state() + (out_dir / "archive-scan.json").write_text( + json.dumps(summary, indent=1, sort_keys=True), encoding="utf-8" + ) + return {**summary, "cached": False} + + +# Reference counts printed by the publisher's guidance.ipynb (KiltHub v1). +PUBLISHED = { + "rows": 34_905_969, + "poisoning_transfers": 17_365_954, + "poisoning_txs": 1_691_529, + "tiny_transfer": 308_881, + "zero_value_transfer": 7_185_298, + "counterfeit_token_transfer": 9_871_775, + "counterfeit_token_contracts": 6_280, + "victims": 1_330_948, + "lookalikes": 6_492_215, + "is_not_categorized": 8_651, +} + + +def reproduced_counts(summary: dict[str, Any]) -> list[dict[str, Any]]: + """Our scan's counts next to the publisher's, row by row.""" + d, c = summary["distinct"], summary["categories"] + ours = { + "rows": summary["reader"]["valid_rows"], + "poisoning_transfers": summary["poisoning_transfers"], + "poisoning_txs": d["poisoning_txs"], + "tiny_transfer": c["tiny_transfer"], + "zero_value_transfer": c["zero_value_transfer"], + "counterfeit_token_transfer": c["counterfeit_token_transfer"], + "counterfeit_token_contracts": d["counterfeit_token_contracts"], + "victims": d["victims"], + "lookalikes": d["lookalikes"], + "is_not_categorized": c["is_not_categorized"], + } + return [ + {"quantity": k, "published": v, "reproduced": ours[k], "match": ours[k] == v} + for k, v in PUBLISHED.items() + ] + + +def decision_gates(summary: dict[str, Any], rec: dict[str, Any]) -> list[dict[str, str]]: + """Stage Z gates, evaluated from the evidence actually available.""" + repro = reproduced_counts(summary) + integrity = summary["reader"]["malformed_rows"] == 0 and all(r["match"] for r in repro) + linked = rec["payoffs"]["linkage"].get("attempt_before_payoff", 0) + + def gate(name: str, status: str, detail: str) -> dict[str, str]: + return {"gate": name, "status": status, "detail": detail} + + return [ + gate( + "1 Data integrity", + "pass" if integrity else "fail", + "pinned size/MD5/SHA-256; 0 malformed rows; publisher counts reproduced" + if integrity + else "see the reproduced-count table and malformed-row reasons", + ), + gate( + "2 Event identity", + "partial", + "transactions, attempts (victim, lookalike, tx) and Poison-Hunter victim-events are " + f"distinct; the archive has no log index ({summary['repeated_transfer_keys']:,} " + "repeated transfer keys) and no campaign identifier", + ), + gate( + "3 Label validity", + "fail", + "archive categories are the source's heuristic labels (lookalike rule, " + "thresholds), not independent review of attempts; payoffs are confirmed " + "outcomes, not attempt labels", + ), + gate( + "4 Temporal integrity", + "partial", + "block-level ordering only (no transaction index or timestamps in the archive): " + "same-block pairs are 'order unknown'; fixture-based features keep exact cutoffs", + ), + gate( + "5 Independent evaluation", + "fail", + "no verified negatives in any source; not listed or not paid does not mean benign", + ), + gate( + "6 Leakage control", + "partial", + "campaign grouping and grouped temporal splits exist, but there are no trainable " + "labels to split", + ), + gate( + "7 Baseline comparability", + "fail", + "the archive holds only poisoning-related transfers, not the wallet histories the " + "deterministic detector needs, so both cannot run on the same observations", + ), + gate( + "8 Operational usefulness", + "fail", + "alert volume on ordinary wallets is known only from 27 recorded wallet-days; " + f"{linked:,} payoff-linked attempts are retrospective, not prospective", + ), + ] + + +def build_report(data_dir: Path, out_dir: Path) -> dict[str, Any]: + """Reconcile the stored subset with Poison-Hunter, payoffs and incidents (offline).""" + import time + + from cryptoguard.ml.events import campaign_groups, deduplicate + from cryptoguard.ml.poisoning_report import poison_hunter_events + from cryptoguard.ml.reconcile import reconcile + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + t0 = time.perf_counter() + rows, summary = load_subset(out_dir / "archive_subset.sqlite") + ph = parse_sample(data_dir / "poison-hunter" / "phishing_transfers_sample.csv").valid + payoffs = parse_payoffs(data_dir / "tsuchiya2025" / PAYOFFS).valid + events, _ = deduplicate(poison_hunter_events(ph)) + groups_by_event = campaign_groups(events) + groups = {e.lookalike: groups_by_event[e.victim_event_id] for e in events} + rec = reconcile(rows, summary, ph, payoffs, incident_refs(), groups) + from cryptoguard.ml.reconcile import ArchiveIndex, payoff_review_packets + from cryptoguard.ml.review import export_packets + + packets = payoff_review_packets(payoffs, ArchiveIndex(rows)) + rec["review_packets"] = { + "payoff_linked_attempts": export_packets( + packets, out_dir / "review_packets_payoff_linked.jsonl" + ), + "with_competing_lookalikes": sum(1 for p in packets if p.competing_lookalikes), + "note": "local review queue (addresses; git-ignored); no label is assigned", + } + scan_meta = json.loads((out_dir / "archive-scan.json").read_text(encoding="utf-8")) + if scan_meta.get("target_manifest_sha256") != summary["target_manifest_sha256"]: + raise ArchiveError("archive-scan.json does not describe the stored subset; rescan") + extra = ("source", "target_groups", "output_bytes", "git") + return { + "scan": {**summary, **{k: scan_meta[k] for k in extra if k in scan_meta}}, + "reproduced": reproduced_counts(summary), + "reconcile": rec, + "gates": decision_gates(summary, rec), + "git": git_state(), + "reconcile_runtime_seconds": round(time.perf_counter() - t0, 1), + "reconcile_peak_rss_bytes": peak_rss_bytes(), + "rpc_requests": 0, + } + + +def _pct(n: int, d: int) -> str: + return f"{n:,} / {d:,} ({n / d:.1%})" if d else f"{n:,} / 0" + + +def _kv(d: dict[str, Any]) -> str: + return ", ".join(f"{k} {v:,}" for k, v in d.items()) or "none" + + +def _q(q: dict[str, Any] | None) -> str: + if not q: + return "n/a" + return ( + f"n {q['n']:,}; min {q['min']:,}, p25 {q['p25']:,.0f}, median {q['median']:,.0f}, " + f"p75 {q['p75']:,.0f}, max {q['max']:,}" + ) + + +def _below_3_4(key: str) -> bool: + try: + a, b = (int(x) for x in key.split("+")) + except ValueError: + return True # missing digit counts + return a < 3 or b < 4 + + +def _yes(flag: bool) -> str: + return "yes" if flag else "no" + + +def render(report: dict[str, Any]) -> str: + """Aggregate-only Markdown tables (no addresses or hashes from the sources).""" + s, rec = report["scan"], report["reconcile"] + src = s.get("source") or {} + rd = s["reader"] + blocks, pblocks = s["block_range"], s["poisoning_block_range"] + preamble = ", ".join(f"{k} {v}" for k, v in rd["preamble_statements"].items()) + lines = [ + "# Cross-dataset validation tables (Phase 11.3)", + "", + "Generated by `cryptoguard ml cross-dataset-report` from local, git-ignored files " + f"(0 RPC requests) at git `{(report.get('git') or {}).get('commit') or '?'}`" + f"{' with uncommitted changes' if (report.get('git') or {}).get('dirty') else ''}. " + "Narrative and limitations: " + "[ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md).", + "", + "## Source and scan", + "", + "| Quantity | Value |", + "|---|---|", + f"| Archive | `address_poisoning_ethereum.sql.gz`, {src.get('size', 0):,} bytes, " + f"KiltHub {src.get('record', '?')} ({src.get('license', '?')}) |", + f"| Integrity | size and MD5 match the published values; SHA-256 " + f"`{str(src.get('sha256', '?'))[:16]}…` pinned |", + f"| Format | PostgreSQL plain dump, one table, one COPY block; parser " + f"`{s['parser_version']}` |", + f"| Decompressed bytes read | {rd['decompressed_bytes']:,} |", + f"| Data rows / valid / malformed | {rd['data_rows']:,} / {rd['valid_rows']:,} / " + f"{rd['malformed_rows']:,} |", + f"| Preamble statements (recognised and skipped, never executed) | {preamble} |", + f"| Block range: all rows / poisoning rows | {blocks[0]:,}-{blocks[1]:,} / " + f"{pblocks[0]:,}-{pblocks[1]:,} |", + f"| Missing amount / USD value (NaN) | {s['nan_value']:,} / {s['nan_value_usd']:,} |", + f"| Repeated (tx, token, from, to, value) keys | {s['repeated_transfer_keys']:,} " + "(no log index, so repeats cannot be told from duplicates) |", + f"| Poisoning rows whose declared digit counts differ from the addresses | " + f"{s['declared_digits_disagree']:,} |", + f"| Rows stored for the target manifest | {s['stored_target_rows']:,} " + f"({s.get('output_bytes', 0):,} bytes) |", + f"| Scan runtime / peak RSS / peak spill | {s['runtime_seconds']:,} s / " + f"{(s['peak_rss_bytes'] or 0) / 2**20:,.0f} MiB / " + f"{s['peak_spill_bytes'] / 2**20:,.0f} MiB |", + "", + "## Publisher counts reproduced", + "", + "| Quantity | Published (guidance.ipynb) | Reproduced | Match |", + "|---|---|---|---|", + *( + f"| {r['quantity']} | {r['published']:,} | {r['reproduced']:,} | " + f"{'yes' if r['match'] else '**no**'} |" + for r in report["reproduced"] + ), + "", + "## Poisoning rows by subtype and direction", + "", + "| Subtype | Rows | Victim receives | Victim sends (spoofed sender) |", + "|---|---|---|---|", + ] + for name, n in sorted(s["poisoning_by_subtype"].items()): + recv = s["poisoning_direction"].get(f"{name}/victim_receives", 0) + send = s["poisoning_direction"].get(f"{name}/victim_sends", 0) + lines.append(f"| {name} | {n:,} | {recv:,} | {send:,} |") + lows = {k: v for k, v in s["poisoning_digit_pairs"].items() if _below_3_4(k)} + low_detail = f" ({_kv(dict(sorted(lows.items())))})" if lows else "" + lines += [ + "", + f"Poisoning rows whose declared digits are below 3 leading + 4 trailing: " + f"{sum(lows.values()):,} of {s['poisoning_transfers']:,}{low_detail}.", + "", + "## CryptoGuard candidate rules on source-labelled poisoning rows", + "", + "Denominator: the source's poisoning rows of each subtype (rows can carry several " + "subtypes). Single-transfer rules only. `lookalike_in` assumes the intended address " + "was an earlier counterparty, which the source's own selection presumes, so it " + "measures agreement with the source's rule, not detection. `spoofed_out` needs the " + "transaction signer, which the archive lacks.", + "", + "| Subtype | Rows | zero_value_in | dust_in | lookalike_in | untrusted_token_in | " + "Any rule | Detector predicate |", + "|---|---|---|---|---|---|---|---|", + ] + cov = s["rule_coverage"] + for name, n in sorted(s["poisoning_by_subtype"].items()): + cells = " | ".join( + _pct(cov.get(f"{name}/{m}", 0), n) + for m in ("zero_value_in", "dust_in", "lookalike_in", "untrusted_token_in") + ) + lines.append( + f"| {name} | {n:,} | {cells} | {_pct(s['any_candidate_rule'].get(name, 0), n)} | " + f"{_pct(cov.get(f'{name}/detector_predicate', 0), n)} |" + ) + ph = rec["poison_hunter"] + lines += [ + "", + "## Poison-Hunter rows against the archive", + "", + f"Unit: {ph['unit']}. Each row gets its strongest level.", + "", + "| Match level | Rows | Distinct victims | Distinct lookalikes | Distinct planting txs |", + "|---|---|---|---|---|", + *( + f"| {lv} | {n} | {ph['distinct_victims'][lv]} | {ph['distinct_lookalikes'][lv]} | " + f"{ph['distinct_planting_txs'][lv]} |" + for lv, n in ph["levels"].items() + ), + "", + f"Subtype agreement on exact matches: {_kv(ph['subtype_agreement_on_exact'])}. " + f"Rows without an exact match: {_kv(ph['not_exact_reasons'])}. Transaction-only " + f"matches (batched plantings): {_kv(ph['tx_only_detail'])}.", + "", + ] + po = rec["payoffs"] + cmp = po["similarity_recency_comparison"] + linked = po["linked_distinct"] + lines += [ + "## Payoffs linked to earlier attempts", + "", + f"Unit: {po['unit']}; {po['payoffs']:,} payoffs.", + "", + "| Quantity | Value |", + "|---|---|", + f"| Archive status of the payoff row | {_kv(po['archive_status'])} |", + f"| Linkage | {_kv(po['linkage'])} |", + f"| Linked: distinct victims / lookalikes / payoff txs | {linked['victims']:,} / " + f"{linked['lookalikes']:,} / {linked['payoff_txs']:,} |", + f"| Blocks from the last pair attempt to the payoff | " + f"{_q(po['blocks_from_last_attempt_to_payoff'])} |", + f"| Pair attempts before the payoff | {_q(po['attempts_by_pair_before_payoff'])} |", + f"| Rival lookalikes that reached the victim before the payoff | " + f"{_q(po['rival_lookalikes_before_payoff'])} |", + f"| Payoffs with a rival imitating the same intended address | " + f"{_pct(po['payoffs_with_rival_of_same_intended'], po['payoffs'])} |", + f"| Of those (linked): paid lookalike was the most similar | " + f"{cmp['paid_lookalike_most_similar']:,} of {cmp['payoffs_compared']:,} " + f"(uniform expectation {cmp['expected_if_uniform']:,}) |", + f"| Of those (linked): paid lookalike was the most recent | " + f"{cmp['paid_lookalike_most_recent']:,} of {cmp['payoffs_compared']:,} " + f"(uniform expectation {cmp['expected_if_uniform_recent']:,}) |", + "", + f"Both comparisons cover {cmp['payoffs_compared']:,} payoffs from " + f"{cmp['distinct_victims_compared']:,} victims. They are observational: payoffs of one " + "victim are not independent, the uniform expectation counts ties, and neither " + "similarity nor recency is shown to cause a payment.", + "", + ] + rq = rec.get("review_packets") + if rq: + lines += [ + f"Review queue: {rq['payoff_linked_attempts']:,} payoff-linked attempt events " + f"({rq['with_competing_lookalikes']:,} with competing lookalikes) exported for " + "independent review; no label is assigned and the packets stay local.", + "", + ] + oc = rec["outcomes"] + lines += [ + "## Outcome levels for the Poison-Hunter rows", + "", + f"Unit: {oc['unit']} ({oc['rows']} rows). Note: {oc['note']}.", + "", + "| Outcome | Rows |", + "|---|---|", + *(f"| {k} | {v} |" for k, v in oc["outcomes"].items()), + "", + f"Payment pairs by temporal category: {_kv(oc['payment_pairs_by_temporal_category'])}.", + "", + "## Recorded incidents (case studies, not evaluation data)", + "", + "| Incident | Harm in archive period | Victim attempts | Harm-recipient attempts | " + "Pair attempts before harm | Harm tx in archive |", + "|---|---|---|---|---|---|", + *( + f"| {i['case']} | {_yes(i['harm_in_archive_period'])} | " + f"{i['victim_attempts_in_archive']} | {i['harm_recipient_attempts_in_archive']} | " + f"{i['pair_attempts_before_harm']} | {_yes(i['harm_tx_in_archive'])} |" + for i in rec["incidents"] + ), + "", + "## Decision gates", + "", + "| Gate | Status | Evidence |", + "|---|---|---|", + *(f"| {g['gate']} | {g['status']} | {g['detail']} |" for g in report["gates"]), + "", + f"Reconciliation runtime {report['reconcile_runtime_seconds']} s, peak RSS " + f"{(report['reconcile_peak_rss_bytes'] or 0) / 2**20:,.0f} MiB.", + "", + ] + return "\n".join(lines) + + +def write_report(report: dict[str, Any], out_dir: Path, tables: Path) -> Path: + import hashlib + + text = render(report) + tables.write_text(text, encoding="utf-8", newline="\n") + body = {**report, "tables_sha256": hashlib.sha256(text.encode()).hexdigest()} + path = out_dir / "cross-dataset.json" + path.write_text(json.dumps(body, indent=1, sort_keys=True, default=str), encoding="utf-8") + return path diff --git a/src/cryptoguard/ml/fetch.py b/src/cryptoguard/ml/fetch.py new file mode 100644 index 0000000..b523525 --- /dev/null +++ b/src/cryptoguard/ml/fetch.py @@ -0,0 +1,258 @@ +"""Verified, resumable download of one pinned large research file (no default caller). + +Nothing here runs from a build, test or default command: ``cryptoguard ml fetch-file`` +downloads only the file named on its command line, and only after the user approved it. + +Guarantees: +- The data lands in ``.part`` and is renamed only after size, published MD5, + SHA-256 and (for ``.gz``) a full gzip CRC check pass. +- A resume sends ``Range: bytes=-`` and appends only to a ``206`` whose + ``Content-Range`` starts exactly at that offset with the pinned total. A ``200`` means + the server ignored the range, so the partial file is restarted from byte 0 rather than + appended to. +- The download stops before free disk would fall below ``reserve_bytes``. +- A completed file that fails verification is renamed ``.corrupt``, never deleted + and never resumed. +""" + +from __future__ import annotations + +import gzip +import hashlib +import os +import re +import shutil +import time +from collections.abc import Callable +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import httpx + +CHUNK = 1 << 20 +DEFAULT_RESERVE = 10 << 30 # keep 10 GiB free on the target disk +GUARD_EVERY_BYTES = 256 << 20 # re-check free space every 256 MiB written +_CONTENT_RANGE = re.compile(r"^bytes (\d+)-(\d+)/(\d+)$") + + +@dataclass(frozen=True) +class PinnedFile: + name: str + url: str + size: int + md5: str # as published by the repository + source: str # DOI or stable identifier + license: str + sha256: str | None = None # pinned after the first verified download + + +TSUCHIYA_RECORD = "10.1184/R1/29212703.v1" +TSUCHIYA_LICENSE = "CC BY-NC-ND 4.0" +TSUCHIYA_FILES: dict[str, PinnedFile] = { + f.name: f + for f in ( + PinnedFile( + "address_poisoning_ethereum.sql.gz", + "https://ndownloader.figshare.com/files/55052912", + 2_316_354_530, + "5001c79f81741eabf54d2917a7954330", + TSUCHIYA_RECORD, + TSUCHIYA_LICENSE, + "270211acb28684dd6eeae549c7b4cec1c8276bee2d302cad0fa79a233b227cea", + ), + PinnedFile( + "README.txt", + "https://ndownloader.figshare.com/files/55053422", + 9_981, + "e8cd076a9ba1474133262d43dafa56dc", + TSUCHIYA_RECORD, + TSUCHIYA_LICENSE, + "f5805a108d7b3cbe9a70df721a7f997f6020e303909863bce86d329c4aeed142", + ), + PinnedFile( + "guidance.ipynb", + "https://ndownloader.figshare.com/files/55053158", + 22_830, + "10cdc28bb347ebc7eb3e80d9a3891a8e", + TSUCHIYA_RECORD, + TSUCHIYA_LICENSE, + "12d173523d0dcf42f2789fe37aaed7b5c6732b2ec003ad737ed08b6efdb66f85", + ), + PinnedFile( + "payoff_transfers_ethereum.csv", + "https://ndownloader.figshare.com/files/55053137", + 482_397, + "a42bda4339981d31a7e31b66c2d92297", + TSUCHIYA_RECORD, + TSUCHIYA_LICENSE, + "7851f9f9edcf04189137894e16dd228a544d13f4a0799548ece79c69762f2f78", + ), + ) +} + + +class DownloadError(RuntimeError): + """The transfer could not be completed safely; the partial file is kept for resume.""" + + +class DiskReserveError(DownloadError): + """Continuing would push free disk space below the configured reserve.""" + + +class IntegrityError(DownloadError): + """The completed file does not match its pinned size, checksum or gzip structure.""" + + +def digests(path: Path) -> tuple[str, str]: + md5, sha = hashlib.md5(usedforsecurity=False), hashlib.sha256() + with path.open("rb") as fh: + while block := fh.read(CHUNK): + md5.update(block) + sha.update(block) + return md5.hexdigest(), sha.hexdigest() + + +def gzip_check(path: Path) -> int: + """Decompress to nowhere, verifying every member's CRC and length; returns the + decompressed size. Raises ``IntegrityError`` on truncation or corruption.""" + total = 0 + try: + with gzip.open(path, "rb") as fh: + while block := fh.read(CHUNK): + total += len(block) + except (OSError, EOFError) as exc: + raise IntegrityError(f"{path}: gzip check failed: {exc}") from exc + return total + + +def _free(path: Path) -> int: + return shutil.disk_usage(path).free + + +def verify_local(pinned: PinnedFile, path: Path, *, gzip_crc: bool = True) -> dict[str, Any]: + """Size and checksums of an already-present file (raises ``IntegrityError``).""" + return _verify(pinned, path, gzip_crc=gzip_crc) + + +def _verify(pinned: PinnedFile, path: Path, *, gzip_crc: bool = True) -> dict[str, Any]: + size = path.stat().st_size + if size != pinned.size: + raise IntegrityError(f"{path}: {size} bytes, pinned {pinned.size}") + md5, sha = digests(path) + if md5 != pinned.md5: + raise IntegrityError(f"{path}: md5 {md5} != published {pinned.md5}") + if pinned.sha256 is not None and sha != pinned.sha256: + raise IntegrityError(f"{path}: sha256 {sha} != pinned {pinned.sha256}") + record: dict[str, Any] = {"name": pinned.name, "size": size, "md5": md5, "sha256": sha} + if gzip_crc and pinned.name.endswith(".gz"): + record["decompressed_size"] = gzip_check(path) + return record + + +def download( + pinned: PinnedFile, + dest_dir: Path, + *, + client: httpx.Client | None = None, + reserve_bytes: int = DEFAULT_RESERVE, + retries: int = 5, + backoff_s: float = 2.0, + progress: Callable[[int, int], None] | None = None, + free_bytes: Callable[[Path], int] = _free, +) -> dict[str, Any]: + """Download ``pinned`` into ``dest_dir``; returns its verification record.""" + dest_dir.mkdir(parents=True, exist_ok=True) + final = dest_dir / pinned.name + part = dest_dir / (pinned.name + ".part") + if final.exists(): + return {**_verify(pinned, final), "status": "cached"} + + def guard() -> None: + if free_bytes(dest_dir) < reserve_bytes: + raise DiskReserveError(f"free disk fell below the {reserve_bytes}-byte reserve") + + own = client is None + http = client or httpx.Client(timeout=httpx.Timeout(60, read=120), follow_redirects=True) + try: + failures = 0 + while True: + offset = part.stat().st_size if part.exists() else 0 + if offset > pinned.size: + part.write_bytes(b"") # our own partial file overshot: restart it + offset = 0 + if offset == pinned.size: + break + if free_bytes(dest_dir) - (pinned.size - offset) < reserve_bytes: + raise DiskReserveError( + f"need {pinned.size - offset} more bytes and a {reserve_bytes}-byte reserve" + ) + try: + _transfer(http, pinned, part, offset, progress, guard) + except (httpx.TransportError, httpx.HTTPStatusError) as exc: + failures += 1 + if failures > retries: + raise DownloadError(f"{pinned.url}: gave up after {retries} retries") from exc + time.sleep(backoff_s * failures) + finally: + if own: + http.close() + try: + record = _verify(pinned, part) + except IntegrityError: + os.replace(part, dest_dir / (pinned.name + ".corrupt")) + raise + os.replace(part, final) + return { + **record, + "status": "downloaded", + "url": pinned.url, + "source": pinned.source, + "license": pinned.license, + "downloaded_at": datetime.now(UTC).isoformat(timespec="seconds"), + } + + +def _transfer( + http: httpx.Client, + pinned: PinnedFile, + part: Path, + offset: int, + progress: Callable[[int, int], None] | None, + guard: Callable[[], None], +) -> None: + headers = {"Range": f"bytes={offset}-"} if offset else {} + with http.stream("GET", pinned.url, headers=headers) as resp: + resp.raise_for_status() + mode = "ab" + if offset and resp.status_code == 206: + m = _CONTENT_RANGE.match(resp.headers.get("content-range", "")) + if not m or int(m[1]) != offset or int(m[3]) != pinned.size: + raise DownloadError( + f"unexpected Content-Range {resp.headers.get('content-range')!r} " + f"for offset {offset}" + ) + elif resp.status_code == 200: + if offset: + offset, mode = 0, "wb" # range ignored: never append a full body + length = resp.headers.get("content-length") + if length is not None and int(length) != pinned.size: + raise DownloadError(f"Content-Length {length}, pinned {pinned.size}") + else: + raise DownloadError(f"unexpected HTTP {resp.status_code}") + written = offset + next_guard = written + with part.open(mode) as fh: + for block in resp.iter_bytes(CHUNK): + if written + len(block) > pinned.size: + raise DownloadError("server sent more bytes than the pinned size") + if written >= next_guard: + guard() + next_guard = written + GUARD_EVERY_BYTES + fh.write(block) + written += len(block) + if progress is not None: + progress(written, pinned.size) + fh.flush() + os.fsync(fh.fileno()) diff --git a/src/cryptoguard/ml/reconcile.py b/src/cryptoguard/ml/reconcile.py new file mode 100644 index 0000000..0e4aa9c --- /dev/null +++ b/src/cryptoguard/ml/reconcile.py @@ -0,0 +1,503 @@ +"""Reconciliation of Poison-Hunter rows, Tsuchiya et al. attempts and payoffs (offline). + +Units (never mixed): + +- **attempt**: one archive poisoning transfer, keyed ``(victim, lookalike, tx)``; the + archive has no log index, so repeats of that key inside one transaction count once. +- **victim-event**: one Poison-Hunter row's ``(victim, lookalike, planting tx)``. +- **payoff**: one row of ``payoff_transfers_ethereum.csv`` (one transaction each). + +Outcome levels (Stage H), each answered separately and never inferred from another: + +- *attempt outcome*: the victim paid **this** lookalike after this planting; +- *victim outcome*: the victim paid **any** lookalike after this planting; +- *address outcome*: this lookalike received a payoff from **any** victim (before or after); +- *campaign outcome*: some lookalike in the row's campaign group received a payoff. + +Temporal categories for a (planting, payment) pair: ``before_planting``, +``same_block_order_unknown`` (the archive has no transaction index), ``after_planting``, +and ``temporally_ambiguous`` (a block is missing). A payment before a planting is history +about the address, never an outcome of that planting. + +Match levels for a Poison-Hunter row against the archive (strongest first): +``exact_tx_event`` > ``victim_lookalike_imitated`` > ``victim_lookalike`` > +``tx_only`` > ``shared_lookalike`` > ``competing_lookalike`` > ``victim_only`` > ``none``. +Weaker levels are reported, never converted into labels. +""" + +from __future__ import annotations + +import statistics +from collections import Counter, defaultdict +from collections.abc import Iterable +from dataclasses import dataclass +from typing import Any, Literal + +from cryptoguard.detectors.poisoning import affix_match +from cryptoguard.ml.events import PoisoningEvent, Subtype +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.ml.poison_hunter import PoisonHunterRecord +from cryptoguard.ml.review import ReviewPacket, packet +from cryptoguard.ml.tsuchiya import PayoffTransfer +from cryptoguard.ml.tsuchiya_archive import ( + COUNTERFEIT, + PAYOFF, + PAYOFF_UNCONFIRMED, + POISONING, + TINY, + ZERO, + ArchiveTransfer, +) + +RECONCILE_VERSION = "reconcile/1" +WINDOW_BLOCKS = 50_400 # 7 days, the pilot's window + +Temporal = Literal[ + "before_planting", "same_block_order_unknown", "after_planting", "temporally_ambiguous" +] +MatchLevel = Literal[ + "exact_tx_event", + "victim_lookalike_imitated", + "victim_lookalike", + "tx_only", + "shared_lookalike", + "competing_lookalike", + "victim_only", + "none", +] +LEVELS: tuple[MatchLevel, ...] = MatchLevel.__args__ # type: ignore[attr-defined] +_PH_SUBTYPE = {"dust": TINY, "zero": ZERO, "fake": COUNTERFEIT} + + +def temporal(planting_block: int | None, payment_block: int | None) -> Temporal: + if planting_block is None or payment_block is None: + return "temporally_ambiguous" + if payment_block < planting_block: + return "before_planting" + if payment_block == planting_block: + return "same_block_order_unknown" + return "after_planting" + + +@dataclass(frozen=True, slots=True) +class Attempt: + victim: str + lookalike: str + tx: str + block: int + flags: int + intended: str | None + token: str = "" + victim_sends: bool = False + + +class ArchiveIndex: + """Hash indexes over the stored archive subset (attempts deduplicated by key).""" + + def __init__(self, rows: Iterable[ArchiveTransfer]) -> None: + self.by_pair: dict[tuple[str, str], list[Attempt]] = defaultdict(list) + self.by_victim: dict[str, list[Attempt]] = defaultdict(list) + self.by_lookalike: dict[str, list[Attempt]] = defaultdict(list) + self.by_tx: dict[str, list[Attempt]] = defaultdict(list) + self.payoff_rows: dict[tuple[str, str, str], int] = {} + self.repeated_attempt_rows = 0 + seen: set[tuple[str, str, str]] = set() + for r in rows: + victim, lookalike = r.victim, r.counterparty + if r.flags & (PAYOFF | PAYOFF_UNCONFIRMED) and r.sender_is_victim: + key = (r.tx, r.sender, r.receiver) + self.payoff_rows[key] = self.payoff_rows.get(key, 0) | r.flags + if not r.flags & POISONING or victim is None or lookalike is None: + continue + k = (victim, lookalike, r.tx) + if k in seen: + self.repeated_attempt_rows += 1 + continue + seen.add(k) + a = Attempt( + victim, lookalike, r.tx, r.block, r.flags, r.intended, r.token, r.sender == victim + ) + self.by_pair[(victim, lookalike)].append(a) + self.by_victim[victim].append(a) + self.by_lookalike[lookalike].append(a) + self.by_tx[r.tx].append(a) + for index in (self.by_pair, self.by_victim, self.by_lookalike, self.by_tx): + for attempts in index.values(): + attempts.sort(key=lambda a: (a.block, a.tx, a.victim, a.lookalike)) + + @property + def attempts(self) -> int: + return sum(len(v) for v in self.by_pair.values()) + + +def _level(r: PoisonHunterRecord, ix: ArchiveIndex) -> tuple[MatchLevel, list[Attempt]]: + same_tx = ix.by_tx.get(r.planting_tx, []) + exact = [a for a in same_tx if (a.victim, a.lookalike) == (r.victim, r.lookalike)] + if exact: + return "exact_tx_event", exact + pair = ix.by_pair.get((r.victim, r.lookalike), []) + if any(a.intended == r.imitated for a in pair): + return "victim_lookalike_imitated", pair + if pair: + return "victim_lookalike", pair + if same_tx: + return "tx_only", same_tx + if ix.by_lookalike.get(r.lookalike): + return "shared_lookalike", ix.by_lookalike[r.lookalike] + competing = [ + a + for a in ix.by_victim.get(r.victim, []) + if a.intended == r.imitated and a.lookalike != r.lookalike + ] + if competing: + return "competing_lookalike", competing + if ix.by_victim.get(r.victim): + return "victim_only", ix.by_victim[r.victim] + return "none", [] + + +def _distinct(values: Iterable[Any]) -> int: + return len(set(values)) + + +def _quantiles(values: list[int]) -> dict[str, float] | None: + if not values: + return None + s = sorted(values) + q = statistics.quantiles(s, n=4, method="inclusive") if len(s) > 1 else [s[0]] * 3 + return {"n": len(s), "min": s[0], "p25": q[0], "median": q[1], "p75": q[2], "max": s[-1]} + + +def ph_matches( + ph: list[PoisonHunterRecord], + ix: ArchiveIndex, + poisoning_block_range: tuple[int, int] | None, +) -> dict[str, Any]: + """Match level per Poison-Hunter row, with the reasons unmatched rows differ.""" + levels: Counter[str] = Counter() + per_level: dict[str, list[PoisonHunterRecord]] = defaultdict(list) + subtype_agreement: Counter[str] = Counter() + reasons: Counter[str] = Counter() + tx_only: Counter[str] = Counter() + lines: dict[str, list[int]] = defaultdict(list) + for r in ph: + level, hits = _level(r, ix) + levels[level] += 1 + per_level[level].append(r) + lines[level].append(r.source_line) + if level == "tx_only": + with_victim = any(a.victim == r.victim for a in hits) + tx_only[ + "victim_listed_with_another_lookalike" if with_victim else "victim_not_listed" + ] += 1 + if level == "exact_tx_event": + agree = any(a.flags & _PH_SUBTYPE.get(r.subtype, 0) for a in hits) + subtype_agreement[f"{r.subtype}->{'agrees' if agree else _flags(hits)}"] += 1 + else: + in_range = ( + poisoning_block_range is not None + and r.block_number is not None + and poisoning_block_range[0] <= r.block_number <= poisoning_block_range[1] + ) + if not in_range: + reasons["outside_archive_period"] += 1 + elif not r.tsuchiya_lookalike: + reasons["below_3_plus_4_similarity"] += 1 + else: + reasons["inside_period_and_definition"] += 1 + return { + "unit": "Poison-Hunter row (149 valid rows; 6 duplicate victim-events)", + "levels": {lv: levels.get(lv, 0) for lv in LEVELS}, + "distinct_victims": {lv: _distinct(r.victim for r in per_level[lv]) for lv in LEVELS}, + "distinct_lookalikes": {lv: _distinct(r.lookalike for r in per_level[lv]) for lv in LEVELS}, + "distinct_planting_txs": { + lv: _distinct(r.planting_tx for r in per_level[lv]) for lv in LEVELS + }, + "lines": {lv: lines[lv] for lv in LEVELS if lines[lv]}, + "subtype_agreement_on_exact": dict(sorted(subtype_agreement.items())), + "not_exact_reasons": dict(sorted(reasons.items())), + "tx_only_detail": dict(sorted(tx_only.items())), + } + + +def _flags(hits: list[Attempt]) -> str: + names = {ZERO: "zero", TINY: "tiny", COUNTERFEIT: "counterfeit"} + found = sorted({n for a in hits for b, n in names.items() if a.flags & b}) + return "+".join(found) or "other" + + +def payoff_linkage(payoffs: list[PayoffTransfer], ix: ArchiveIndex) -> dict[str, Any]: + """For each payoff: is it in the archive, and which attempts preceded it? + + A payoff is *attempt-linked* when the archive holds a poisoning transfer between the + same victim and the same lookalike in an earlier block. Same-block attempts are + reported separately (order unknown); later ones are not causes.""" + status: Counter[str] = Counter() + linked: Counter[str] = Counter() + lead: list[int] = [] + competitors: list[int] = [] + competitors_same_intended: list[int] = [] + paid_most_similar = paid_most_recent = ranked = 0 + ranked_victims: set[str] = set() + expected_similar = expected_recent = 0.0 + attempts_before: list[int] = [] + linked_victims: set[str] = set() + linked_lookalikes: set[str] = set() + linked_payoff_txs: set[str] = set() + for p in payoffs: + flags = ix.payoff_rows.get((p.tx_hash, p.payer, p.lookalike)) + if flags is None: + status["payoff_not_in_archive_subset"] += 1 + elif flags & PAYOFF: + status["archive_flag_payoff_confirmed"] += 1 + else: + status["archive_flag_payoff_unconfirmed_only"] += 1 + pair = ix.by_pair.get((p.payer, p.lookalike), []) + # From the payoff's side: attempts *before the payment* are candidate causes. + before = [a for a in pair if p.block_number is not None and a.block < p.block_number] + same = [a for a in pair if a.block == p.block_number] + if before: + linked["attempt_before_payoff"] += 1 + lead.append(p.block_number - before[-1].block) # type: ignore[operator] + attempts_before.append(len(before)) + linked_victims.add(p.payer) + linked_lookalikes.add(p.lookalike) + linked_payoff_txs.add(p.tx_hash) + elif same: + linked["same_block_only"] += 1 + elif pair: + linked["attempts_only_after_payoff"] += 1 + else: + linked["no_attempt_between_pair"] += 1 + if p.block_number is None: + continue + rivals = { + a.lookalike: a + for a in ix.by_victim.get(p.payer, []) + if a.block < p.block_number and a.lookalike != p.lookalike + } + competitors.append(len(rivals)) + same_target = { + lk: a for lk, a in rivals.items() if a.intended is not None and a.intended == p.intended + } + competitors_same_intended.append(len(same_target)) + if before and same_target: + # Observational comparison among lookalikes of the same intended address that + # reached this victim before the payment (no causal reading). + # The null is a uniform choice among the k candidates; with ties, the chance of + # picking one of the best is (number tied at the maximum) / k, not 1 / k. + ranked += 1 + ranked_victims.add(p.payer) + k = len(same_target) + 1 + scores = [sum(affix_match(lk, p.intended)) for lk in same_target] + paid_score = sum(affix_match(p.lookalike, p.intended)) + best = max([paid_score, *scores]) + paid_most_similar += paid_score == best + expected_similar += ( + 1 + scores.count(best) if paid_score == best else scores.count(best) + ) / k + cutoff = p.block_number + seen = [ + max(a.block for a in ix.by_pair.get((p.payer, lk), []) if a.block < cutoff) + for lk in same_target + ] + paid_seen = before[-1].block + latest = max([paid_seen, *seen]) + paid_most_recent += paid_seen == latest + expected_recent += ( + 1 + seen.count(latest) if paid_seen == latest else seen.count(latest) + ) / k + return { + "unit": "payoff transfer (payoff_transfers_ethereum.csv row)", + "payoffs": len(payoffs), + "archive_status": dict(sorted(status.items())), + "linkage": dict(sorted(linked.items())), + "linked_distinct": { + "victims": len(linked_victims), + "lookalikes": len(linked_lookalikes), + "payoff_txs": len(linked_payoff_txs), + }, + "blocks_from_last_attempt_to_payoff": _quantiles(lead), + "attempts_by_pair_before_payoff": _quantiles(attempts_before), + "rival_lookalikes_before_payoff": _quantiles(competitors), + "payoffs_with_rival_of_same_intended": sum(1 for c in competitors_same_intended if c), + "rival_lookalikes_same_intended": _quantiles(competitors_same_intended), + "similarity_recency_comparison": { + "payoffs_compared": ranked, + "distinct_victims_compared": len(ranked_victims), + "paid_lookalike_most_similar": paid_most_similar, + "expected_if_uniform": round(expected_similar, 1), + "paid_lookalike_most_recent": paid_most_recent, + "expected_if_uniform_recent": round(expected_recent, 1), + "caveat": "observational; ties count as most similar or most recent and the " + "uniform expectation accounts for them; one victim can appear in several " + "payoffs; not a causal effect of similarity or recency", + }, + } + + +def ph_outcomes( + ph: list[PoisonHunterRecord], + payoffs: list[PayoffTransfer], + groups: dict[str, str] | None = None, + window_blocks: int = WINDOW_BLOCKS, +) -> dict[str, Any]: + """The four outcome levels for each Poison-Hunter row, with temporal categories. + + ``groups`` maps a lookalike to its campaign group id (``events.campaign_groups``).""" + by_payer: dict[str, list[PayoffTransfer]] = defaultdict(list) + by_lookalike: dict[str, list[PayoffTransfer]] = defaultdict(list) + for p in payoffs: + by_payer[p.payer].append(p) + by_lookalike[p.lookalike].append(p) + group_lookalikes: dict[str, set[str]] = defaultdict(set) + for lk, g in (groups or {}).items(): + group_lookalikes[g].add(lk) + out: Counter[str] = Counter() + pairs: Counter[str] = Counter() + for r in ph: + b = r.block_number + this = [p for p in by_payer.get(r.victim, []) if p.lookalike == r.lookalike] + anyl = by_payer.get(r.victim, []) + addr = by_lookalike.get(r.lookalike, []) + for p in anyl + [q for q in addr if q.payer != r.victim]: + who = "this_pair" if p in this else ("victim" if p in anyl else "address") + pairs[f"{who}/{temporal(b, p.block_number)}"] += 1 + after = [p for p in this if temporal(b, p.block_number) == "after_planting"] + out["attempt_outcome_paid_after"] += bool(after) + out["attempt_outcome_paid_in_window"] += any( + b is not None and p.block_number is not None and p.block_number - b <= window_blocks + for p in after + ) + out["victim_outcome_paid_any_lookalike_after"] += any( + temporal(b, p.block_number) == "after_planting" for p in anyl + ) + out["address_outcome_paid_by_anyone_before"] += any( + temporal(b, p.block_number) == "before_planting" for p in addr + ) + out["address_outcome_paid_by_anyone_after"] += any( + temporal(b, p.block_number) == "after_planting" for p in addr + ) + if groups is not None and r.lookalike in groups: + mates = group_lookalikes[groups[r.lookalike]] + out["campaign_outcome_paid_after"] += any( + temporal(b, p.block_number) == "after_planting" + for lk in mates + for p in by_lookalike.get(lk, []) + ) + return { + "unit": "Poison-Hunter row", + "rows": len(ph), + "outcomes": dict(sorted(out.items())), + "payment_pairs_by_temporal_category": dict(sorted(pairs.items())), + "note": "a victim's loss to another lookalike is never credited to this attempt; " + "payments before the planting are address history, not outcomes", + } + + +def incident_case_studies( + incidents: list[dict[str, Any]], ix: ArchiveIndex, block_range: tuple[int, int] | None +) -> list[dict[str, Any]]: + out = [] + for inc in incidents: + pair = ix.by_pair.get((inc["victim"], inc["recipient"]), []) + out.append( + { + "case": inc["case"], + "harm_in_archive_period": block_range is not None + and block_range[0] <= inc["block"] <= block_range[1], + "victim_attempts_in_archive": len(ix.by_victim.get(inc["victim"], [])), + "harm_recipient_attempts_in_archive": len( + ix.by_lookalike.get(inc["recipient"], []) + ), + "pair_attempts_before_harm": sum(1 for a in pair if a.block < inc["block"]), + "harm_tx_in_archive": any(k[0] == inc["tx"] for k in ix.payoff_rows) + or inc["tx"] in ix.by_tx, + } + ) + return out + + +def reconcile( + rows: Iterable[ArchiveTransfer], + summary: dict[str, Any], + ph: list[PoisonHunterRecord], + payoffs: list[PayoffTransfer], + incidents: list[dict[str, Any]], + groups: dict[str, str] | None = None, +) -> dict[str, Any]: + ix = ArchiveIndex(rows) + prange = summary.get("poisoning_block_range") + brange = summary.get("block_range") + return { + "version": RECONCILE_VERSION, + "subset": { + "attempts": ix.attempts, + "repeated_attempt_rows": ix.repeated_attempt_rows, + "victims": len(ix.by_victim), + "lookalikes": len(ix.by_lookalike), + "payoff_flag_rows": len(ix.payoff_rows), + }, + "poison_hunter": ph_matches(ph, ix, tuple(prange) if prange else None), + "payoffs": payoff_linkage(payoffs, ix), + "outcomes": ph_outcomes(ph, payoffs, groups), + "incidents": incident_case_studies(incidents, ix, tuple(brange) if brange else None), + } + + +def _subtype(a: Attempt) -> Subtype: + if a.flags & ZERO: + return "spoofed_transfer_from" if a.victim_sends else "zero_value" + if a.flags & COUNTERFEIT: + return "fake_token" + if a.flags & TINY: + return "dust" + return "unknown" + + +def payoff_review_packets(payoffs: list[PayoffTransfer], ix: ArchiveIndex) -> list[ReviewPacket]: + """One review packet per payoff-linked attempt: the latest archive attempt by the same + lookalike against the same victim before the payment. These are review candidates for + ``verified_attempt``; nothing here assigns a label.""" + out: dict[str, ReviewPacket] = {} + for p in payoffs: + if p.block_number is None: + continue + before = [a for a in ix.by_pair.get((p.payer, p.lookalike), []) if a.block < p.block_number] + if not before: + continue + a = before[-1] + event = PoisoningEvent( + chain_id=1, + victim=a.victim, + lookalike=a.lookalike, + imitated=a.intended, + planting_tx=a.tx, + planting_block=a.block, + planting_tx_index=None, + planting_log_index=None, + observation_timestamp=None, + subtype=_subtype(a), + tx_signer=None, + log_contract=a.token or None, + token_contract=a.token if a.token in TRUSTED_TOKENS else None, + candidate_method="tsuchiya-archive:latest-attempt-before-payoff", + evidence_refs=(f"tsuchiya-archive:{a.tx}", f"tsuchiya-payoff:{p.tx_hash}"), + coverage="unavailable", + dataset_version=RECONCILE_VERSION, + ) + competing = { + r.lookalike + for r in ix.by_victim.get(p.payer, []) + if r.block < p.block_number and r.lookalike != p.lookalike and r.intended == a.intended + } + out[event.victim_event_id] = packet( + event, + (f"tsuchiya-archive:{_subtype(a)}", "tsuchiya-payoff:confirmed"), + f"Source-labelled poisoning transfer at block {a.block:,}; the victim paid this " + f"lookalike {p.block_number - a.block:,} blocks later. {len(before)} attempt(s) by " + "this lookalike preceded the payment.", + competing=sorted(competing), + payments=(f"{p.tx_hash} block {p.block_number} after_planting (confirmed payoff)",), + ) + return [out[k] for k in sorted(out)] diff --git a/src/cryptoguard/ml/review.py b/src/cryptoguard/ml/review.py index 156988c..f2bc3b8 100644 --- a/src/cryptoguard/ml/review.py +++ b/src/cryptoguard/ml/review.py @@ -37,9 +37,11 @@ class ReviewPacket(BaseModel): + """v2 adds competing lookalikes and observed-payment evidence; v1 packets still load.""" + model_config = ConfigDict(extra="forbid", frozen=True) - schema_version: Literal["poisoning-review/1"] = "poisoning-review/1" + schema_version: Literal["poisoning-review/1", "poisoning-review/2"] = "poisoning-review/2" victim_event_id: str victim: str lookalike: str @@ -50,6 +52,8 @@ class ReviewPacket(BaseModel): evidence_summary: str coverage_limitations: str source_labels: tuple[str, ...] + competing_lookalikes: tuple[str, ...] = () # same victim and imitated address, earlier + payment_evidence: tuple[str, ...] = () # observed payments, each with its time category class ReviewDecision(BaseModel): @@ -67,7 +71,14 @@ class ReviewImportError(ValueError): pass -def packet(event: PoisoningEvent, source_labels: Sequence[str], evidence: str) -> ReviewPacket: +def packet( + event: PoisoningEvent, + source_labels: Sequence[str], + evidence: str, + *, + competing: Sequence[str] = (), + payments: Sequence[str] = (), +) -> ReviewPacket: limits = { "complete": "wallet window fully observed", "partial": "wallet history incomplete: unobserved events may exist", @@ -84,6 +95,8 @@ def packet(event: PoisoningEvent, source_labels: Sequence[str], evidence: str) - evidence_summary=evidence, coverage_limitations=limits, source_labels=tuple(source_labels), + competing_lookalikes=tuple(sorted(competing)), + payment_evidence=tuple(payments), ) diff --git a/src/cryptoguard/ml/tsuchiya_archive.py b/src/cryptoguard/ml/tsuchiya_archive.py new file mode 100644 index 0000000..4bdba93 --- /dev/null +++ b/src/cryptoguard/ml/tsuchiya_archive.py @@ -0,0 +1,858 @@ +"""Safe streaming reader for Tsuchiya et al.'s ``address_poisoning_ethereum.sql.gz``. + +The archive is a PostgreSQL 16 plain-format dump: a preamble (``SET``, ``CREATE DATABASE``, +the psql meta-command ``\\connect``, one ``CREATE TABLE``), one ``COPY ... FROM stdin;`` +block of tab-separated rows terminated by ``\\.``, and nothing else of substance. It is +**data, never instructions**: nothing here executes, evaluates or forwards any of its text +to a database. The reader recognises a small whitelist of statement prefixes, checks the +table definition and the COPY column list against the documented schema, parses each row +with type checks, and refuses anything else (another table, ``INSERT`` statements, unknown +statements, truncated input) with a specific error rather than producing partial data. + +Memory: the gzip stream is read line by line with a bounded line length (no +decompression to disk, no full materialisation). Exact distinct counts of millions of +addresses spill to bucketed temporary files (``SpillDistinct``) instead of growing an +in-memory set. Only rows touching a small target manifest are stored, in SQLite. + +Resumption: gzip offers no record-level seek, so an interrupted scan restarts from byte 0 +(deterministic replay). The output database is built under a temporary name and renamed +only when the whole pass completes, so a rerun can never mix partial and complete results. + +Column notes (dump header, checked against the README): the COPY column order differs from +the README's (``zero_value_transfer`` precedes ``tiny_transfer``), so columns are always +mapped by name. ``value``/``value_usd`` are PostgreSQL ``real`` (float4, about 7 +significant digits) with ``NaN`` for missing: amounts are approximate. There is no log +index, so two identical transfers in one transaction cannot be told apart. +""" + +from __future__ import annotations + +import gzip +import hashlib +import io +import json +import os +import re +import sqlite3 +import sys +import time +import zlib +from collections import Counter +from collections.abc import Callable, Iterable, Iterator +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from cryptoguard.detectors.poisoning import PoisoningConfig, affix_match, is_lookalike +from cryptoguard.ml.candidates import similar, transfer_methods + +PARSER_VERSION = "tsuchiya-archive/1" +SCHEMA_VERSION = 1 +TABLE = "address_poisoning_ethereum" +COLUMNS: dict[str, str] = { + "block_number": "integer", + "tx_hash": "character(66)", + "addr": "character(42)", + "topics_from_addr": "character(42)", + "topics_to_addr": "character(42)", + "is_sender_victim": "boolean", + "value": "real", + "value_usd": "real", + "intended_transfer": "boolean", + "zero_value_transfer": "boolean", + "tiny_transfer": "boolean", + "counterfeit_token_transfer": "boolean", + "payoff_transfer": "boolean", + "payoff_transfer_unconfirmed": "boolean", + "is_not_categorized": "boolean", + "intended_addr": "character(42)", + "num_first_matched_digits": "integer", + "num_last_matched_digits": "integer", +} +MAX_LINE = 4096 # a valid row is about 400 bytes +NULL = "\\N" + +# Category flags (bitmask), in the README's vocabulary. +INTENDED, ZERO, TINY, COUNTERFEIT, PAYOFF, PAYOFF_UNCONFIRMED, UNCATEGORIZED = ( + 1 << i for i in range(7) +) +FLAG_COLUMNS = { + "intended_transfer": INTENDED, + "zero_value_transfer": ZERO, + "tiny_transfer": TINY, + "counterfeit_token_transfer": COUNTERFEIT, + "payoff_transfer": PAYOFF, + "payoff_transfer_unconfirmed": PAYOFF_UNCONFIRMED, + "is_not_categorized": UNCATEGORIZED, +} +FLAG_NAMES = {v: k for k, v in FLAG_COLUMNS.items()} +_FLAG_BITS = tuple(FLAG_COLUMNS.values()) # same order as the flag columns in COLUMNS +_BOOLS: dict[str, bool | None] = {"t": True, "f": False, NULL: None} +POISONING = ZERO | TINY | COUNTERFEIT # the notebook's definition of a poisoning transfer + +_ADDR = re.compile(r"0x[0-9a-fA-F]{40}") +_HASH = re.compile(r"0x[0-9a-fA-F]{64}") +_COPY = re.compile(rb"^COPY public\.(\w+) \(([^)]*)\) FROM stdin;\n$") +_COLUMN_DEF = re.compile(rb"^ (\w+) ([a-z ]+(?:\(\d+\))?),?\n$") +_PREAMBLE_OK = ( + b"--", + b"SET ", + b"SELECT pg_catalog.set_config(", + b"CREATE DATABASE ", + b"\\connect ", +) +_POSTAMBLE_OK = ( + b"--", + b"SET ", + b"SELECT pg_catalog.", + b"CREATE INDEX ", + b"CREATE UNIQUE INDEX ", + b"ALTER TABLE ", +) +_ESCAPES = {"b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v", "\\": "\\"} + + +class ArchiveError(ValueError): + """The archive cannot be read safely; nothing partial is produced.""" + + +class InvalidArchiveError(ArchiveError): + """Not a gzip stream, or the gzip stream is corrupt.""" + + +class TruncatedArchiveError(ArchiveError): + """The stream ended inside the data block or inside a gzip member.""" + + +class UnsupportedDumpError(ArchiveError): + """A statement, table or dump format outside the narrow supported subset.""" + + +class SchemaMismatchError(ArchiveError): + """The table definition or COPY column list differs from the documented schema.""" + + +class TooManyMalformedError(ArchiveError): + """More rows failed validation than the configured tolerance.""" + + +def copy_unescape(text: str) -> str: + """Decode PostgreSQL COPY text escapes (``\\t``, ``\\\\``, octal ``\\NNN``, ``\\xHH``).""" + if "\\" not in text: + return text + out: list[str] = [] + i = 0 + while i < len(text): + ch = text[i] + if ch != "\\" or i + 1 == len(text): + out.append(ch) + i += 1 + continue + nxt = text[i + 1] + if nxt in _ESCAPES: + out.append(_ESCAPES[nxt]) + i += 2 + elif nxt == "x" and i + 2 < len(text) and text[i + 2] in "0123456789abcdefABCDEF": + j = i + 2 + while j < min(i + 4, len(text)) and text[j] in "0123456789abcdefABCDEF": + j += 1 + out.append(chr(int(text[i + 2 : j], 16))) + i = j + elif nxt in "01234567": + j = i + 1 + while j < min(i + 4, len(text)) and text[j] in "01234567": + j += 1 + out.append(chr(int(text[i + 1 : j], 8))) + i = j + else: + out.append(nxt) # PostgreSQL: any other backslashed character stands for itself + i += 2 + return "".join(out) + + +@dataclass(frozen=True, slots=True) +class ArchiveTransfer: + """One validated source row. ``line`` (1-based line in the decompressed dump) is the + stable source identifier; addresses and hashes are lowercase.""" + + line: int + block: int + tx: str + token: str + sender: str + receiver: str + sender_is_victim: bool | None + value: float | None # base units, float4-approximate; None for NaN/NULL + value_usd: float | None + flags: int + intended: str | None + first_digits: int | None + last_digits: int | None + + @property + def is_poisoning(self) -> bool: + return bool(self.flags & POISONING) + + @property + def victim(self) -> str | None: + if self.sender_is_victim is None: + return None + return self.sender if self.sender_is_victim else self.receiver + + @property + def counterparty(self) -> str | None: + """The non-victim side: the lookalike for poisoning and payoff rows.""" + if self.sender_is_victim is None: + return None + return self.receiver if self.sender_is_victim else self.sender + + +@dataclass +class ReaderStats: + lines: int = 0 + data_rows: int = 0 + valid_rows: int = 0 + decompressed_bytes: int = 0 + preamble: Counter[str] = field(default_factory=Counter) + postamble: Counter[str] = field(default_factory=Counter) + malformed: Counter[str] = field(default_factory=Counter) + malformed_lines: dict[str, list[int]] = field(default_factory=dict) + + def reject(self, reason: str, line: int) -> None: + self.malformed[reason] += 1 + examples = self.malformed_lines.setdefault(reason, []) + if len(examples) < 5: + examples.append(line) + + def as_dict(self) -> dict[str, Any]: + return { + "lines": self.lines, + "data_rows": self.data_rows, + "valid_rows": self.valid_rows, + "malformed_rows": sum(self.malformed.values()), + "decompressed_bytes": self.decompressed_bytes, + "preamble_statements": dict(sorted(self.preamble.items())), + "postamble_statements": dict(sorted(self.postamble.items())), + "malformed": dict(sorted(self.malformed.items())), + "malformed_example_lines": dict(sorted(self.malformed_lines.items())), + } + + +def _keyword(line: bytes) -> str: + head = line.strip().split(b" ", 2) + word = b" ".join(head[:2]) if head[0] in (b"CREATE", b"ALTER") else head[0] + return word.decode("ascii", "replace")[:40] or "(blank)" + + +def _bool(text: str) -> bool | None: + if text == "t": + return True + if text == "f": + return False + if text == NULL: + return None + raise ValueError("boolean") + + +def _real(text: str) -> float | None: + if text in ("NaN", NULL): + return None + try: + value = float(text) + except ValueError: + raise ValueError("real") from None + if value != value or value in (float("inf"), float("-inf")): + raise ValueError("non_finite_real") + return value + + +def _int(text: str) -> int: + try: + return int(text) + except ValueError: + raise ValueError("integer") from None + + +def _opt_int(text: str) -> int | None: + return None if text == NULL else _int(text) + + +def _addr(text: str) -> str: + if not _ADDR.fullmatch(text): + raise ValueError("address") + return text.lower() + + +class ArchiveReader: + """Iterate validated rows of the dump. Raises an ``ArchiveError`` subclass for + anything outside the supported subset; per-row validation failures are counted in + ``stats`` (and fail the read when ``max_malformed_fraction`` is exceeded).""" + + def __init__(self, path: Path, *, max_malformed_fraction: float = 0.001) -> None: + self.path = path + self.max_malformed_fraction = max_malformed_fraction + self.stats = ReaderStats() + self.columns: list[str] = [] + + def __iter__(self) -> Iterator[ArchiveTransfer]: + try: + with gzip.open(self.path, "rb") as fh: + yield from self._read(fh) + except EOFError as exc: + raise TruncatedArchiveError(f"{self.path}: gzip stream ended early") from exc + except (gzip.BadGzipFile, zlib.error) as exc: + raise InvalidArchiveError(f"{self.path}: {exc}") from exc + rows = self.stats.data_rows + bad = rows - self.stats.valid_rows + if rows and bad / rows > self.max_malformed_fraction: + raise TooManyMalformedError( + f"{bad} of {rows} rows malformed: {dict(self.stats.malformed)}" + ) + + def _readline(self, fh: io.BufferedIOBase) -> bytes: + line = fh.readline(MAX_LINE + 1) + self.stats.decompressed_bytes += len(line) + if line: + self.stats.lines += 1 + return line + + def _skip_rest(self, fh: io.BufferedIOBase) -> None: + while True: + chunk = fh.readline(MAX_LINE + 1) + self.stats.decompressed_bytes += len(chunk) + if not chunk or chunk.endswith(b"\n"): + return + + def _read(self, fh: io.BufferedIOBase) -> Iterator[ArchiveTransfer]: + self._preamble(fh) # validates the table definition and the COPY column set + index = {name: i for i, name in enumerate(self.columns)} + perm = tuple(index[name] for name in COLUMNS) # dump order -> documented order + while True: + raw = self._readline(fh) + n = self.stats.lines + if not raw: + raise TruncatedArchiveError(f"line {n}: end of input inside the COPY block") + if not raw.endswith(b"\n"): + if len(raw) > MAX_LINE: + self.stats.data_rows += 1 + self.stats.reject("oversize_line", n) + self._skip_rest(fh) + continue + raise TruncatedArchiveError(f"line {n}: last line has no terminator") + if raw == b"\\.\n": + break + self.stats.data_rows += 1 + row = self._row(raw, n, perm) + if row is not None: + self.stats.valid_rows += 1 + yield row + self._postamble(fh) + + def _preamble(self, fh: io.BufferedIOBase) -> dict[str, str]: + table: dict[str, str] | None = None + while True: + raw = self._readline(fh) + n = self.stats.lines + if not raw: + raise TruncatedArchiveError(f"line {n}: no COPY block found") + if len(raw) > MAX_LINE: + raise UnsupportedDumpError(f"line {n}: statement longer than {MAX_LINE} bytes") + if raw.strip() == b"": + continue + if raw.startswith(f"CREATE TABLE public.{TABLE} (".encode()): + if table is not None: + raise UnsupportedDumpError(f"line {n}: table {TABLE} defined twice") + table = self._table(fh) + self.stats.preamble["CREATE TABLE"] += 1 + continue + if raw.startswith(b"COPY "): + m = _COPY.match(raw) + if not m or m[1].decode() != TABLE: + raise UnsupportedDumpError(f"line {n}: COPY for an unsupported table") + if table is None: + raise SchemaMismatchError(f"line {n}: COPY before the table definition") + self.columns = [c.strip().decode() for c in m[2].split(b",")] + if sorted(self.columns) != sorted(COLUMNS): + raise SchemaMismatchError(f"line {n}: COPY columns {self.columns}") + self.stats.preamble["COPY"] += 1 + return table + if raw.startswith(b"INSERT "): + raise UnsupportedDumpError(f"line {n}: INSERT-format dumps are not supported") + if not raw.startswith(_PREAMBLE_OK): + raise UnsupportedDumpError(f"line {n}: unexpected statement {_keyword(raw)!r}") + self.stats.preamble[_keyword(raw)] += 1 + + def _table(self, fh: io.BufferedIOBase) -> dict[str, str]: + found: dict[str, str] = {} + while True: + raw = self._readline(fh) + n = self.stats.lines + if not raw: + raise TruncatedArchiveError(f"line {n}: end of input inside CREATE TABLE") + if raw == b");\n": + break + m = _COLUMN_DEF.match(raw) + if not m: + raise SchemaMismatchError(f"line {n}: unexpected table definition line") + found[m[1].decode()] = m[2].decode() + if found != COLUMNS: + raise SchemaMismatchError(f"table definition {found} differs from {COLUMNS}") + return found + + def _postamble(self, fh: io.BufferedIOBase) -> None: + while raw := self._readline(fh): + n = self.stats.lines + if len(raw) > MAX_LINE: + raise UnsupportedDumpError(f"line {n}: statement longer than {MAX_LINE} bytes") + if raw.strip() == b"": + continue + if raw.startswith(b"COPY "): + raise UnsupportedDumpError(f"line {n}: a second COPY block is not supported") + if not raw.startswith(_POSTAMBLE_OK) and not raw.startswith(b" "): + raise UnsupportedDumpError(f"line {n}: unexpected statement {_keyword(raw)!r}") + self.stats.postamble[_keyword(raw)] += 1 + + def _row(self, raw: bytes, n: int, perm: tuple[int, ...]) -> ArchiveTransfer | None: + try: + text = raw[:-1].decode("utf-8") + except UnicodeDecodeError: + self.stats.reject("encoding", n) + return None + parts = text.split("\t") + if len(parts) != len(COLUMNS): + self.stats.reject("field_count", n) + return None + if "\\" in text: + parts = [copy_unescape(p) if "\\" in p and p != NULL else p for p in parts] + (block, tx, token, sender, receiver, siv, value, usd, *flag_values, intended, + first, last) = [parts[i] for i in perm] # fmt: skip + try: + if not _HASH.fullmatch(tx): + raise ValueError("tx_hash") + flags = 0 + for v, bit in zip(flag_values, _FLAG_BITS, strict=True): + if _BOOLS[v]: + flags |= bit + return ArchiveTransfer( + line=n, + block=_int(block), + tx=tx.lower(), + token=_addr(token), + sender=_addr(sender), + receiver=_addr(receiver), + sender_is_victim=_BOOLS[siv], + value=_real(value), + value_usd=_real(usd), + flags=flags, + intended=None if intended == NULL else _addr(intended), + first_digits=_opt_int(first), + last_digits=_opt_int(last), + ) + except KeyError: + self.stats.reject("invalid_boolean", n) + except ValueError as exc: # every helper raises with a short tag + self.stats.reject(f"invalid_{exc.args[0]}", n) + return None + + +class SpillDistinct: + """Exact distinct count of fixed-width byte strings with bounded memory. + + Values are deduplicated in memory up to ``mem_items``, then appended to one of + ``BUCKETS`` files chosen by a middle byte (addresses share prefixes and suffixes with + their targets, so the ends are not uniform). ``count`` deduplicates each bucket on its + own. Bucket files stay open between flushes: opening files is slow on some Windows + setups (about 28 ms per open was measured here).""" + + BUCKETS = 64 + + def __init__(self, directory: Path, name: str, width: int, mem_items: int = 500_000) -> None: + self.directory = directory / name + self.directory.mkdir(parents=True, exist_ok=True) + for stale in self.directory.glob("b*.bin"): + stale.unlink() # our own spill files from an interrupted run + self.width = width + self.mem_items = mem_items + self.added = 0 + self.bytes_written = 0 + self._pending: set[bytes] = set() + self._files: dict[int, io.BufferedWriter] = {} + + def add(self, value: bytes) -> None: + if len(value) != self.width: + raise ValueError(f"expected {self.width} bytes, got {len(value)}") + self.added += 1 + self._pending.add(value) + if len(self._pending) >= self.mem_items: + self.flush() + + def flush(self) -> None: + if not self._pending: + return + buckets: dict[int, list[bytes]] = {} + mid, n = self.width // 2, self.BUCKETS + for v in self._pending: + buckets.setdefault(v[mid] % n, []).append(v) + for b, values in buckets.items(): + fh = self._files.get(b) + if fh is None: + fh = self._files[b] = (self.directory / f"b{b:03d}.bin").open("ab") + data = b"".join(values) + fh.write(data) + self.bytes_written += len(data) + self._pending = set() + + def _close_files(self) -> None: + for fh in self._files.values(): + fh.close() + self._files = {} + + def count(self) -> int: + self.flush() + self._close_files() + total = 0 + w = self.width + for path in sorted(self.directory.glob("b*.bin")): + data = path.read_bytes() + total += len({data[i : i + w] for i in range(0, len(data), w)}) + return total + + def close(self) -> None: + self._pending = set() + self._close_files() + for path in self.directory.glob("b*.bin"): + path.unlink() + self.directory.rmdir() + + +@dataclass(frozen=True) +class TargetManifest: + addresses: frozenset[str] + txs: frozenset[str] + sha256: str + + +def build_targets(groups: dict[str, Iterable[str]]) -> dict[str, Any]: + """Deterministic manifest: sorted lowercase addresses and tx hashes from named groups + (for example ``ph_victims``, ``payoff_lookalikes``), with a hash over the content.""" + body: dict[str, list[str]] = { + name: sorted({v.lower() for v in values}) for name, values in sorted(groups.items()) + } + for name, values in body.items(): + pattern = _HASH if name.endswith("_txs") else _ADDR + bad = [v for v in values if not pattern.fullmatch(v)] + if bad: + raise ValueError(f"target group {name}: {len(bad)} malformed values") + digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + return {"version": 1, "groups": body, "sha256": digest} + + +def load_targets(path: Path) -> TargetManifest: + """Load and verify a manifest; a modified or truncated file is refused.""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + body = data["groups"] + digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + except (OSError, ValueError, KeyError, TypeError) as exc: + raise ArchiveError(f"{path}: unreadable target manifest: {exc}") from exc + if digest != data.get("sha256"): + raise ArchiveError(f"{path}: target manifest hash mismatch (modified or corrupt)") + addresses = frozenset(v for k, vs in body.items() if not k.endswith("_txs") for v in vs) + txs = frozenset(v for k, vs in body.items() if k.endswith("_txs") for v in vs) + return TargetManifest(addresses, txs, digest) + + +def peak_rss_bytes() -> int | None: + """Peak resident set size of this process, from the OS (None if unavailable).""" + if sys.platform == "win32": + import ctypes + from ctypes import wintypes + + class Counters(ctypes.Structure): + _fields_ = [ + ("cb", wintypes.DWORD), + ("PageFaultCount", wintypes.DWORD), + ("PeakWorkingSetSize", ctypes.c_size_t), + ("WorkingSetSize", ctypes.c_size_t), + ("QuotaPeakPagedPoolUsage", ctypes.c_size_t), + ("QuotaPagedPoolUsage", ctypes.c_size_t), + ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), + ("QuotaNonPagedPoolUsage", ctypes.c_size_t), + ("PagefileUsage", ctypes.c_size_t), + ("PeakPagefileUsage", ctypes.c_size_t), + ] + + c = Counters() + c.cb = ctypes.sizeof(c) + psapi = ctypes.WinDLL("psapi") + kernel = ctypes.WinDLL("kernel32") + kernel.GetCurrentProcess.restype = wintypes.HANDLE + psapi.GetProcessMemoryInfo.argtypes = [ + wintypes.HANDLE, + ctypes.POINTER(Counters), + wintypes.DWORD, + ] + ok = psapi.GetProcessMemoryInfo(kernel.GetCurrentProcess(), ctypes.byref(c), c.cb) + return int(c.PeakWorkingSetSize) if ok else None + import resource + + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return int(peak) if sys.platform == "darwin" else int(peak) * 1024 + + +_SUBTYPES = ((ZERO, "zero_value"), (TINY, "tiny"), (COUNTERFEIT, "counterfeit_token")) +_SIDE = {True: "victim_sends", False: "victim_receives", None: "unknown"} +_DB_FIELDS = ( + "line", "block", "tx", "token", "sender", "receiver", "sender_is_victim", "value", + "value_usd", "flags", "intended", "first_digits", "last_digits", +) # fmt: skip + + +def _to_db(t: ArchiveTransfer) -> tuple[Any, ...]: + return tuple(getattr(t, f) for f in _DB_FIELDS) + + +def _from_db(r: tuple[Any, ...]) -> ArchiveTransfer: + values = dict(zip(_DB_FIELDS, r, strict=True)) + if values["sender_is_victim"] is not None: + values["sender_is_victim"] = bool(values["sender_is_victim"]) + return ArchiveTransfer(**values) + + +def rule_coverage(t: ArchiveTransfer, config: PoisoningConfig) -> tuple[str, ...]: + """CryptoGuard's single-transfer candidate rules applied to a source poisoning row, + seen from the victim. ``lookalike_in`` assumes the intended address was a counterparty + the victim chose earlier (the source's own selection presumes that). The planting + signer is not in the archive, so ``spoofed_out`` cannot be evaluated.""" + lookalike, victim = t.counterparty, t.victim + if lookalike is None or victim is None: + return ("direction_unknown",) + matched = t.intended is not None and similar(lookalike, t.intended) is not None + methods = transfer_methods( + incoming=t.receiver == victim, + outgoing=t.sender == victim, + value=int(t.value) if t.value is not None else -1, + token=t.token, + wallet_signed=None, + matched=matched, + ) + out = list(methods) + if t.intended and is_lookalike(lookalike, t.intended, config): + out.append("detector_predicate") + return tuple(out) + + +def scan( + archive: Path, + targets: TargetManifest, + out_db: Path, + *, + work_dir: Path, + source_sha256: str | None = None, + progress: Callable[[ReaderStats], None] | None = None, + progress_every: int = 1_000_000, + batch: int = 20_000, + mem_items: int = 500_000, + max_malformed_fraction: float = 0.001, + max_stored_rows: int = 5_000_000, +) -> dict[str, Any]: + """One pass over the archive: reproduce the publisher's aggregate counts, measure + candidate-rule coverage per subtype, and store the rows touching ``targets``. + + The database is written to ``.tmp`` and renamed on success; the returned + summary is also stored in its ``meta`` table.""" + t0 = time.perf_counter() + tmp = out_db.with_name(out_db.name + ".tmp") + out_db.parent.mkdir(parents=True, exist_ok=True) + # Our own incomplete output from an interrupted (possibly killed) run. The rollback + # journal must go too: SQLite would replay a stale "hot" journal into the new file. + for leftover in (tmp, *(tmp.with_name(tmp.name + s) for s in ("-journal", "-wal", "-shm"))): + leftover.unlink(missing_ok=True) + db = sqlite3.connect(tmp) + db.executescript(_DDL) + db.executemany( + "INSERT INTO meta(key, value) VALUES (?, ?)", + [("schema_version", str(SCHEMA_VERSION)), ("parser_version", PARSER_VERSION)], + ) + reader = ArchiveReader(archive, max_malformed_fraction=max_malformed_fraction) + config = PoisoningConfig() + counters = { + "poisoning_txs": SpillDistinct(work_dir, "poisoning_txs", 32, mem_items), + "victims": SpillDistinct(work_dir, "victims", 20, mem_items), + "lookalikes": SpillDistinct(work_dir, "lookalikes", 20, mem_items), + "transfer_keys": SpillDistinct(work_dir, "transfer_keys", 16, mem_items), + } + flags = Counter[int]() + digits = Counter[tuple[int | None, int | None]]() + declared_mismatch = 0 + coverage = Counter[tuple[str, str]]() + any_rule = Counter[str]() + by_subtype = Counter[str]() + direction = Counter[tuple[str, str]]() + tokens_genuine = Counter[str]() + counterfeit_contracts: set[str] = set() + nan_value = nan_usd = 0 + blocks = [sys.maxsize, -1] + poisoning_blocks = [sys.maxsize, -1] + pending: list[tuple[Any, ...]] = [] + stored = 0 + addresses, txs = targets.addresses, targets.txs + try: + for t in reader: + flags[t.flags] += 1 + blocks[0] = min(blocks[0], t.block) + blocks[1] = max(blocks[1], t.block) + nan_value += t.value is None + nan_usd += t.value_usd is None + key = f"{t.tx}|{t.token}|{t.sender}|{t.receiver}|{t.value!r}".encode() + counters["transfer_keys"].add(hashlib.blake2b(key, digest_size=16).digest()) + if t.flags & POISONING: + poisoning_blocks[0] = min(poisoning_blocks[0], t.block) + poisoning_blocks[1] = max(poisoning_blocks[1], t.block) + counters["poisoning_txs"].add(bytes.fromhex(t.tx[2:])) + if t.victim is not None and t.counterparty is not None: + counters["victims"].add(bytes.fromhex(t.victim[2:])) + counters["lookalikes"].add(bytes.fromhex(t.counterparty[2:])) + digits[(t.first_digits, t.last_digits)] += 1 + if ( + t.intended + and t.counterparty + and (t.first_digits, t.last_digits) != (affix_match(t.counterparty, t.intended)) + ): + declared_mismatch += 1 + methods = rule_coverage(t, config) + side = _SIDE[t.sender_is_victim] + for bit, name in _SUBTYPES: + if t.flags & bit: + by_subtype[name] += 1 + direction[(name, side)] += 1 + for m in methods: + coverage[(name, m)] += 1 + if set(methods) - {"detector_predicate", "direction_unknown"}: + any_rule[name] += 1 + if t.flags & COUNTERFEIT: + counterfeit_contracts.add(t.token) + elif t.flags & (ZERO | TINY): + tokens_genuine[t.token] += 1 + if t.sender in addresses or t.receiver in addresses or t.tx in txs: + pending.append(_to_db(t)) + if len(pending) >= batch: + stored += _insert(db, pending) + pending = [] + if stored > max_stored_rows: + raise ArchiveError( + f"target subset exceeded {max_stored_rows} rows: the manifest " + "is too broad for a bounded subset" + ) + if progress is not None and reader.stats.data_rows % progress_every == 0: + progress(reader.stats) + stored += _insert(db, pending) + distinct = {name: c.count() for name, c in counters.items()} + # Spill files only grow until cleanup, so the total written after the final flush + # in ``count`` is the peak temporary disk use. + peak_spill = sum(c.bytes_written for c in counters.values()) + added = {name: c.added for name, c in counters.items()} + except BaseException: + db.close() + tmp.unlink(missing_ok=True) + raise + finally: + for c in counters.values(): + if c.directory.exists(): + c.close() + category_counts = { + name: sum(c for f, c in flags.items() if f & bit) for bit, name in FLAG_NAMES.items() + } + summary: dict[str, Any] = { + "parser_version": PARSER_VERSION, + "schema_version": SCHEMA_VERSION, + "source_sha256": source_sha256, + "target_manifest_sha256": targets.sha256, + "reader": reader.stats.as_dict(), + "columns_in_dump_order": reader.columns, + "block_range": blocks if blocks[1] >= 0 else None, + "poisoning_block_range": poisoning_blocks if poisoning_blocks[1] >= 0 else None, + "categories": category_counts, + "category_combinations": { + "+".join(n for b, n in FLAG_NAMES.items() if f & b) or "(none)": c + for f, c in sorted(flags.items()) + }, + "poisoning_transfers": sum(c for f, c in flags.items() if f & POISONING), + "poisoning_by_subtype": dict(by_subtype), + "poisoning_direction": {f"{a}/{b}": c for (a, b), c in sorted(direction.items())}, + "distinct": { + "poisoning_txs": distinct["poisoning_txs"], + "victims": distinct["victims"], + "lookalikes": distinct["lookalikes"], + "counterfeit_token_contracts": len(counterfeit_contracts), + "transfer_keys": distinct["transfer_keys"], + }, + "repeated_transfer_keys": added["transfer_keys"] - distinct["transfer_keys"], + "nan_value": nan_value, + "nan_value_usd": nan_usd, + "poisoning_digit_pairs": {f"{a}+{b}": c for (a, b), c in sorted(digits.items(), key=str)}, + "declared_digits_disagree": declared_mismatch, + "rule_coverage": {f"{s}/{m}": c for (s, m), c in sorted(coverage.items())}, + "any_candidate_rule": dict(any_rule), + "genuine_token_top": dict(tokens_genuine.most_common(10)), + "genuine_tokens_distinct": len(tokens_genuine), + "stored_target_rows": stored, + "runtime_seconds": round(time.perf_counter() - t0, 1), + "peak_rss_bytes": peak_rss_bytes(), + "peak_spill_bytes": peak_spill, + } + db.execute( + "INSERT INTO meta(key, value) VALUES (?, ?)", + ("summary", json.dumps(summary, sort_keys=True)), + ) + db.execute("INSERT INTO meta(key, value) VALUES ('complete', '1')") + db.commit() + db.close() + summary["output_bytes"] = tmp.stat().st_size + os.replace(tmp, out_db) + return summary + + +_DDL = """ +PRAGMA journal_mode = DELETE; +CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE transfers ( + line INTEGER PRIMARY KEY, + block INTEGER NOT NULL, + tx TEXT NOT NULL, + token TEXT NOT NULL, + sender TEXT NOT NULL, + receiver TEXT NOT NULL, + sender_is_victim INTEGER, + value REAL, + value_usd REAL, + flags INTEGER NOT NULL, + intended TEXT, + first_digits INTEGER, + last_digits INTEGER +); +CREATE INDEX transfers_sender ON transfers(sender); +CREATE INDEX transfers_receiver ON transfers(receiver); +CREATE INDEX transfers_tx ON transfers(tx); +""" + + +def _insert(db: sqlite3.Connection, rows: list[tuple[Any, ...]]) -> int: + if not rows: + return 0 + with db: + db.executemany("INSERT INTO transfers VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", rows) + return len(rows) + + +def load_subset(db_path: Path) -> tuple[list[ArchiveTransfer], dict[str, Any]]: + """Rows stored by ``scan`` and its summary; refuses an incomplete or foreign file.""" + db = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True) + try: + meta = dict(db.execute("SELECT key, value FROM meta").fetchall()) + if meta.get("complete") != "1" or meta.get("parser_version") != PARSER_VERSION: + raise ArchiveError(f"{db_path}: incomplete scan or parser version mismatch") + rows = [_from_db(r) for r in db.execute("SELECT * FROM transfers ORDER BY line")] + finally: + db.close() + return rows, json.loads(meta["summary"]) diff --git a/tests/unit/test_ml_fetch.py b/tests/unit/test_ml_fetch.py new file mode 100644 index 0000000..81ae5b8 --- /dev/null +++ b/tests/unit/test_ml_fetch.py @@ -0,0 +1,171 @@ +"""Pinned large-file download: range validation, verification and disk safety. + +All transfers are mocked (no network). Each test states the invariant it guards. +""" + +from __future__ import annotations + +import gzip +import hashlib +import random +from pathlib import Path + +import httpx +import pytest + +from cryptoguard.ml.fetch import ( + DiskReserveError, + DownloadError, + IntegrityError, + PinnedFile, + download, + gzip_check, +) + +BODY = gzip.compress(random.Random(0).randbytes(50_000)) # incompressible: about 50 KB + + +def pinned(body: bytes = BODY, name: str = "x.sql.gz") -> PinnedFile: + md5 = hashlib.md5(body, usedforsecurity=False).hexdigest() + return PinnedFile(name, "https://example.test/f", len(body), md5, "doi:test", "test") + + +def server(body: bytes, *, honour_range: bool = True, log: list[str] | None = None) -> httpx.Client: + def handle(request: httpx.Request) -> httpx.Response: + rng = request.headers.get("range") + if log is not None: + log.append(rng or "") + if rng and honour_range: + start = int(rng.removeprefix("bytes=").rstrip("-")) + return httpx.Response( + 206, + content=body[start:], + headers={"content-range": f"bytes {start}-{len(body) - 1}/{len(body)}"}, + ) + return httpx.Response(200, content=body, headers={"content-length": str(len(body))}) + + return httpx.Client(transport=httpx.MockTransport(handle)) + + +def plenty(_: Path) -> int: + return 1 << 40 + + +def test_fresh_download_is_verified_then_renamed(tmp_path: Path) -> None: + """The file appears under its final name only after size, MD5, SHA-256 and gzip pass.""" + rec = download(pinned(), tmp_path, client=server(BODY), free_bytes=plenty, reserve_bytes=0) + assert rec["status"] == "downloaded" + assert rec["sha256"] == hashlib.sha256(BODY).hexdigest() + assert rec["decompressed_size"] == len(gzip.decompress(BODY)) + assert (tmp_path / "x.sql.gz").read_bytes() == BODY + assert not (tmp_path / "x.sql.gz.part").exists() + + +def test_resume_appends_only_a_matching_206(tmp_path: Path) -> None: + """A partial file resumes from its exact length when the server honours the range.""" + (tmp_path / "x.sql.gz.part").write_bytes(BODY[:1000]) + log: list[str] = [] + download(pinned(), tmp_path, client=server(BODY, log=log), free_bytes=plenty, reserve_bytes=0) + assert log == ["bytes=1000-"] + assert (tmp_path / "x.sql.gz").read_bytes() == BODY + + +def test_ignored_range_restarts_instead_of_appending(tmp_path: Path) -> None: + """A 200 to a ranged request carries the whole file: appending it would corrupt the + download, so it is written from byte 0.""" + (tmp_path / "x.sql.gz.part").write_bytes(BODY[:1000]) + download( + pinned(), + tmp_path, + client=server(BODY, honour_range=False), + free_bytes=plenty, + reserve_bytes=0, + ) + assert (tmp_path / "x.sql.gz").read_bytes() == BODY + + +def test_misaligned_content_range_is_refused(tmp_path: Path) -> None: + (tmp_path / "x.sql.gz.part").write_bytes(BODY[:1000]) + + def handle(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 206, + content=BODY[500:], + headers={"content-range": f"bytes 500-{len(BODY) - 1}/{len(BODY)}"}, + ) + + with pytest.raises(DownloadError, match="Content-Range"): + download( + pinned(), + tmp_path, + client=httpx.Client(transport=httpx.MockTransport(handle)), + free_bytes=plenty, + reserve_bytes=0, + ) + assert (tmp_path / "x.sql.gz.part").read_bytes() == BODY[:1000] # kept for a later resume + + +def test_checksum_mismatch_quarantines_the_file(tmp_path: Path) -> None: + """A complete file with the wrong content is renamed .corrupt, never kept as final.""" + bad = PinnedFile("x.sql.gz", "https://example.test/f", len(BODY), "0" * 32, "doi:test", "test") + with pytest.raises(IntegrityError, match="md5"): + download(bad, tmp_path, client=server(BODY), free_bytes=plenty, reserve_bytes=0) + assert (tmp_path / "x.sql.gz.corrupt").exists() + assert not (tmp_path / "x.sql.gz").exists() + + +def test_truncated_gzip_fails_integrity(tmp_path: Path) -> None: + """Right size and checksum can still describe a broken archive: the gzip CRC decides.""" + broken = BODY[: len(BODY) // 2] + path = tmp_path / "b.gz" + path.write_bytes(broken) + with pytest.raises(IntegrityError, match="gzip"): + gzip_check(path) + + +def test_disk_reserve_is_checked_before_and_during_transfer(tmp_path: Path) -> None: + """Nothing is written when the reserve cannot be kept, and a shrinking disk stops it.""" + with pytest.raises(DiskReserveError): + download( + pinned(), tmp_path, client=server(BODY), free_bytes=lambda _: len(BODY), reserve_bytes=1 + ) + assert not (tmp_path / "x.sql.gz.part").exists() + calls = iter([1 << 40, 0]) + with pytest.raises(DiskReserveError, match="fell below"): + download( + pinned(), + tmp_path, + client=server(BODY), + free_bytes=lambda _: next(calls), + reserve_bytes=1, + ) + + +def test_transient_errors_retry_with_a_bound(tmp_path: Path) -> None: + attempts = [] + + def handle(request: httpx.Request) -> httpx.Response: + attempts.append(1) + raise httpx.ConnectError("boom", request=request) + + with pytest.raises(DownloadError, match="retries"): + download( + pinned(), + tmp_path, + client=httpx.Client(transport=httpx.MockTransport(handle)), + free_bytes=plenty, + reserve_bytes=0, + retries=2, + backoff_s=0, + ) + assert len(attempts) == 3 + + +def test_existing_final_file_is_reverified_not_redownloaded(tmp_path: Path) -> None: + (tmp_path / "x.sql.gz").write_bytes(BODY) + log: list[str] = [] + rec = download( + pinned(), tmp_path, client=server(BODY, log=log), free_bytes=plenty, reserve_bytes=0 + ) + assert rec["status"] == "cached" + assert log == [] diff --git a/tests/unit/test_ml_reconcile.py b/tests/unit/test_ml_reconcile.py new file mode 100644 index 0000000..131b71a --- /dev/null +++ b/tests/unit/test_ml_reconcile.py @@ -0,0 +1,468 @@ +"""Cross-dataset reconciliation: match levels, payoff-attempt linkage, outcome levels and +temporal categories, with the line-74 (competing lookalike) and line-87 (payment before +planting) patterns as regression cases. + +Synthetic records only. Each test states the invariant it guards. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from cryptoguard.ml import reconcile as rc +from cryptoguard.ml.poison_hunter import PoisonHunterRecord +from cryptoguard.ml.tsuchiya import PayoffTransfer +from cryptoguard.ml.tsuchiya_archive import ( + COUNTERFEIT, + PAYOFF, + PAYOFF_UNCONFIRMED, + TINY, + ZERO, + ArchiveTransfer, +) + +VICTIM = "0x" + "11" * 20 +OTHER_VICTIM = "0x" + "22" * 20 +FRIEND = "0xd296222fb44f5ec8d9600a8c91ed70ed5657d7d5" +LOOKALIKE = "0xd296261b103d698c272887274f38d7ea8097d7d5" # 5+5 with FRIEND +RIVAL = "0xd29" + "0" * 33 + "d7d5" # 3+4 with FRIEND +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" + + +def h(n: int) -> str: + return "0x" + f"{n:064x}" + + +def att( + block: int, + *, + victim: str = VICTIM, + lookalike: str = LOOKALIKE, + tx: int = 1, + flags: int = ZERO, + intended: str | None = FRIEND, + line: int = 0, + victim_sends: bool = False, +) -> ArchiveTransfer: + sender, receiver = (victim, lookalike) if victim_sends else (lookalike, victim) + return ArchiveTransfer( + line=line or block + tx, + block=block, + tx=h(tx), + token=USDT, + sender=sender, + receiver=receiver, + sender_is_victim=victim_sends, + value=0.0, + value_usd=0.0, + flags=flags, + intended=intended, + first_digits=5, + last_digits=5, + ) + + +def pay_row( + block: int, + *, + victim: str = VICTIM, + lookalike: str = LOOKALIKE, + tx: int = 900, + flags: int = PAYOFF, +) -> ArchiveTransfer: + return att(block, victim=victim, lookalike=lookalike, tx=tx, flags=flags, victim_sends=True) + + +def ph( + line: int = 2, + *, + victim: str = VICTIM, + lookalike: str = LOOKALIKE, + tx: int = 1, + block: int | None = 1_000, + subtype: str = "zero", + imitated: str = FRIEND, +) -> PoisonHunterRecord: + return PoisonHunterRecord( + source_line=line, + status="valid", + issues=(), + lookalike=lookalike, + victim=victim, + imitated=imitated, + planting_tx=h(tx), + token_symbol="usdt", + subtype=subtype, + log_contract=USDT, + fake_token_deployer=None, + tx_signer=lookalike, + tx_target=USDT, + batch_size=1, + block_number=block, + block_distance=1, + imitated_direction="from", + source_similarity=10, + prefix_match=5, + suffix_match=5, + cryptoguard_lookalike=True, + tsuchiya_lookalike=True, + ) + + +def payoff( + block: int, + *, + victim: str = VICTIM, + lookalike: str = LOOKALIKE, + tx: int = 900, + intended: str = FRIEND, +) -> PayoffTransfer: + p, s = (5, 5) if lookalike == LOOKALIKE else (3, 4) + return PayoffTransfer( + source_line=2, + status="valid", + issues=(), + block_number=block, + tx_hash=h(tx), + token=USDT, + payer=victim, + lookalike=lookalike, + intended=intended, + value_usd=1000.0, + prefix_match=p, + suffix_match=s, + ) + + +@pytest.mark.parametrize( + ("planting", "payment", "category"), + [ + (100, 99, "before_planting"), + (100, 100, "same_block_order_unknown"), + (100, 101, "after_planting"), + (None, 5, "temporally_ambiguous"), + (5, None, "temporally_ambiguous"), + ], +) +def test_temporal_categories(planting: int | None, payment: int | None, category: str) -> None: + assert rc.temporal(planting, payment) == category + + +# --- match levels ------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("rows", "level"), + [ + ([att(1_000)], "exact_tx_event"), + ([att(900, tx=7)], "victim_lookalike_imitated"), + ([att(900, tx=7, intended="0x" + "33" * 20)], "victim_lookalike"), + ([att(1_000, victim=OTHER_VICTIM)], "tx_only"), + ([att(900, victim=OTHER_VICTIM, tx=7)], "shared_lookalike"), + ([att(900, lookalike=RIVAL, tx=7)], "competing_lookalike"), + ([att(900, lookalike=RIVAL, tx=7, intended="0x" + "44" * 20)], "victim_only"), + ([], "none"), + ], +) +def test_each_match_level_is_distinct(rows: list[ArchiveTransfer], level: str) -> None: + """The strongest applicable level wins, and weaker evidence keeps its own name.""" + out = rc.ph_matches([ph()], rc.ArchiveIndex(rows), (0, 10**9)) + assert out["levels"][level] == 1 + assert sum(out["levels"].values()) == 1 + + +def test_unmatched_reasons_and_subtype_agreement() -> None: + rows = [att(1_000, flags=TINY)] + out = rc.ph_matches( + [ + ph(2), + ph(3, tx=5, block=50), + ph(4, tx=6).model_copy(update={"tsuchiya_lookalike": False, "victim": OTHER_VICTIM}), + ], + rc.ArchiveIndex(rows), + (100, 10**9), + ) + assert out["subtype_agreement_on_exact"] == {"zero->tiny": 1} # disagreement is reported + assert out["not_exact_reasons"] == {"outside_archive_period": 1, "below_3_plus_4_similarity": 1} + + +def test_repeated_rows_in_one_transaction_count_as_one_attempt() -> None: + ix = rc.ArchiveIndex([att(1_000, line=1), att(1_000, line=2)]) + assert ix.attempts == 1 + assert ix.repeated_attempt_rows == 1 + + +def test_non_poisoning_rows_are_not_attempts() -> None: + """Intended transfers and payoffs are not attempts, even between the same pair.""" + ix = rc.ArchiveIndex([att(1_000, flags=1), pay_row(1_500)]) + assert ix.attempts == 0 + assert ix.payoff_rows == {(h(900), VICTIM, LOOKALIKE): PAYOFF} + + +# --- payoff linkage ---------------------------------------------------------------------- + + +def test_payoff_links_only_to_earlier_attempts_by_the_same_pair() -> None: + ix = rc.ArchiveIndex([att(1_000), att(1_200, tx=2), att(2_000, tx=3), pay_row(1_500)]) + out = rc.payoff_linkage([payoff(1_500)], ix) + assert out["linkage"] == {"attempt_before_payoff": 1} + assert out["blocks_from_last_attempt_to_payoff"]["median"] == 300 # from block 1,200 + assert out["attempts_by_pair_before_payoff"]["median"] == 2 # the 2,000 attempt is later + assert out["archive_status"] == {"archive_flag_payoff_confirmed": 1} + + +@pytest.mark.parametrize( + ("rows", "category"), + [ + ([att(1_500)], "same_block_only"), + ([att(1_600)], "attempts_only_after_payoff"), + ([att(1_000, lookalike=RIVAL)], "no_attempt_between_pair"), + ], +) +def test_payoffs_without_an_earlier_attempt_are_not_linked( + rows: list[ArchiveTransfer], category: str +) -> None: + out = rc.payoff_linkage([payoff(1_500)], rc.ArchiveIndex(rows)) + assert out["linkage"] == {category: 1} + assert out["linked_distinct"]["payoff_txs"] == 0 + + +def test_unconfirmed_and_missing_archive_payoffs_are_distinguished() -> None: + ix = rc.ArchiveIndex([pay_row(1_500, flags=PAYOFF_UNCONFIRMED)]) + out = rc.payoff_linkage([payoff(1_500), payoff(1_600, tx=901)], ix) + assert out["archive_status"] == { + "archive_flag_payoff_unconfirmed_only": 1, + "payoff_not_in_archive_subset": 1, + } + + +def test_competing_lookalikes_are_counted_and_compared() -> None: + """Line-74 pattern: several lookalikes of the same intended address reach the victim; + the comparison is reported against the uniform expectation, not as an effect.""" + rows = [att(1_000), att(1_100, lookalike=RIVAL, tx=2), pay_row(1_500)] + out = rc.payoff_linkage([payoff(1_500)], rc.ArchiveIndex(rows)) + assert out["payoffs_with_rival_of_same_intended"] == 1 + cmp = out["similarity_recency_comparison"] + assert ( + cmp["payoffs_compared"], + cmp["paid_lookalike_most_similar"], + cmp["paid_lookalike_most_recent"], + ) == (1, 1, 0) + assert cmp["expected_if_uniform"] == 0.5 + + +# --- outcome levels ---------------------------------------------------------------------- + + +def test_line_74_loss_to_a_rival_is_a_victim_outcome_not_an_attempt_outcome() -> None: + out = rc.ph_outcomes([ph(74)], [payoff(12_653, lookalike=RIVAL)])["outcomes"] + assert out["attempt_outcome_paid_after"] == 0 + assert out["victim_outcome_paid_any_lookalike_after"] == 1 + + +def test_line_87_earlier_payment_is_address_history_not_an_outcome() -> None: + out = rc.ph_outcomes([ph(87)], [payoff(500, victim=OTHER_VICTIM)]) + o = out["outcomes"] + assert o["attempt_outcome_paid_after"] == 0 + assert o["address_outcome_paid_by_anyone_before"] == 1 + assert o["address_outcome_paid_by_anyone_after"] == 0 + assert out["payment_pairs_by_temporal_category"] == {"address/before_planting": 1} + + +def test_attempt_outcome_window_and_same_block() -> None: + out = rc.ph_outcomes([ph(2)], [payoff(1_000), payoff(60_000, tx=901)]) + o = out["outcomes"] + assert o["attempt_outcome_paid_after"] == 1 + assert o["attempt_outcome_paid_in_window"] == 0 # 59,000 blocks later + assert out["payment_pairs_by_temporal_category"]["this_pair/same_block_order_unknown"] == 1 + + +def test_campaign_outcome_uses_group_mates() -> None: + other_lk = "0x" + "55" * 20 + groups = {LOOKALIKE: "g0001", other_lk: "g0001"} + out = rc.ph_outcomes([ph(2)], [payoff(2_000, victim=OTHER_VICTIM, lookalike=other_lk)], groups) + assert out["outcomes"]["campaign_outcome_paid_after"] == 1 + assert out["outcomes"]["attempt_outcome_paid_after"] == 0 + + +def test_zero_match_scenario_has_complete_denominators() -> None: + out = rc.reconcile( + [], {"poisoning_block_range": None, "block_range": None}, [ph()], [payoff(5)], [] + ) + assert out["poison_hunter"]["levels"]["none"] == 1 + assert out["payoffs"]["linkage"] == {"no_attempt_between_pair": 1} + assert out["subset"]["attempts"] == 0 + + +def test_incident_case_study_counts_only_earlier_pair_attempts() -> None: + inc = { + "case": "c", + "victim": VICTIM, + "recipient": LOOKALIKE, + "block": 1_500, + "tx": h(900), + "token": USDT, + } + out = rc.incident_case_studies( + [inc], rc.ArchiveIndex([att(1_000), att(2_000, tx=2)]), (0, 10**9) + ) + assert out[0]["pair_attempts_before_harm"] == 1 + assert out[0]["harm_tx_in_archive"] is False + + +def test_counterfeit_rows_are_attempts() -> None: + assert rc.ArchiveIndex([att(1, flags=COUNTERFEIT)]).attempts == 1 + + +# --- shadow-mode isolation ---------------------------------------------------------------- + +RESEARCH = ( + "cryptoguard.ml.fetch", + "cryptoguard.ml.tsuchiya", + "cryptoguard.ml.tsuchiya_archive", + "cryptoguard.ml.reconcile", + "cryptoguard.ml.cross_dataset", + "cryptoguard.ml.bench_archive", +) +# The pure lookalike predicates live in detectors.poisoning, whose base module imports type +# definitions from history/services/risk. Persistence and the API are what could create, +# change or serve findings, so those must stay unloaded. +PRODUCTION_STATE = ("cryptoguard.database", "cryptoguard.api") + + +def test_research_pipeline_cannot_reach_findings_or_persistence() -> None: + """Running the whole research pipeline (scan, subset, reconciliation) never loads the + application database or API layers, so it cannot persist, change or serve findings.""" + import subprocess + import sys + + code = ( + "import sys, json, tempfile, pathlib\n" + f"mods = {RESEARCH!r}\n" + "for m in mods: __import__(m)\n" + "from cryptoguard.ml.bench_archive import run_one\n" + "from cryptoguard.ml.reconcile import reconcile\n" + "from cryptoguard.ml.tsuchiya_archive import load_subset\n" + "from cryptoguard.ml.cross_dataset import incident_refs\n" + "d = pathlib.Path(tempfile.mkdtemp())\n" + "run_one(200, d)\n" + "rows, summary = load_subset(d / 'a.sqlite')\n" + "reconcile(rows, summary, [], [], incident_refs())\n" + "print(json.dumps(sorted(m for m in sys.modules if m.startswith('cryptoguard.'))))\n" + ) + out = subprocess.run( # noqa: S603 - a fixed in-test script + [sys.executable, "-c", code], capture_output=True, text=True, check=True + ) + loaded = __import__("json").loads(out.stdout.strip().splitlines()[-1]) + leaked = [m for m in loaded if m.startswith(PRODUCTION_STATE)] + assert leaked == [] + + +# --- review queue ------------------------------------------------------------------------- + + +def test_payoff_linked_attempts_become_review_packets_without_labels_or_scores() -> None: + """Only attempts before a payoff become packets; each carries the payment and the + competing lookalikes, and no score or label.""" + rows = [att(1_000), att(1_100, lookalike=RIVAL, tx=2), att(2_000, tx=3)] + packets = rc.payoff_review_packets([payoff(1_500), payoff(500, tx=901)], rc.ArchiveIndex(rows)) + assert len(packets) == 1 + p = packets[0] + assert p.planting_tx == h(1) + assert p.competing_lookalikes == (RIVAL,) + assert p.payment_evidence[0].startswith(h(900)) + assert "after_planting" in p.payment_evidence[0] + assert "score" not in p.model_dump() + assert p.source_labels == ("tsuchiya-archive:zero_value", "tsuchiya-payoff:confirmed") + + +def test_spoofed_sender_attempts_are_typed_as_transfer_from() -> None: + rows = [att(1_000, victim_sends=True)] + (p,) = rc.payoff_review_packets([payoff(1_500)], rc.ArchiveIndex(rows)) + assert p.subtype == "spoofed_transfer_from" + + +def test_version_1_review_packets_still_load() -> None: + from cryptoguard.ml.review import ReviewPacket + + v1 = { + "schema_version": "poisoning-review/1", "victim_event_id": "e", "victim": VICTIM, + "lookalike": LOOKALIKE, "imitated": FRIEND, "planting_tx": h(1), + "observation_block": 1, "subtype": "dust", "evidence_summary": "x", + "coverage_limitations": "y", "source_labels": ["s"], + } # fmt: skip + p = ReviewPacket.model_validate(v1) + assert (p.competing_lookalikes, p.payment_evidence) == ((), ()) + + +def test_similarity_comparison_counts_ties_in_the_uniform_expectation() -> None: + """When the paid lookalike ties with a rival on similarity, chance alone picks one of + the best with probability 2/2, so the tie is not evidence of anything.""" + twin = "0xd2962" + "a" * 29 + "07d7d5" # also 5+5 with FRIEND + rows = [att(1_000), att(1_100, lookalike=twin, tx=2)] + cmp = rc.payoff_linkage([payoff(1_500)], rc.ArchiveIndex(rows))["similarity_recency_comparison"] + assert cmp["paid_lookalike_most_similar"] == 1 + assert cmp["expected_if_uniform"] == 1.0 + assert cmp["paid_lookalike_most_recent"] == 0 + assert cmp["expected_if_uniform_recent"] == 0.5 + + +def test_transaction_only_matches_say_whether_the_victim_was_listed() -> None: + rows = [att(1_000, lookalike=RIVAL), att(1_000, victim=OTHER_VICTIM)] + out = rc.ph_matches([ph()], rc.ArchiveIndex(rows), (0, 10**9)) + assert out["levels"]["tx_only"] == 1 + assert out["tx_only_detail"] == {"victim_listed_with_another_lookalike": 1} + + +# --- end-to-end report on synthetic inputs ------------------------------------------------ + + +def test_cross_dataset_report_end_to_end_on_synthetic_inputs(tmp_path: Path) -> None: + """Scan -> subset -> reconciliation -> tables, with no real data: the integrity gate + fails because synthetic counts differ from the publisher's, and no address leaks.""" + import json + import re + + from cryptoguard.ml import cross_dataset as cd + from cryptoguard.ml import tsuchiya_archive as ta + from cryptoguard.ml.bench_archive import synthetic_dump + from tests.unit.test_ml_poisoning import ph_row, write_ph + from tests.unit.test_ml_tsuchiya import payoff as payoff_row + from tests.unit.test_ml_tsuchiya import write_payoffs + + data, out = tmp_path / "data", tmp_path / "out" + (data / "poison-hunter").mkdir(parents=True) + (data / "tsuchiya2025").mkdir(parents=True) + write_ph(data / "poison-hunter" / "phishing_transfers_sample.csv", [ph_row()]) + write_payoffs(data / "tsuchiya2025" / "payoff_transfers_ethereum.csv", [payoff_row()]) + out.mkdir() + manifest = out / "targets.json" + manifest.write_text(json.dumps(ta.build_targets({"x": [VICTIM]})), encoding="utf-8") + summary = ta.scan( + synthetic_dump(tmp_path / "d.gz", 500), + ta.load_targets(manifest), + out / "archive_subset.sqlite", + work_dir=out / "spill", + ) + (out / "archive-scan.json").write_text(json.dumps(summary), encoding="utf-8") + + report = cd.build_report(data, out) + gates = {g["gate"]: g["status"] for g in report["gates"]} + assert gates["1 Data integrity"] == "fail" + assert gates["5 Independent evaluation"] == "fail" + assert report["rpc_requests"] == 0 + text = cd.render(report) + assert "Publisher counts reproduced" in text + assert "**no**" in text + assert not re.search(r"0x[0-9a-fA-F]{40}", text) + written = cd.write_report(report, out, tmp_path / "tables.md") + assert json.loads(written.read_text(encoding="utf-8"))["tables_sha256"] + + +def test_scan_refuses_a_missing_archive_without_downloading(tmp_path: Path) -> None: + from cryptoguard.ml.cross_dataset import run_scan + + with pytest.raises(FileNotFoundError, match="never fetched automatically"): + run_scan(tmp_path, tmp_path / "out") diff --git a/tests/unit/test_ml_tsuchiya_archive.py b/tests/unit/test_ml_tsuchiya_archive.py new file mode 100644 index 0000000..e71b57b --- /dev/null +++ b/tests/unit/test_ml_tsuchiya_archive.py @@ -0,0 +1,469 @@ +"""Streaming reader for the Tsuchiya et al. PostgreSQL dump: safety, schema checks, +row validation, bounded memory, the target subset and deterministic replay. + +Synthetic gzip dumps only (no network, no third-party data). Each test states the invariant +it guards. +""" + +from __future__ import annotations + +import gzip +import json +import sqlite3 +from pathlib import Path + +import pytest + +from cryptoguard.ml import tsuchiya_archive as ta + +VICTIM = "0x" + "11" * 20 +FRIEND = "0xd296222fb44f5ec8d9600a8c91ed70ed5657d7d5" +LOOKALIKE = "0xd296261b103d698c272887274f38d7ea8097d7d5" # 5+5 with FRIEND +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +FAKE = "0x" + "fa" * 20 +ORDER = list(ta.COLUMNS) +DUMP_ORDER = ORDER # the real dump's order (zero_value before tiny), as in COLUMNS + + +def h(n: int) -> str: + return "0x" + f"{n:064x}" + + +def row(**over: str) -> dict[str, str]: + base = { + "block_number": "16000000", "tx_hash": h(1), "addr": USDT, "topics_from_addr": LOOKALIKE, + "topics_to_addr": VICTIM, "is_sender_victim": "f", "value": "0", "value_usd": "0", + "intended_transfer": "f", "zero_value_transfer": "t", "tiny_transfer": "f", + "counterfeit_token_transfer": "f", "payoff_transfer": "f", + "payoff_transfer_unconfirmed": "f", "is_not_categorized": "f", "intended_addr": FRIEND, + "num_first_matched_digits": "5", "num_last_matched_digits": "5", + } # fmt: skip + return {**base, **over} + + +PREAMBLE = [ + "--", + "-- PostgreSQL database dump", + "--", + "", + "SET statement_timeout = 0;", + "SELECT pg_catalog.set_config('search_path', '', false);", + "CREATE DATABASE addrpoisoning WITH TEMPLATE = template0 ENCODING = 'UTF8';", + "\\connect addrpoisoning", + "", +] + + +def table(columns: dict[str, str] = ta.COLUMNS) -> list[str]: + items = list(columns.items()) + body = [f" {n} {t}," for n, t in items[:-1]] + [f" {items[-1][0]} {items[-1][1]}"] + return [f"CREATE TABLE public.{ta.TABLE} (", *body, ");", ""] + + +def dump( + path: Path, + rows: list[dict[str, str]], + *, + order: list[str] = DUMP_ORDER, + preamble: list[str] | None = None, + postamble: list[str] | None = None, + terminate: bool = True, + raw_lines: list[str] | None = None, +) -> Path: + lines = [*(PREAMBLE if preamble is None else preamble), *table()] + lines.append(f"COPY public.{ta.TABLE} ({', '.join(order)}) FROM stdin;") + lines += ["\t".join(r[c] for c in order) for r in rows] + lines += raw_lines or [] + if terminate: + lines.append("\\.") + lines += postamble if postamble is not None else ["", "--", "-- done", "--"] + path.write_bytes(gzip.compress(("\n".join(lines) + "\n").encode())) + return path + + +def read(path: Path, **kw: float) -> tuple[list[ta.ArchiveTransfer], ta.ArchiveReader]: + reader = ta.ArchiveReader(path, **kw) + return list(reader), reader + + +# --- format and safety ------------------------------------------------------------------ + + +def test_valid_dump_parses_by_column_name_with_provenance(tmp_path: Path) -> None: + """Columns are mapped by the COPY header's names; each row keeps its dump line number.""" + shuffled = ORDER[::-1] + rows, reader = read( + dump( + tmp_path / "d.gz", + [row(), row(tx_hash=h(2), tiny_transfer="t", zero_value_transfer="f", value="5000")], + order=shuffled, + ) + ) + assert [r.flags for r in rows] == [ta.ZERO, ta.TINY] + assert rows[0].victim == VICTIM and rows[0].counterparty == LOOKALIKE # noqa: PT018 + assert rows[0].line == len(PREAMBLE) + len(table()) + 2 + assert reader.stats.preamble["CREATE DATABASE"] == 1 + assert reader.stats.preamble["\\connect"] == 1 + + +def test_nothing_is_executed_or_imported(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The reader never opens a database connection or evaluates dump text: hostile + statements in the preamble are refused, not run.""" + + def forbidden(*_: object, **__: object) -> None: + raise AssertionError("the reader must not touch a database") + + monkeypatch.setattr(sqlite3, "connect", forbidden) + rows, _ = read(dump(tmp_path / "d.gz", [row()])) + assert len(rows) == 1 + hostile = [*PREAMBLE, "DROP TABLE users;"] + with pytest.raises(ta.UnsupportedDumpError, match="DROP"): + read(dump(tmp_path / "h.gz", [row()], preamble=hostile)) + + +@pytest.mark.parametrize( + ("extra", "error", "match"), + [ + ( + ["INSERT INTO public.address_poisoning_ethereum VALUES (1);"], + ta.UnsupportedDumpError, + "INSERT", + ), + ( + ["CREATE FUNCTION evil() RETURNS void AS $$ $$ LANGUAGE sql;"], + ta.UnsupportedDumpError, + "CREATE FUNCTION", + ), + (["COPY public.other (a) FROM stdin;"], ta.UnsupportedDumpError, "unsupported table"), + ], +) +def test_unsupported_statements_fail_explicitly( + tmp_path: Path, extra: list[str], error: type[Exception], match: str +) -> None: + with pytest.raises(error, match=match): + read(dump(tmp_path / "d.gz", [row()], preamble=[*PREAMBLE, *extra])) + + +def test_second_copy_block_is_refused(tmp_path: Path) -> None: + post = ["", f"COPY public.{ta.TABLE} ({', '.join(ORDER)}) FROM stdin;", "\\."] + with pytest.raises(ta.UnsupportedDumpError, match="second COPY"): + read(dump(tmp_path / "d.gz", [row()], postamble=post)) + + +def test_schema_changes_are_refused(tmp_path: Path) -> None: + """A changed type in CREATE TABLE or a missing COPY column is a schema change.""" + path = dump(tmp_path / "d.gz", [row()]) + text = ( + gzip.decompress(path.read_bytes()).decode().replace(" value real,", " value numeric,") + ) + path.write_bytes(gzip.compress(text.encode())) + with pytest.raises(ta.SchemaMismatchError): + read(path) + with pytest.raises(ta.SchemaMismatchError, match="COPY columns"): + read(dump(tmp_path / "e.gz", [row()], order=ORDER[:-1])) + + +def test_invalid_and_truncated_gzip(tmp_path: Path) -> None: + """Not-gzip input and a cut-off gzip stream fail with distinct, explicit errors.""" + bad = tmp_path / "bad.gz" + bad.write_bytes(b"not a gzip stream at all") + with pytest.raises(ta.InvalidArchiveError): + read(bad) + good = dump(tmp_path / "d.gz", [row(tx_hash=h(i)) for i in range(2000)]).read_bytes() + cut = tmp_path / "cut.gz" + cut.write_bytes(good[: len(good) // 2]) + with pytest.raises(ta.TruncatedArchiveError): + read(cut) + + +def test_missing_terminator_is_truncation_not_success(tmp_path: Path) -> None: + """A dump whose COPY block never ends (valid gzip, cut text) is not a complete read.""" + with pytest.raises(ta.TruncatedArchiveError, match="inside the COPY block"): + read(dump(tmp_path / "d.gz", [row()], terminate=False)) + + +# --- row validation --------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("over", "reason"), + [ + ({"tx_hash": "0x12"}, "invalid_tx_hash"), + ({"topics_to_addr": "0xnothex"}, "invalid_address"), + ({"is_sender_victim": "yes"}, "invalid_boolean"), + ({"block_number": "16.5"}, "invalid_integer"), + ({"value": "Infinity"}, "invalid_non_finite_real"), + ({"value": "lots"}, "invalid_real"), + ], +) +def test_malformed_rows_are_counted_with_reasons( + tmp_path: Path, over: dict[str, str], reason: str +) -> None: + rows, reader = read( + dump(tmp_path / "d.gz", [row(), row(**{"tx_hash": h(2), **over})]), + max_malformed_fraction=1.0, + ) + assert len(rows) == 1 + assert list(reader.stats.malformed) == [reason] + assert reader.stats.malformed_lines[reason] == [rows[0].line + 1] + + +def test_field_count_encoding_and_oversize_lines(tmp_path: Path) -> None: + good = "\t".join(row()[c] for c in DUMP_ORDER) + path = tmp_path / "d.gz" + lines = [*PREAMBLE, *table(), f"COPY public.{ta.TABLE} ({', '.join(DUMP_ORDER)}) FROM stdin;"] + body = ( + "\n".join(lines).encode() + + b"\n" + + good.encode() + + b"\n" + + b"a\tb\n" + + good.encode()[:-3] + + b"\xff\xfe\n" + + b"x" * (ta.MAX_LINE + 50) + + b"\n" + + b"\\.\n" + ) + path.write_bytes(gzip.compress(body)) + rows, reader = read(path, max_malformed_fraction=1.0) + assert len(rows) == 1 + assert reader.stats.malformed == {"field_count": 1, "encoding": 1, "oversize_line": 1} + + +def test_too_many_malformed_rows_fail_the_read(tmp_path: Path) -> None: + rows = [row(tx_hash=h(i)) for i in range(10)] + [row(tx_hash="bad")] + with pytest.raises(ta.TooManyMalformedError): + read(dump(tmp_path / "d.gz", rows), max_malformed_fraction=0.05) + + +def test_nan_and_null_markers_are_missing_not_zero(tmp_path: Path) -> None: + rows, _ = read( + dump( + tmp_path / "d.gz", + [ + row( + value="NaN", + value_usd="\\N", + intended_addr="\\N", + is_sender_victim="\\N", + num_first_matched_digits="\\N", + ) + ], + ) + ) + r = rows[0] + assert (r.value, r.value_usd, r.intended, r.sender_is_victim, r.first_digits) == ( + None, + None, + None, + None, + None, + ) + assert r.victim is None + + +def test_copy_escapes_and_unicode() -> None: + assert ta.copy_unescape("a\\tb\\\\c\\nd") == "a\tb\\c\nd" + assert ta.copy_unescape("\\101\\x42é") == "ABé" + assert ta.copy_unescape("plain") == "plain" + + +def test_escaped_separator_does_not_split_a_field(tmp_path: Path) -> None: + """A backslash-escaped tab inside a field stays one field (and then fails validation as + an address), instead of shifting every later column.""" + rows, reader = read( + dump(tmp_path / "d.gz", [row(), row(tx_hash=h(2), topics_to_addr="0xab\\tcd")]), + max_malformed_fraction=1.0, + ) + assert len(rows) == 1 + assert reader.stats.malformed == {"invalid_address": 1} + + +# --- distinct counting, targets, scan --------------------------------------------------- + + +def test_spill_distinct_is_exact_with_tiny_memory(tmp_path: Path) -> None: + """Exact counts survive many flushes and duplicates across flushes.""" + c = ta.SpillDistinct(tmp_path, "x", 4, mem_items=7) + for i in range(1000): + c.add((i % 300).to_bytes(4, "big")) + assert c.count() == 300 + assert c.added == 1000 + c.close() + assert not (tmp_path / "x").exists() + + +def test_target_manifest_round_trip_and_corruption(tmp_path: Path) -> None: + m = ta.build_targets({"ph_victims": [VICTIM.upper().replace("0X", "0x")], "payoff_txs": [h(5)]}) + path = tmp_path / "m.json" + path.write_text(json.dumps(m), encoding="utf-8") + t = ta.load_targets(path) + assert t.addresses == {VICTIM} + assert t.txs == {h(5)} + m["groups"]["ph_victims"].append(LOOKALIKE) + path.write_text(json.dumps(m), encoding="utf-8") + with pytest.raises(ta.ArchiveError, match="hash mismatch"): + ta.load_targets(path) + path.write_text('{"groups":', encoding="utf-8") + with pytest.raises(ta.ArchiveError, match="unreadable"): + ta.load_targets(path) + with pytest.raises(ValueError, match="malformed"): + ta.build_targets({"ph_victims": ["0x12"]}) + + +def _targets(tmp_path: Path, **groups: list[str]) -> ta.TargetManifest: + path = tmp_path / "targets.json" + path.write_text(json.dumps(ta.build_targets(groups)), encoding="utf-8") + return ta.load_targets(path) + + +def _rows() -> list[dict[str, str]]: + other = "0x" + "22" * 20 + return [ + row(), # zero-value planting to VICTIM + row( + tx_hash=h(2), + tiny_transfer="t", + zero_value_transfer="f", + value="5000", + value_usd="0.005", + ), + row( + tx_hash=h(3), + addr=FAKE, + counterfeit_token_transfer="t", + zero_value_transfer="f", + value="1e+06", + value_usd="NaN", + ), + row( + tx_hash=h(4), + topics_from_addr=VICTIM, + topics_to_addr=LOOKALIKE, + is_sender_victim="t", + payoff_transfer="t", + zero_value_transfer="f", + value="5e+09", + value_usd="5000", + ), + row( + tx_hash=h(5), + topics_to_addr=other, + intended_addr="0x" + "33" * 20, + zero_value_transfer="t", + ), # declares 5+5, really 0+0 + row(tx_hash=h(1)), # same key as the first row: indistinguishable without a log index + ] + + +def test_scan_reproduces_counts_and_stores_only_targets(tmp_path: Path) -> None: + archive = dump(tmp_path / "d.gz", _rows()) + out = tmp_path / "subset.sqlite" + s = ta.scan( + archive, _targets(tmp_path, ph_victims=[VICTIM]), out, work_dir=tmp_path / "w", mem_items=2 + ) + assert s["poisoning_transfers"] == 5 + assert s["categories"]["payoff_transfer"] == 1 + assert s["distinct"]["poisoning_txs"] == 4 + assert s["distinct"]["victims"] == 2 + assert s["distinct"]["counterfeit_token_contracts"] == 1 + assert s["repeated_transfer_keys"] == 1 + assert s["nan_value_usd"] == 1 + assert s["stored_target_rows"] == 5 # every row touching VICTIM, not the other victim + # every counted value reached a spill file, including the final flush + assert s["peak_spill_bytes"] >= 32 * 4 + 20 * 4 + 16 * 5 + rows, summary = ta.load_subset(out) + assert [r.tx for r in rows] == [h(1), h(2), h(3), h(4), h(1)] + assert summary["target_manifest_sha256"] == s["target_manifest_sha256"] + assert not (tmp_path / "w" / "victims").exists() # spill files cleaned up + + +def test_rule_coverage_is_measured_per_subtype(tmp_path: Path) -> None: + """Zero-value rows trigger zero_value_in; 5,000-unit USDT dust triggers dust_in; the + counterfeit row triggers lookalike_in + untrusted_token_in; a 0+0 lookalike does not, + and its wrong declared digit counts are counted.""" + s = ta.scan( + dump(tmp_path / "d.gz", _rows()), + _targets(tmp_path, ph_victims=[VICTIM]), + tmp_path / "s.sqlite", + work_dir=tmp_path / "w", + ) + cov = s["rule_coverage"] + assert cov["zero_value/zero_value_in"] == 3 + assert cov["zero_value/lookalike_in"] == 2 + assert cov["tiny/dust_in"] == 1 + assert cov["counterfeit_token/untrusted_token_in"] == 1 + assert s["declared_digits_disagree"] == 1 + + +def test_rerun_is_idempotent_and_interruption_leaves_no_output(tmp_path: Path) -> None: + """A rerun replaces the output with identical content; an interrupted scan leaves the + previous complete file untouched and no temporary file behind.""" + archive = dump(tmp_path / "d.gz", _rows()) + targets = _targets(tmp_path, ph_victims=[VICTIM]) + out = tmp_path / "s.sqlite" + first = ta.scan(archive, targets, out, work_dir=tmp_path / "w") + before = ta.load_subset(out)[0] + second = ta.scan(archive, targets, out, work_dir=tmp_path / "w") + assert ta.load_subset(out)[0] == before + assert { + k: v + for k, v in first.items() + if k not in ("runtime_seconds", "peak_rss_bytes", "output_bytes") + } == { + k: v + for k, v in second.items() + if k not in ("runtime_seconds", "peak_rss_bytes", "output_bytes") + } + + def boom(_: ta.ReaderStats) -> None: + raise KeyboardInterrupt + + with pytest.raises(KeyboardInterrupt): + ta.scan(archive, targets, out, work_dir=tmp_path / "w", progress=boom, progress_every=2) + assert ta.load_subset(out)[0] == before + assert not (tmp_path / "s.sqlite.tmp").exists() + + +JOURNAL_HEADER = bytes.fromhex("d9d505f920a163d7") # SQLite rollback-journal magic + + +def test_killed_run_leftovers_are_cleared_before_rescan(tmp_path: Path) -> None: + """A hard kill leaves the temporary database, its rollback journal and spill files. + A rescan must not let SQLite replay that stale journal into the new database.""" + archive = dump(tmp_path / "d.gz", _rows()) + out = tmp_path / "s.sqlite" + (tmp_path / "s.sqlite.tmp").write_bytes(b"partial") + (tmp_path / "s.sqlite.tmp-journal").write_bytes(JOURNAL_HEADER + bytes(504)) + spill = tmp_path / "w" / "victims" + spill.mkdir(parents=True) + (spill / "b000.bin").write_bytes(bytes([1]) * 20) + s = ta.scan(archive, _targets(tmp_path, ph_victims=[VICTIM]), out, work_dir=tmp_path / "w") + assert s["distinct"]["victims"] == 2 # the stale spill value was not counted + assert len(ta.load_subset(out)[0]) == 5 + assert not (tmp_path / "s.sqlite.tmp-journal").exists() + + +def test_incomplete_or_foreign_subset_is_refused(tmp_path: Path) -> None: + path = tmp_path / "x.sqlite" + db = sqlite3.connect(path) + db.executescript(ta._DDL) + db.commit() + db.close() + with pytest.raises(ta.ArchiveError, match="incomplete"): + ta.load_subset(path) + + +def test_peak_rss_is_reported() -> None: + peak = ta.peak_rss_bytes() + assert peak is None or peak > 1 << 20 + + +def test_synthetic_benchmark_runs_and_is_deterministic(tmp_path: Path) -> None: + """The scaling benchmark's generator yields a dump the scanner accepts, twice alike.""" + from cryptoguard.ml.bench_archive import run_one + + out = run_one(300, tmp_path) + assert out["rows"] == 300 + assert out["deterministic"] is True + assert out["distinct_lookalikes"] > 0 From 873169068909dbdf70d07a8b3cb27079aa9ec311 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 09:02:45 +0300 Subject: [PATCH 17/92] docs(ml): Phase 11.3 cross-dataset validation report ML_CROSS_DATASET_VALIDATION.md documents provenance, licence, the actual archive format, the streaming parser, performance, record counts, Poison-Hunter and payoff overlap, outcome levels, competing lookalikes, temporal handling, selection bias, rule dependence, label quality, decision gates (no supervised benchmark is possible yet), audit issues 13-20 and the next experiment. Existing ML docs, the proposal, the changelog and the README point to it; earlier conclusions are kept. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++ ML.md | 10 +- ML_CROSS_DATASET_TABLES.md | 131 +++++++++ ML_CROSS_DATASET_VALIDATION.md | 483 +++++++++++++++++++++++++++++++ ML_PILOT_AUDIT.md | 17 ++ ML_POISONING_DATASET.md | 30 +- ML_RESEARCH_PLAN.md | 24 +- README.md | 1 + docs/ml/proposal-next-dataset.md | 6 + 9 files changed, 709 insertions(+), 12 deletions(-) create mode 100644 ML_CROSS_DATASET_TABLES.md create mode 100644 ML_CROSS_DATASET_VALIDATION.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c50d3d..c2d7c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,25 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Cross-dataset validation of poisoning research data (Phase 11.3) +- Added a verified, resumable downloader for one approved file at a time + (`ml fetch-file`). Resume needs a matching `206`, the file is renamed only after size, + MD5, SHA-256 and gzip checks, and a disk reserve is kept. It has no default caller. +- Added a safe streaming reader for Tsuchiya et al.'s PostgreSQL attempt archive + (`ml scan-archive`). It never executes the dump, whitelists statements, checks the schema, + bounds line lengths, counts distinct values exactly with bounded memory, and stores only a + target subset (renamed only after a complete pass). On the real archive: 34,905,969 rows, + 0 malformed, all ten publisher counts reproduced, peak RSS 279 MiB. +- Added the reconciliation (`ml cross-dataset-report`): match levels for Poison-Hunter + rows, payoff-to-attempt linkage, separate attempt/victim/address/campaign outcomes, + temporal categories, competing-lookalike analysis, decision gates and a local review + queue of 1,469 payoff-linked attempts. +- Fixed: payoff amounts are float4 in the source, so 1,644 of 1,738 are approximations + (Phase 11.2 reported 41). Payoffs now carry a stable identity and provenance. +- Fixed: a killed scan's stale SQLite journal is removed before a rescan. +- Review packets (v2) carry competing lookalikes and payment evidence. +- Docs: ML_CROSS_DATASET_VALIDATION.md, ML_CROSS_DATASET_TABLES.md. + ### Wallet-centric poisoning research platform (Phase 11.2) - Fixed: the option A pilot lost three wallet recordings because its post-processing read a non-existent field (`transactions`, not `wallet_transactions`) inside a broad exception diff --git a/ML.md b/ML.md index 16bf0e1..7981c81 100644 --- a/ML.md +++ b/ML.md @@ -37,10 +37,18 @@ method and decision log. - `ml/candidates.py`: candidate generation and point-in-time event features; - `ml/review.py`: label review export and import; - `ml/planner.py`: collection cost planning, which never collects; - - `ml/poisoning_report.py`: the offline report (`cryptoguard ml poisoning-report`). + - `ml/poisoning_report.py`: the offline report (`cryptoguard ml poisoning-report`); + - Phase 11.3: `ml/fetch.py` (verified, resumable download of one approved file), + `ml/tsuchiya.py` and `ml/tsuchiya_archive.py` (payoff list and streaming attempt-archive + parser, never executes SQL), `ml/reconcile.py` and `ml/cross_dataset.py` + (`cryptoguard ml scan-archive`, `cryptoguard ml cross-dataset-report`). - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. + [ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md) reconciles Poison-Hunter + with Tsuchiya et al.'s attempts and payoffs, and records why no supervised benchmark is + possible yet. The PTXPhish metrics below belong to the transaction task only and say + nothing about poisoning-attempt detection. - **Monitoring correction.** PSI reference bins created from now on keep a tied decile in its own bin (`closed="left"`). The Phase 11 card's bins use the original binning, under which a feature that is mostly one value sits in one bin and its shifts are invisible. diff --git a/ML_CROSS_DATASET_TABLES.md b/ML_CROSS_DATASET_TABLES.md new file mode 100644 index 0000000..34724a8 --- /dev/null +++ b/ML_CROSS_DATASET_TABLES.md @@ -0,0 +1,131 @@ +# Cross-dataset validation tables (Phase 11.3) + +Generated by `cryptoguard ml cross-dataset-report` from local, git-ignored files (0 RPC requests) at git `2a783978ce7b03aa018a6b01b5427df67a845e36` with uncommitted changes. Narrative and limitations: [ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md). + +## Source and scan + +| Quantity | Value | +|---|---| +| Archive | `address_poisoning_ethereum.sql.gz`, 2,316,354,530 bytes, KiltHub 10.1184/R1/29212703.v1 (CC BY-NC-ND 4.0) | +| Integrity | size and MD5 match the published values; SHA-256 `270211acb28684dd…` pinned | +| Format | PostgreSQL plain dump, one table, one COPY block; parser `tsuchiya-archive/1` | +| Decompressed bytes read | 9,850,567,622 | +| Data rows / valid / malformed | 34,905,969 / 34,905,969 / 0 | +| Preamble statements (recognised and skipped, never executed) | -- 14, COPY 1, CREATE DATABASE 1, CREATE TABLE 1, SELECT 2, SET 20, \connect 1 | +| Block range: all rows / poisoning rows | 15,053,226-20,208,032 / 15,773,071-20,208,026 | +| Missing amount / USD value (NaN) | 0 / 9,880,119 | +| Repeated (tx, token, from, to, value) keys | 895,966 (no log index, so repeats cannot be told from duplicates) | +| Poisoning rows whose declared digit counts differ from the addresses | 3 | +| Rows stored for the target manifest | 301,370 (146,198,528 bytes) | +| Scan runtime / peak RSS / peak spill | 1,295.7 s / 287 MiB / 972 MiB | + +## Publisher counts reproduced + +| Quantity | Published (guidance.ipynb) | Reproduced | Match | +|---|---|---|---| +| rows | 34,905,969 | 34,905,969 | yes | +| poisoning_transfers | 17,365,954 | 17,365,954 | yes | +| poisoning_txs | 1,691,529 | 1,691,529 | yes | +| tiny_transfer | 308,881 | 308,881 | yes | +| zero_value_transfer | 7,185,298 | 7,185,298 | yes | +| counterfeit_token_transfer | 9,871,775 | 9,871,775 | yes | +| counterfeit_token_contracts | 6,280 | 6,280 | yes | +| victims | 1,330,948 | 1,330,948 | yes | +| lookalikes | 6,492,215 | 6,492,215 | yes | +| is_not_categorized | 8,651 | 8,651 | yes | + +## Poisoning rows by subtype and direction + +| Subtype | Rows | Victim receives | Victim sends (spoofed sender) | +|---|---|---|---| +| counterfeit_token | 9,871,775 | 134,233 | 9,737,542 | +| tiny | 308,881 | 308,881 | 0 | +| zero_value | 7,185,298 | 182,876 | 7,002,422 | + +Poisoning rows whose declared digits are below 3 leading + 4 trailing: 0 of 17,365,954. + +## CryptoGuard candidate rules on source-labelled poisoning rows + +Denominator: the source's poisoning rows of each subtype (rows can carry several subtypes). Single-transfer rules only. `lookalike_in` assumes the intended address was an earlier counterparty, which the source's own selection presumes, so it measures agreement with the source's rule, not detection. `spoofed_out` needs the transaction signer, which the archive lacks. + +| Subtype | Rows | zero_value_in | dust_in | lookalike_in | untrusted_token_in | Any rule | Detector predicate | +|---|---|---|---|---|---|---|---| +| counterfeit_token | 9,871,775 | 9 / 9,871,775 (0.0%) | 0 / 9,871,775 (0.0%) | 134,233 / 9,871,775 (1.4%) | 134,233 / 9,871,775 (1.4%) | 134,233 / 9,871,775 (1.4%) | 9,871,775 / 9,871,775 (100.0%) | +| tiny | 308,881 | 0 / 308,881 (0.0%) | 28,780 / 308,881 (9.3%) | 308,881 / 308,881 (100.0%) | 853 / 308,881 (0.3%) | 308,881 / 308,881 (100.0%) | 308,881 / 308,881 (100.0%) | +| zero_value | 7,185,298 | 182,876 / 7,185,298 (2.5%) | 0 / 7,185,298 (0.0%) | 182,876 / 7,185,298 (2.5%) | 3,752 / 7,185,298 (0.1%) | 182,876 / 7,185,298 (2.5%) | 7,185,298 / 7,185,298 (100.0%) | + +## Poison-Hunter rows against the archive + +Unit: Poison-Hunter row (149 valid rows; 6 duplicate victim-events). Each row gets its strongest level. + +| Match level | Rows | Distinct victims | Distinct lookalikes | Distinct planting txs | +|---|---|---|---|---| +| exact_tx_event | 89 | 81 | 82 | 61 | +| victim_lookalike_imitated | 0 | 0 | 0 | 0 | +| victim_lookalike | 0 | 0 | 0 | 0 | +| tx_only | 16 | 11 | 15 | 14 | +| shared_lookalike | 0 | 0 | 0 | 0 | +| competing_lookalike | 40 | 27 | 27 | 39 | +| victim_only | 3 | 3 | 3 | 3 | +| none | 1 | 1 | 1 | 1 | + +Subtype agreement on exact matches: dust->agrees 8, fake->agrees 38, zero->agrees 43. Rows without an exact match: below_3_plus_4_similarity 44, inside_period_and_definition 16. Transaction-only matches (batched plantings): victim_listed_with_another_lookalike 4, victim_not_listed 12. + +## Payoffs linked to earlier attempts + +Unit: payoff transfer (payoff_transfers_ethereum.csv row); 1,738 payoffs. + +| Quantity | Value | +|---|---| +| Archive status of the payoff row | archive_flag_payoff_confirmed 1,634, archive_flag_payoff_unconfirmed_only 104 | +| Linkage | attempt_before_payoff 1,635, attempts_only_after_payoff 13, no_attempt_between_pair 90 | +| Linked: distinct victims / lookalikes / payoff txs | 1,407 / 1,450 / 1,635 | +| Blocks from the last pair attempt to the payoff | n 1,635; min 1, p25 1,039, median 19,953, p75 82,432, max 2,097,556 | +| Pair attempts before the payoff | n 1,635; min 1, p25 1, median 1, p75 3, max 139 | +| Rival lookalikes that reached the victim before the payoff | n 1,738; min 0, p25 1, median 3, p75 9, max 1,741 | +| Payoffs with a rival imitating the same intended address | 1,088 / 1,738 (62.6%) | +| Of those (linked): paid lookalike was the most similar | 629 of 1,007 (uniform expectation 483.1) | +| Of those (linked): paid lookalike was the most recent | 724 of 1,007 (uniform expectation 324.1) | + +Both comparisons cover 1,007 payoffs from 852 victims. They are observational: payoffs of one victim are not independent, the uniform expectation counts ties, and neither similarity nor recency is shown to cause a payment. + +Review queue: 1,469 payoff-linked attempt events (892 with competing lookalikes) exported for independent review; no label is assigned and the packets stay local. + +## Outcome levels for the Poison-Hunter rows + +Unit: Poison-Hunter row (149 rows). Note: a victim's loss to another lookalike is never credited to this attempt; payments before the planting are address history, not outcomes. + +| Outcome | Rows | +|---|---| +| address_outcome_paid_by_anyone_after | 0 | +| address_outcome_paid_by_anyone_before | 1 | +| attempt_outcome_paid_after | 0 | +| attempt_outcome_paid_in_window | 0 | +| campaign_outcome_paid_after | 0 | +| victim_outcome_paid_any_lookalike_after | 1 | + +Payment pairs by temporal category: address/before_planting 1, victim/after_planting 1. + +## Recorded incidents (case studies, not evaluation data) + +| Incident | Harm in archive period | Victim attempts | Harm-recipient attempts | Pair attempts before harm | Harm tx in archive | +|---|---|---|---|---|---| +| eth-140-poisoning-2025-08-14 | no | 0 | 0 | 0 | no | +| eth-4556-poisoning-2026-01-30 | no | 16 | 0 | 0 | no | +| usdt-50m-poisoning-2025-12-19 | no | 234 | 0 | 0 | no | +| wbtc-1155-poisoning-2024-05-03 | yes | 0 | 0 | 0 | no | + +## Decision gates + +| Gate | Status | Evidence | +|---|---|---| +| 1 Data integrity | pass | pinned size/MD5/SHA-256; 0 malformed rows; publisher counts reproduced | +| 2 Event identity | partial | transactions, attempts (victim, lookalike, tx) and Poison-Hunter victim-events are distinct; the archive has no log index (895,966 repeated transfer keys) and no campaign identifier | +| 3 Label validity | fail | archive categories are the source's heuristic labels (lookalike rule, thresholds), not independent review of attempts; payoffs are confirmed outcomes, not attempt labels | +| 4 Temporal integrity | partial | block-level ordering only (no transaction index or timestamps in the archive): same-block pairs are 'order unknown'; fixture-based features keep exact cutoffs | +| 5 Independent evaluation | fail | no verified negatives in any source; not listed or not paid does not mean benign | +| 6 Leakage control | partial | campaign grouping and grouped temporal splits exist, but there are no trainable labels to split | +| 7 Baseline comparability | fail | the archive holds only poisoning-related transfers, not the wallet histories the deterministic detector needs, so both cannot run on the same observations | +| 8 Operational usefulness | fail | alert volume on ordinary wallets is known only from 27 recorded wallet-days; 1,635 payoff-linked attempts are retrospective, not prospective | + +Reconciliation runtime 6.1 s, peak RSS 339 MiB. diff --git a/ML_CROSS_DATASET_VALIDATION.md b/ML_CROSS_DATASET_VALIDATION.md new file mode 100644 index 0000000..0f222ab --- /dev/null +++ b/ML_CROSS_DATASET_VALIDATION.md @@ -0,0 +1,483 @@ +# Cross-dataset validation of poisoning research data (Phase 11.3) + +Status: research only. No model was trained. 0 Ethereum RPC requests. Every number below +comes from [ML_CROSS_DATASET_TABLES.md](ML_CROSS_DATASET_TABLES.md) (generated by +`cryptoguard ml cross-dataset-report`) or [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md) +(`cryptoguard ml poisoning-report`); raw and address-level files stay in the git-ignored +`data/` directory. + +## 1. Executive summary + +- **The archive is intact and read correctly.** Tsuchiya et al.'s attempt archive (2.32 GB + gzip, 9.85 GB of SQL) was streamed once without being executed: + - **34,905,969 rows, 0 malformed**; + - every one of the publisher's ten reference counts reproduced exactly (17,365,954 + poisoning transfers, 1,691,529 poisoning transactions, 1,330,948 victims, 6,492,215 + lookalikes, ...); + - peak memory under 290 MiB, 22–32 minutes per pass; + - two passes gave identical results. +- **The Poison-Hunter sample largely agrees with it, within Tsuchiya's definition.** + - Of the 105 Poison-Hunter rows that meet Tsuchiya's lookalike rule (at least 3 leading + and 4 trailing hex characters), 89 (84.8%) match an archive transfer exactly: same + transaction, victim and lookalike, and the same subtype every time. + - The other 44 rows fall below that rule (mostly 2-character "dust"), so they cannot + appear in the archive by construction. Still, for 37 of them the archive shows the same + victim targeted by *other* lookalikes of the same address. +- **Payoffs link to earlier attempts.** 1,635 of the 1,738 confirmed payoffs (94.1%) have + an archive poisoning transfer from the same lookalike to the same victim in an earlier + block. The median gap is 19,953 blocks (about 2.8 days). + - 62.6% of payoffs had a *rival* lookalike imitating the same intended address. + - Among 1,007 linked payoffs from 852 victims, the paid lookalike was the most recent + attempt 724 times (324.1 expected by chance) and the most similar 629 times (483.1 + expected). These are observational associations, not causal effects. +- **The Poison-Hunter outcomes stay as reported in Phase 11.2.** No row has an attempt-level + payoff; one victim paid a competing lookalike (line 74); one lookalike had been paid + before its planting (line 87). +- **No supervised benchmark is possible yet.** + - Data integrity passes. Event identity, temporal integrity and leakage control are + partial. Label validity, independent evaluation, baseline comparability and operational + usefulness fail. + - The archive's categories are the source's own heuristics: every poisoning row meets the + source's 3+4 rule, so CryptoGuard's lookalike predicates agree with 100% of rows by + construction. + - No source contains verified negatives. +- **The useful product of this phase:** + - a safe, tested ingestion path; + - a reproducible reconciliation; + - a local review queue of **1,469 payoff-linked attempt events**, candidates for + independent `verified_attempt` labels. + +## 2. Objectives + +1. Verify the integrity of, and the parser for, the Tsuchiya payoff file and attempt + archive without executing untrusted SQL or making RPC requests. +2. Reconcile three sources (Poison-Hunter sample, Tsuchiya attempts, Tsuchiya payoffs), + with the four recorded incidents as separate case studies. +3. Keep attempt, victim, address and campaign outcomes apart; handle competing lookalikes + and temporal order explicitly. +4. Decide, with evidence, whether these labels support a wallet-centric benchmark. + +## 3. Source provenance + +| File | Bytes | Integrity | Use | +|---|---|---|---| +| `address_poisoning_ethereum.sql.gz` | 2,316,354,530 (9,850,567,622 decompressed) | size and MD5 `5001c79f…7954330` match KiltHub; SHA-256 `270211ac…227cea` pinned; gzip CRC verified | attempt archive, streamed | +| `payoff_transfers_ethereum.csv` | 482,397 | MD5 matches KiltHub; SHA-256 pinned | confirmed payoffs | +| `README.txt`, `guidance.ipynb` | 9,981 / 22,830 | MD5 match KiltHub; SHA-256 pinned | schema and reference counts | +| Poison-Hunter `phishing_transfers_sample.csv` | 63,454 | SHA-256 pinned at commit `74ff6f7d` | weak attempt labels | + +- **Record:** Tsuchiya, Dong, Soska, Christin, *Blockchain Address Poisoning (Companion + Dataset)*, Carnegie Mellon University, KiltHub, DOI 10.1184/R1/29212703.v1, version 1, + published 2025-06-03 and unchanged since (checked 2026-11-02). Companion to the USENIX + Security 2025 paper (arXiv 2501.16681). Data period per the README: 2022-07-01 to + 2024-06-30. +- **Download:** approved by the user on 2026-11-02 for the archive, README and notebook. + `cryptoguard ml fetch-file` wrote each file to `.part`, verified size, MD5, + SHA-256 and (for the archive) the full gzip CRC, then renamed it. The pinned values live + in `ml/fetch.py`. Nothing downloads these files from a build, test or default command; + `scan-archive` fails with instructions if the archive is missing. + +## 4. Licence + +- The KiltHub record states **CC BY-NC-ND 4.0** for the dataset; the files carry no + separate licence. CryptoGuard's MIT licence does not apply to them. +- What is done here: local, non-commercial research use; aggregate statistics and + Poison-Hunter line numbers in the repository; attribution in this document and the + module docstrings. +- What is not done: no raw rows, address-level tables, extracted subsets or review queues + are committed or published (the subset database, target manifest and review packets stay + in `data/ml/poisoning/`). Whether a model trained on these labels, or a public + publication of derived per-address tables, would be an "adaptation" under ND is not + settled here and needs a licensing decision before any such step. +- Poison-Hunter publishes no licence (all rights reserved): local use only. + +## 5. File integrity + +- **At download:** byte count equal to the published size; MD5 equal to KiltHub's + `computed_md5` and `supplied_md5`; SHA-256 recorded and pinned; the full gzip stream + decompressed to nowhere to verify every CRC (9,850,567,622 bytes). +- **At every scan:** `scan-archive` re-verifies size, MD5 and SHA-256 against the pinned + values before reading, and refuses a mismatch. +- **Resume.** The download went through in one transfer. Resume support is implemented and + tested against a mock server: a `206` with a matching `Content-Range` is required, a + `200` restarts from byte 0, and a completed file that fails verification is renamed + `.corrupt`. The live server's range support was not exercised. + +## 6. Actual archive format + +- PostgreSQL 16.8 plain-format dump (pg_dump 16.9). The preamble contains `SET` + statements, `SELECT pg_catalog.set_config(...)`, `CREATE DATABASE addrpoisoning`, the psql + meta-command `\connect addrpoisoning`, one `CREATE TABLE public.address_poisoning_ethereum` + with 18 columns, then one `COPY ... FROM stdin;` block of tab-separated rows ending with + `\.`. The README's restore instruction pipes the dump into `psql`, which would execute + `CREATE DATABASE` and `\connect`; CryptoGuard never does. +- Unit: **one row is one token transfer** (an ERC-20 `Transfer` log) with category flags: + `intended_transfer`, `zero_value_transfer`, `tiny_transfer`, `counterfeit_token_transfer`, + `payoff_transfer`, `payoff_transfer_unconfirmed`, `is_not_categorized`. A poisoning + transfer is one flagged zero-value, tiny or counterfeit (the notebook's definition). + Direction comes from `is_sender_victim`: the victim is the sender when true (a spoofed + `transferFrom`-style planting), otherwise the receiver; the lookalike is the other side. +- Columns are mapped **by name from the COPY header**: the dump's order differs from the + README's (`zero_value_transfer` precedes `tiny_transfer`). +- No log index, transaction index or timestamp: two identical transfers in one + transaction cannot be told apart, and events in one block cannot be ordered. +- `value` and `value_usd` are PostgreSQL `real` (float4, about 7 significant digits): + base-unit amounts above 2^24 are rounded, and `NaN` marks missing values. + +## 7. Streaming parser (`ml/tsuchiya_archive.py`, `tsuchiya-archive/1`) + +- **Never executes the dump.** Lines are matched against a whitelist of preamble prefixes + (`--`, `SET`, `SELECT pg_catalog.set_config(`, `CREATE DATABASE`, `\connect`), one + `CREATE TABLE` whose 18 column names and types must equal the README's, and one `COPY` + whose column set must match. `INSERT`-format dumps, any other statement, another table, a + second COPY block, a missing terminator and truncated gzip each raise a specific error; + nothing partial is returned. A test confirms the reader opens no database at all. +- **Rows** are split on tabs (the COPY text format escapes tabs and newlines, so one + physical line is one row; escapes are decoded) and type-checked: 32-byte hash, + addresses, `t`/`f`/`\N` booleans, finite reals or `NaN`, integers. Bad rows are counted + by reason with example line numbers; the read fails above 0.1% malformed. Lines longer + than 4,096 bytes are rejected without being buffered whole. +- **Memory:** gzip is decompressed as a stream with bounded line reads. Exact distinct + counts of millions of victims, lookalikes, transactions and transfer keys spill to 64 + bucket files per counter (`SpillDistinct`), so memory stays flat. Only rows whose sender, + receiver or transaction is in a deterministic **target manifest** are stored, in SQLite + (parameterised inserts, unique source line numbers, indexes on sender, receiver and + transaction; a 5-million-row cap fails the scan rather than filling the disk). +- **Target manifest** (`data/ml/poisoning/archive_targets.json`, hashed): Poison-Hunter + victims, lookalikes and planting transactions; payoff victims, lookalikes and + transactions; incident victims, harm recipients and transactions. Imitated addresses are + deliberately excluded: they can be exchange wallets with millions of rows, and every row + involving a target victim already carries its intended address. +- **Recovery:** gzip has no record-level seek, so a resumed scan replays from byte 0. The + database is built as `.tmp` and renamed only after the whole pass; leftovers of an + interrupted or killed run (temporary database, its SQLite rollback journal, spill files) + are deleted first. A rerun with the same archive, manifest and parser is skipped as + cached; a forced rerun produces identical content (tested). + +## 8. Processing performance + +| Run | Rows | Runtime | Throughput | Peak RSS | Temporary disk | +|---|---|---|---|---|---| +| Full archive, first pass | 34,905,969 | 1,931 s | about 18,100 rows/s | 279 MiB | about 0.95 GiB (measured before the final flush) | +| Full archive, second pass (`--force`) | 34,905,969 | 1,296 s | about 26,900 rows/s | 287 MiB | 972 MiB | +| Synthetic, 1,000 rows | 1,000 | 3.0 s | 335 rows/s | 43 MiB | negligible | +| Synthetic, 10,000 rows | 10,000 | 4.1 s | 2,464 rows/s | 49 MiB | negligible | +| Synthetic, 100,000 rows | 100,000 | 8.4 s | 11,904 rows/s | 85 MiB | negligible | +| Reconciliation (301,370 stored rows) | - | 6–15 s | - | 339 MiB | - | + +- **Small runs are dominated by fixed costs.** Opening files takes about 28 ms each on this + machine; it was measured, probably because of antivirus scanning. The spill counter's + 256 bucket files cost about 14 s per run regardless of size. +- **Two performance defects were found and fixed.** A first version reopened the bucket + files on every flush, which made the first million rows take 128 s. A first full attempt + was stopped at 7 million rows and restarted with the fix. +- **Deterministic.** The two full passes gave identical summaries (all fields except + timing and spill) and an identical stored subset (same SHA-256 over all 301,370 rows). + The runtime difference (32 vs 22 minutes) came from other work on the machine during + the first pass. +- **Memory stays flat.** Peak RSS grows with the in-memory deduplication buffers (500,000 + values per counter), not with archive size. The full pass stayed under the 512 MiB + target. +- **Disk:** + - archive 2.32 GB; + - target subset 146 MB (SQLite); + - temporary spill files of 972 MiB during the pass, deleted afterwards; + - no decompressed copy is ever written. + +## 9. Extracted record counts (whole archive) + +| Category | Rows | +|---|---| +| Poisoning transfers (zero-value, tiny or counterfeit) | 17,365,954 in 1,691,529 transactions | +| Counterfeit-token | 9,871,775 (6,280 token contracts) | +| Zero-value | 7,185,298 | +| Tiny | 308,881 | +| Uncategorized | 8,651 | +| Rows with `value_usd` NaN | 9,880,119 (counterfeit tokens have no price) | +| Repeated (tx, token, from, to, value) keys | 895,966 | + +- **Direction.** 98.6% of counterfeit-token rows and 97.5% of zero-value rows have the + victim as the *sender*: spoofed transfers emitted by a token contract the victim never + called. Every tiny transfer has the victim as receiver. +- **The source's selection rule holds everywhere.** All 17,365,954 poisoning rows declare + at least 3 leading and 4 trailing matched characters. Only 3 rows declare digit counts + that differ from their addresses. +- **Repeats.** The 895,966 repeated keys are rows identical in transaction, token, sender, + recipient and amount. Without a log index, legitimate repeats inside one transaction + cannot be told from duplicates, so attempts are deduplicated by (victim, lookalike, + transaction). + +## 10. Poison-Hunter overlap + +Unit: Poison-Hunter row (149 valid rows: 143 distinct victim-events plus 6 duplicates). +All 149 rows fall inside the archive's poisoning-block range. Each row is assigned its +strongest match level. + +| Level | Rows | Meets the 3+4 rule | Below it | +|---|---|---|---| +| `exact_tx_event` (same tx, victim, lookalike) | 89 | 89 (8 dust, 38 fake, 43 zero) | 0 | +| `tx_only` (same tx, other victim/lookalike) | 16 | 13 (12 fake, 1 zero) | 3 (zero) | +| `competing_lookalike` (victim listed with another lookalike of the same address) | 40 | 3 | 37 (dust) | +| `victim_only` | 3 | 0 | 3 | +| `none` | 1 | 0 | 1 | +| `victim_lookalike(_imitated)`, `shared_lookalike` | 0 | 0 | 0 | + +- **Agreement within the definition:** 89 of 105 rows (84.8%) match exactly, and the + subtype agrees in all 89: dust→tiny, fake→counterfeit, zero→zero. +- **The 16 transaction-only rows are all batched plantings** (batches of 8–422 victims). + - In 4 fake-token rows the archive lists the same victim in the same transaction but + with a **different lookalike**: the sources disagree on the attacker address. + - In 12 rows the victim is absent from that transaction in the archive. Three of these + fall below 3+4. For the others the cause is not visible offline; one possibility is that + Tsuchiya et al. require an observed intended transfer. +- **The 44 rows below 3+4 are a definition difference, not a disagreement about attacks.** + The archive cannot contain them by construction. +- **"Tsuchiya-only" events are not measurable.** The Poison-Hunter file is a 150-row + sample of an unpublished dataset, so most archive events are absent from it by design. + +## 11. Payoff dataset overlap + +- All 1,738 payoffs are in the archive. 1,634 carry the `payoff_transfer` flag. The other + 104 carry only `payoff_transfer_unconfirmed`; the authors confirmed those manually + (notebook remark), which explains the gap. +- **Attempt linkage** (unit: payoff): + - 1,635 (94.1%) have an earlier attempt from the same lookalike to the same victim: + 1,407 victims, 1,450 lookalikes. + - 13 have attempts only after the payment. + - 90 have none in the archive. +- **Timing and repetition.** + - Gap from the last attempt to the payoff: p25 1,039 blocks (about 3.5 h), median 19,953 + (about 2.8 days), p75 82,432 (about 11 days), maximum 2,097,556 (about 290 days). + - Most victims saw one attempt from the paid lookalike (median 1, p75 3, maximum 139). +- The 103 unlinked payoffs stay unlinked. They are not attributed to any other attempt. + +## 12. Victim-level versus attempt-level outcomes + +The four outcome levels (`ml/reconcile.py`) are computed separately for each Poison-Hunter +row: + +| Outcome | Rows of 149 | +|---|---| +| Attempt: the victim paid **this** lookalike after the planting | 0 (0 within 7 days) | +| Victim: the victim paid **any** lookalike after the planting | 1 (line 74) | +| Address: this lookalike was paid by anyone **before** the planting | 1 (line 87) | +| Address: ... **after** the planting | 0 | +| Campaign: a lookalike in the row's campaign group was paid after the planting | 0 | + +- A victim-level loss is never credited to an attempt. +- A payment before a planting is address history, never an outcome. +- Regression tests encode lines 74 and 87. + +## 13. Competing lookalikes + +- **Rivals are the norm.** Before their payoff, victims had been reached by a median of 3 + other lookalikes (p75 9, maximum 1,741). 1,088 payoffs (62.6%) had at least one rival + imitating the *same* intended address. +- **Which rival got paid** (1,007 linked payoffs with such rivals, 852 victims): + - the paid lookalike was the **most recent** attempt in 724 cases, against 324.1 expected + if the victim had picked uniformly among the candidates; + - it was the **most similar** (leading+trailing characters) in 629 cases, against 483.1 + expected; ties count, and the expectation accounts for them. +- **Interpretation.** Recency is the stronger association. It fits victims copying the + latest entry in their history, but the data cannot show cause. Payoffs from one victim are + not independent, and missing attempts (other tokens, ETH, outside the 3+4 rule) are + unobserved. No confidence interval is reported because the payoffs are not a random + sample of anything. +- **Poison-Hunter rows:** 40 rows show the victim targeted by other lookalikes of the same + address. + +## 14. Temporal correctness + +- **Categories.** A (planting, payment) pair is `before_planting`, `same_block_order_unknown` + (the archive has no transaction index), `after_planting` or `temporally_ambiguous` (a + block is missing). Negative delays are never shown as lead times. +- **Payoff linkage** uses only attempts in strictly earlier blocks. Same-block attempts are + reported separately: 0 payoffs were linked only by a same-block attempt. +- **No future-data leakage.** Payoff status is an evaluation outcome. It is never a feature, + never in a review packet as a score, and never used to classify an earlier planting. + The point-in-time event features (Phase 11.2) see only strictly earlier positions. +- **Not checked:** reorganisations. The archive gives no block hashes, so a reorg cannot be + detected from it; its blocks are deep in history. + +## 15. Dataset-selection bias + +- **Lookalike rule:** the archive keeps only lookalikes with at least 3+4 matching + characters, so poisoning with less similar addresses (41 of the Poison-Hunter dust rows + use 2 leading characters) is invisible. +- **Tokens:** + - payoffs are ERC-20 only, with no native ETH; + - USD values exist only for priced tokens (counterfeit rows are NaN); + - three of the four recorded incidents were paid in ETH or WBTC, or happened after + June 2024. +- **Period:** July 2022 to June 2024 (blocks 15,053,226–20,208,032). +- **Detection pipeline:** what counts as a victim, an intended transfer or a tiny transfer + (under 10 USD, per the notebook) is the source's definition. +- **Payoff confirmation:** 104 payoffs were promoted from "unconfirmed" by manual Etherscan + review, so the payoff list mixes automated and manual evidence. + +## 16. Detection-rule dependence + +The agreement figures fall into five tiers of evidence; only the first was measured here. + +| Agreement with | Result | +|---|---| +| The source's lookalike rule | 100% for CryptoGuard's detector predicate and candidate rule, **implied** by the 3+4 selection | +| The source's candidate detection (Poison-Hunter vs Tsuchiya) | 89/105 exact within the shared definition | +| Independently validated attacks | not measured: no independent attack labels exist | +| Independent victim outcomes | payoffs exist, but only for attempts the source already selected | +| Generalization to unselected events | not measurable from these sources | + +CryptoGuard's single-transfer candidate rules on source-labelled rows: + +- **The relevant rule cannot be checked here.** The source's poisoning is mostly spoofed + *outgoing* transfers, which CryptoGuard's `spoofed_out` rule targets. That rule needs the + planting transaction's signer, and the archive does not have it. +- **The rules that can be checked:** + - `zero_value_in` fires on the 2.5% of zero-value rows the victim receives; + - `dust_in` (at most 0.01 USDT/USDC) catches **9.3%** of the source's tiny transfers. + This is a real threshold difference: the source's tiny goes up to 10 USD. + - `lookalike_in` agrees with all incoming rows, by construction. + +## 17. Label quality + +| Source | What its labels are | Tier here | +|---|---|---| +| Poison-Hunter sample | the source pipeline's attempts | `weak_attempt` | +| Tsuchiya archive categories | the source's heuristics (lookalike rule, value thresholds, intended-transfer matching) | research-source-labelled; not loaded as labels | +| Tsuchiya payoffs | confirmed losses (automated, plus manual Etherscan review) | outcomes, not attempt labels | +| Payoff-linked attempts | attempts followed by a confirmed loss to the same lookalike | review candidates (1,469 packets); no label assigned | + +None of these is a verified negative. + +## 18. Candidate-generation evaluation + +- Phase 11.2 reported candidate recall on the 4 recorded incidents (4 of 4, not untouched + data). +- Phase 11.3 adds the rule coverage above, on 17.4 million source-labelled rows. It is a + measure of agreement with the source's definitions, not detector recall: + - the source's lookalike rule is a subset of CryptoGuard's; + - the most common planting shape needs data (the signer) the archive lacks; + - no ordinary wallet histories are available to measure false candidates. +- Wallet-level candidate generation needs full victim histories, which these sources do not + contain. + +## 19. Unknown and unmatched outcomes + +- **The 97 pilot rows the Phase 11.2 pilot could not check.** The payoff list has no + attempt-level payoff for any of them. That absence counts only for ERC-20 payments in the + study period to lookalikes the study detected: + - **62 of the 97 rows** (39 not evaluated, 23 unresolved) are exact archive matches, so + for those the study demonstrably tracked the attempt. "No ERC-20 payoff to this + lookalike was confirmed by July 2024" is supported for them. + - The other 35 rows lack even that coverage condition. + - It is not proof of no payment for any row (ETH, other tokens, after June 2024). +- **The 52 complete pilot rows:** 27 are exact matches, and both sources agree that no + payoff occurred. +- **Unmatched records.** + - 103 payoffs have no earlier attempt in the archive; + - 12 batched Poison-Hunter rows are absent from their transaction in the archive; + - 4 rows disagree on the lookalike; + - 1 row has no archive trace at all. + None of these is relabelled. + +## 20. Statistical limitations + +- **Denominators.** Every rate above names its unit and denominator. +- **No random samples.** + - The Poison-Hunter file is a published sample of unknown design. + - Payoffs are a selected subset of victims. + - The pilot's complete rows were the least active victims. + So no population rate, precision, recall or theft probability is reported. +- **Correlation.** Rows share victims, lookalikes, batch transactions and campaigns. + Reported counts are descriptive; any later test needs grouping by victim and campaign. +- **Earlier conclusions stand.** The Phase 11.2 correction is unchanged: the pilot's 0.069 + bound applies only to the 52 completely checked rows. + +## 21. Reproducibility + +``` +cryptoguard ml fetch-file address_poisoning_ethereum.sql.gz # only after approval +cryptoguard ml scan-archive # verifies size/MD5/SHA-256, one pass, cached +cryptoguard ml cross-dataset-report # reconciliation; writes ML_CROSS_DATASET_TABLES.md +cryptoguard ml poisoning-report # Phase 11.2 tables, including the payoff cross-check +cryptoguard ml bench-archive 1000 10000 100000 +``` + +Each run records the git commit (Phase 11.2 report), source SHA-256, parser and +reconciliation versions, the target-manifest hash, row counts, malformed-row reasons, +runtime, peak RSS and spill size; the JSON reports in `data/ml/poisoning/` carry a hash of +the generated tables. + +## 22. Memory and disk + +| Resource | Use | +|---|---| +| Peak RSS, full scan | 279 MiB and 287 MiB in two passes (target under 512 MiB) | +| Peak RSS, reconciliation | 339 MiB (6–15 s) | +| Archive on disk | 2,316,354,530 bytes; never decompressed to disk | +| Temporary spill files | 972 MiB at peak, deleted at the end of the pass | +| Stored target subset | 301,370 rows, 146 MB (git-ignored) | +| Free disk kept in reserve by the downloader | 10 GiB | + +## 23. ML readiness (decision gates) + +| Gate | Status | Why | +|---|---|---| +| 1 Data integrity | **pass** | pinned hashes; 0 malformed rows; ten publisher counts reproduced | +| 2 Event identity | partial | attempts, transactions and victim-events are distinct, but the archive has no log index and no campaign identifier | +| 3 Label validity | **fail** | archive categories are the source's heuristics, not independent review of attempts | +| 4 Temporal integrity | partial | block-level order only; same-block pairs are "order unknown" | +| 5 Independent evaluation | **fail** | no verified negatives anywhere | +| 6 Leakage control | partial | grouping and grouped splits exist; there are no trainable labels to split | +| 7 Baseline comparability | **fail** | the archive lacks the wallet histories the detector needs | +| 8 Operational usefulness | **fail** | alert volume on ordinary wallets is known from 27 wallet-days only | + +**Conclusion.** The available research data cannot support a valid supervised benchmark +for `poisoning-attempt/1`. No model was trained, and none should be until gates 3, 5 and 7 +pass. + +What the data does support: +- positive-case reproduction; +- agreement analysis between sources; +- retrospective payoff studies; +- a concrete review queue. + +## 24. Audit register (Phase 11.3) + +| ID | Pri | Finding | Status | +|---|---|---|---| +| 13 | P1 | **Payoff amounts mislabelled as exact.** The source columns are PostgreSQL `real` (float4: exact only up to 2^24 base units). Phase 11.2 used the float64 limit and reported 41 inexact amounts; in fact 1,644 of 1,738 are float4 approximations | Fixed (`tsuchiya-payoff/2`): precision class per amount, verbatim source text, human amount only for known decimals, USD kept as the source's valuation | +| 14 | P1 | **Stale SQLite journal after a killed scan.** A hard kill left `*.tmp-journal`; SQLite could replay it into the next run's database | Fixed: temporary database, journal and spill leftovers are removed before a scan; regression test | +| 15 | P1 | **Spill counter reopened files on every flush.** About 28 ms per open on this machine made the scan about 5 times slower | Fixed: 64 bucket files kept open | +| 16 | P1 | **Similarity comparison ignored ties.** A first version compared "most similar, ties included" against a no-ties 1/k expectation (319.6 instead of 483.1) | Fixed before reporting; regression test | +| 17 | P2 | **Spill size measured before the final flush** | Fixed; the full-scan value comes from the second pass | +| 18 | P2 | **README column order differs from the dump** (zero-value before tiny) | Handled: columns are mapped by COPY-header name | +| 19 | P2 | **Payoff "study period" in the Phase 11.2 cross-check** used the payoff block range (from 16.06M), not the data period (from 15.05M) | Documented. The archive now gives the real range; the Phase 11.2 table is labelled "payoff period" | +| 20 | P2 | **No log index in the archive** (895,966 repeated transfer keys) | Documented: attempts deduplicated by (victim, lookalike, tx) | + +Issues 1–12 are in ML_RESEARCH_PLAN.md §1. + +## 25. Recommended next experiment + +**Independently review a stratified sample of the payoff-linked review queue, and collect +matched legitimate look-alike interactions as negatives.** + +- **Positives.** From the 1,469 payoff-linked attempt packets + (`data/ml/poisoning/review_packets_payoff_linked.jsonl`), draw a stratified sample: + - by subtype (zero-value, counterfeit, tiny, spoofed); + - by year; + - by whether a rival lookalike existed; + - with one packet per victim and campaign group. + About 60 packets give the 30 needed per class with margin. Reviewers would confirm each + planting on a block explorer from the packet's evidence, with no model score shown. +- **Negatives.** For the same victims, take transfers from addresses that share 3+4 or more + characters with a real counterparty but are legitimate, for example a counterparty's own + second wallet. Finding and verifying them needs the victims' wallet histories. + - This is the first step that would need new chain data, so it needs a separately + approved, capped RPC budget. + - It should be sized with `cryptoguard ml plan-collection` before any request is made. +- **Exact evidence needed:** + - reviewer decisions in `poisoning-review/1` format; + - for negatives, the victims' full transfer histories over the review window; + - a frozen sampling manifest, written before any review. +- **What not to do:** no broad crawl, no paid service, no labels inferred from overlap. diff --git a/ML_PILOT_AUDIT.md b/ML_PILOT_AUDIT.md index b4349fa..c6b6d2f 100644 --- a/ML_PILOT_AUDIT.md +++ b/ML_PILOT_AUDIT.md @@ -173,3 +173,20 @@ three wallet-days and biased low (busier wallets were excluded). - **Effect on the pilot outcomes: none.** Pilot outcomes record only payments the pilot observed itself. Line 74 shows that a *victim's* loss and a *given event's* outcome can differ: the payment went to a competing lookalike. + +## 8. Coverage check against Tsuchiya et al.'s attempt archive (Phase 11.3, 0 RPC requests) + +- The archive (34.9 million transfers, July 2022 to June 2024) lists the planting itself + (same transaction, victim and lookalike) for: + - **27 of the 52 complete-coverage rows**; + - **62 of the 97 rows the pilot could not check** (39 not evaluated, 23 unresolved). +- For those 62 rows the study demonstrably tracked the attempt, and its payoff list + confirms no ERC-20 payoff to the row's lookalike. This is stronger than the bare + absence reported in §7. It still says nothing about ETH, other tokens or payments after + June 2024. +- The remaining rows are mostly "dust" plantings below the archive's 3+4 lookalike rule. + For most of them, the archive shows the same victim targeted by other lookalikes of the + same address. +- The pilot's outcomes and the conditional 0.069 bound are unchanged. Details: + ML_CROSS_DATASET_VALIDATION.md §10–12 and §19. + diff --git a/ML_POISONING_DATASET.md b/ML_POISONING_DATASET.md index 1385a0f..b3c5e17 100644 --- a/ML_POISONING_DATASET.md +++ b/ML_POISONING_DATASET.md @@ -150,12 +150,12 @@ ML_RESEARCH_PLAN.md §5. | Source | What it offers | Blocker | |---|---|---| -| Tsuchiya et al., USENIX Security 2025 (KiltHub DOI 10.1184/R1/29212703.v1) | Ethereum attempts (2.3 GB SQL dump) plus payoff-transfer CSVs (under 2 MB) | Licence CC BY-NC-ND 4.0. The Ethereum payoff CSV is downloaded (§8); every other file needs your approval | +| Tsuchiya et al., USENIX Security 2025 (KiltHub DOI 10.1184/R1/29212703.v1) | Ethereum attempts (2.3 GB SQL dump) plus payoff-transfer CSVs (under 2 MB) | Licence CC BY-NC-ND 4.0. The Ethereum payoff CSV (§8) and the attempt archive (§9) are downloaded with approval; the BSC file is not | | Poison-Hunter full data | Withheld; "contact us", with no address published | Request needed | | Forta labelled datasets | MIT, Etherscan-derived address labels | No poisoning category, no loss transactions | | Etherscan labels | Underlie Forta and Poison-Hunter ground truth | Terms require written permission for ML or dataset use | -## 8. Tsuchiya et al. payoff transfers (`ml/tsuchiya.py`, `tsuchiya-payoff/1`) +## 8. Tsuchiya et al. payoff transfers (`ml/tsuchiya.py`, `tsuchiya-payoff/2`) **Source.** - `payoff_transfers_ethereum.csv` from KiltHub DOI 10.1184/R1/29212703.v1, CC BY-NC-ND 4.0. @@ -171,7 +171,8 @@ ML_RESEARCH_PLAN.md §5. - token contract (`addr`); - payer, the victim (`topics_from_addr`); - recipient, the lookalike (`topics_to_addr`); -- amount (float-encoded base units, plus USD); +- amount in base units, printed from a PostgreSQL `real` (float4), plus the source's + historical USD valuation; - `is_sender_victim` (always `True`); - leading and trailing matched digits; - the intended address. @@ -182,7 +183,13 @@ ML_RESEARCH_PLAN.md §5. - One row per transaction: 1,502 payers and 1,551 lookalikes. - Blocks 16,060,625–20,207,365. - Tokens: USDT 1,154, USDC 543, DAI 36, other 5. None are native ETH. -- 41 amounts cannot be represented exactly as stored, so only `value_usd` is used. +- Amount precision (corrected in Phase 11.3; Phase 11.2 reported 41 inexact amounts + using the float64 limit): float4 is exact only up to 2^24 base units, so 1,644 amounts + are approximations and 94 are exact. Each record keeps the verbatim source text, a + precision class, and a human amount only for tokens with known decimals (USDT, USDC, + DAI). USD values stay the source's valuation and are never recomputed. +- Identity: `payoff_id` = chain, transaction, token, payer, recipient (the source has no + log index); 0 duplicates. **How it is used.** - **As outcome evidence only: a victim paid a lookalike.** It contains no planting @@ -192,3 +199,18 @@ ML_RESEARCH_PLAN.md §5. at least 3 leading and 4 trailing matches, and ends in mid-2024. - **Per-event attribution.** A payoff to a different lookalike of the same address (one case, line 74) is a loss for the victim, not an outcome of that Poison-Hunter event. + +## 9. Tsuchiya et al. attempt archive (`ml/tsuchiya_archive.py`, `tsuchiya-archive/1`) + +- `address_poisoning_ethereum.sql.gz`: a PostgreSQL dump of 34,905,969 token transfers + (July 2022 to June 2024), each flagged intended, zero-value, tiny, counterfeit, payoff, + unconfirmed payoff or uncategorized. It is streamed, never executed; only rows touching a + target manifest are kept, in a local SQLite subset. +- Its categories are the source's heuristic labels. Every poisoning row meets the source's + 3+4 lookalike rule. They are not loaded as `LabelRecord`s. +- **Payoff-linked attempts** are the latest archive attempt by the paid lookalike against + the victim before the payoff. They become `PoisoningEvent`s only inside review packets + (`ml/reconcile.py`, coverage `unavailable`, `candidate_method` + `tsuchiya-archive:latest-attempt-before-payoff`). A label comes only from an independent + review decision. +- Full results, format and limitations: ML_CROSS_DATASET_VALIDATION.md. diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index b30855f..0d7491d 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -1,7 +1,10 @@ # ML research plan: wallet-centric poisoning detection (Phase 11.2) Status: infrastructure done, gates B and D fail (no verified labels), and no model is trained -for this task. The Tsuchiya et al. payoff cross-check is done (§6). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). +for this task. The Tsuchiya et al. payoff cross-check (§6) and the attempt-archive +reconciliation (§7, Phase 11.3) are done; the next experiment is in +[ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md) §25. Data model and labels: +[ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). @@ -90,11 +93,11 @@ at 26 requests each, 10% retries, 4 requests/s. archive indexer would provide, replaces bisection. - None of this has been run, and none is authorized. -## 5. External data (checked on 2026-11-02; only the Ethereum payoff CSV downloaded) +## 5. External data (checked on 2026-11-02) | Source | Verified facts | Fit | Blocker | |---|---|---|---| -| Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. KiltHub DOI 10.1184/R1/29212703.v1 | Files: `payoff_transfers_ethereum.csv` (482 KB, **downloaded with approval, parsed**: 1,738 token payoffs, no ETH), `payoff_transfers_bsc.csv` (1.33 MB), `address_poisoning_ethereum.sql.gz` (2.32 GB, the attempt table). Licence CC BY-NC-ND 4.0 | Payoffs: independent confirmed losses. The dump: the attempts behind them | NC-ND allows local research use only, with no redistributed derivatives. Each further file needs your approval | +| Tsuchiya et al., "Blockchain Address Poisoning", USENIX Security 2025. KiltHub DOI 10.1184/R1/29212703.v1 | Files: `payoff_transfers_ethereum.csv` (482 KB, **downloaded with approval, parsed**: 1,738 token payoffs, no ETH), `payoff_transfers_bsc.csv` (1.33 MB), `address_poisoning_ethereum.sql.gz` (2.32 GB, **downloaded with approval, streamed**: 34,905,969 transfers, publisher counts reproduced), README and notebook (downloaded). Licence CC BY-NC-ND 4.0 | Payoffs: independent confirmed losses. The archive: the source-labelled attempts behind them | NC-ND allows local research use only, with no redistributed derivatives. The BSC file is not downloaded | | Poison-Hunter (Guan and Li, CCS 2024), `DS2L/Poison-Hunter` | 5 files in the repository, no licence; full data "available on request", with no contact address published | Weak attempt labels | A request is needed; a draft request exists, not sent | | RMIT arXiv 2609.23405 | Claims 4,209 victim transfers; its artifact link showed no files | — | Unverified | | Forta labelled datasets | MIT; Etherscan phish-hack/exploit/heist labels | Contamination checks only | No poisoning category | @@ -126,16 +129,23 @@ whenever the file is present. - The source's declared affix counts equal `affix_match` on all 1,738 rows. - Both CryptoGuard predicates accept all 1,738 lookalikes. The study's 3+4 selection implies this, so it is not recall. - - 41 amounts are float-encoded beyond exact precision. Only `value_usd` is used. + - ~~41 amounts are float-encoded beyond exact precision.~~ Corrected in Phase 11.3 + (issue 13): the source column is float4, so 1,644 of 1,738 amounts are approximations. + Only `value_usd` is used. - **Incidents.** - Three of the four are after the file's last block. - wbtc-1155 is inside the period but was paid in WBTC, and the file has no WBTC payoffs. - None appears in the file. -## 7. Next experiment (highest value, 0 RPC requests) +## 7. Done (Phase 11.3): payoffs turned into reviewable attempt events -**Turn confirmed payoffs into reviewable attempt events using Tsuchiya et al.'s attempt -table.** +Approved and run on 2026-11-02 as planned below; results in +[ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md): +- 1,635 of 1,738 payoffs link to an earlier attempt by the same lookalike; +- 89 of 105 in-definition Poison-Hunter rows match an archive attempt exactly; +- 1,469 payoff-linked attempt events are exported for review. + +Issues 13–20 are in that document's §24. The plan as approved: - **Needs:** - your approval to download `address_poisoning_ethereum.sql.gz` (2.32 GB, CC BY-NC-ND diff --git a/README.md b/README.md index 36e2bc6..9f55852 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ evidence of common ownership ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). | Network, structural and activity-rate analyses (graph propagation, spectral features, robust burst statistics) over stored observations, coverage-aware and point in time | Experimental, **off by default**: evaluated with no measurable gain over the existing detector; available in shadow mode only (see [DETECTION_METHODS.md](DETECTION_METHODS.md)) | | Wallet-signed transactions (incl. native-ETH payments) located by nonce search in snapshots and scans; used by the poisoning detector and the graph; degrades to explicit "unlocated" counts without archive state | Implemented | | Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, approval-gated model registry, offline generalization audit, wallet-history feature infrastructure ([ML.md](ML.md), [ML_GENERALIZATION_AUDIT.md](ML_GENERALIZATION_AUDIT.md)) | Experimental, **research-only** (`ml` extra): AP 0.999 on a development benchmark (not an untouched holdout), false-positive rate 7/43 from 12 benign senders (cluster interval 4% to 36%); the API does not score with it; never creates findings | +| Wallet-centric address-poisoning research: typed event and label model, offline payment verification, candidate rules, point-in-time features, review workflow, and a safe streaming reconciliation of the Poison-Hunter and Tsuchiya et al. (USENIX Security 2025) datasets ([ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md)) | Experimental, **research-only**: no model, because the available labels cannot support a valid supervised benchmark; third-party data stays local (CC BY-NC-ND / unlicensed) | | Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals | Not yet | ## Quick start diff --git a/docs/ml/proposal-next-dataset.md b/docs/ml/proposal-next-dataset.md index 7a6be7c..e836951 100644 --- a/docs/ml/proposal-next-dataset.md +++ b/docs/ml/proposal-next-dataset.md @@ -9,6 +9,12 @@ ML_GENERALIZATION_AUDIT.md §16–17. claims below were corrected: the 0.069 bound (§11.2) is conditional, not a population bound, and the CSV header is aligned, not shifted. See ML_PILOT_AUDIT.md and ML_RESEARCH_PLAN.md. +**Phase 11.3 (2026-11-02):** Tsuchiya et al.'s attempt archive was reconciled offline (0 RPC +requests; ML_CROSS_DATASET_VALIDATION.md). It confirms that the pilot's sample lies mostly +inside a well-documented attempt population, and it yields 1,469 payoff-linked attempts for +independent review. It does not change §11, and it supplies no verified negatives. Any +collection for negatives still needs a new, separately approved RPC cap. + **Pilot verdict: option B as costed here is not viable.** Cost per wallet is about twice the §7 estimate, the free endpoint's throughput is about a third of the Phase 11 figure, and no positive was confirmed. See §11 before deciding on B, C or stopping. From 76acf7e256e0d0b099aad016b6e58ebb3b391cb3 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 09:03:09 +0300 Subject: [PATCH 18/92] docs(ml): regenerate cross-dataset and poisoning tables at 8731690 Co-Authored-By: Claude Opus 5.5 --- ML_CROSS_DATASET_TABLES.md | 4 ++-- ML_POISONING_TABLES.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ML_CROSS_DATASET_TABLES.md b/ML_CROSS_DATASET_TABLES.md index 34724a8..583691a 100644 --- a/ML_CROSS_DATASET_TABLES.md +++ b/ML_CROSS_DATASET_TABLES.md @@ -1,6 +1,6 @@ # Cross-dataset validation tables (Phase 11.3) -Generated by `cryptoguard ml cross-dataset-report` from local, git-ignored files (0 RPC requests) at git `2a783978ce7b03aa018a6b01b5427df67a845e36` with uncommitted changes. Narrative and limitations: [ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md). +Generated by `cryptoguard ml cross-dataset-report` from local, git-ignored files (0 RPC requests) at git `873169068909dbdf70d07a8b3cb27079aa9ec311`. Narrative and limitations: [ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md). ## Source and scan @@ -128,4 +128,4 @@ Payment pairs by temporal category: address/before_planting 1, victim/after_plan | 7 Baseline comparability | fail | the archive holds only poisoning-related transfers, not the wallet histories the deterministic detector needs, so both cannot run on the same observations | | 8 Operational usefulness | fail | alert volume on ordinary wallets is known only from 27 recorded wallet-days; 1,635 payoff-linked attempts are retrospective, not prospective | -Reconciliation runtime 6.1 s, peak RSS 339 MiB. +Reconciliation runtime 5.7 s, peak RSS 339 MiB. diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md index bed0f42..235fde1 100644 --- a/ML_POISONING_TABLES.md +++ b/ML_POISONING_TABLES.md @@ -1,7 +1,7 @@ # ML Phase 11.2 tables Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). -Git `2a783978ce7b03aa018a6b01b5427df67a845e36`; runtime 12.16 s (per-window generation memory is in the JSON report). +Git `873169068909dbdf70d07a8b3cb27079aa9ec311`; runtime 5.74 s (per-window generation memory is in the JSON report). ## Poison-Hunter sample From a273f8ad67006238b8558a1d6b7fb319f3911f30 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 10:22:28 +0300 Subject: [PATCH 19/92] feat(ml): frozen stratified review sample from the payoff-linked queue `cryptoguard ml freeze-review-sample` draws, once and before any review, a stratified sample of the payoff-linked review packets: one representative per campaign group (victim, lookalike, planting tx, imitated address), strata subtype x year x rival lookalike, fixed subtype quotas (60 in all) split proportionally with at least one per cell, keyed SHA-256 ranking, ordered reserves, design weights. Writes a blinded reviewer sheet, a separate unblinding key and a manifest with a selection hash; refuses to re-draw once frozen. Offline, 0 RPC requests. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 31 +++ src/cryptoguard/ml/review_sample.py | 297 ++++++++++++++++++++++++++++ tests/unit/test_ml_review_sample.py | 209 ++++++++++++++++++++ 3 files changed, 537 insertions(+) create mode 100644 src/cryptoguard/ml/review_sample.py create mode 100644 tests/unit/test_ml_review_sample.py diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 81ded20..bc964b3 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -84,6 +84,14 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None cr.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) cr.add_argument("--out", type=Path, default=ML_DIR / "poisoning") cr.add_argument("--tables", type=Path, default=Path("ML_CROSS_DATASET_TABLES.md")) + fr = ml.add_parser( + "freeze-review-sample", + help="draw the stratified review sample once, before any review (offline, no RPC)", + ) + fr.add_argument( + "--queue", type=Path, default=ML_DIR / "poisoning" / "review_packets_payoff_linked.jsonl" + ) + fr.add_argument("--out", type=Path, default=ML_DIR / "poisoning" / "review_sample") bz = ml.add_parser("bench-archive", help="archive-scanner scaling on synthetic dumps") bz.add_argument("sizes", type=int, nargs="+") bz.add_argument("--work", type=Path, default=ML_DIR / "bench") @@ -125,6 +133,8 @@ def run(args: argparse.Namespace) -> int: return _scan_archive(args) if args.ml_command == "cross-dataset-report": return _cross_dataset_report(args) + if args.ml_command == "freeze-review-sample": + return _freeze_review_sample(args) if args.ml_command == "bench-archive": import json @@ -261,6 +271,27 @@ def _cross_dataset_report(args: argparse.Namespace) -> int: return 0 +def _freeze_review_sample(args: argparse.Namespace) -> int: + from cryptoguard.ml.review_sample import ReviewSampleError, freeze + + try: + manifest, written = freeze(args.queue, args.out) + except FileNotFoundError as exc: + print(f"error [FileNotFoundError]: {exc} (run `cryptoguard ml cross-dataset-report`)") + return 1 + except ReviewSampleError as exc: + print(f"error [{type(exc).__name__}]: {exc}") + return 1 + for row in manifest["strata_table"]: + print(f"{row['stratum']:36} {row['groups']:5} groups {row['selected']:3} selected") + state = "Froze" if written else "Already frozen (unchanged):" + print( + f"{state} {len(manifest['selected'])} of {manifest['queue_packets']} packets in " + f"{args.out}; selection sha256 {manifest['selection_sha256']} (0 RPC requests)." + ) + return 0 + + def _shadow(args: argparse.Namespace) -> int: import json diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py new file mode 100644 index 0000000..1e60e61 --- /dev/null +++ b/src/cryptoguard/ml/review_sample.py @@ -0,0 +1,297 @@ +"""Frozen, stratified review sample from the payoff-linked review queue (offline, 0 RPC). + +The sample is drawn once, before any review. ``freeze`` writes a manifest whose selection +hash is committed to the repository; the manifest, reviewer sheet and unblinding key hold +addresses derived from CC BY-NC-ND data and stay in the git-ignored data directory. +Selection is a keyed SHA-256 ranking rather than a seeded RNG, so it is identical across +Python versions and can be checked by hand. + +Design (``SAMPLE_VERSION``): + +1. Campaign groups: packets sharing a victim, lookalike, planting transaction or imitated + address are linked. Each group contributes one representative (its lowest rank), so no + two sampled packets share a victim or a campaign. +2. Strata: subtype x calendar year (by block height) x whether a rival lookalike existed. +3. Allocation: a fixed quota per subtype (all representatives when there are fewer), split + across that subtype's cells in proportion to size, at least one per non-empty cell + (largest remainder). +4. Within a cell the lowest ranks are selected; the rest, in rank order, are reserves, + used only to replace an item that cannot be reviewed. +5. The reviewer sheet is blinded: no source label, subtype, imitated address, payoff or + evidence summary, and its order is a separate ranking unrelated to the strata. The + unblinding key (full packets) is a separate file. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +from collections import Counter, defaultdict +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +from pydantic import ValidationError + +from cryptoguard.ml.events import _UnionFind +from cryptoguard.ml.review import ReviewPacket + +SAMPLE_VERSION = "review-sample/1" +SHEET_SCHEMA = "review-sheet/1" +SEED = "cryptoguard-review-sample/1" # fixed before the only draw; never re-seeded +# Representatives per subtype (60 in all). Subtypes not listed are not sampled. +SUBTYPE_QUOTA: dict[str, int] = { + "fake_token": 24, + "spoofed_transfer_from": 24, + "dust": 9, + "zero_value": 3, +} +# First block of each calendar year (UTC), from a block explorer; a packet within a few +# blocks of a boundary could fall in the neighbouring year, which does not affect validity. +YEAR_STARTS: tuple[tuple[int, int], ...] = ((2024, 18_908_895), (2023, 16_308_190)) +MANIFEST = "sample_manifest.json" +SHEET = "reviewer_sheet.jsonl" +KEY = "unblinding_key.jsonl" + +Stratum = tuple[str, int, bool] + + +class ReviewSampleError(ValueError): + pass + + +class SampleFrozenError(ReviewSampleError): + """A different sample is already frozen in the output directory.""" + + +def year(block: int) -> int: + return next((y for y, start in YEAR_STARTS if block >= start), 2022) + + +def stratum(p: ReviewPacket) -> Stratum: + return (p.subtype, year(p.observation_block), bool(p.competing_lookalikes)) + + +def stratum_name(s: Stratum) -> str: + return f"{s[0]}|{s[1]}|{'rival' if s[2] else 'no_rival'}" + + +def rank(*parts: str) -> str: + return hashlib.sha256("|".join((SEED, *parts)).encode()).hexdigest() + + +def load_queue(path: Path) -> list[ReviewPacket]: + """All or nothing: a malformed line or a repeated event id rejects the whole queue.""" + packets: list[ReviewPacket] = [] + seen: set[str] = set() + for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + if not line.strip(): + continue + try: + p = ReviewPacket.model_validate(json.loads(line)) + except (json.JSONDecodeError, ValidationError) as exc: + raise ReviewSampleError(f"{path}: line {i}: {exc}") from None + if p.victim_event_id in seen: + raise ReviewSampleError(f"{path}: line {i}: repeated event {p.victim_event_id}") + seen.add(p.victim_event_id) + packets.append(p) + if not packets: + raise ReviewSampleError(f"{path}: empty review queue") + return packets + + +def groups(packets: Sequence[ReviewPacket]) -> dict[str, str]: + """``victim_event_id -> group root``.""" + uf = _UnionFind() + for p in packets: + node = "e:" + p.victim_event_id + uf.find(node) + for kind, value in ( + ("v", p.victim), + ("l", p.lookalike), + ("t", p.planting_tx), + ("i", p.imitated), + ): + if value: + uf.union(node, f"{kind}:{value.lower()}") + return {p.victim_event_id: uf.find("e:" + p.victim_event_id) for p in packets} + + +def allocate[K: tuple[Any, ...]](sizes: dict[K, int], quota: int) -> dict[K, int]: + """Proportional allocation with at least one per non-empty cell (largest remainder).""" + total = sum(sizes.values()) + if quota >= total: + return dict(sizes) + cells = sorted(sizes) + if quota < sum(1 for c in cells if sizes[c]): + raise ReviewSampleError(f"quota {quota} is below the number of non-empty cells") + ideal = {c: quota * sizes[c] / total for c in cells} + n = {c: min(sizes[c], max(1, math.floor(ideal[c]))) if sizes[c] else 0 for c in cells} + + def pick(eligible: list[K], key: Callable[[K], float]) -> K: + return max(eligible, key=lambda c: (key(c), c)) + + while sum(n.values()) < quota: + c = pick([c for c in cells if n[c] < sizes[c]], lambda c: ideal[c] - n[c]) + n[c] += 1 + while sum(n.values()) > quota: + c = pick([c for c in cells if n[c] > 1], lambda c: n[c] - ideal[c]) + n[c] -= 1 + return n + + +def blind(p: ReviewPacket, item: int) -> dict[str, Any]: + """The reviewer's view: where to look on a block explorer, nothing about the source's + verdict or the later payment.""" + return { + "schema_version": SHEET_SCHEMA, + "item": item, + "victim_event_id": p.victim_event_id, + "chain_id": 1, + "wallet": p.victim, + "address_under_review": p.lookalike, + "transaction": p.planting_tx, + "block": p.observation_block, + } + + +def _canonical(obj: Any) -> bytes: + return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode() + + +def _jsonl(rows: Sequence[dict[str, Any]]) -> bytes: + return b"".join(json.dumps(r, sort_keys=True).encode() + b"\n" for r in rows) + + +def _write(path: Path, data: bytes) -> None: + tmp = path.with_name(path.name + ".tmp") + tmp.write_bytes(data) + os.replace(tmp, path) + + +def draw(packets: Sequence[ReviewPacket], queue_sha256: str) -> dict[str, Any]: + """The full sample (manifest, sheet and key contents); writes nothing.""" + by_id = {p.victim_event_id: p for p in packets} + root = groups(packets) + members: dict[str, list[str]] = defaultdict(list) + for event_id, g in root.items(): + members[g].append(event_id) + reps = [min(ids, key=lambda e: rank("rep", e)) for ids in members.values()] + group_size = {e: len(members[root[e]]) for e in reps} + + cells: dict[Stratum, list[str]] = defaultdict(list) + for e in reps: + cells[stratum(by_id[e])].append(e) + for ids in cells.values(): + ids.sort(key=lambda e: rank("select", e)) + packets_per_cell = Counter(stratum(p) for p in packets) + + alloc: dict[Stratum, int] = {} + for subtype in sorted({s[0] for s in cells}): + sizes = {s: len(ids) for s, ids in cells.items() if s[0] == subtype} + quota = SUBTYPE_QUOTA.get(subtype, 0) + alloc |= allocate(sizes, quota) if quota else dict.fromkeys(sizes, 0) + + selected: list[dict[str, Any]] = [] + reserves: dict[str, list[str]] = {} + strata: list[dict[str, Any]] = [] + for s in sorted(cells): + ids, n = cells[s], alloc[s] + weight = round(len(ids) / n, 6) if n else None + strata.append( + { + "stratum": stratum_name(s), + "packets": packets_per_cell[s], + "groups": len(ids), + "selected": n, + "weight": weight, + } + ) + selected += [ + { + "victim_event_id": e, + "stratum": stratum_name(s), + "group_size": group_size[e], + "weight": weight, + } + for e in ids[:n] + ] + reserves[stratum_name(s)] = ids[n:] + + order = sorted((r["victim_event_id"] for r in selected), key=lambda e: rank("order", e)) + sheet = [blind(by_id[e], i) for i, e in enumerate(order, start=1)] + role = {r["victim_event_id"]: ("selected", r["stratum"]) for r in selected} + for name, ids in reserves.items(): + role |= {e: ("reserve", name) for e in ids} + key = [ + {"role": role[e][0], "stratum": role[e][1], "packet": by_id[e].model_dump(mode="json")} + for e in sorted(role) + ] + design = { + "seed": SEED, + "subtype_quota": SUBTYPE_QUOTA, + "year_starts": dict(YEAR_STARTS), + "group_links": ["victim", "lookalike", "planting_tx", "imitated"], + "strata": ["subtype", "year", "rival_lookalike"], + "allocation": "fixed quota per subtype; proportional within subtype, at least 1 per " + "non-empty cell, largest remainder", + "ranking": "sha256(seed|purpose|victim_event_id), lowest first", + } + selection = { + "sample_version": SAMPLE_VERSION, + "queue_sha256": queue_sha256, + "design": design, + "selected": selected, + "reserves": reserves, + } + group_sizes = Counter(len(ids) for ids in members.values()) + manifest = { + **selection, + "selection_sha256": hashlib.sha256(_canonical(selection)).hexdigest(), + "queue_packets": len(packets), + "groups": { + "count": len(members), + "multi_packet": sum(v for k, v in group_sizes.items() if k > 1), + "largest": max(group_sizes), + }, + "strata_table": strata, + "rpc_requests": 0, + } + return {"manifest": manifest, "sheet": sheet, "key": key} + + +def freeze(queue: Path, out_dir: Path) -> tuple[dict[str, Any], bool]: + """Draw and write the sample once. Returns ``(manifest, newly_written)``. + + If a manifest already exists, the draw is recomputed and compared: identical selection + -> nothing is rewritten; anything else (changed queue, design or code) raises + ``SampleFrozenError`` and leaves the frozen files untouched.""" + from cryptoguard.ml.cross_dataset import git_state + + queue_sha = hashlib.sha256(queue.read_bytes()).hexdigest() + sample = draw(load_queue(queue), queue_sha) + manifest = sample["manifest"] + existing = out_dir / MANIFEST + if existing.exists(): + old = json.loads(existing.read_text(encoding="utf-8")) + if old.get("queue_sha256") != queue_sha: + raise SampleFrozenError( + f"{existing}: the review queue changed after the sample was frozen" + ) + if old.get("selection_sha256") != manifest["selection_sha256"]: + raise SampleFrozenError(f"{existing}: a different sample is already frozen") + return old, False + + out_dir.mkdir(parents=True, exist_ok=True) + sheet, key = _jsonl(sample["sheet"]), _jsonl(sample["key"]) + manifest["files"] = { + SHEET: hashlib.sha256(sheet).hexdigest(), + KEY: hashlib.sha256(key).hexdigest(), + } + manifest["git"] = git_state() + _write(out_dir / SHEET, sheet) + _write(out_dir / KEY, key) + _write(existing, json.dumps(manifest, indent=1, sort_keys=True).encode() + b"\n") + return manifest, True diff --git a/tests/unit/test_ml_review_sample.py b/tests/unit/test_ml_review_sample.py new file mode 100644 index 0000000..523bbd6 --- /dev/null +++ b/tests/unit/test_ml_review_sample.py @@ -0,0 +1,209 @@ +"""Frozen review sample: allocation, one packet per campaign group, determinism, blinding, +and refusal to re-draw once frozen. + +Synthetic packets only. Each test states the invariant it guards. +""" + +from __future__ import annotations + +import json +from collections import Counter +from pathlib import Path + +import pytest + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.review import ReviewPacket + +B2022, B2023, B2024 = 16_000_000, 17_000_000, 19_000_000 + + +def addr(n: int) -> str: + return "0x" + f"{n:040x}" + + +def pkt( + n: int, + *, + subtype: str = "fake_token", + block: int = B2023, + victim: int | None = None, + lookalike: int | None = None, + rival: bool = False, +) -> ReviewPacket: + return ReviewPacket( + victim_event_id=f"{n:016x}", + victim=addr(victim if victim is not None else 10_000 + n), + lookalike=addr(lookalike if lookalike is not None else 20_000 + n), + imitated=addr(30_000 + n), + planting_tx="0x" + f"{n:064x}", + observation_block=block + n, + subtype=subtype, + evidence_summary=f"Source-labelled poisoning transfer {n}; the victim paid later.", + coverage_limitations="no wallet history observed", + source_labels=(f"tsuchiya-archive:{subtype}", "tsuchiya-payoff:confirmed"), + competing_lookalikes=(addr(40_000 + n),) if rival else (), + payment_evidence=(f"0x{n + 7:064x} block {block + n + 50} after_planting",), + ) + + +def queue() -> list[ReviewPacket]: + out: list[ReviewPacket] = [] + n = 0 + for subtype, block, rival, count in ( + ("fake_token", B2023, False, 40), + ("fake_token", B2023, True, 50), + ("fake_token", B2024, True, 6), + ("spoofed_transfer_from", B2022, False, 20), + ("spoofed_transfer_from", B2023, True, 60), + ("dust", B2023, True, 12), + ("zero_value", B2023, True, 2), + ("unknown", B2023, False, 3), + ): + for _ in range(count): + n += 1 + out.append(pkt(n, subtype=subtype, block=block, rival=rival)) + return out + + +def write_queue(path: Path, packets: list[ReviewPacket]) -> Path: + path.write_text("".join(p.model_dump_json() + "\n" for p in packets), encoding="utf-8") + return path + + +def test_allocation_is_proportional_with_one_per_cell_and_exact_total() -> None: + sizes = {("a",): 300, ("b",): 100, ("c",): 2, ("d",): 0} + n = rs.allocate(sizes, 20) + assert sum(n.values()) == 20 + assert n[("c",)] == 1 + assert n[("d",)] == 0 + assert n[("a",)] > n[("b",)] > n[("c",)] + assert rs.allocate(sizes, 500) == sizes # take-all below quota + assert rs.allocate(sizes, 20) == n # deterministic + + +def test_allocation_refuses_more_cells_than_quota() -> None: + with pytest.raises(rs.ReviewSampleError): + rs.allocate({("a",): 5, ("b",): 5, ("c",): 5}, 2) + + +def test_quotas_strata_and_weights() -> None: + sample = rs.draw(queue(), "q") + m = sample["manifest"] + per_subtype = Counter(r["stratum"].split("|")[0] for r in m["selected"]) + assert per_subtype == {"fake_token": 24, "spoofed_transfer_from": 24, "dust": 9, + "zero_value": 2} # fmt: skip + assert "unknown" not in per_subtype # unlisted subtypes are not sampled + table = {row["stratum"]: row for row in m["strata_table"]} + assert table["fake_token|2024|rival"]["selected"] >= 1 + assert table["spoofed_transfer_from|2022|no_rival"]["groups"] == 20 + for row in table.values(): # weights reproduce each cell's group count + if row["selected"]: + got = sum(r["weight"] for r in m["selected"] if r["stratum"] == row["stratum"]) + assert got == pytest.approx(row["groups"]) + + +def test_one_packet_per_victim_and_campaign_group() -> None: + packets = queue() + # Five packets against one victim, two sharing a lookalike with another victim. + packets += [pkt(900 + i, victim=1, rival=True) for i in range(5)] + packets += [pkt(910, lookalike=20_000 + 900), pkt(911, victim=10_000 + 910)] + sample = rs.draw(packets, "q") + root = rs.groups(packets) + chosen = [r["victim_event_id"] for r in sample["manifest"]["selected"]] + assert len({root[e] for e in chosen}) == len(chosen) + chained = {root[f"{n:016x}"] for n in (900, 901, 902, 903, 904, 910, 911)} + assert len(chained) == 1 # victim -> lookalike -> lookalike links form one group + by_id = {p.victim_event_id: p for p in packets} + assert len({by_id[e].victim for e in chosen}) == len(chosen) + + +def test_reserves_are_disjoint_ordered_and_cover_every_representative() -> None: + m = rs.draw(queue(), "q")["manifest"] + chosen = {r["victim_event_id"] for r in m["selected"]} + reserved = [e for ids in m["reserves"].values() for e in ids] + assert not chosen & set(reserved) + assert len(chosen) + len(reserved) == m["groups"]["count"] + for ids in m["reserves"].values(): + assert ids == sorted(ids, key=lambda e: rs.rank("select", e)) + + +def test_draw_is_deterministic_and_independent_of_input_order() -> None: + packets = queue() + a = rs.draw(packets, "q") + b = rs.draw(list(reversed(packets)), "q") + assert a == b + assert ( + a["manifest"]["selection_sha256"] + != rs.draw(packets, "other")["manifest"]["selection_sha256"] + ) # the queue hash is part of the frozen selection + + +def test_reviewer_sheet_is_blinded() -> None: + packets = queue() + sample = rs.draw(packets, "q") + by_id = {p.victim_event_id: p for p in packets} + allowed = {"schema_version", "item", "victim_event_id", "chain_id", "wallet", + "address_under_review", "transaction", "block"} # fmt: skip + for line in sample["sheet"]: + assert set(line) == allowed + p = by_id[line["victim_event_id"]] + text = json.dumps(line) + for leaked in (p.imitated, p.subtype, *p.payment_evidence, *p.competing_lookalikes): + assert leaked + assert leaked.split()[0] not in text + items = [line["item"] for line in sample["sheet"]] + assert items == list(range(1, len(items) + 1)) + ids = [line["victim_event_id"] for line in sample["sheet"]] + assert ids == sorted(ids, key=lambda e: rs.rank("order", e)) # not grouped by stratum + key = {k["packet"]["victim_event_id"]: k for k in sample["key"]} + assert all(key[e]["role"] == "selected" for e in ids) # the key unblinds every item + + +def test_freeze_writes_once_then_verifies_and_refuses_a_redraw(tmp_path: Path) -> None: + q = write_queue(tmp_path / "queue.jsonl", queue()) + out = tmp_path / "sample" + manifest, written = rs.freeze(q, out) + assert written + assert manifest["rpc_requests"] == 0 + files = {p.name: p.read_bytes() for p in out.iterdir()} + assert set(files) == {rs.MANIFEST, rs.SHEET, rs.KEY} # no temporary files left + again, written = rs.freeze(q, out) + assert not written + assert again["selection_sha256"] == manifest["selection_sha256"] + assert {p.name: p.read_bytes() for p in out.iterdir()} == files + + write_queue(q, queue()[:-1]) + with pytest.raises(rs.SampleFrozenError, match="queue changed"): + rs.freeze(q, out) + assert {p.name: p.read_bytes() for p in out.iterdir()} == files # untouched + + +def test_freeze_is_reproducible_in_a_fresh_directory(tmp_path: Path) -> None: + q = write_queue(tmp_path / "queue.jsonl", queue()) + a, _ = rs.freeze(q, tmp_path / "a") + b, _ = rs.freeze(q, tmp_path / "b") + assert a["selection_sha256"] == b["selection_sha256"] + assert a["files"] == b["files"] + for name in (rs.SHEET, rs.KEY): + assert (tmp_path / "a" / name).read_bytes() == (tmp_path / "b" / name).read_bytes() + + +def test_malformed_or_repeated_packets_reject_the_whole_queue(tmp_path: Path) -> None: + packets = queue() + q = write_queue(tmp_path / "queue.jsonl", [*packets, packets[0]]) + with pytest.raises(rs.ReviewSampleError, match="repeated event"): + rs.load_queue(q) + q.write_text(packets[0].model_dump_json() + "\n{not json\n", encoding="utf-8") + with pytest.raises(rs.ReviewSampleError, match="line 2"): + rs.load_queue(q) + q.write_text("", encoding="utf-8") + with pytest.raises(rs.ReviewSampleError, match="empty"): + rs.load_queue(q) + assert not (tmp_path / "sample").exists() + + +def test_year_bins_follow_block_height() -> None: + assert rs.year(16_308_189) == 2022 + assert rs.year(16_308_190) == 2023 + assert rs.year(18_908_895) == 2024 From 84ac3c065fd7831b31b8c553867e111715b05f3c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 10:24:30 +0300 Subject: [PATCH 20/92] docs(ml): freeze the payoff-linked review sample and fix the protocol Records the frozen review-sample/1 draw (60 of 1,469 packets, 15 strata, one per campaign group) with SHA-256 commitments for the input queue, selection, reviewer sheet, unblinding key and manifest, made before any review. Adds the review protocol and pre-specified analysis plan. The sample files themselves stay local (CC BY-NC-ND derived addresses). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ ML.md | 5 +- ML_CROSS_DATASET_VALIDATION.md | 75 +++++++++++++++++++++++- ML_RESEARCH_PLAN.md | 5 +- docs/ml/review-protocol.md | 101 +++++++++++++++++++++++++++++++++ 5 files changed, 185 insertions(+), 5 deletions(-) create mode 100644 docs/ml/review-protocol.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c2d7c61..f56865b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,10 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m (Phase 11.2 reported 41). Payoffs now carry a stable identity and provenance. - Fixed: a killed scan's stale SQLite journal is removed before a rescan. - Review packets (v2) carry competing lookalikes and payment evidence. +- Added `ml freeze-review-sample`. Before any review, it draws a stratified sample of 60 of + the 1,469 payoff-linked packets, one per campaign group. It writes a blinded reviewer + sheet, a separate unblinding key and a hash-committed manifest, and refuses to draw + again. The protocol and analysis plan are in docs/ml/review-protocol.md. - Docs: ML_CROSS_DATASET_VALIDATION.md, ML_CROSS_DATASET_TABLES.md. ### Wallet-centric poisoning research platform (Phase 11.2) diff --git a/ML.md b/ML.md index 7981c81..ca9906c 100644 --- a/ML.md +++ b/ML.md @@ -41,7 +41,10 @@ method and decision log. - Phase 11.3: `ml/fetch.py` (verified, resumable download of one approved file), `ml/tsuchiya.py` and `ml/tsuchiya_archive.py` (payoff list and streaming attempt-archive parser, never executes SQL), `ml/reconcile.py` and `ml/cross_dataset.py` - (`cryptoguard ml scan-archive`, `cryptoguard ml cross-dataset-report`). + (`cryptoguard ml scan-archive`, `cryptoguard ml cross-dataset-report`), + `ml/review_sample.py` (frozen, blinded review sample: + `cryptoguard ml freeze-review-sample`; protocol in + [docs/ml/review-protocol.md](docs/ml/review-protocol.md)). - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. diff --git a/ML_CROSS_DATASET_VALIDATION.md b/ML_CROSS_DATASET_VALIDATION.md index 0f222ab..9f093d7 100644 --- a/ML_CROSS_DATASET_VALIDATION.md +++ b/ML_CROSS_DATASET_VALIDATION.md @@ -401,6 +401,7 @@ cryptoguard ml scan-archive # verifies size/MD5/SHA-256, one pass, cach cryptoguard ml cross-dataset-report # reconciliation; writes ML_CROSS_DATASET_TABLES.md cryptoguard ml poisoning-report # Phase 11.2 tables, including the payoff cross-check cryptoguard ml bench-archive 1000 10000 100000 +cryptoguard ml freeze-review-sample # draws once (§26); later runs only verify ``` Each run records the git commit (Phase 11.2 report), source SHA-256, parser and @@ -468,8 +469,8 @@ matched legitimate look-alike interactions as negatives.** - by year; - by whether a rival lookalike existed; - with one packet per victim and campaign group. - About 60 packets give the 30 needed per class with margin. Reviewers would confirm each - planting on a block explorer from the packet's evidence, with no model score shown. + Reviewers confirm each planting on a block explorer, with no model score shown. **The + sample of 60 is frozen (§26).** - **Negatives.** For the same victims, take transfers from addresses that share 3+4 or more characters with a real counterparty but are legitimate, for example a counterparty's own second wallet. Finding and verifying them needs the victims' wallet histories. @@ -481,3 +482,73 @@ matched legitimate look-alike interactions as negatives.** - for negatives, the victims' full transfer histories over the review window; - a frozen sampling manifest, written before any review. - **What not to do:** no broad crawl, no paid service, no labels inferred from overlap. + +## 26. Frozen review sample (2026-11-02, 0 RPC requests) + +The positive half of §25 is ready for review. The sample was drawn once, before any review, +by `cryptoguard ml freeze-review-sample` (`ml/review_sample.py`, `review-sample/1`) at +commit `a273f8a` on a clean tree. Reviewer instructions and the analysis plan, fixed at the +same time: [docs/ml/review-protocol.md](docs/ml/review-protocol.md). + +- **Design.** + - **Campaign groups.** Packets that share a victim, lookalike, planting transaction or + imitated address form one group: 1,469 packets in 1,395 groups, 62 of them with more + than one packet (at most 6). Each group contributes one representative, so no two + sampled packets share a victim or campaign. + - **Strata.** Subtype × year (by block height) × whether a rival lookalike existed. + - **Allocation.** Quotas per subtype: fake token 24, spoofed `transferFrom` 24, dust 9, + zero-value 3 (all of them). Within a subtype, the quota is split in proportion to + stratum size, with at least one per non-empty stratum. + - **Selection.** A keyed SHA-256 ranking with a fixed seed, so it is reproducible by hand + and independent of input order. The other 1,335 representatives are ordered reserves. + - **Weights.** Each item's design weight is its stratum's group count divided by its + selected count. +- **Result.** 60 items: + - by rival lookalike: 38 with, 22 without; + - by year: 6 from 2022, 46 from 2023, 8 from 2024. + +| Stratum (subtype, year, rival) | Groups | Selected | +|---|---|---| +| dust, 2023, no rival | 8 | 1 | +| dust, 2023, rival | 25 | 5 | +| dust, 2024, no rival | 8 | 1 | +| dust, 2024, rival | 9 | 2 | +| fake token, 2023, no rival | 293 | 10 | +| fake token, 2023, rival | 339 | 11 | +| fake token, 2024, no rival | 39 | 1 | +| fake token, 2024, rival | 59 | 2 | +| spoofed transferFrom, 2022, no rival | 103 | 4 | +| spoofed transferFrom, 2022, rival | 58 | 2 | +| spoofed transferFrom, 2023, no rival | 103 | 4 | +| spoofed transferFrom, 2023, rival | 330 | 12 | +| spoofed transferFrom, 2024, no rival | 1 | 1 | +| spoofed transferFrom, 2024, rival | 17 | 1 | +| zero-value, 2023, rival | 3 | 3 | + +- **Blinding.** The reviewer sheet lists only: + - the wallet; + - the address under review; + - the transaction and block. + + It leaves out the subtype, source labels, imitated address, payoff and rival lookalikes, + and its order is unrelated to the strata. The unblinding key is a separate file. An + explorer still shows the later payment, so the blinding is partial (protocol §6). +- **Commitments.** The files are local and git-ignored. Their hashes, recorded here before + any review, make later changes detectable: + +| Item | SHA-256 | +|---|---| +| review queue `review_packets_payoff_linked.jsonl` (input) | `84f8268e7328b320d49b06808811bb27f821dcedb1319a9d090b1c3b27f42e83` | +| selection (design, queue hash, items, reserves) | `e368beb4c179f02bf916ef3dcbb89c4a8260d17956fa897264959477b5b85a62` | +| `reviewer_sheet.jsonl` | `a0ec4b6e5620cf001e8e048f37cfca5553c24296318a67b86dddd87772814027` | +| `unblinding_key.jsonl` | `407b412f9e97e2aac269af0f0be565223dcfe851412458cee639396b8503bb2d` | +| `sample_manifest.json` | `c38ae31d598bb58c33fcd2d6553823fc1880b25a4b49b8764d32a290bc7dbdc3` | + +- **Safeguards.** + - Rerunning the command only verifies the frozen sample. + - A changed queue or a different draw is refused (`SampleFrozenError`), and the frozen + files are left untouched. +- **Still open.** + - The review itself: two independent reviewers, per the protocol. + - The matched negatives from §25, which need a separately approved RPC cap. + - No label exists until reviewed decisions are imported. diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 0d7491d..133eb57 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -2,8 +2,9 @@ Status: infrastructure done, gates B and D fail (no verified labels), and no model is trained for this task. The Tsuchiya et al. payoff cross-check (§6) and the attempt-archive -reconciliation (§7, Phase 11.3) are done; the next experiment is in -[ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md) §25. Data model and labels: +reconciliation (§7, Phase 11.3) are done. The next experiment is in +[ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md) §25; its review sample of +60 is frozen and waiting for reviewers (§26). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). diff --git a/docs/ml/review-protocol.md b/docs/ml/review-protocol.md new file mode 100644 index 0000000..cf2d872 --- /dev/null +++ b/docs/ml/review-protocol.md @@ -0,0 +1,101 @@ +# Review protocol for the frozen payoff-linked sample (`review-sample/1`) + +This protocol was fixed on 2026-11-02, together with the sample and before any review. The +sample's design and hashes are in +[ML_CROSS_DATASET_VALIDATION.md](../../ML_CROSS_DATASET_VALIDATION.md) §26. + +## 1. What the review is for + +The archive's poisoning categories are Tsuchiya et al.'s own heuristics. The review checks, +independently of them, whether each sampled planting transaction is an address-poisoning +attempt against the listed wallet. Only a reviewed decision can turn a packet into a +`verified_attempt` label (`ml/review.py`). Nothing is labelled from source overlap. + +## 2. Materials + +All three files are local and git-ignored (`data/ml/poisoning/review_sample/`). They hold +addresses derived from CC BY-NC-ND 4.0 data, so share them only with reviewers, for this +review, and never publish them. + +| File | Who sees it | Contents | +|---|---|---| +| `reviewer_sheet.jsonl` | reviewers | 60 items: event id, wallet, address under review, transaction, block | +| `unblinding_key.jsonl` | the maintainer only, after all decisions are in | full packets (subtype, source labels, imitated address, payoff, rival lookalikes) for the 60 items and the 1,335 reserves | +| `sample_manifest.json` | anyone with data access | design, strata, weights, reserves, file hashes | + +Before the review starts, check the hashes. Rerunning `cryptoguard ml freeze-review-sample` +verifies the frozen files and changes nothing. + +## 3. What a reviewer checks, per item + +Use a public block explorer. **No model score exists or is shown.** + +1. Does the transaction exist at the given block, and did it move a token (or a + zero-value transfer record) between the wallet and the address under review? +2. Did the wallet, before that block, transact with a *different* address that shares the + leading and trailing characters of the address under review? Record which address it + was and how many characters match. +3. What kind of token is it: a widely used token, or a contract that imitates one (name, + symbol, decimals)? What is the value: zero, dust, or ordinary? +4. Who initiated the transfer: the wallet itself, or a third party, for example through + `transferFrom` with zero value? +5. Is there a plausible legitimate reason for this interaction? For example, the address + under review is the wallet's own second address, or a known counterparty's. + +## 4. Decisions + +Each reviewer returns one line per item in `poisoning-review/1` format +(`ml/review.py: ReviewDecision`): +- `victim_event_id`; +- `decision`; +- `rationale`, naming the evidence from §3; +- `reviewer` (a pseudonym); +- `reviewed_at` (an ISO time). + +| Decision | Use when | +|---|---| +| `confirmed_poisoning_attempt` | 1–4 show an imitation of a real earlier counterparty with no legitimate explanation | +| `likely_poisoning_attempt` | the pattern fits but one element cannot be checked | +| `confirmed_legitimate_interaction` | 5 shows a legitimate relationship | +| `insufficient_evidence` | the explorer data does not allow a decision | +| `conflicting_evidence` | the evidence points both ways | + +## 5. Rules + +- **Two independent reviewers per item.** Neither sees the other's decisions before both + have submitted. A disagreement stays on record (`resolve_labels` turns it into + `conflicting`). Adjudication, if any, is a third, separately recorded decision. +- **Review blind.** Do not open the unblinding key until all decisions are in. +- **No replacements for difficulty.** An item that is hard or ambiguous gets + `insufficient_evidence` or `conflicting_evidence`. Replacing it would bias the sample. + A reserve (the next one in the same stratum, in manifest order) is used only when an + item cannot be presented at all. The replacement and its reason are recorded. +- **Import is all-or-nothing.** `review.import_reviews` validates every line before + anything is appended. Earlier labels are never overwritten. + +## 6. Known limits of the blinding + +- An explorer page for the wallet also shows the later payment to the address under + review. The payment is not hidden; it is only left off the sheet. +- Every item is a source-flagged candidate, with no decoys, so reviewers may expect most + to be attempts. The rationale requirement and two-reviewer agreement are the + safeguards. Agreement with the source labels measures label validity on payoff-linked + attempts. It is not detector precision. +- The sample covers payoff-linked attempts only: attempts that later succeeded. Its + results do not carry over to attempts in general without the design weights. Even with + them, they cover the 1,469-packet queue, not the whole archive. + +## 7. Analysis plan (fixed in advance) + +- **Primary.** The share of items both reviewers mark `confirmed_poisoning_attempt` or + `likely_poisoning_attempt`. + - Overall and per subtype, with Wilson 95% intervals (unweighted). + - Also a design-weighted estimate for the queue. +- **Agreement.** Raw agreement and Cohen's kappa between the two reviewers. +- **Disagreement with the source.** Every item a reviewer marks + `confirmed_legitimate_interaction` is listed and examined. +- **For scale.** If all 60 items were confirmed, the Wilson 95% lower bound would be 0.94 + overall and 0.86 for each 24-item subtype. The dust (9) and zero-value (3) cells are + descriptive only. +- **Not concluded from this review:** detector precision or recall, theft probability, or + any population rate. From 5f0fc8043de388b561029a0412a584043ff6a732 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 11:13:10 +0300 Subject: [PATCH 21/92] feat(ml): verify the frozen review sample and audit its design verify_frozen checks the five committed hashes (raw bytes, plus the selection hash recomputed from the manifest) and never writes. The design audit recomputes groups, strata, allocation, exact inclusion probabilities and weights from the queue, explains the 1,401 versus 1,395 group count (exploratory links without the imitated address), and adds a stratified estimator with collapsed-strata variance, design-effect Wilson intervals, nonresponse bounds and attempt-level bounds. Corrects the year-boundary comment (values unchanged). Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/review_sample.py | 87 +++++- src/cryptoguard/ml/sample_design.py | 441 ++++++++++++++++++++++++++++ tests/review_fixtures.py | 116 ++++++++ tests/unit/test_ml_sample_design.py | 232 +++++++++++++++ 4 files changed, 874 insertions(+), 2 deletions(-) create mode 100644 src/cryptoguard/ml/sample_design.py create mode 100644 tests/review_fixtures.py create mode 100644 tests/unit/test_ml_sample_design.py diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py index 1e60e61..174d582 100644 --- a/src/cryptoguard/ml/review_sample.py +++ b/src/cryptoguard/ml/review_sample.py @@ -48,8 +48,9 @@ "dust": 9, "zero_value": 3, } -# First block of each calendar year (UTC), from a block explorer; a packet within a few -# blocks of a boundary could fall in the neighbouring year, which does not affect validity. +# Approximate first block of each calendar year (UTC), entered from memory and not checked +# against an explorer (the archive has no timestamps). The strata are defined by these +# block ranges, so they are exact; only the calendar-year names are approximate. YEAR_STARTS: tuple[tuple[int, int], ...] = ((2024, 18_908_895), (2023, 16_308_190)) MANIFEST = "sample_manifest.json" SHEET = "reviewer_sheet.jsonl" @@ -295,3 +296,85 @@ def freeze(queue: Path, out_dir: Path) -> tuple[dict[str, Any], bool]: _write(out_dir / KEY, key) _write(existing, json.dumps(manifest, indent=1, sort_keys=True).encode() + b"\n") return manifest, True + + +# --- verification of the frozen draw (never writes) ------------------------------------ + + +class FrozenIntegrityError(ReviewSampleError): + """A frozen file is missing or differs from its committed hash. Its bytes are left as + they are; nothing is regenerated.""" + + +# Committed in ML_CROSS_DATASET_VALIDATION.md §26 before any review (raw-byte SHA-256 of +# each file; the selection hash is over ``_canonical`` of the selection fields). +FROZEN_V1: dict[str, str] = { + "queue": "84f8268e7328b320d49b06808811bb27f821dcedb1319a9d090b1c3b27f42e83", + "selection": "e368beb4c179f02bf916ef3dcbb89c4a8260d17956fa897264959477b5b85a62", + SHEET: "a0ec4b6e5620cf001e8e048f37cfca5553c24296318a67b86dddd87772814027", + KEY: "407b412f9e97e2aac269af0f0be565223dcfe851412458cee639396b8503bb2d", + MANIFEST: "c38ae31d598bb58c33fcd2d6553823fc1880b25a4b49b8764d32a290bc7dbdc3", +} +SELECTION_FIELDS = ("sample_version", "queue_sha256", "design", "selected", "reserves") + + +def file_sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def selection_sha256(manifest: dict[str, Any]) -> str: + return hashlib.sha256(_canonical({k: manifest[k] for k in SELECTION_FIELDS})).hexdigest() + + +def verify_frozen( + sample_dir: Path, + *, + queue: Path | None = None, + expected: dict[str, str] = FROZEN_V1, + with_key: bool = True, +) -> dict[str, Any]: + """Check every frozen file against ``expected`` and the manifest's own records; return + the manifest. Raises ``FrozenIntegrityError`` naming every mismatch. ``with_key=False`` + skips the unblinding key (for a reviewer package, which does not contain it).""" + problems: list[str] = [] + names = [MANIFEST, SHEET] + ([KEY] if with_key else []) + got: dict[str, str] = {} + for name in names: + path = sample_dir / name + if not path.is_file(): + problems.append(f"{name}: missing") + continue + got[name] = file_sha256(path) + if got[name] != expected[name]: + problems.append(f"{name}: sha256 {got[name]} != committed {expected[name]}") + if problems: + raise FrozenIntegrityError("; ".join(problems)) + manifest: dict[str, Any] = json.loads((sample_dir / MANIFEST).read_text(encoding="utf-8")) + if manifest.get("sample_version") != SAMPLE_VERSION: + problems.append(f"sample_version {manifest.get('sample_version')!r}") + if selection_sha256(manifest) != expected["selection"]: + problems.append("selection hash does not match the committed value") + if manifest.get("selection_sha256") != expected["selection"]: + problems.append("manifest records a different selection hash") + if manifest.get("queue_sha256") != expected["queue"]: + problems.append("manifest records a different review queue") + for name in names[1:]: + if manifest.get("files", {}).get(name) != got[name]: + problems.append(f"{name}: differs from the hash recorded in the manifest") + if queue is not None and file_sha256(queue) != expected["queue"]: + problems.append(f"{queue.name}: review queue differs from the committed hash") + ids = [r["victim_event_id"] for r in manifest.get("selected", [])] + sheet_ids = [r["victim_event_id"] for r in read_sheet(sample_dir / SHEET)] + if len(set(ids)) != len(ids) or set(ids) != set(sheet_ids) or len(sheet_ids) != len(ids): + problems.append("selected ids and reviewer-sheet ids differ or repeat") + if problems: + raise FrozenIntegrityError("; ".join(problems)) + return manifest + + +def read_sheet(path: Path) -> list[dict[str, Any]]: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] + for r in rows: + if r.get("schema_version") != SHEET_SCHEMA: + raise ReviewSampleError(f"{path}: unexpected sheet schema {r.get('schema_version')!r}") + return rows diff --git a/src/cryptoguard/ml/sample_design.py b/src/cryptoguard/ml/sample_design.py new file mode 100644 index 0000000..ae5f0ea --- /dev/null +++ b/src/cryptoguard/ml/sample_design.py @@ -0,0 +1,441 @@ +"""Design-based analysis of the frozen review sample (``review-sample/1``), offline. + +Units, kept distinct: + +- *attempt*: one packet of the payoff-linked queue (1,469); +- *campaign group*: attempts linked by victim, lookalike, planting transaction or imitated + address (1,395); +- *representative*: the one attempt per group with the lowest ``rank("rep", id)``; +- *item*: a representative drawn into the sample (60). + +The implemented design is (1) one representative per group, then (2) stratified simple +random sampling without replacement of representatives: ``n_c`` of ``N_c`` in stratum +``c``, lowest ``rank("select", id)`` first. The ranks are SHA-256 of fixed strings and are +treated as a pseudo-random permutation. Given the representatives, an item's inclusion +probability is exactly ``n_c / N_c``. + +- The *campaign* estimand (each group represented by its fixed representative) is + therefore design-estimable. +- The *attempt* estimand is not. Under the fixed hash, non-representative attempts have + inclusion probability zero, so it is reported only as bounds (``attempt_bounds``). +- *Victim-level* rates are not estimated. Victims are nested in groups, and 12 groups hold + two victims. + +Everything here is aggregate: no address or event id leaves these functions except the +ids the caller passes in. +""" + +from __future__ import annotations + +import math +from collections import Counter, defaultdict +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from fractions import Fraction +from typing import Any + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.review import ReviewPacket + +DESIGN_VERSION = "sample-design/1" +Z95 = 1.959963984540054 # two-sided 95% + + +@dataclass(frozen=True) +class Cell: + name: str + subtype: str + year: int + rival: bool + groups: int # N_c: representatives in the stratum + selected: int # n_c + packets: int # attempts whose own stratum is c (descriptive only) + + @property + def census(self) -> bool: + return self.selected == self.groups + + +@dataclass(frozen=True) +class Design: + cells: dict[str, Cell] + item_cell: dict[str, str] # victim_event_id -> stratum name + group_size: dict[str, int] + queue_packets: int + + @property + def population(self) -> int: + return sum(c.groups for c in self.cells.values()) + + def inclusion(self, event_id: str) -> Fraction: + """Exact inclusion probability of a selected representative, given the + representatives.""" + c = self.cells[self.item_cell[event_id]] + return Fraction(c.selected, c.groups) + + def weight(self, event_id: str) -> Fraction: + return 1 / self.inclusion(event_id) + + +def parse_stratum(name: str) -> tuple[str, int, bool]: + subtype, year, rival = name.split("|") + if rival not in ("rival", "no_rival"): + raise ValueError(f"bad stratum name {name!r}") + return subtype, int(year), rival == "rival" + + +def design(manifest: Mapping[str, Any]) -> Design: + """Rebuild the design from a frozen manifest; checks the manifest is self-consistent.""" + cells: dict[str, Cell] = {} + for row in manifest["strata_table"]: + subtype, year, rival = parse_stratum(row["stratum"]) + cells[row["stratum"]] = Cell( + row["stratum"], subtype, year, rival, row["groups"], row["selected"], row["packets"] + ) + item_cell = {r["victim_event_id"]: r["stratum"] for r in manifest["selected"]} + if len(item_cell) != len(manifest["selected"]): + raise rs.ReviewSampleError("manifest repeats a selected item") + per_cell = Counter(item_cell.values()) + for name, c in cells.items(): + if per_cell[name] != c.selected or not 0 <= c.selected <= c.groups: + raise rs.ReviewSampleError(f"{name}: selected count inconsistent with the items") + if set(per_cell) - set(cells): + raise rs.ReviewSampleError("an item belongs to an unknown stratum") + return Design( + cells, + item_cell, + {r["victim_event_id"]: r["group_size"] for r in manifest["selected"]}, + manifest["queue_packets"], + ) + + +# --- intervals ------------------------------------------------------------------------- + + +def wilson(p: float, n: float, z: float = Z95) -> tuple[float, float] | None: + """Two-sided Wilson score interval for a proportion ``p`` with (effective) size ``n``.""" + if n <= 0: + return None + z2 = z * z + centre = (p + z2 / (2 * n)) / (1 + z2 / n) + half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n) + return max(0.0, centre - half), min(1.0, centre + half) + + +def kish_deff(weights: Sequence[float]) -> float: + return len(weights) * sum(w * w for w in weights) / sum(weights) ** 2 + + +# --- the stratified estimator ----------------------------------------------------------- + + +def collapse_partners(cells: Sequence[Cell], responded: Mapping[str, int]) -> dict[str, str]: + """Pre-specified collapse rule for variance estimation (fixed before any review). + + A stratum with one respondent and no census is pooled with another stratum of the + same subtype that has respondents. The partner is chosen in this order: + 1. the same rival status, nearest year, earlier year on ties; + 2. otherwise the largest stratum. + Returns ``stratum -> collapsed group name``.""" + parent = {c.name: c.name for c in cells} + + def find(x: str) -> str: + while parent[x] != x: + x = parent[x] + return x + + for c in sorted(cells, key=lambda c: c.name): + if responded.get(c.name, 0) != 1 or responded[c.name] >= c.groups: + continue + others = [o for o in cells if o.subtype == c.subtype and o.name != c.name] + others = [o for o in others if responded.get(o.name, 0) >= 1] + same = [o for o in others if o.rival == c.rival] + if same: + partner = min(same, key=lambda o: (abs(o.year - c.year), o.year)) + elif others: + partner = max(others, key=lambda o: (o.groups, o.name)) + else: + continue + a, b = find(c.name), find(partner.name) + if a != b: + parent[max(a, b)] = min(a, b) + return {c.name: find(c.name) for c in cells} + + +def subtype_scope(subtype: str) -> Callable[[Cell], bool]: + return lambda c: c.subtype == subtype + + +def estimate( + d: Design, + outcomes: Mapping[str, bool | None], + *, + scope: Callable[[Cell], bool] = lambda c: True, +) -> dict[str, Any]: + """Campaign-level proportion of ``True`` in the strata selected by ``scope``. + + Missing outcomes (``None``, or an item absent from ``outcomes``) are nonresponse. The + point estimate assumes they are missing at random within the stratum. ``bounds`` set + them all to False and all to True instead. An undefined quantity is ``None`` with a + reason, never zero.""" + cells = [c for c in d.cells.values() if scope(c) and c.selected] + population = sum(c.groups for c in d.cells.values() if scope(c)) + items = [e for e, s in d.item_cell.items() if s in {c.name for c in cells}] + ys: dict[str, list[bool]] = defaultdict(list) + missing: Counter[str] = Counter() + for e in items: + y = outcomes.get(e) + if y is None: + missing[d.item_cell[e]] += 1 + else: + ys[d.item_cell[e]].append(bool(y)) + responded = {c.name: len(ys[c.name]) for c in cells} + n, r = len(items), sum(responded.values()) + positives = sum(sum(v) for v in ys.values()) + out: dict[str, Any] = { + "population_groups": population, + "strata": len(cells), + "census": bool(cells) and all(c.census for c in cells), + "items": n, + "responded": r, + "missing": n - r, + "positives": positives, + "unweighted": { + "proportion": positives / r if r else None, + "wilson95": wilson(positives / r, r) if r else None, + "note": "illustrative only: treats the items as a simple random sample", + }, + } + if not cells: + return out | {"estimate": None, "reason": "no sampled stratum in scope"} + + def strat(fill: bool | None) -> float | None: + total = Fraction(0) # exact, so a unanimous sample gives exactly 1.0 + for c in cells: + vals = ys[c.name] + ([fill] * missing[c.name] if fill is not None else []) + if not vals: + return None + total += Fraction(c.groups, population) * Fraction(sum(vals), len(vals)) + return float(total) + + out["bounds_missing_as_false_true"] = (strat(False), strat(True)) + p = strat(None) + if p is None: + return out | {"estimate": None, "reason": "a sampled stratum has no responses"} + weights = [c.groups / responded[c.name] for c in cells for _ in ys[c.name]] + deff = kish_deff(weights) + var, reason = _variance(cells, ys, responded, population) + if var is not None and var > 0 and 0 < p < 1: + n_eff = min(r, p * (1 - p) / var) + basis = "variance (collapsed strata, finite-population correction)" + else: + n_eff = r / deff + basis = "Kish weighting effect only" + (f" ({reason})" if reason else "") + if out["census"] and not missing: + interval: tuple[float, float] | None = (p, p) + basis = "census of the frame: no sampling error (review error remains)" + else: + interval = wilson(p, n_eff) + return out | { + "estimate": p, + "variance": var, + "variance_note": reason, + "kish_deff": deff, + "effective_n": n_eff, + "wilson95_design": interval, + "interval_basis": basis, + } + + +def _variance( + cells: Sequence[Cell], + ys: Mapping[str, list[bool]], + responded: Mapping[str, int], + population: int, +) -> tuple[float | None, str | None]: + group = collapse_partners(cells, responded) + pooled: dict[str, list[bool]] = defaultdict(list) + for c in cells: + pooled[group[c.name]] += ys[c.name] + var = 0.0 + for c in cells: + r = responded[c.name] + fpc = 1 - r / c.groups + if fpc <= 0: + continue + vals = pooled[group[c.name]] + if len(vals) < 2: + return None, f"{c.name}: one response and no stratum to pool with" + mean = sum(vals) / len(vals) + s2 = sum((v - mean) ** 2 for v in vals) / (len(vals) - 1) + var += (c.groups / population) ** 2 * fpc * s2 / r + collapsed = sum(1 for c in cells if group[c.name] != c.name) + return var, f"{collapsed} strata pooled for variance" if collapsed else None + + +def attempt_bounds( + campaign_interval: tuple[float, float] | None, groups: int, attempts: int +) -> tuple[float, float] | None: + """Bounds on the attempt-level share from a campaign-level interval. The + ``attempts - groups`` non-representative attempts were never eligible for selection, + so they are bounded at 0 and 1.""" + if campaign_interval is None: + return None + lo, hi = campaign_interval + extra = attempts - groups + return lo * groups / attempts, (hi * groups + extra) / attempts + + +# --- audit of the frozen design ----------------------------------------------------------- + + +def _groups_with(packets: Sequence[ReviewPacket], keys: Sequence[str]) -> dict[str, str]: + from cryptoguard.ml.events import _UnionFind + + uf = _UnionFind() + for p in packets: + node = "e:" + p.victim_event_id + uf.find(node) + for k in keys: + value = getattr(p, k) + if value: + uf.union(node, f"{k}:{value.lower()}") + return {p.victim_event_id: uf.find("e:" + p.victim_event_id) for p in packets} + + +def audit(packets: Sequence[ReviewPacket], manifest: Mapping[str, Any]) -> dict[str, Any]: + """Recompute the frozen design from the queue and check it. Aggregate output only.""" + by_id = {p.victim_event_id: p for p in packets} + root = rs.groups(packets) + members: dict[str, list[str]] = defaultdict(list) + for e, g in root.items(): + members[g].append(e) + reps = {min(ids, key=lambda e: rs.rank("rep", e)) for ids in members.values()} + exploratory = _groups_with(packets, ("victim", "lookalike", "planting_tx")) + merged: dict[str, set[str]] = defaultdict(set) + for e, g in root.items(): + merged[g].add(exploratory[e]) + merges = [s for s in merged.values() if len(s) > 1] + d = design(manifest) + selected = list(d.item_cell) + reserves = [e for ids in manifest["reserves"].values() for e in ids] + sizes = Counter(len(ids) for ids in members.values()) + + # Allocation recomputed from representative counts per stratum. + cell_reps = Counter(rs.stratum_name(rs.stratum(by_id[e])) for e in reps) + realloc: dict[str, int] = {} + ideal: dict[str, float] = {} + for subtype in sorted({c.subtype for c in d.cells.values()}): + names = {(n,): cell_reps[n] for n, c in d.cells.items() if c.subtype == subtype} + quota = rs.SUBTYPE_QUOTA.get(subtype, 0) + total = sum(names.values()) + got = rs.allocate(names, quota) if quota else dict.fromkeys(names, 0) + realloc |= {k[0]: v for k, v in got.items()} + ideal |= {k[0]: (quota * v / total if quota < total else v) for k, v in names.items()} + + weights = [float(d.weight(e)) for e in selected] + recorded = {r["victim_event_id"]: r["weight"] for r in manifest["selected"]} + blocks = sorted(p.observation_block for p in packets) + + def near(boundary: int, k: int) -> int: + return sum(1 for b in blocks if abs(b - boundary) <= k) + + checks = { + "items_unique": len(set(selected)) == len(selected), + "one_item_per_group": len({root[e] for e in selected}) == len(selected), + "one_item_per_victim": len({by_id[e].victim for e in selected}) == len(selected), + "items_are_representatives": set(selected) <= reps, + "strata_partition_representatives": sum(c.groups for c in d.cells.values()) == len(reps), + "strata_counts_match_queue": all(cell_reps[n] == c.groups for n, c in d.cells.items()), + "allocation_reproduced": all(realloc[n] == c.selected for n, c in d.cells.items()), + "reserves_disjoint_and_complete": not set(reserves) & set(selected) + and len(reserves) + len(selected) == len(reps), + "reserves_in_rank_order": all( + ids == sorted(ids, key=lambda e: rs.rank("select", e)) + for ids in manifest["reserves"].values() + ), + "recorded_weights_match_exact": max(abs(recorded[e] - float(d.weight(e))) for e in selected) + < 1e-6, + "weights_sum_to_groups": abs(sum(weights) - len(reps)) < 1e-9, + } + return { + "design_version": DESIGN_VERSION, + "sample_version": manifest["sample_version"], + "selection_sha256": manifest["selection_sha256"], + "checks": checks, + "all_checks_pass": all(checks.values()), + "units": { + "attempts": len(packets), + "campaign_groups": len(members), + "representatives": len(reps), + "non_representative_attempts": len(packets) - len(reps), + "multi_attempt_groups": sum(v for k, v in sizes.items() if k > 1), + "attempts_in_multi_attempt_groups": sum(k * v for k, v in sizes.items() if k > 1), + "multi_stratum_groups": sum( + 1 for ids in members.values() if len({rs.stratum(by_id[e]) for e in ids}) > 1 + ), + "largest_group": max(sizes), + "victims": len({p.victim for p in packets}), + "groups_with_two_or_more_victims": sum( + 1 for ids in members.values() if len({by_id[e].victim for e in ids}) > 1 + ), + "selected_items": len(selected), + "selected_from_multi_attempt_groups": sum( + 1 for e in selected if len(members[root[e]]) > 1 + ), + }, + "grouping_discrepancy": { + "groups_victim_lookalike_tx": len(set(exploratory.values())), + "groups_frozen_links_with_imitated": len(members), + "frozen_groups_merging_several": len(merges), + "exploratory_groups_absorbed": sum(len(s) for s in merges), + }, + "strata": [ + { + "stratum": c.name, + "attempts": c.packets, + "groups": c.groups, + "ideal_share": round(ideal[c.name], 3), + "selected": c.selected, + "census": c.census, + "inclusion_probability": f"{c.selected}/{c.groups}", + "weight": round(c.groups / c.selected, 4) if c.selected else None, + "reserves": len(manifest["reserves"].get(c.name, [])), + } + for c in sorted(d.cells.values(), key=lambda c: c.name) + ], + "weights": { + "kish_deff_all": kish_deff(weights), + "kish_deff_by_subtype": { + s: kish_deff( + [float(d.weight(e)) for e in selected if d.item_cell[e].startswith(s + "|")] + ) + for s in sorted({c.subtype for c in d.cells.values() if c.selected}) + }, + "max_recorded_rounding_error": max( + abs(recorded[e] - float(d.weight(e))) for e in selected + ), + }, + "year_boundaries": { + str(y): { + "block": b, + "attempts_within_7200": near(b, 7_200), + "attempts_within_50400": near(b, 50_400), + } + for y, b in rs.YEAR_STARTS + }, + "protocol_bounds_if_all_confirmed": { + "unweighted_wilson95_lower_60": wilson(1.0, 60)[0], # type: ignore[index] + "unweighted_wilson95_lower_24": wilson(1.0, 24)[0], # type: ignore[index] + "design_wilson95_lower_all": estimate(d, dict.fromkeys(selected, True))[ + "wilson95_design" + ][0], + "design_wilson95_lower_by_subtype": { + s: estimate(d, dict.fromkeys(selected, True), scope=subtype_scope(s))[ + "wilson95_design" + ][0] + for s in sorted({c.subtype for c in d.cells.values() if c.selected}) + }, + }, + "rpc_requests": 0, + } diff --git a/tests/review_fixtures.py b/tests/review_fixtures.py new file mode 100644 index 0000000..d301772 --- /dev/null +++ b/tests/review_fixtures.py @@ -0,0 +1,116 @@ +"""Synthetic frozen review samples and reviewer decisions for the Phase 11.4 tests. + +Nothing here is a real label: decisions are generated to exercise the software.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.review import ReviewPacket + +B2022, B2023, B2024 = 16_000_000, 17_000_000, 19_000_000 + + +def addr(n: int) -> str: + return "0x" + f"{n:040x}" + + +def pkt( + n: int, + *, + subtype: str = "fake_token", + block: int = B2023, + victim: int | None = None, + lookalike: int | None = None, + rival: bool = False, +) -> ReviewPacket: + return ReviewPacket( + victim_event_id=f"{n:016x}", + victim=addr(victim if victim is not None else 10_000 + n), + lookalike=addr(lookalike if lookalike is not None else 20_000 + n), + imitated=addr(30_000 + n), + planting_tx="0x" + f"{n:064x}", + observation_block=block + n, + subtype=subtype, + evidence_summary=f"Source-labelled poisoning transfer {n}; the victim paid later.", + coverage_limitations="no wallet history observed", + source_labels=(f"tsuchiya-archive:{subtype}", "tsuchiya-payoff:confirmed"), + competing_lookalikes=(addr(40_000 + n),) if rival else (), + payment_evidence=(f"0x{n + 7_000_000:064x} block {block + n + 50} after_planting",), + ) + + +def queue() -> list[ReviewPacket]: + out: list[ReviewPacket] = [] + n = 0 + for subtype, block, rival, count in ( + ("fake_token", B2023, False, 40), + ("fake_token", B2023, True, 50), + ("fake_token", B2024, True, 6), + ("spoofed_transfer_from", B2022, False, 20), + ("spoofed_transfer_from", B2023, True, 60), + ("dust", B2023, True, 12), + ("zero_value", B2023, True, 2), + ): + for _ in range(count): + n += 1 + out.append(pkt(n, subtype=subtype, block=block, rival=rival)) + # Two attempts against one victim: a two-attempt campaign group. + out.append(pkt(500, victim=10_001, rival=False)) + return out + + +def write_queue(path: Path, packets: list[ReviewPacket]) -> Path: + path.write_text("".join(p.model_dump_json() + "\n" for p in packets), encoding="utf-8") + return path + + +def frozen(tmp: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path, dict[str, Any]]: + """Freeze a synthetic sample and make its hashes the 'committed' ones for this test.""" + q = write_queue(tmp / "queue.jsonl", queue()) + sample = tmp / "sample" + manifest, _ = rs.freeze(q, sample) + for name in (rs.SHEET, rs.KEY, rs.MANIFEST): + monkeypatch.setitem(rs.FROZEN_V1, name, rs.file_sha256(sample / name)) + monkeypatch.setitem(rs.FROZEN_V1, "selection", manifest["selection_sha256"]) + monkeypatch.setitem(rs.FROZEN_V1, "queue", rs.file_sha256(q)) + return q, sample, manifest + + +ATTEMPT_FIELDS: dict[str, Any] = { + "decision": "confirmed_poisoning_attempt", + "confidence": "high", + "planting_transfer": "observed", + "prior_counterparty": "observed", + "prior_counterparty_address": addr(99), + "matched_leading": 4, + "matched_trailing": 4, + "token": "imitation", + "value_class": "zero", + "initiator": "third_party", + "legitimate_explanation": "not_observed", + "used_explorer": True, + "viewed_after_cutoff": "no", + "saw_external_label": "no", + "saw_source_or_model_output": False, + "rationale": "Lookalike of the earlier recipient, imitation token, no relationship found.", +} +INSUFFICIENT_FIELDS: dict[str, Any] = { + **ATTEMPT_FIELDS, + "decision": "insufficient_evidence", + "confidence": "low", + "prior_counterparty": "not_available", + "prior_counterparty_address": None, + "matched_leading": None, + "matched_trailing": None, + "legitimate_explanation": "not_loaded", + "rationale": "History before the block could not be loaded.", +} + + +def fields(item: int, event_id: str, base: dict[str, Any] = ATTEMPT_FIELDS) -> dict[str, Any]: + return {**base, "item": item, "victim_event_id": event_id} diff --git a/tests/unit/test_ml_sample_design.py b/tests/unit/test_ml_sample_design.py new file mode 100644 index 0000000..c16ef93 --- /dev/null +++ b/tests/unit/test_ml_sample_design.py @@ -0,0 +1,232 @@ +"""Frozen-sample verification and the design-based estimator (Phase 11.4). + +Synthetic samples only. Estimator tests use populations small enough to check by hand or +by enumerating every possible sample. +""" + +from __future__ import annotations + +import itertools +import json +import shutil +from fractions import Fraction +from pathlib import Path + +import pytest + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import sample_design as sd +from tests.review_fixtures import frozen, pkt, queue + +# --- frozen-sample verification ----------------------------------------------------------- + + +def test_verification_passes_on_untouched_files(tmp_path: Path, monkeypatch) -> None: + q, sample, manifest = frozen(tmp_path, monkeypatch) + assert rs.verify_frozen(sample, queue=q)["selection_sha256"] == manifest["selection_sha256"] + + +@pytest.mark.parametrize("name", [rs.SHEET, rs.KEY, rs.MANIFEST]) +def test_any_changed_byte_is_refused_and_left_in_place( + tmp_path: Path, monkeypatch, name: str +) -> None: + """A modified file is reported, never regenerated: its bytes stay as found.""" + _, sample, _ = frozen(tmp_path, monkeypatch) + path = sample / name + tampered = path.read_bytes().replace(b"\n", b"\r\n", 1) + path.write_bytes(tampered) + with pytest.raises(rs.FrozenIntegrityError, match=name): + rs.verify_frozen(sample) + assert path.read_bytes() == tampered + + +def test_missing_manifest_and_wrong_queue_are_refused(tmp_path: Path, monkeypatch) -> None: + q, sample, _ = frozen(tmp_path, monkeypatch) + q.write_text(q.read_text(encoding="utf-8") + "\n", encoding="utf-8") + with pytest.raises(rs.FrozenIntegrityError, match="review queue"): + rs.verify_frozen(sample, queue=q) + (sample / rs.MANIFEST).unlink() + with pytest.raises(rs.FrozenIntegrityError, match="missing"): + rs.verify_frozen(sample) + + +def test_selection_hash_is_recomputed_not_trusted(tmp_path: Path, monkeypatch) -> None: + """A manifest edited consistently (new selection, matching file hash) still fails, + because the selection hash committed in the docs no longer matches.""" + _, sample, manifest = frozen(tmp_path, monkeypatch) + manifest["selected"][0]["victim_event_id"] = manifest["selected"][1]["victim_event_id"] + (sample / rs.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8") + monkeypatch.setitem(rs.FROZEN_V1, rs.MANIFEST, rs.file_sha256(sample / rs.MANIFEST)) + with pytest.raises(rs.FrozenIntegrityError, match="selection hash"): + rs.verify_frozen(sample) + + +def test_reviewer_package_verification_needs_no_key(tmp_path: Path, monkeypatch) -> None: + _, sample, _ = frozen(tmp_path, monkeypatch) + pkg = tmp_path / "pkg" + pkg.mkdir() + for name in (rs.SHEET, rs.MANIFEST): + shutil.copyfile(sample / name, pkg / name) + rs.verify_frozen(pkg, with_key=False) + with pytest.raises(rs.FrozenIntegrityError, match="missing"): + rs.verify_frozen(pkg) + + +# --- audit --------------------------------------------------------------------------------- + + +def test_audit_reproduces_the_design_and_reports_units(tmp_path: Path, monkeypatch) -> None: + _, _, manifest = frozen(tmp_path, monkeypatch) + a = sd.audit(queue(), manifest) + assert a["all_checks_pass"], a["checks"] + u = a["units"] + assert u["attempts"] == len(queue()) + assert u["campaign_groups"] == u["representatives"] == u["attempts"] - 1 + assert u["non_representative_attempts"] == 1 + assert u["multi_attempt_groups"] == 1 + + +def test_audit_catches_tampered_weights_and_reserve_order(tmp_path: Path, monkeypatch) -> None: + _, _, manifest = frozen(tmp_path, monkeypatch) + manifest["selected"][0]["weight"] += 0.5 + name = next(k for k, v in manifest["reserves"].items() if len(v) > 1) + manifest["reserves"][name] = list(reversed(manifest["reserves"][name])) + checks = sd.audit(queue(), manifest)["checks"] + assert not checks["recorded_weights_match_exact"] + assert not checks["reserves_in_rank_order"] + + +def test_design_rejects_duplicate_or_misallocated_items(tmp_path: Path, monkeypatch) -> None: + _, _, manifest = frozen(tmp_path, monkeypatch) + dup = json.loads(json.dumps(manifest)) + dup["selected"].append(dup["selected"][0]) + with pytest.raises(rs.ReviewSampleError): + sd.design(dup) + bad = json.loads(json.dumps(manifest)) + bad["strata_table"][0]["selected"] += 1 + with pytest.raises(rs.ReviewSampleError, match="inconsistent"): + sd.design(bad) + + +def test_grouping_links_campaigns_that_span_strata() -> None: + """Attempts of one campaign in different strata form one group; only one can be + sampled, and the audit counts the group as multi-stratum.""" + packets = [*queue(), pkt(600, subtype="dust", victim=10_001, rival=True)] + root = rs.groups(packets) + assert root["0000000000000258"] == root["0000000000000001"] # 600 and 1 share a victim + m = rs.draw(packets, "q")["manifest"] + a = sd.audit(packets, m) + assert a["all_checks_pass"] + assert a["units"]["multi_stratum_groups"] == 1 + + +# --- allocation edge cases ------------------------------------------------------------------- + + +def test_allocation_edge_cases() -> None: + assert rs.allocate({("a",): 1, ("b",): 50}, 5) == {("a",): 1, ("b",): 4} # single item + assert rs.allocate({("a",): 2, ("b",): 3}, 9) == {("a",): 2, ("b",): 3} # census + assert rs.allocate({("a",): 0, ("b",): 10}, 3) == {("a",): 0, ("b",): 3} # empty + # Ties in the remainder are broken by the cell key, deterministically. + assert rs.allocate({("a",): 10, ("b",): 10}, 3) == {("a",): 1, ("b",): 2} + + +# --- estimator ------------------------------------------------------------------------------- + + +def two_strata(n_a: int = 4, n_b: int = 2) -> sd.Design: + cells = { + "x|2023|rival": sd.Cell("x|2023|rival", "x", 2023, True, 8, n_a, 8), + "x|2024|rival": sd.Cell("x|2024|rival", "x", 2024, True, 2, n_b, 2), + } + items = {f"a{i}": "x|2023|rival" for i in range(n_a)} | { + f"b{i}": "x|2024|rival" for i in range(n_b) + } + return sd.Design(cells, items, dict.fromkeys(items, 1), 10) + + +def test_stratified_estimate_weights_strata_by_population() -> None: + d = two_strata() + y = {"a0": True, "a1": True, "a2": False, "a3": False, "b0": True, "b1": True} + est = sd.estimate(d, y) + assert est["estimate"] == pytest.approx(0.8 * 0.5 + 0.2 * 1.0) + assert est["unweighted"]["proportion"] == pytest.approx(4 / 6) # differs: unequal weights + # Only stratum A has sampling variance (B is a census): (N_a/N)^2 (1-n/N) s^2 / n. + assert est["variance"] == pytest.approx(0.8**2 * (1 - 4 / 8) * (1 / 3) / 4) + assert d.inclusion("a0") == Fraction(1, 2) + assert d.weight("b0") == 1 + + +def test_estimator_is_design_unbiased_by_enumeration() -> None: + """Average the estimate over every possible stratified sample: it equals the true + population proportion exactly.""" + pop_a = [True, True, True, False, False, True, False, False] # 4/8 + pop_b = [True, False] # census of 2 + truth = (sum(pop_a) + sum(pop_b)) / 10 + total, count = 0.0, 0 + d = two_strata() + for pick in itertools.combinations(range(8), 4): + y = {f"a{i}": pop_a[j] for i, j in enumerate(pick)} | {"b0": pop_b[0], "b1": pop_b[1]} + total += sd.estimate(d, y)["estimate"] + count += 1 + assert total / count == pytest.approx(truth) + + +def test_all_and_none_confirmed() -> None: + d = two_strata() + ids = list(d.item_cell) + one = sd.estimate(d, dict.fromkeys(ids, True)) + zero = sd.estimate(d, dict.fromkeys(ids, False)) + assert one["estimate"] == 1.0 and zero["estimate"] == 0.0 # noqa: PT018 + lo, hi = one["wilson95_design"] + assert hi == 1.0 and 0.5 < lo < 1.0 # noqa: PT018 + assert "Kish" in one["interval_basis"] # zero variance: weighting effect only + assert zero["wilson95_design"][0] == 0.0 + + +def test_census_scope_has_no_sampling_error() -> None: + d = two_strata() + est = sd.estimate(d, {"b0": True, "b1": False}, scope=lambda c: c.year == 2024) + assert est["census"] is True + assert est["wilson95_design"] == (0.5, 0.5) + + +def test_nonresponse_gives_bounds_and_an_empty_stratum_gives_no_estimate() -> None: + d = two_strata() + y = {"a0": True, "a1": None, "a2": False, "a3": True, "b0": True, "b1": True} + est = sd.estimate(d, y) + assert est["missing"] == 1 + lo, hi = est["bounds_missing_as_false_true"] + assert lo == pytest.approx(0.8 * 0.5 + 0.2) and hi == pytest.approx(0.8 * 0.75 + 0.2) # noqa: PT018 + assert lo <= est["estimate"] <= hi + none_b = sd.estimate(d, {"a0": True, "a1": True, "a2": False, "a3": True}) + assert none_b["estimate"] is None + assert "no responses" in none_b["reason"] + + +def test_single_item_strata_are_collapsed_by_the_fixed_rule() -> None: + cells = [ + sd.Cell("x|2023|rival", "x", 2023, True, 30, 5, 30), + sd.Cell("x|2024|rival", "x", 2024, True, 10, 1, 10), + sd.Cell("x|2022|no_rival", "x", 2022, False, 10, 1, 10), + sd.Cell("y|2023|rival", "y", 2023, True, 5, 1, 5), + ] + responded = {c.name: c.selected for c in cells} + g = sd.collapse_partners(cells, responded) + assert g["x|2024|rival"] == g["x|2023|rival"] # same rival status, nearest year + assert g["x|2022|no_rival"] == g["x|2023|rival"] # no same-rival partner: largest + assert g["y|2023|rival"] == "y|2023|rival" # no partner in its subtype + d = sd.Design({c.name: c for c in cells}, {"y1": "y|2023|rival"}, {"y1": 1}, 55) + est = sd.estimate(d, {"y1": True}, scope=lambda c: c.subtype == "y") + assert est["variance"] is None + assert "no stratum to pool" in est["variance_note"] + + +def test_reported_numbers_match_known_values() -> None: + lo, _ = sd.wilson(1.0, 60) + assert lo == pytest.approx(0.93983, abs=1e-5) # protocol's unweighted 0.94 + lo24, _ = sd.wilson(1.0, 24) + assert lo24 == pytest.approx(0.86202, abs=1e-5) + assert sd.wilson(0.5, 0) is None + assert sd.kish_deff([1, 1, 1]) == 1.0 + assert sd.attempt_bounds((0.9, 1.0), 1395, 1469) == pytest.approx((0.9 * 1395 / 1469, 1.0)) From e3f37ec96526513a298135d1fa902e3afbb75e84 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 11:13:14 +0300 Subject: [PATCH 22/92] feat(ml): blinded two-reviewer annotation workflow with gated unblinding Structured decisions with evidence and exposure fields; a hash-chained, atomically written reviewer store with finalization; a loopback-only review app (session token, Host check, strict CSP) that serves only the blinded sheet; per-reviewer packages; replacements in frozen reserve order; kappa (undefined, never 0) and Gwet's AC1; and an unblinding gate with no override and a key-access log. Commands: cryptoguard ml review verify|audit|package|serve|status|replace|unblind. Offline, 0 RPC. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/agreement.py | 80 ++++ src/cryptoguard/ml/annotation.py | 474 +++++++++++++++++++++ src/cryptoguard/ml/cli.py | 144 +++++++ src/cryptoguard/ml/review_app/__init__.py | 1 + src/cryptoguard/ml/review_app/app.css | 55 +++ src/cryptoguard/ml/review_app/app.js | 312 ++++++++++++++ src/cryptoguard/ml/review_app/index.html | 70 ++++ src/cryptoguard/ml/review_server.py | 207 ++++++++++ src/cryptoguard/ml/unblind.py | 479 ++++++++++++++++++++++ tests/unit/test_ml_annotation.py | 220 ++++++++++ tests/unit/test_ml_reconcile.py | 7 + tests/unit/test_ml_review_server.py | 187 +++++++++ tests/unit/test_ml_unblind.py | 278 +++++++++++++ 13 files changed, 2514 insertions(+) create mode 100644 src/cryptoguard/ml/agreement.py create mode 100644 src/cryptoguard/ml/annotation.py create mode 100644 src/cryptoguard/ml/review_app/__init__.py create mode 100644 src/cryptoguard/ml/review_app/app.css create mode 100644 src/cryptoguard/ml/review_app/app.js create mode 100644 src/cryptoguard/ml/review_app/index.html create mode 100644 src/cryptoguard/ml/review_server.py create mode 100644 src/cryptoguard/ml/unblind.py create mode 100644 tests/unit/test_ml_annotation.py create mode 100644 tests/unit/test_ml_review_server.py create mode 100644 tests/unit/test_ml_unblind.py diff --git a/src/cryptoguard/ml/agreement.py b/src/cryptoguard/ml/agreement.py new file mode 100644 index 0000000..27cecf0 --- /dev/null +++ b/src/cryptoguard/ml/agreement.py @@ -0,0 +1,80 @@ +"""Agreement between two reviewers on nominal labels (exact arithmetic, no fabricated values). + +Undefined statistics are returned as ``None`` with a reason, never as 0: +- Cohen's kappa is undefined when there are no paired items, or when chance agreement is 1 + (both reviewers used one and the same category for every item). +- Gwet's AC1 uses the fixed category set, so it is defined whenever items exist. Its + chance term is (1/(K-1)) * sum_k pi_k (1 - pi_k), with pi_k the mean of the two + reviewers' shares (Gwet 2008). It is reported alongside kappa because kappa is unstable + when one category dominates, which is expected here. + +Weighted kappa is not offered: the decision categories have no justified ordering. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Mapping, Sequence +from fractions import Fraction +from typing import Any + +from cryptoguard.ml.annotation import ATTEMPT +from cryptoguard.ml.review import DECISION_TIER + +DECISIONS: tuple[str, ...] = tuple(DECISION_TIER) +BINARY: tuple[str, ...] = ("attempt", "not_attempt") + + +def binary(decision: str) -> str: + """Protocol §7: confirmed or likely attempt versus every other decision.""" + return "attempt" if decision in ATTEMPT else "not_attempt" + + +def agreement( + a: Mapping[str, str], b: Mapping[str, str], categories: Sequence[str] = DECISIONS +) -> dict[str, Any]: + """Compare two reviewers' labels keyed by item. Items labelled by only one reviewer + are counted as unpaired, not dropped silently.""" + unknown = sorted({*a.values(), *b.values()} - set(categories)) + if unknown: + raise ValueError(f"labels outside the category set: {unknown}") + paired = sorted(set(a) & set(b)) + n = len(paired) + matrix = {x: dict.fromkeys(categories, 0) for x in categories} + for i in paired: + matrix[a[i]][b[i]] += 1 + out: dict[str, Any] = { + "categories": list(categories), + "paired_items": n, + "unpaired": {"only_a": len(set(a) - set(b)), "only_b": len(set(b) - set(a))}, + "counts_a": dict(Counter(a[i] for i in paired)), + "counts_b": dict(Counter(b[i] for i in paired)), + "confusion": matrix, # rows: reviewer A, columns: reviewer B + "disagreements": n - sum(matrix[x][x] for x in categories), + } + if n == 0: + reason = "no item was labelled by both reviewers" + return out | { + "observed_agreement": None, + "cohen_kappa": None, + "kappa_note": reason, + "gwet_ac1": None, + "ac1_note": reason, + } + po = Fraction(sum(matrix[x][x] for x in categories), n) + pa = {x: Fraction(sum(matrix[x].values()), n) for x in categories} + pb = {x: Fraction(sum(matrix[y][x] for y in categories), n) for x in categories} + pe = sum(pa[x] * pb[x] for x in categories) + out["observed_agreement"] = float(po) + if pe == 1: + out |= { + "cohen_kappa": None, + "kappa_note": "undefined: both reviewers used a single, identical category", + } + else: + out |= {"cohen_kappa": float((po - pe) / (1 - pe)), "kappa_note": None} + k = len(categories) + pi = {x: (pa[x] + pb[x]) / 2 for x in categories} + pe_ac1 = sum(pi[x] * (1 - pi[x]) for x in categories) / (k - 1) + out |= {"gwet_ac1": float((po - pe_ac1) / (1 - pe_ac1)), "ac1_note": None} + return out diff --git a/src/cryptoguard/ml/annotation.py b/src/cryptoguard/ml/annotation.py new file mode 100644 index 0000000..7c6fa0c --- /dev/null +++ b/src/cryptoguard/ml/annotation.py @@ -0,0 +1,474 @@ +"""Independent human annotation of the frozen review sample (``review-protocol/1``, +amendment 1). + +- ``Annotation``: one reviewer's structured decision on one item. A strong decision must + carry the evidence it rests on, and the reviewer's exposure to later or external + information is recorded, never inferred. +- ``ReviewerStore``: one reviewer's append-only, hash-chained log. Each save rewrites the + whole file atomically (temporary file, fsync, replace), so a crash leaves the old or the + new log, never a torn one. A revision appends; nothing is erased. +- ``finalize``: once every item has a decision, the submission is written with a content + hash, and the store refuses further saves. Changes then need a protocol amendment. +- ``Submission``, ``ReplacementRecord``, ``AdjudicationRecord``: the files the maintainer + combines in ``unblind``. + +The store never reads the unblinding key, and nothing here assigns a label. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +from collections.abc import Iterable, Mapping, Sequence +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator + +from cryptoguard.ml.review import Decision, ReviewDecision + +ANNOTATION_SCHEMA = "poisoning-annotation/1" +SUBMISSION_SCHEMA = "poisoning-submission/1" +PROTOCOL = "review-protocol/1+amendment-1" +LOG = "annotations.log.jsonl" +SUBMISSION = "submission.json" +LOCK = ".lock" +ATTEMPT = frozenset({"confirmed_poisoning_attempt", "likely_poisoning_attempt"}) + +Evidence = Literal[ + "observed", # seen and supports the check + "not_observed", # looked for, with adequate data, and absent + "not_available", # the data needed does not exist or cannot be reached + "not_loaded", # not looked at + "not_applicable", + "contradictory", # observations disagree +] +Token = Literal["genuine", "imitation", "unknown", "not_applicable"] +ValueClass = Literal["zero", "dust", "ordinary", "unknown"] +Initiator = Literal["wallet", "third_party", "unknown"] +Exposure = Literal["no", "yes", "unsure"] +Confidence = Literal["high", "medium", "low"] +REVIEWER_ID = re.compile(r"^[A-Za-z0-9_-]{1,32}$") +ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$") + + +class AnnotationError(ValueError): + pass + + +class StoreCorruptError(AnnotationError): + """The log or submission fails its hash chain or schema; nothing is repaired.""" + + +class FinalizedError(AnnotationError): + """The reviewer's submission is finalized; edits need a protocol amendment.""" + + +class Annotation(BaseModel): + """One decision. ``reviewer``, ``revision`` and ``saved_at`` are set by the store.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-annotation/1"] = "poisoning-annotation/1" + protocol: Literal["review-protocol/1+amendment-1"] = "review-protocol/1+amendment-1" + item: int = Field(ge=1) + victim_event_id: str = Field(pattern=r"^[0-9a-f]{16}$") + reviewer: str + revision: int = Field(ge=1) + saved_at: str + decision: Decision + confidence: Confidence + # Protocol §3 checks, in order. + planting_transfer: Evidence + prior_counterparty: Evidence + prior_counterparty_address: str | None = None + matched_leading: int | None = Field(default=None, ge=0, le=40) + matched_trailing: int | None = Field(default=None, ge=0, le=40) + token: Token + value_class: ValueClass + initiator: Initiator + legitimate_explanation: Evidence + # Exposure (amendment 1): recorded, never inferred. + used_explorer: bool + viewed_after_cutoff: Exposure + saw_external_label: Exposure + saw_source_or_model_output: bool + rationale: str = Field(min_length=1, max_length=4000) + notes: str = Field(default="", max_length=4000) + + @model_validator(mode="after") + def _evidence_supports_decision(self) -> Annotation: + problems = evidence_problems(self) + if problems: + raise ValueError("; ".join(problems)) + return self + + def to_review_decision(self) -> ReviewDecision: + """The ``poisoning-review/1`` record that ``review.import_reviews`` accepts.""" + return ReviewDecision( + victim_event_id=self.victim_event_id, + decision=self.decision, + rationale=self.rationale, + reviewer=self.reviewer, + reviewed_at=self.saved_at, + ) + + +def evidence_problems(a: Annotation) -> list[str]: + """Rules from protocol amendment 1 §4. Missing evidence is never read as negative.""" + out: list[str] = [] + if not REVIEWER_ID.match(a.reviewer): + out.append("reviewer must be a pseudonym of 1-32 letters, digits, '-' or '_'") + addr = a.prior_counterparty_address + if addr is not None and not ADDRESS.match(addr): + out.append("prior_counterparty_address must be a 0x-prefixed 40-hex address") + if addr is not None and a.prior_counterparty not in ("observed", "contradictory"): + out.append( + "a prior counterparty address needs prior_counterparty observed or contradictory" + ) + words = len(a.rationale.split()) + d = a.decision + if d == "confirmed_poisoning_attempt": + if a.planting_transfer != "observed": + out.append("confirmed: the planting transfer must be observed") + if a.prior_counterparty != "observed" or addr is None: + out.append("confirmed: the imitated earlier counterparty must be observed and given") + if a.matched_leading is None or a.matched_trailing is None: + out.append("confirmed: record the matched leading and trailing characters") + if a.legitimate_explanation not in ("not_observed",): + out.append("confirmed: a legitimate explanation must have been looked for and absent") + elif d == "likely_poisoning_attempt": + if a.planting_transfer != "observed": + out.append("likely: the planting transfer must be observed") + if a.legitimate_explanation == "observed": + out.append("likely: contradicts an observed legitimate explanation") + elif d == "confirmed_legitimate_interaction": + if a.legitimate_explanation != "observed": + out.append("legitimate: the legitimate explanation must be observed") + elif d == "conflicting_evidence": + checks = (a.planting_transfer, a.prior_counterparty, a.legitimate_explanation) + if "contradictory" not in checks: + out.append("conflicting: mark the contradictory check") + if d in ("confirmed_poisoning_attempt", "confirmed_legitimate_interaction") and words < 5: + out.append("a confirmed decision needs a rationale of at least 5 words") + return out + + +# --- durable store ------------------------------------------------------------------------ + + +def _canonical(obj: Any) -> bytes: + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def atomic_write(path: Path, data: bytes) -> None: + """Temporary file, fsync, replace: readers see the old or the new file, never a mix.""" + tmp = path.with_name(path.name + ".tmp") + with tmp.open("wb") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + + +def now() -> str: + return datetime.now(UTC).isoformat(timespec="seconds") + + +class ReviewerStore: + """One reviewer's log in ``root``. Use as a context manager to hold the OS lock, which + keeps a second server (or a second copy of the app) off the same store.""" + + def __init__(self, root: Path, reviewer: str, items: Mapping[int, str]) -> None: + if not REVIEWER_ID.match(reviewer): + raise AnnotationError(f"invalid reviewer pseudonym {reviewer!r}") + self.root, self.reviewer, self.items = root, reviewer, dict(items) + self._fd: int | None = None + self.entries: list[dict[str, Any]] = [] + self.root.mkdir(parents=True, exist_ok=True) + leftover = self.root / (LOG + ".tmp") + if leftover.exists(): # an interrupted save; the log itself is intact + leftover.unlink() + self._load() + + def __enter__(self) -> ReviewerStore: + from cryptoguard.ml.collect import _try_os_lock + + fd = os.open(self.root / LOCK, os.O_RDWR | os.O_CREAT) + if not _try_os_lock(fd): + os.close(fd) + raise AnnotationError(f"{self.root}: another review session holds this store") + self._fd = fd + return self + + def __exit__(self, *exc: object) -> None: + from cryptoguard.ml.collect import _os_unlock + + if self._fd is not None: + _os_unlock(self._fd) + os.close(self._fd) + self._fd = None + + # Log format: {"seq", "prev", "kind", "record", "sha256"}; sha256 covers the rest. + def _load(self) -> None: + path = self.root / LOG + if not path.exists(): + return + prev = None + for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + try: + entry = json.loads(line) + body = {k: entry[k] for k in ("seq", "prev", "kind", "record")} + except (json.JSONDecodeError, KeyError, TypeError) as exc: + raise StoreCorruptError(f"{path}: line {i}: {exc}") from None + if entry["sha256"] != _sha(_canonical(body)) or entry["prev"] != prev: + raise StoreCorruptError(f"{path}: line {i}: hash chain broken") + if entry["seq"] != i: + raise StoreCorruptError(f"{path}: line {i}: sequence {entry['seq']}") + if entry["kind"] == "annotation": + try: + a = Annotation.model_validate(entry["record"]) + except ValidationError as exc: + raise StoreCorruptError(f"{path}: line {i}: {exc}") from None + if a.reviewer != self.reviewer: + raise StoreCorruptError(f"{path}: line {i}: reviewer {a.reviewer!r}") + prev = entry["sha256"] + self.entries.append(entry) + + def _append(self, kind: str, record: dict[str, Any]) -> None: + if self._fd is None: + raise AnnotationError("open the store with `with` before writing") + body = { + "seq": len(self.entries) + 1, + "prev": self.entries[-1]["sha256"] if self.entries else None, + "kind": kind, + "record": record, + } + entry = {**body, "sha256": _sha(_canonical(body))} + data = b"".join(_canonical(e) + b"\n" for e in [*self.entries, entry]) + atomic_write(self.root / LOG, data) # raises before memory changes on a failed write + self.entries.append(entry) + + @property + def finalized(self) -> bool: + return any(e["kind"] == "finalize" for e in self.entries) + + def history(self, item: int) -> list[Annotation]: + return [ + Annotation.model_validate(e["record"]) + for e in self.entries + if e["kind"] == "annotation" and e["record"]["item"] == item + ] + + def latest(self) -> dict[int, Annotation]: + out: dict[int, Annotation] = {} + for e in self.entries: + if e["kind"] == "annotation": + a = Annotation.model_validate(e["record"]) + out[a.item] = a + return out + + def save( + self, fields: Mapping[str, Any], *, expected_revision: int | None = None + ) -> Annotation: + """Validate and append. ``expected_revision`` (the revision the client last saw) + rejects a save based on a stale copy instead of silently overwriting. An identical + resubmission is a no-op that returns the stored record.""" + if self.finalized: + raise FinalizedError("submission finalized; edits need a protocol amendment") + item = fields.get("item") + if not isinstance(item, int) or item not in self.items: + raise AnnotationError(f"unknown item {item!r}") + if fields.get("victim_event_id") != self.items[item]: + raise AnnotationError(f"item {item}: event id does not match the reviewer sheet") + prior = self.history(item) + current = prior[-1].revision if prior else 0 + if expected_revision is not None and expected_revision != current: + raise AnnotationError( + f"item {item}: saved revision is {current}, not {expected_revision}; reload" + ) + record = { + **{k: v for k, v in fields.items() if k not in ("reviewer", "revision", "saved_at")}, + "reviewer": self.reviewer, + "revision": current + 1, + "saved_at": now(), + } + try: + a = Annotation.model_validate(record) + except ValidationError as exc: + raise AnnotationError(_messages(exc)) from None + if prior and _decision_view(prior[-1]) == _decision_view(a): + return prior[-1] + self._append("annotation", a.model_dump(mode="json")) + return a + + def finalize(self, sample: Mapping[str, str]) -> Submission: + """Write the submission once every item has a decision. ``sample`` holds + ``selection_sha256`` and ``sheet_sha256`` of the frozen sample.""" + if self.finalized: + raise FinalizedError("already finalized") + latest = self.latest() + missing = sorted(set(self.items) - set(latest)) + if missing: + raise AnnotationError(f"{len(missing)} item(s) have no decision: {missing[:10]}") + log_sha = _sha((self.root / LOG).read_bytes()) + body = { + "schema_version": SUBMISSION_SCHEMA, + "protocol": PROTOCOL, + "reviewer": self.reviewer, + "selection_sha256": sample["selection_sha256"], + "sheet_sha256": sample["sheet_sha256"], + "decisions": [latest[i].model_dump(mode="json") for i in sorted(latest)], + "revisions": sum(1 for e in self.entries if e["kind"] == "annotation"), + "log_sha256": log_sha, + "finalized_at": now(), + } + sub = Submission.model_validate({**body, "content_sha256": _sha(_canonical(body))}) + self._append("finalize", {"content_sha256": sub.content_sha256, "log_sha256": log_sha}) + atomic_write(self.root / SUBMISSION, sub.model_dump_json(indent=1).encode() + b"\n") + return sub + + +def _decision_view(a: Annotation) -> dict[str, Any]: + return a.model_dump(exclude={"revision", "saved_at"}) + + +def _messages(exc: ValidationError) -> str: + return "; ".join( + (".".join(str(p) for p in e["loc"]) + ": " if e["loc"] else "") + e["msg"] + for e in exc.errors() + ) + + +# --- submissions, replacements and adjudication ------------------------------------------- + + +class Submission(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-submission/1"] + protocol: Literal["review-protocol/1+amendment-1"] + reviewer: str + selection_sha256: str + sheet_sha256: str + decisions: tuple[Annotation, ...] + revisions: int + log_sha256: str + finalized_at: str + content_sha256: str + + def body_sha256(self) -> str: + body = self.model_dump(mode="json", exclude={"content_sha256"}) + return _sha(_canonical(body)) + + +def load_submission(path: Path) -> Submission: + try: + sub = Submission.model_validate_json(path.read_bytes()) + except ValidationError as exc: + raise StoreCorruptError(f"{path}: {_messages(exc)}") from None + if sub.body_sha256() != sub.content_sha256: + raise StoreCorruptError(f"{path}: content hash does not match; the file was edited") + if any(a.reviewer != sub.reviewer for a in sub.decisions): + raise StoreCorruptError(f"{path}: a decision belongs to another reviewer") + items = [a.item for a in sub.decisions] + if len(set(items)) != len(items): + raise StoreCorruptError(f"{path}: repeated item") + return sub + + +ReplacementReason = Literal[ + "transaction_not_found", # the planting transaction cannot be retrieved anywhere + "chain_data_unavailable", # no explorer or archive can show the block + "sheet_record_malformed", # the frozen sheet line cannot be presented +] + + +class ReplacementRecord(BaseModel): + """Replacement for technical inaccessibility only; difficulty, disagreement or an + apparently benign item is a result, never a reason.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-replacement/1"] = "poisoning-replacement/1" + original_event_id: str + original_item: int = Field(ge=1) + replacement_event_id: str + replacement_item: int = Field(ge=1) # numbered after the frozen sheet + sheet_line: dict[str, Any] # blinded, as ``review_sample.blind`` builds it + stratum: str # maintainer-only: never copied into a reviewer package + reserve_position: int = Field(ge=0) # index in the stratum's frozen reserve list + reason: ReplacementReason + inaccessibility_evidence: str = Field(min_length=10) + reviewers_exposed_to_original: tuple[str, ...] + recorded_by: str + recorded_at: str + protocol: Literal["review-protocol/1+amendment-1"] = "review-protocol/1+amendment-1" + + +def validate_replacements( + manifest: Mapping[str, Any], records: Sequence[ReplacementRecord] +) -> list[str]: + """Each replacement must replace an active item and take the next unused reserve of its + stratum, in frozen order. A replacement can itself be replaced, by the same rule.""" + problems: list[str] = [] + active = {r["victim_event_id"]: r["stratum"] for r in manifest["selected"]} + used: dict[str, int] = {} + for rec in records: + s = active.get(rec.original_event_id) + if s is None: + problems.append(f"{rec.original_event_id}: not an active sampled item") + continue + if rec.stratum != s: + problems.append(f"{rec.original_event_id}: stratum {rec.stratum} != {s}") + reserves = manifest["reserves"].get(s, []) + pos = used.get(s, 0) + if pos >= len(reserves) or reserves[pos] != rec.replacement_event_id: + problems.append(f"{rec.original_event_id}: not the next reserve of {s}") + if rec.reserve_position != pos: + problems.append(f"{rec.original_event_id}: reserve position {rec.reserve_position}") + if rec.sheet_line.get("victim_event_id") != rec.replacement_event_id: + problems.append(f"{rec.original_event_id}: sheet line is for another event") + del active[rec.original_event_id] + active[rec.replacement_event_id] = s + used[s] = pos + 1 + return problems + + +class AdjudicationRecord(BaseModel): + """A third, separately recorded decision. It never replaces the two originals.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: Literal["poisoning-adjudication/1"] = "poisoning-adjudication/1" + victim_event_id: str + adjudicator: str + reviewer_decisions: dict[str, Decision] # as finalized, by reviewer pseudonym + final_decision: Decision + rationale: str = Field(min_length=10) + additional_evidence_used: bool + saw_source_labels: bool + adjudicated_at: str + + +def read_jsonl[M: BaseModel](path: Path, model: type[M]) -> list[M]: + out: list[M] = [] + for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + if not line.strip(): + continue + try: + out.append(model.model_validate_json(line)) + except ValidationError as exc: + raise AnnotationError(f"{path}: line {i}: {_messages(exc)}") from None + return out + + +def to_review_decisions(subs: Iterable[Submission]) -> list[ReviewDecision]: + return [a.to_review_decision() for s in subs for a in s.decisions] diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index bc964b3..0e17762 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -92,6 +92,7 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None "--queue", type=Path, default=ML_DIR / "poisoning" / "review_packets_payoff_linked.jsonl" ) fr.add_argument("--out", type=Path, default=ML_DIR / "poisoning" / "review_sample") + _add_review_parser(ml) bz = ml.add_parser("bench-archive", help="archive-scanner scaling on synthetic dumps") bz.add_argument("sizes", type=int, nargs="+") bz.add_argument("--work", type=Path, default=ML_DIR / "bench") @@ -135,6 +136,8 @@ def run(args: argparse.Namespace) -> int: return _cross_dataset_report(args) if args.ml_command == "freeze-review-sample": return _freeze_review_sample(args) + if args.ml_command == "review": + return _review(args) if args.ml_command == "bench-archive": import json @@ -292,6 +295,147 @@ def _freeze_review_sample(args: argparse.Namespace) -> int: return 0 +SAMPLE_DIR = ML_DIR / "poisoning" / "review_sample" +REVIEW_WORK = ML_DIR / "poisoning" / "review" +QUEUE = ML_DIR / "poisoning" / "review_packets_payoff_linked.jsonl" + + +def _add_review_parser(ml: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: + rv = ml.add_parser("review", help="independent human review of the frozen sample (offline)") + sub = rv.add_subparsers(dest="review_command", required=True) + for name, text in ( + ("verify", "check the frozen sample against its committed hashes (reads only)"), + ("audit", "recompute and check the sampling design; aggregate JSON"), + ): + p = sub.add_parser(name, help=text) + p.add_argument("--sample", type=Path, default=SAMPLE_DIR) + p.add_argument("--queue", type=Path, default=QUEUE) + sub.choices["audit"].add_argument("--out", type=Path, default=REVIEW_WORK / "design_audit.json") + pk = sub.add_parser("package", help="make one reviewer's package (blinded sheet only)") + pk.add_argument("--reviewer", required=True, help="pseudonym, e.g. A") + pk.add_argument("--out", type=Path, required=True) + pk.add_argument("--sample", type=Path, default=SAMPLE_DIR) + pk.add_argument("--work", type=Path, default=REVIEW_WORK) + sv = sub.add_parser("serve", help="run the local review app for one reviewer package") + sv.add_argument("--package", type=Path, required=True) + sv.add_argument("--port", type=int, default=0) + sv.add_argument("--no-browser", action="store_true") + st = sub.add_parser("status", help="progress of one reviewer package (no decisions shown)") + st.add_argument("--package", type=Path, required=True) + rp = sub.add_parser("replace", help="replace a technically inaccessible item (maintainer)") + rp.add_argument("--event", required=True) + rp.add_argument( + "--reason", + required=True, + choices=["transaction_not_found", "chain_data_unavailable", "sheet_record_malformed"], + ) + rp.add_argument("--evidence", required=True) + rp.add_argument("--exposed", default="", help="reviewers who already saw the original") + rp.add_argument("--by", required=True) + rp.add_argument("--sample", type=Path, default=SAMPLE_DIR) + rp.add_argument("--work", type=Path, default=REVIEW_WORK) + ub = sub.add_parser("unblind", help="gate, then compare reviews with the source (maintainer)") + ub.add_argument("--submission", type=Path, action="append", required=True) + ub.add_argument("--adjudication", type=Path) + ub.add_argument("--sample", type=Path, default=SAMPLE_DIR) + ub.add_argument("--work", type=Path, default=REVIEW_WORK) + + +def _review(args: argparse.Namespace) -> int: + import json + + from cryptoguard.ml import review_sample as rs + from cryptoguard.ml.annotation import AnnotationError + + cmd = args.review_command + try: + if cmd == "verify": + manifest = rs.verify_frozen(args.sample, queue=args.queue) + print( + f"Frozen sample verified: {len(manifest['selected'])} items, selection " + f"{manifest['selection_sha256']}; all five committed hashes match." + ) + return 0 + if cmd == "audit": + from cryptoguard.ml.sample_design import audit + + manifest = rs.verify_frozen(args.sample, queue=args.queue) + report = audit(rs.load_queue(args.queue), manifest) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8") + print(json.dumps(report["checks"], indent=1)) + print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") + return 0 if report["all_checks_pass"] else 2 + if cmd == "package": + from cryptoguard.ml.unblind import make_package + + out = make_package(args.sample, args.work, args.reviewer, args.out) + print(f"Reviewer package for {args.reviewer} in {out} (blinded sheet only).") + return 0 + if cmd == "serve": + return _review_serve(args) + if cmd == "status": + from cryptoguard.ml.review_server import ReviewApp + + state = ReviewApp(args.package).state() + print( + f"Reviewer {state['reviewer']}: {len(state['decisions'])} of " + f"{len(state['items'])} items saved; finalized: {state['finalized']}." + ) + return 0 + if cmd == "replace": + from cryptoguard.ml.unblind import record_replacement + + rec = record_replacement( + args.sample, + args.work, + original_event_id=args.event, + reason=args.reason, + evidence=args.evidence, + exposed=[x for x in args.exposed.split(",") if x], + recorded_by=args.by, + ) + print( + f"Item {rec.original_item} replaced by item {rec.replacement_item} (reserve " + f"{rec.reserve_position}); remake reviewer packages to include it." + ) + return 0 + if cmd == "unblind": + from cryptoguard.ml.unblind import unblind + + report = unblind(args.sample, args.work, args.submission, args.adjudication) + primary = report["primary_all_reviewers_attempt"]["overall"] + keys = ("items", "positives", "estimate", "wilson95_design") + print(json.dumps({k: primary.get(k) for k in keys}, indent=1)) + print(f"Wrote {args.work / 'unblinded_report.json'} (0 RPC requests).") + return 0 + except (rs.ReviewSampleError, AnnotationError, FileNotFoundError) as exc: + print(f"error [{type(exc).__name__}]: {exc}") + return 1 + raise AssertionError(cmd) + + +def _review_serve(args: argparse.Namespace) -> int: + import webbrowser + + from cryptoguard.ml.review_server import ReviewApp, serve + + app = ReviewApp(args.package) + with app.store: + httpd, url = serve(app, args.port) + print(f"Reviewer {app.pkg['reviewer']}: open {url}") + print("Keep this window open while reviewing; press Ctrl+C to stop (saves are on disk).") + if not args.no_browser: + webbrowser.open(url) + try: + httpd.serve_forever() + except KeyboardInterrupt: + pass + finally: + httpd.server_close() + return 0 + + def _shadow(args: argparse.Namespace) -> int: import json diff --git a/src/cryptoguard/ml/review_app/__init__.py b/src/cryptoguard/ml/review_app/__init__.py new file mode 100644 index 0000000..339a5ba --- /dev/null +++ b/src/cryptoguard/ml/review_app/__init__.py @@ -0,0 +1 @@ +"""Static files of the local review app (no data).""" diff --git a/src/cryptoguard/ml/review_app/app.css b/src/cryptoguard/ml/review_app/app.css new file mode 100644 index 0000000..39c34ec --- /dev/null +++ b/src/cryptoguard/ml/review_app/app.css @@ -0,0 +1,55 @@ +:root { + --bg: #f6f7f9; --card: #ffffff; --text: #1d2330; --muted: #5b6577; --line: #d6dbe3; + --accent: #2456c7; --ok: #1d7a46; --err: #b42318; --errbg: #fdecea; --okbg: #e8f5ee; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #14171c; --card: #1d2128; --text: #e6e9ef; --muted: #9aa4b5; --line: #343a45; + --accent: #7aa2ff; --ok: #5fd08e; --err: #ff8a80; --errbg: #3a1d1b; --okbg: #17331f; + } +} +* { box-sizing: border-box; } +body { margin: 0; font: 15px/1.5 system-ui, sans-serif; background: var(--bg); color: var(--text); } +header { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; padding: 10px 16px; + border-bottom: 1px solid var(--line); background: var(--card); } +header h1 { font-size: 17px; margin: 0; } +#who, #progress { color: var(--muted); } +#finalize { margin-left: auto; } +#banner { margin: 10px 16px; padding: 10px 12px; border-radius: 6px; } +#banner.error { background: var(--errbg); color: var(--err); } +#banner.ok { background: var(--okbg); color: var(--ok); } +main { display: grid; grid-template-columns: 150px 1fr; gap: 16px; padding: 16px; max-width: 1100px; } +nav ol { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px; } +nav button { width: 44px; padding: 4px 0; font-size: 13px; } +nav button.done { border-color: var(--ok); color: var(--ok); } +nav button[aria-current="true"] { outline: 2px solid var(--accent); } +.card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; margin-bottom: 14px; } +.item-title { margin: 0 0 6px; font-size: 18px; } +.cutoff { color: var(--muted); margin: 0 0 10px; } +.facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 12px; margin: 0; } +.facts dt { color: var(--muted); } +.facts dd { margin: 0; display: flex; gap: 8px; align-items: center; min-width: 0; } +code { font: 13px/1.4 ui-monospace, monospace; overflow-wrap: anywhere; word-break: break-all; } +fieldset { border: 1px solid var(--line); border-radius: 6px; margin: 0 0 12px; padding: 8px 12px; } +legend { padding: 0 4px; font-weight: 600; } +.radio { display: block; padding: 2px 0; } +.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 10px 14px; margin-bottom: 12px; } +label { display: flex; flex-direction: column; gap: 3px; font-size: 14px; } +label.check, label.radio { flex-direction: row; align-items: center; gap: 6px; } +label.wide { grid-column: 1 / -1; margin-bottom: 10px; } +input, select, textarea, button { font: inherit; color: inherit; background: var(--bg); + border: 1px solid var(--line); border-radius: 5px; padding: 5px 8px; } +textarea { resize: vertical; } +button { cursor: pointer; background: var(--card); } +button:disabled { opacity: 0.5; cursor: default; } +button.save { border-color: var(--accent); color: var(--accent); font-weight: 600; } +button.copy { font-size: 12px; padding: 1px 6px; } +.actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.status { color: var(--muted); } +.kbd { font-size: 11px; color: var(--muted); border: 1px solid var(--line); border-radius: 3px; padding: 0 3px; } +.muted { color: var(--muted); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +@media (max-width: 700px) { + main { grid-template-columns: 1fr; padding: 10px 16px; } + .facts { grid-template-columns: 1fr; } +} diff --git a/src/cryptoguard/ml/review_app/app.js b/src/cryptoguard/ml/review_app/app.js new file mode 100644 index 0000000..02e47ff --- /dev/null +++ b/src/cryptoguard/ml/review_app/app.js @@ -0,0 +1,312 @@ +// Local review app. Text is rendered with textContent only; the page holds no data until +// /api/state answers, and that answer contains only the blinded sheet and this +// reviewer's own decisions. +"use strict"; + +const DECISIONS = [ + ["confirmed_poisoning_attempt", "Confirmed poisoning attempt"], + ["likely_poisoning_attempt", "Likely poisoning attempt"], + ["confirmed_legitimate_interaction", "Confirmed legitimate interaction"], + ["insufficient_evidence", "Insufficient evidence"], + ["conflicting_evidence", "Conflicting evidence"], +]; +const CHOICES = { + evidence: [["not_loaded", "not looked at"], ["observed", "observed"], + ["not_observed", "looked for, absent"], ["not_available", "data not available"], + ["not_applicable", "not applicable"], ["contradictory", "contradictory"]], + exposure: [["unsure", "unsure"], ["no", "no"], ["yes", "yes"]], + confidence: [["medium", "medium"], ["high", "high"], ["low", "low"]], + token: [["unknown", "unknown"], ["genuine", "genuine token"], + ["imitation", "imitation contract"], ["not_applicable", "not applicable"]], + value_class: [["unknown", "unknown"], ["zero", "zero"], ["dust", "dust"], + ["ordinary", "ordinary"]], + initiator: [["unknown", "unknown"], ["wallet", "the wallet"], + ["third_party", "a third party"]], +}; +const FACTS = [ + ["wallet", "Wallet"], + ["address_under_review", "Address under review"], + ["transaction", "Transaction"], + ["block", "Block (observation cutoff)"], +]; + +// The token arrives in the URL fragment; it is kept for this tab only (so a refresh works) +// and removed from the address bar. +const token = (() => { + const fromUrl = new URLSearchParams(location.hash.slice(1)).get("token"); + try { + if (fromUrl) sessionStorage.setItem("cg-review-token", fromUrl); + return fromUrl || sessionStorage.getItem("cg-review-token") || ""; + } catch { + return fromUrl || ""; + } +})(); +history.replaceState(null, "", location.pathname); +let state = null; +let index = 0; +let dirty = false; + +const $ = (sel, root = document) => root.querySelector(sel); +const el = (tag, text, cls) => { + const e = document.createElement(tag); + if (text !== undefined) e.textContent = String(text); + if (cls) e.className = cls; + return e; +}; + +function banner(msg, kind = "error") { + const b = $("#banner"); + b.textContent = msg; + b.className = kind; + b.hidden = !msg; +} + +async function api(path, body) { + const opts = { headers: { "X-Review-Token": token } }; + if (body !== undefined) { + opts.method = "POST"; + opts.headers["Content-Type"] = "application/json"; + opts.body = JSON.stringify(body); + } + let res; + try { + res = await fetch(path, opts); + } catch (e) { + throw new Error("the review server is not reachable; your form is kept, try again"); + } + const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` })); + if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`); + return data; +} + +function draftKey(item) { + return `cg-review:${state.reviewer}:${state.sample}:${item}`; +} +function readDraft(item) { + try { return JSON.parse(localStorage.getItem(draftKey(item)) || "null"); } catch { return null; } +} +function writeDraft(item, fields) { + try { localStorage.setItem(draftKey(item), JSON.stringify(fields)); } catch { /* optional */ } +} +function clearDraft(item) { + try { localStorage.removeItem(draftKey(item)); } catch { /* optional */ } +} + +function saved(item) { + return state.decisions[String(item)]; +} + +function renderList() { + const ol = $("#items"); + ol.replaceChildren(); + state.items.forEach((it, i) => { + const li = el("li"); + const b = el("button", `#${it.item}`, saved(it.item) ? "done" : ""); + b.type = "button"; + b.setAttribute("aria-current", i === index ? "true" : "false"); + b.setAttribute("aria-label", `Item ${it.item}, ${saved(it.item) ? "saved" : "no decision yet"}`); + b.addEventListener("click", () => go(i)); + li.append(b); + ol.append(li); + }); + const n = state.items.filter((it) => saved(it.item)).length; + $("#progress").textContent = state.finalized + ? `Finalized: ${n} of ${state.items.length} decisions submitted` + : `${n} of ${state.items.length} saved`; + $("#finalize").disabled = state.finalized || n !== state.items.length; +} + +function copyButton(value) { + const b = el("button", "Copy", "copy"); + b.type = "button"; + b.addEventListener("click", async () => { + try { await navigator.clipboard.writeText(String(value)); b.textContent = "Copied"; } + catch { b.textContent = "Select and copy"; } + setTimeout(() => { b.textContent = "Copy"; }, 1500); + }); + return b; +} + +function fill(select, kind) { + for (const [v, label] of CHOICES[kind]) select.append(new Option(label, v)); +} + +function formFields(form) { + const f = new FormData(form); + const num = (k) => (f.get(k) === "" || f.get(k) === null ? null : Number(f.get(k))); + const it = state.items[index]; + const addr = (f.get("prior_counterparty_address") || "").trim(); + return { + item: it.item, + victim_event_id: it.victim_event_id, + decision: f.get("decision"), + confidence: f.get("confidence"), + planting_transfer: f.get("planting_transfer"), + prior_counterparty: f.get("prior_counterparty"), + prior_counterparty_address: addr || null, + matched_leading: num("matched_leading"), + matched_trailing: num("matched_trailing"), + token: f.get("token"), + value_class: f.get("value_class"), + initiator: f.get("initiator"), + legitimate_explanation: f.get("legitimate_explanation"), + used_explorer: f.get("used_explorer") === "on", + viewed_after_cutoff: f.get("viewed_after_cutoff"), + saw_external_label: f.get("saw_external_label"), + saw_source_or_model_output: f.get("saw_source_or_model_output") === "on", + rationale: (f.get("rationale") || "").trim(), + notes: (f.get("notes") || "").trim(), + }; +} + +function setFields(form, v) { + for (const [k, val] of Object.entries(v)) { + const input = form.elements.namedItem(k); + if (!input || k === "decision") continue; + if (input.type === "checkbox") input.checked = Boolean(val); + else input.value = val === null || val === undefined ? "" : String(val); + } + for (const r of form.querySelectorAll('input[name="decision"]')) r.checked = r.value === v.decision; +} + +function matchCounts(a, b) { + const x = a.toLowerCase().slice(2), y = b.toLowerCase().slice(2); + let lead = 0, trail = 0; + while (lead < 40 && x[lead] === y[lead]) lead++; + while (trail < 40 && x[39 - trail] === y[39 - trail]) trail++; + return [lead, trail]; +} + +function go(i) { + if (dirty && !confirm("This item has unsaved changes (kept as a draft in this browser). Leave it?")) return; + index = Math.max(0, Math.min(state.items.length - 1, i)); + render(); +} + +function render() { + dirty = false; + renderList(); + const it = state.items[index]; + const section = $("#item"); + const frag = $("#form-template").content.cloneNode(true); + $(".item-title", frag).textContent = `Item ${it.item} of ${state.items.length}`; + $(".cutoff", frag).textContent = + `Judge the planting with evidence up to block ${it.block}. If you look at later activity ` + + "(an explorer shows it), record that below; it is not hidden from you, only from this sheet."; + const dl = $(".facts", frag); + for (const [k, label] of FACTS) { + const dd = el("dd"); + dd.append(el("code", it[k])); + dd.append(copyButton(it[k])); + dl.append(el("dt", label), dd); + } + const form = $("form", frag); + const fs = $(".decision", form); + DECISIONS.forEach(([v, label], n) => { + const l = el("label", undefined, "radio"); + const r = el("input"); + r.type = "radio"; r.name = "decision"; r.value = v; r.required = true; + l.append(r, el("span", `${n + 1}. ${label}`)); + fs.append(l); + }); + for (const s of form.querySelectorAll("select")) fill(s, s.dataset.kind || s.name); + const current = saved(it.item); + const draft = readDraft(it.item); + if (current) setFields(form, current); + if (draft) { setFields(form, draft); dirty = true; } + const status = $(".status", form); + status.textContent = current + ? `Saved revision ${current.revision} at ${current.saved_at}` + (draft ? " · unsaved draft restored" : "") + : draft ? "Unsaved draft restored" : "No decision saved yet"; + const addr = form.elements.namedItem("prior_counterparty_address"); + addr.addEventListener("change", () => { + const v = addr.value.trim(); + if (/^0x[0-9a-fA-F]{40}$/.test(v)) { + const [lead, trail] = matchCounts(v, it.address_under_review); + form.elements.namedItem("matched_leading").value = lead; + form.elements.namedItem("matched_trailing").value = trail; + } + }); + form.addEventListener("input", () => { + dirty = true; + writeDraft(it.item, formFields(form)); + status.textContent = "Unsaved changes"; + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + await save(form, status); + }); + $(".prev", form).addEventListener("click", () => go(index - 1)); + $(".next", form).addEventListener("click", () => go(index + 1)); + if (state.finalized) for (const x of form.elements) x.disabled = true; + section.replaceChildren(frag); +} + +async function save(form, status) { + if (state.finalized) return; + const fields = formFields(form); + if (!fields.decision) { status.textContent = "Choose a decision (1–5) first"; return; } + const before = saved(fields.item); + status.textContent = "Saving…"; + try { + const res = await api("/api/save", { fields, expected_revision: before ? before.revision : 0 }); + state.decisions[String(fields.item)] = res.saved; + clearDraft(fields.item); + dirty = false; + banner(""); + status.textContent = `Saved revision ${res.saved.revision} at ${res.saved.saved_at}`; + renderList(); + } catch (err) { + status.textContent = "Not saved"; + banner(`Not saved: ${err.message}. Your input is kept as a draft in this browser.`); + } +} + +async function finalize() { + const n = state.items.length; + if (!confirm(`Finalize all ${n} decisions? After this, nothing can be changed without a protocol amendment.`)) return; + try { + const res = await api("/api/finalize", {}); + banner(`Finalized. Submission hash ${res.content_sha256}. Send submission.json to the maintainer.`, "ok"); + state = await api("/api/state"); + render(); + } catch (err) { + banner(`Not finalized: ${err.message}`); + } +} + +document.addEventListener("keydown", (e) => { + if (!state) return; + const form = $("#item form"); + const typing = ["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement?.tagName); + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") { + e.preventDefault(); + if (form) form.requestSubmit(); + return; + } + if (typing) return; + if (e.key === "[") go(index - 1); + else if (e.key === "]") go(index + 1); + else if (/^[1-5]$/.test(e.key) && form && !state.finalized) { + const r = form.querySelectorAll('input[name="decision"]')[Number(e.key) - 1]; + r.checked = true; + r.dispatchEvent(new Event("input", { bubbles: true })); + } +}); +window.addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); }); + +(async () => { + $("#finalize").addEventListener("click", finalize); + if (!token) { banner("Open the exact URL printed by `cryptoguard ml review serve` (it carries a session token)."); return; } + try { + state = await api("/api/state"); + } catch (err) { + banner(`Cannot load the review: ${err.message}`); + return; + } + $("#who").textContent = `Reviewer ${state.reviewer} · sample ${state.sample} · ${state.protocol}`; + const first = state.items.findIndex((it) => !saved(it.item)); + index = first < 0 ? 0 : first; + if (state.finalized) banner("This submission is finalized and read-only.", "ok"); + render(); +})(); diff --git a/src/cryptoguard/ml/review_app/index.html b/src/cryptoguard/ml/review_app/index.html new file mode 100644 index 0000000..93a425c --- /dev/null +++ b/src/cryptoguard/ml/review_app/index.html @@ -0,0 +1,70 @@ + + + + + +CryptoGuard review + + + + +
+

CryptoGuard review

+ + + +
+ +
+ +
+

Loading…

+
+
+ + + diff --git a/src/cryptoguard/ml/review_server.py b/src/cryptoguard/ml/review_server.py new file mode 100644 index 0000000..9bbc8fc --- /dev/null +++ b/src/cryptoguard/ml/review_server.py @@ -0,0 +1,207 @@ +"""Local review app for one reviewer (``cryptoguard ml review serve``). Standard library +only, loopback only, and kept apart from the CryptoGuard API, so no research data reaches +the production service. + +Blinding is enforced on the server. +- The server reads only the reviewer package: the blinded sheet, the reviewer's own store + and any blinded replacement lines. +- It cannot read the unblinding key, the manifest or another reviewer's files, because + none of them is in the package. +- Static files carry no data. + +Local web safety: +- every API call needs a per-session token sent in a custom header, which a cross-site + page cannot send without a CORS preflight that is never granted; +- a Host check stops DNS rebinding; +- a strict CSP is set, and the page renders text only (no ``innerHTML``). +""" + +from __future__ import annotations + +import hmac +import json +import secrets +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import resources +from pathlib import Path +from threading import Lock +from typing import Any + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.annotation import ( + PROTOCOL, + AnnotationError, + ReviewerStore, +) + +PACKAGE_INFO = "reviewer.json" +REPLACEMENT_SHEET = "replacement_sheet.jsonl" +STORE_DIR = "annotations" +MAX_BODY = 64 * 1024 +STATIC = {"/": ("index.html", "text/html"), "/app.js": ("app.js", "text/javascript"), + "/app.css": ("app.css", "text/css")} # fmt: skip +CSP = ( + "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; " + "img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" +) +SHEET_FIELDS = ("item", "victim_event_id", "chain_id", "wallet", "address_under_review", + "transaction", "block") # fmt: skip + + +class PackageError(ValueError): + pass + + +def load_package(package: Path, expected_sheet_sha256: str) -> dict[str, Any]: + """Verify the package and return its reviewer, sample hashes and active items.""" + info = json.loads((package / PACKAGE_INFO).read_text(encoding="utf-8")) + sheet_path = package / rs.SHEET + got = rs.file_sha256(sheet_path) + if got != info["sheet_sha256"] or got != expected_sheet_sha256: + raise PackageError(f"{sheet_path}: sha256 {got} is not the frozen sheet") + items = {r["item"]: {k: r[k] for k in SHEET_FIELDS} for r in rs.read_sheet(sheet_path)} + replaced: list[int] = [] + rep_path = package / REPLACEMENT_SHEET + if rep_path.exists(): + for line in rep_path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + r = json.loads(line) + if r["replaces_item"] not in items or r["item"] in items: + raise PackageError(f"{rep_path}: bad replacement for item {r['replaces_item']}") + del items[r["replaces_item"]] + replaced.append(r["replaces_item"]) + items[r["item"]] = {k: r[k] for k in SHEET_FIELDS} + return { + "reviewer": info["reviewer"], + "selection_sha256": info["selection_sha256"], + "sheet_sha256": got, + "items": dict(sorted(items.items())), + "replaced_items": sorted(replaced), + } + + +class ReviewApp: + def __init__(self, package: Path, expected_sheet_sha256: str | None = None) -> None: + expected = expected_sheet_sha256 or rs.FROZEN_V1[rs.SHEET] + self.pkg = load_package(package, expected) + ids = {i: v["victim_event_id"] for i, v in self.pkg["items"].items()} + self.store = ReviewerStore(package / STORE_DIR, self.pkg["reviewer"], ids) + self.token = secrets.token_urlsafe(24) + self.lock = Lock() + + def state(self) -> dict[str, Any]: + latest = self.store.latest() + return { + "reviewer": self.pkg["reviewer"], + "protocol": PROTOCOL, + "sample": self.pkg["selection_sha256"][:12], + "finalized": self.store.finalized, + "items": list(self.pkg["items"].values()), + "replaced_items": self.pkg["replaced_items"], + "decisions": {str(i): a.model_dump(mode="json") for i, a in latest.items()}, + } + + def save(self, body: dict[str, Any]) -> dict[str, Any]: + fields = body.get("fields") + if not isinstance(fields, dict): + raise AnnotationError("missing fields") + with self.lock: + a = self.store.save(fields, expected_revision=body.get("expected_revision")) + return {"saved": a.model_dump(mode="json")} + + def finalize(self) -> dict[str, Any]: + with self.lock: + sub = self.store.finalize( + { + "selection_sha256": self.pkg["selection_sha256"], + "sheet_sha256": self.pkg["sheet_sha256"], + } + ) + return {"content_sha256": sub.content_sha256, "finalized_at": sub.finalized_at} + + +def make_handler(app: ReviewApp, port_ref: list[int]) -> type[BaseHTTPRequestHandler]: + class Handler(BaseHTTPRequestHandler): + server_version = "cryptoguard-review" + sys_version = "" + + def log_message(self, format: str, *args: Any) -> None: + pass # no request logging: paths and bodies stay off the console + + def _headers(self, status: int, ctype: str, length: int) -> None: + self.send_response(status) + self.send_header("Content-Type", f"{ctype}; charset=utf-8") + self.send_header("Content-Length", str(length)) + self.send_header("Content-Security-Policy", CSP) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cache-Control", "no-store") + self.end_headers() + + def _json(self, status: int, obj: Any) -> None: + data = json.dumps(obj).encode() + self._headers(status, "application/json", len(data)) + self.wfile.write(data) + + def _host_ok(self) -> bool: + port = port_ref[0] + return self.headers.get("Host") in (f"127.0.0.1:{port}", f"localhost:{port}") + + def _authorized(self) -> bool: + token = self.headers.get("X-Review-Token", "") + return hmac.compare_digest(token.encode(), app.token.encode()) + + def do_GET(self) -> None: + if not self._host_ok(): + return self._json(HTTPStatus.MISDIRECTED_REQUEST, {"error": "bad host"}) + path = self.path.split("?", 1)[0] + if path in STATIC: + name, ctype = STATIC[path] + data = resources.files("cryptoguard.ml.review_app").joinpath(name).read_bytes() + self._headers(HTTPStatus.OK, ctype, len(data)) + return self.wfile.write(data) # type: ignore[return-value] + if path == "/api/state": + if not self._authorized(): + return self._json(HTTPStatus.FORBIDDEN, {"error": "missing or bad token"}) + return self._json(HTTPStatus.OK, app.state()) + return self._json(HTTPStatus.NOT_FOUND, {"error": "not found"}) + + def do_POST(self) -> None: + if not self._host_ok(): + return self._json(HTTPStatus.MISDIRECTED_REQUEST, {"error": "bad host"}) + if not self._authorized(): + return self._json(HTTPStatus.FORBIDDEN, {"error": "missing or bad token"}) + if self.headers.get("Content-Type", "").split(";")[0] != "application/json": + return self._json(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, {"error": "JSON only"}) + length = int(self.headers.get("Content-Length") or 0) + if length > MAX_BODY: + return self._json(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, {"error": "too large"}) + try: + body = json.loads(self.rfile.read(length) or b"{}") + if not isinstance(body, dict): + raise AnnotationError("body must be a JSON object") + if self.path == "/api/save": + return self._json(HTTPStatus.OK, app.save(body)) + if self.path == "/api/finalize": + return self._json(HTTPStatus.OK, app.finalize()) + except (AnnotationError, json.JSONDecodeError) as exc: + return self._json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + except OSError as exc: # disk full, permissions: the log on disk is unchanged + return self._json( + HTTPStatus.INTERNAL_SERVER_ERROR, + {"error": f"save failed, nothing was written: {exc.strerror or exc}"}, + ) + return self._json(HTTPStatus.NOT_FOUND, {"error": "not found"}) + + return Handler + + +def serve(app: ReviewApp, port: int = 0) -> tuple[ThreadingHTTPServer, str]: + """Bind to 127.0.0.1 and return the server and the URL (token in the fragment, which + browsers never send to the server or in a Referer).""" + port_ref = [0] + httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(app, port_ref)) + port_ref[0] = httpd.server_address[1] + return httpd, f"http://127.0.0.1:{port_ref[0]}/#token={app.token}" diff --git a/src/cryptoguard/ml/unblind.py b/src/cryptoguard/ml/unblind.py new file mode 100644 index 0000000..e121066 --- /dev/null +++ b/src/cryptoguard/ml/unblind.py @@ -0,0 +1,479 @@ +"""Maintainer side of the review: reviewer packages, replacements, the unblinding gate and +the pre-specified analysis (protocol §7 as amended). + +Only this module reads the unblinding key, and only inside ``record_replacement`` (to +build one blinded line) and ``unblind``. ``unblind`` refuses to open the key until: +- the frozen files match their committed hashes; +- at least two distinct reviewers' finalized submissions cover every active item; +- every hash, id and protocol version checks out. +There is no flag to skip the gate. Each opening of the key is appended to an access log. +""" + +from __future__ import annotations + +import json +import shutil +from collections import Counter +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import sample_design as sd +from cryptoguard.ml.agreement import BINARY, agreement, binary +from cryptoguard.ml.annotation import ( + ATTEMPT, + PROTOCOL, + AdjudicationRecord, + AnnotationError, + ReplacementReason, + ReplacementRecord, + Submission, + _canonical, + atomic_write, + load_submission, + now, + read_jsonl, + validate_replacements, +) +from cryptoguard.ml.review_server import PACKAGE_INFO, REPLACEMENT_SHEET + +UNBLIND_VERSION = "unblind/1" +REPLACEMENTS = "replacements.jsonl" +ACCESS_LOG = "key_access.log.jsonl" +MIN_CELL = 10 # smallest subgroup for which agreement statistics are reported + + +class UnblindingRefused(AnnotationError): + """A precondition of the unblinding gate failed; the key was not opened.""" + + +def _log_access(work: Path, purpose: str, detail: Mapping[str, Any]) -> None: + work.mkdir(parents=True, exist_ok=True) + path = work / ACCESS_LOG + line = json.dumps({"at": now(), "purpose": purpose, **detail}, sort_keys=True) + "\n" + with path.open("a", encoding="utf-8", newline="\n") as fh: + fh.write(line) + + +def _key_rows(sample_dir: Path, wanted: set[str]) -> dict[str, dict[str, Any]]: + out: dict[str, dict[str, Any]] = {} + for line in (sample_dir / rs.KEY).read_text(encoding="utf-8").splitlines(): + row = json.loads(line) + if row["packet"]["victim_event_id"] in wanted: + out[row["packet"]["victim_event_id"]] = row + return out + + +def replacements(work: Path) -> list[ReplacementRecord]: + path = work / REPLACEMENTS + return read_jsonl(path, ReplacementRecord) if path.exists() else [] + + +# --- reviewer packages ------------------------------------------------------------------- + + +def make_package(sample_dir: Path, work: Path, reviewer: str, out: Path) -> Path: + """Copy what one reviewer needs and nothing else: the blinded sheet (byte for byte), any + blinded replacement lines and a small info file. Never the key or the manifest.""" + from cryptoguard.ml.annotation import REVIEWER_ID + + if not REVIEWER_ID.match(reviewer): + raise AnnotationError(f"invalid reviewer pseudonym {reviewer!r}") + manifest = rs.verify_frozen(sample_dir) + info_path = out / PACKAGE_INFO + if info_path.exists(): + existing = json.loads(info_path.read_text(encoding="utf-8")) + if existing.get("reviewer") != reviewer: + raise AnnotationError(f"{out} already belongs to reviewer {existing.get('reviewer')}") + elif out.exists() and any(out.iterdir()): + raise AnnotationError(f"{out} is not empty") + out.mkdir(parents=True, exist_ok=True) + shutil.copyfile(sample_dir / rs.SHEET, out / rs.SHEET) + recs = replacements(work) + problems = validate_replacements(manifest, recs) + if problems: + raise AnnotationError("; ".join(problems)) + lines = [ + json.dumps({"replaces_item": r.original_item, **r.sheet_line}, sort_keys=True) + "\n" + for r in recs + ] + if lines: + atomic_write(out / REPLACEMENT_SHEET, "".join(lines).encode()) + info = { + "reviewer": reviewer, + "protocol": PROTOCOL, + "selection_sha256": manifest["selection_sha256"], + "sheet_sha256": rs.file_sha256(out / rs.SHEET), + } + atomic_write(info_path, json.dumps(info, indent=1).encode() + b"\n") + return out + + +def record_replacement( + sample_dir: Path, + work: Path, + *, + original_event_id: str, + reason: ReplacementReason, + evidence: str, + exposed: Sequence[str], + recorded_by: str, +) -> ReplacementRecord: + """Append the next frozen reserve of the original's stratum. Only for technical + inaccessibility; the log keeps every replacement with its reason.""" + manifest = rs.verify_frozen(sample_dir) + recs = replacements(work) + active = {r["victim_event_id"]: r["stratum"] for r in manifest["selected"]} + items = {r["victim_event_id"]: r["item"] for r in rs.read_sheet(sample_dir / rs.SHEET)} + used: Counter[str] = Counter() + for r in recs: + del active[r.original_event_id] + active[r.replacement_event_id] = r.stratum + items[r.replacement_event_id] = r.replacement_item + used[r.stratum] += 1 + stratum = active.get(original_event_id) + if stratum is None: + raise AnnotationError(f"{original_event_id} is not an active sampled item") + reserves = manifest["reserves"].get(stratum, []) + pos = used[stratum] + if pos >= len(reserves): + raise AnnotationError(f"{stratum}: no reserve left (nonresponse; see protocol §5)") + new_id = reserves[pos] + _log_access(work, "replacement sheet line", {"event": new_id}) + packet = _key_rows(sample_dir, {new_id})[new_id]["packet"] + from cryptoguard.ml.review import ReviewPacket + + item = max(items.values()) + 1 + rec = ReplacementRecord( + original_event_id=original_event_id, + original_item=items[original_event_id], + replacement_event_id=new_id, + replacement_item=item, + sheet_line=rs.blind(ReviewPacket.model_validate(packet), item), + stratum=stratum, + reserve_position=pos, + reason=reason, + inaccessibility_evidence=evidence, + reviewers_exposed_to_original=tuple(exposed), + recorded_by=recorded_by, + recorded_at=now(), + ) + problems = validate_replacements(manifest, [*recs, rec]) + if problems: + raise AnnotationError("; ".join(problems)) + work.mkdir(parents=True, exist_ok=True) + with (work / REPLACEMENTS).open("a", encoding="utf-8", newline="\n") as fh: + fh.write(rec.model_dump_json() + "\n") + return rec + + +# --- gate -------------------------------------------------------------------------------- + + +def preflight( + sample_dir: Path, + work: Path, + submission_paths: Sequence[Path], + adjudication_path: Path | None = None, +) -> dict[str, Any]: + """Every check that must pass before the key may be opened. Raises + ``UnblindingRefused`` listing all failures. Never reads the key's contents (only its + hash).""" + problems: list[str] = [] + try: + manifest = rs.verify_frozen(sample_dir) + except rs.ReviewSampleError as exc: + raise UnblindingRefused(f"frozen sample: {exc}") from None + recs = replacements(work) + problems += validate_replacements(manifest, recs) + active = {r["victim_event_id"] for r in manifest["selected"]} + for r in recs: + active.discard(r.original_event_id) + active.add(r.replacement_event_id) + subs: list[Submission] = [] + for p in submission_paths: + try: + subs.append(load_submission(p)) + except (AnnotationError, OSError) as exc: + problems.append(str(exc)) + reviewers = [s.reviewer for s in subs] + if len(set(reviewers)) < 2: + problems.append("two finalized submissions from distinct reviewers are required") + if len(set(reviewers)) != len(reviewers): + problems.append("a reviewer submitted twice") + for s in subs: + if s.selection_sha256 != manifest["selection_sha256"]: + problems.append(f"{s.reviewer}: submission is for another sample") + if s.sheet_sha256 != rs.FROZEN_V1[rs.SHEET]: + problems.append(f"{s.reviewer}: submission is for another reviewer sheet") + if s.protocol != PROTOCOL: + problems.append(f"{s.reviewer}: protocol {s.protocol}") + got = {a.victim_event_id for a in s.decisions} + if got - active: + problems.append(f"{s.reviewer}: {len(got - active)} unknown or replaced item(s)") + if active - got: + problems.append(f"{s.reviewer}: {len(active - got)} active item(s) without a decision") + adjudications: list[AdjudicationRecord] = [] + if adjudication_path is not None: + adjudications = read_jsonl(adjudication_path, AdjudicationRecord) + decided = {s.reviewer: {a.victim_event_id: a.decision for a in s.decisions} for s in subs} + seen: set[str] = set() + for adj in adjudications: + if adj.victim_event_id in seen: + problems.append(f"{adj.victim_event_id}: adjudicated twice") + seen.add(adj.victim_event_id) + if adj.adjudicator in decided: + problems.append(f"{adj.victim_event_id}: adjudicator is one of the reviewers") + originals = {r: d.get(adj.victim_event_id) for r, d in decided.items()} + if adj.reviewer_decisions != originals: + problems.append( + f"{adj.victim_event_id}: recorded decisions differ from submissions" + ) + if len(set(originals.values())) < 2: + problems.append(f"{adj.victim_event_id}: adjudication of an agreed item") + if problems: + raise UnblindingRefused("; ".join(problems)) + return { + "manifest": manifest, + "submissions": subs, + "replacements": recs, + "adjudications": adjudications, + "active": active, + } + + +def unblind( + sample_dir: Path, + work: Path, + submission_paths: Sequence[Path], + adjudication_path: Path | None = None, +) -> dict[str, Any]: + """Run the gate, open the key, write the local item table and return the aggregate + report. Reviewer decisions are never overwritten by source labels.""" + pre = preflight(sample_dir, work, submission_paths, adjudication_path) + active: set[str] = pre["active"] + subs: list[Submission] = pre["submissions"] + _log_access( + work, + "unblind", + { + "reviewers": sorted(s.reviewer for s in subs), + "submissions": sorted(s.content_sha256 for s in subs), + }, + ) + key = _key_rows(sample_dir, active) + report = analyse(pre["manifest"], subs, pre["replacements"], pre["adjudications"], key) + rows = item_table(subs, pre["adjudications"], key) + work.mkdir(parents=True, exist_ok=True) + atomic_write(work / "unblinded_items.jsonl", b"".join(_canonical(r) + b"\n" for r in rows)) + body = json.dumps(report, indent=1, sort_keys=True).encode() + b"\n" + atomic_write(work / "unblinded_report.json", body) + return report + + +# --- analysis ---------------------------------------------------------------------------- + + +def _decisions(subs: Sequence[Submission]) -> dict[str, dict[str, str]]: + return {s.reviewer: {a.victim_event_id: a.decision for a in s.decisions} for s in subs} + + +def item_table( + subs: Sequence[Submission], + adjudications: Sequence[AdjudicationRecord], + key: Mapping[str, Mapping[str, Any]], +) -> list[dict[str, Any]]: + """Row-level, local only (contains addresses): reviewer decisions next to the source.""" + adj = {a.victim_event_id: a for a in adjudications} + rows = [] + for e in sorted(key): + packet = key[e]["packet"] + reviews = {s.reviewer: next(a for a in s.decisions if a.victim_event_id == e) for s in subs} + found = { + r: a.prior_counterparty_address.lower() + for r, a in reviews.items() + if a.prior_counterparty_address + } + imitated = (packet.get("imitated") or "").lower() + rows.append( + { + "victim_event_id": e, + "stratum": key[e]["stratum"], + "source_subtype": packet["subtype"], + "source_labels": packet["source_labels"], + "rival_lookalikes": len(packet["competing_lookalikes"]), + "reviewer_decisions": {r: a.decision for r, a in reviews.items()}, + "reviewer_counterparty_matches_source_imitated": { + r: addr == imitated for r, addr in found.items() + }, + "adjudicated": adj[e].final_decision if e in adj else None, + } + ) + return rows + + +def _source_category(decisions: Sequence[str]) -> str: + b = {binary(d) for d in decisions} + if any(d == "insufficient_evidence" for d in decisions): + return "insufficient_evidence" + if len(b) > 1: + return "reviewer_disagreement" + if b == {"attempt"}: + both_confirmed = all(d == "confirmed_poisoning_attempt" for d in decisions) + return "full_agreement" if both_confirmed else "partial_agreement" + if any(d == "conflicting_evidence" for d in decisions): + return "unresolved_ambiguity" + return "source_disagreement" + + +def analyse( + manifest: Mapping[str, Any], + subs: Sequence[Submission], + recs: Sequence[ReplacementRecord], + adjudications: Sequence[AdjudicationRecord], + key: Mapping[str, Mapping[str, Any]] | None = None, +) -> dict[str, Any]: + """Pre-specified analysis; aggregate only. + + The primary outcome is an item counted as an attempt only if *every* reviewer marked + it confirmed or likely (protocol §7). A replaced original is nonresponse in the + bounds. ``key`` (source information) is needed only for the source comparison.""" + d = sd.design(manifest) + stratum_of = dict(d.item_cell) + for r in recs: + stratum_of[r.replacement_event_id] = r.stratum + # Replacements take their original's slot in the design (same stratum, frozen order). + slot = {r.replacement_event_id: r.original_event_id for r in recs} + while any(v in slot for v in slot.values()): + slot = {k: slot.get(v, v) for k, v in slot.items()} + decisions = _decisions(subs) + reviewers = sorted(decisions) + items = sorted(set.intersection(*(set(v) for v in decisions.values()))) + + def outcome(rule: str) -> dict[str, bool | None]: + out: dict[str, bool | None] = dict.fromkeys(d.item_cell) + for e in items: + labels = [decisions[r][e] for r in reviewers] + flags = [x in ATTEMPT for x in labels] + out[slot.get(e, e)] = all(flags) if rule == "all" else any(flags) + return out + + primary, lenient = outcome("all"), outcome("any") + adjudicated = dict(primary) + for a in adjudications: + adjudicated[slot.get(a.victim_event_id, a.victim_event_id)] = a.final_decision in ATTEMPT + subtypes = sorted({c.subtype for c in d.cells.values() if c.selected}) + + def block(o: Mapping[str, bool | None]) -> dict[str, Any]: + overall = sd.estimate(d, o) + return { + "overall": overall, + "attempt_level_bounds": sd.attempt_bounds( + overall.get("wilson95_design"), d.population, d.queue_packets + ), + "by_subtype": {s: sd.estimate(d, o, scope=sd.subtype_scope(s)) for s in subtypes}, + } + + pair = reviewers[:2] + a_lab = decisions[pair[0]] + b_lab = decisions[pair[1]] + agree: dict[str, Any] = { + "reviewers": pair, + "five_category": agreement(a_lab, b_lab), + "binary": agreement( + {k: binary(v) for k, v in a_lab.items()}, + {k: binary(v) for k, v in b_lab.items()}, + BINARY, + ), + "by_subgroup": {}, + } + for name, member in _subgroups(stratum_of).items(): + ids = [e for e in items if e in member] + if len(ids) < MIN_CELL: + agree["by_subgroup"][name] = {"items": len(ids), "note": f"fewer than {MIN_CELL}"} + continue + agree["by_subgroup"][name] = agreement( + {e: binary(a_lab[e]) for e in ids}, {e: binary(b_lab[e]) for e in ids}, BINARY + ) + exposure = { + r: { + "used_explorer": sum(a.used_explorer for a in s.decisions), + "viewed_after_cutoff": dict(Counter(a.viewed_after_cutoff for a in s.decisions)), + "saw_external_label": dict(Counter(a.saw_external_label for a in s.decisions)), + "saw_source_or_model_output": sum(a.saw_source_or_model_output for a in s.decisions), + } + for r, s in zip(reviewers, sorted(subs, key=lambda s: s.reviewer), strict=True) + } + # Exploratory (protocol amendment 1 §6): attempt decisions by whether the reviewer saw + # activity after the cutoff. Not a causal comparison. + exposure_comparison = { + s.reviewer: { + seen: { + "items": sum(1 for a in s.decisions if a.viewed_after_cutoff == seen), + "attempt": sum( + 1 + for a in s.decisions + if a.viewed_after_cutoff == seen and a.decision in ATTEMPT + ), + } + for seen in ("no", "yes", "unsure") + } + for s in subs + } + report: dict[str, Any] = { + "unblind_version": UNBLIND_VERSION, + "exposure_comparison_exploratory": exposure_comparison, + "protocol": PROTOCOL, + "selection_sha256": manifest["selection_sha256"], + "submissions": {s.reviewer: s.content_sha256 for s in subs}, + "items_reviewed_by_all": len(items), + "replacements": [ + {"stratum": r.stratum, "reason": r.reason, "reserve_position": r.reserve_position} + for r in recs + ], + "primary_all_reviewers_attempt": block(primary), + "sensitivity_any_reviewer_attempt": block(lenient), + "secondary_adjudicated": block(adjudicated) if adjudications else None, + "replacement_sensitivity": block( + { + **primary, + **dict.fromkeys( + (slot.get(r.original_event_id, r.original_event_id) for r in recs), None + ), + } + ) + if recs + else None, + "agreement": agree, + "exposure": exposure, + "decision_counts": {r: dict(Counter(decisions[r].values())) for r in reviewers}, + "rpc_requests": 0, + } + if key is not None: + cats = Counter(_source_category([decisions[r][e] for r in reviewers]) for e in items) + matched: Counter[str] = Counter() + for e in items: + imitated = (key[e]["packet"].get("imitated") or "").lower() + for s in subs: + ann = next(x for x in s.decisions if x.victim_event_id == e) + if ann.prior_counterparty_address: + matched[ + "same" if ann.prior_counterparty_address.lower() == imitated else "other" + ] += 1 + report["source_comparison"] = { + "categories": dict(cats), + "reviewer_counterparty_vs_source_imitated": dict(matched), + "note": "the source labels every item a poisoning attempt; reviewer decisions are " + "never overwritten by it", + } + return report + + +def _subgroups(stratum_of: Mapping[str, str]) -> dict[str, set[str]]: + groups: dict[str, set[str]] = {} + for e, name in stratum_of.items(): + subtype, year, rival = sd.parse_stratum(name) + for g in (f"subtype={subtype}", f"year={year}", f"rival={'yes' if rival else 'no'}"): + groups.setdefault(g, set()).add(e) + return dict(sorted(groups.items())) diff --git a/tests/unit/test_ml_annotation.py b/tests/unit/test_ml_annotation.py new file mode 100644 index 0000000..a319b8e --- /dev/null +++ b/tests/unit/test_ml_annotation.py @@ -0,0 +1,220 @@ +"""Annotation schema, durable reviewer store and submission finalization (Phase 11.4). + +Decisions here are synthetic test inputs, not labels. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from cryptoguard.ml import annotation as an +from cryptoguard.ml.review import import_reviews +from tests.review_fixtures import ATTEMPT_FIELDS, INSUFFICIENT_FIELDS, fields + +ITEMS = {1: "00000000000000a1", 2: "00000000000000a2", 3: "00000000000000a3"} +SAMPLE = {"selection_sha256": "s" * 64, "sheet_sha256": "h" * 64} + + +def store(tmp: Path, reviewer: str = "A") -> an.ReviewerStore: + return an.ReviewerStore(tmp / reviewer, reviewer, ITEMS) + + +def complete(s: an.ReviewerStore) -> None: + for item, e in ITEMS.items(): + s.save(fields(item, e)) + + +# --- schema -------------------------------------------------------------------------------- + + +def make(**over: object) -> an.Annotation: + return an.Annotation.model_validate( + {**fields(1, ITEMS[1]), "reviewer": "A", "revision": 1, "saved_at": "t", **over} + ) + + +def test_confirmed_needs_evidence_but_insufficient_does_not() -> None: + make() + make(**{k: v for k, v in INSUFFICIENT_FIELDS.items() if k != "rationale"}, rationale="x") + for bad, match in ( + ({"prior_counterparty": "not_loaded", "prior_counterparty_address": None}, "imitated"), + ({"matched_leading": None}, "matched"), + ({"legitimate_explanation": "not_loaded"}, "legitimate explanation"), + ({"planting_transfer": "not_available"}, "planting"), + ({"rationale": "looks bad"}, "5 words"), + ): + with pytest.raises(ValueError, match=match): + make(**bad) + + +def test_other_decisions_have_their_own_rules() -> None: + with pytest.raises(ValueError, match="legitimate"): + make(decision="confirmed_legitimate_interaction") + with pytest.raises(ValueError, match="contradictory"): + make(decision="conflicting_evidence") + make(decision="conflicting_evidence", prior_counterparty="contradictory") + with pytest.raises(ValueError, match="pseudonym"): + make(reviewer="Dr. Real Name") + with pytest.raises(ValueError, match="decision"): + make(decision="probably_fine") + + +def test_missing_evidence_is_not_negative_evidence() -> None: + """'likely' with unavailable counterparty data is allowed; it does not become + 'not observed' or a legitimate label.""" + a = make( + decision="likely_poisoning_attempt", + prior_counterparty="not_available", + prior_counterparty_address=None, + matched_leading=None, + matched_trailing=None, + legitimate_explanation="not_available", + ) + assert a.prior_counterparty == "not_available" + + +def test_annotations_convert_to_the_existing_review_import(tmp_path: Path) -> None: + a = make() + path = tmp_path / "decisions.jsonl" + path.write_text(a.to_review_decision().model_dump_json() + "\n", encoding="utf-8") + history = import_reviews(path, {ITEMS[1]}, []) + assert history[0].tier == "verified_attempt" + assert history[0].source == "review:A" + + +# --- store --------------------------------------------------------------------------------- + + +def test_save_revise_and_resume(tmp_path: Path) -> None: + with store(tmp_path) as s: + first = s.save(fields(1, ITEMS[1])) + second = s.save(fields(1, ITEMS[1], INSUFFICIENT_FIELDS), expected_revision=1) + assert (first.revision, second.revision) == (1, 2) + again = store(tmp_path) # a new process + assert again.latest()[1].decision == "insufficient_evidence" + assert [a.revision for a in again.history(1)] == [1, 2] # the original is kept + + +def test_duplicate_submit_is_idempotent_and_stale_edits_are_refused(tmp_path: Path) -> None: + with store(tmp_path) as s: + a = s.save(fields(1, ITEMS[1])) + assert s.save(fields(1, ITEMS[1])) == a + assert len(s.entries) == 1 + with pytest.raises(an.AnnotationError, match="reload"): + s.save(fields(1, ITEMS[1], INSUFFICIENT_FIELDS), expected_revision=0) + + +def test_unknown_item_wrong_event_and_invalid_fields_are_rejected(tmp_path: Path) -> None: + with store(tmp_path) as s: + with pytest.raises(an.AnnotationError, match="unknown item"): + s.save(fields(9, "0" * 16)) + with pytest.raises(an.AnnotationError, match="does not match"): + s.save(fields(1, ITEMS[2])) + with pytest.raises(an.AnnotationError, match="planting"): + s.save({**fields(1, ITEMS[1]), "planting_transfer": "not_loaded"}) + assert s.entries == [] + + +def test_the_store_must_be_locked_to_write_and_only_once(tmp_path: Path) -> None: + s = store(tmp_path) + with pytest.raises(an.AnnotationError, match="with"): + s.save(fields(1, ITEMS[1])) + with s, pytest.raises(an.AnnotationError, match="another review session"), store(tmp_path): + pass + + +def test_a_failed_disk_write_changes_nothing(tmp_path: Path, monkeypatch) -> None: + with store(tmp_path) as s: + s.save(fields(1, ITEMS[1])) + before = (tmp_path / "A" / an.LOG).read_bytes() + + def full_disk(*_: object) -> None: + raise OSError(28, "No space left on device") + + monkeypatch.setattr(an.os, "replace", full_disk) + with pytest.raises(OSError, match="No space"): + s.save(fields(2, ITEMS[2])) + assert len(s.entries) == 1 + assert (tmp_path / "A" / an.LOG).read_bytes() == before + + +def test_an_interrupted_save_leaves_the_log_intact(tmp_path: Path) -> None: + with store(tmp_path) as s: + s.save(fields(1, ITEMS[1])) + (tmp_path / "A" / (an.LOG + ".tmp")).write_bytes(b'{"half a reco') + s2 = store(tmp_path) + assert len(s2.entries) == 1 + assert not (tmp_path / "A" / (an.LOG + ".tmp")).exists() + + +@pytest.mark.parametrize("edit", ["flip", "truncate", "drop_first", "other_reviewer"]) +def test_tampering_breaks_the_hash_chain(tmp_path: Path, edit: str) -> None: + with store(tmp_path) as s: + s.save(fields(1, ITEMS[1])) + s.save(fields(2, ITEMS[2])) + log = tmp_path / "A" / an.LOG + lines = log.read_text(encoding="utf-8").splitlines() + if edit == "flip": + lines[0] = lines[0].replace("confirmed_poisoning_attempt", "likely_poisoning_attempt") + elif edit == "truncate": + lines[1] = lines[1][:40] + elif edit == "drop_first": + lines = lines[1:] + else: + lines[0] = lines[0].replace('"reviewer":"A"', '"reviewer":"B"') + log.write_text("\n".join(lines) + "\n", encoding="utf-8") + with pytest.raises(an.StoreCorruptError): + store(tmp_path) + + +# --- finalization ---------------------------------------------------------------------------- + + +def test_finalize_needs_every_item_then_freezes(tmp_path: Path) -> None: + with store(tmp_path) as s: + s.save(fields(1, ITEMS[1])) + with pytest.raises(an.AnnotationError, match="2 item"): + s.finalize(SAMPLE) + s.save(fields(2, ITEMS[2])) + s.save(fields(3, ITEMS[3], INSUFFICIENT_FIELDS)) + sub = s.finalize(SAMPLE) + with pytest.raises(an.FinalizedError): + s.save(fields(1, ITEMS[1], INSUFFICIENT_FIELDS)) + with pytest.raises(an.FinalizedError): + s.finalize(SAMPLE) + loaded = an.load_submission(tmp_path / "A" / an.SUBMISSION) + assert loaded == sub + assert [a.item for a in loaded.decisions] == [1, 2, 3] + assert store(tmp_path).finalized # survives a restart + + +def test_edited_submissions_are_detected(tmp_path: Path) -> None: + with store(tmp_path) as s: + complete(s) + s.finalize(SAMPLE) + path = tmp_path / "A" / an.SUBMISSION + body = json.loads(path.read_text(encoding="utf-8")) + body["decisions"][0]["decision"] = "likely_poisoning_attempt" + path.write_text(json.dumps(body), encoding="utf-8") + with pytest.raises(an.StoreCorruptError, match="edited"): + an.load_submission(path) + path.write_text("{not json", encoding="utf-8") + with pytest.raises(an.StoreCorruptError): + an.load_submission(path) + + +def test_reviewers_have_separate_stores(tmp_path: Path) -> None: + with store(tmp_path, "A") as a, store(tmp_path, "B") as b: + a.save(fields(1, ITEMS[1])) + b.save(fields(1, ITEMS[1], INSUFFICIENT_FIELDS)) + assert store(tmp_path, "A").latest()[1].reviewer == "A" + assert store(tmp_path, "B").latest()[1].decision == "insufficient_evidence" + with pytest.raises(an.StoreCorruptError, match="reviewer"): + an.ReviewerStore(tmp_path / "A", "B", ITEMS) # B cannot open A's log as its own + + +def test_attempt_fields_fixture_is_valid() -> None: + assert ATTEMPT_FIELDS["decision"] in an.ATTEMPT diff --git a/tests/unit/test_ml_reconcile.py b/tests/unit/test_ml_reconcile.py index 131b71a..b6c670e 100644 --- a/tests/unit/test_ml_reconcile.py +++ b/tests/unit/test_ml_reconcile.py @@ -325,6 +325,13 @@ def test_counterfeit_rows_are_attempts() -> None: "cryptoguard.ml.reconcile", "cryptoguard.ml.cross_dataset", "cryptoguard.ml.bench_archive", + "cryptoguard.ml.review_sample", + "cryptoguard.ml.sample_design", + "cryptoguard.ml.annotation", + "cryptoguard.ml.agreement", + "cryptoguard.ml.review_server", + "cryptoguard.ml.unblind", + "cryptoguard.ml.benchmark", ) # The pure lookalike predicates live in detectors.poisoning, whose base module imports type # definitions from history/services/risk. Persistence and the API are what could create, diff --git a/tests/unit/test_ml_review_server.py b/tests/unit/test_ml_review_server.py new file mode 100644 index 0000000..5003eaf --- /dev/null +++ b/tests/unit/test_ml_review_server.py @@ -0,0 +1,187 @@ +"""Local review app: blinding, token and host checks, durable saves and finalization. + +The server runs on 127.0.0.1 with a synthetic frozen sample. Every response is searched for +values that only the unblinding key holds. +""" + +from __future__ import annotations + +import json +import re +import threading +import urllib.error +import urllib.request +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.review_server import ReviewApp, serve +from cryptoguard.ml.unblind import make_package +from tests.review_fixtures import INSUFFICIENT_FIELDS, fields, frozen + + +@pytest.fixture +def running(tmp_path: Path, monkeypatch) -> Iterator[dict[str, Any]]: + _, sample, _ = frozen(tmp_path, monkeypatch) + pkg = make_package(sample, tmp_path / "work", "A", tmp_path / "pkg-A") + app = ReviewApp(pkg) + with app.store: + httpd, url = serve(app) + t = threading.Thread(target=httpd.serve_forever, daemon=True) + t.start() + base = url.split("/#")[0] + try: + yield {"base": base, "token": app.token, "sample": sample, "pkg": pkg, "app": app} + finally: + httpd.shutdown() + httpd.server_close() + + +def call( + env: dict[str, Any], + path: str, + body: Any = None, + *, + token: str | None = None, + headers: dict[str, str] | None = None, +) -> tuple[int, Any, dict[str, str]]: + h = {"X-Review-Token": env["token"] if token is None else token, **(headers or {})} + data = None + if body is not None: + data = json.dumps(body).encode() + h.setdefault("Content-Type", "application/json") + req = urllib.request.Request(env["base"] + path, data=data, headers=h) # noqa: S310 + try: + with urllib.request.urlopen(req, timeout=10) as res: # noqa: S310 - loopback test + raw = res.read() + return res.status, _parse(raw, res.headers), dict(res.headers) + except urllib.error.HTTPError as err: + return err.code, json.loads(err.read() or b"{}"), dict(err.headers) + + +def _parse(raw: bytes, headers: Any) -> Any: + return json.loads(raw) if "json" in headers.get("Content-Type", "") else raw.decode() + + +def hidden_values(sample: Path) -> set[str]: + """Strings only the key holds: imitated addresses, payoffs, rivals, subtypes, labels.""" + out: set[str] = set() + for line in (sample / rs.KEY).read_text(encoding="utf-8").splitlines(): + p = json.loads(line)["packet"] + out |= {p["imitated"], *p["competing_lookalikes"], *p["source_labels"]} + out |= {x.split()[0] for x in p["payment_evidence"]} + out.add(p["evidence_summary"]) + return out + + +def test_package_holds_only_the_blinded_sheet(running: dict[str, Any]) -> None: + files = {p.name for p in running["pkg"].iterdir()} + assert files == {rs.SHEET, "reviewer.json", "annotations"} + assert (running["pkg"] / rs.SHEET).read_bytes() == (running["sample"] / rs.SHEET).read_bytes() + + +def test_no_response_contains_hidden_answers(running: dict[str, Any]) -> None: + hidden = hidden_values(running["sample"]) + subtypes = ("fake_token", "spoofed_transfer_from", "zero_value", "dust") + bodies = [] + for path in ("/", "/app.js", "/app.css"): + _, body, _ = call(running, path) + bodies.append(body) + static = "\n".join(bodies) + bodies = [] + for path in ("/api/state", "/nope"): + _, body, _ = call(running, path) + bodies.append(json.dumps(body)) + status, saved, _ = call(running, "/api/save", {"fields": fields(1, _event(running, 1))}) + assert status == 200 + bodies.append(json.dumps(saved)) + _, bad, _ = call(running, "/api/save", {"fields": fields(1, "0" * 16)}) + bodies.append(json.dumps(bad)) # error messages too + api = "\n".join(bodies) + leaked = [h for h in hidden if h and h in api + static] + assert leaked == [] + assert not any(s in api for s in subtypes) + assert not re.search(r"0x[0-9a-fA-F]{40}", static) # static files carry no addresses + + +def _event(env: dict[str, Any], item: int) -> str: + state = env["app"].state() + return next(i["victim_event_id"] for i in state["items"] if i["item"] == item) + + +def test_api_needs_the_session_token_and_a_loopback_host(running: dict[str, Any]) -> None: + assert call(running, "/api/state", token="")[0] == 403 + assert call(running, "/api/state", token="guess")[0] == 403 + body = {"fields": fields(1, _event(running, 1))} + assert call(running, "/api/save", body, token="")[0] == 403 + assert call(running, "/api/state", headers={"Host": "evil.example:80"})[0] == 421 + assert call(running, "/", headers={"Host": "evil.example"})[0] == 421 + + +def test_security_headers_and_request_limits(running: dict[str, Any]) -> None: + _, _, headers = call(running, "/") + assert "script-src 'self'" in headers["Content-Security-Policy"] + assert headers["X-Content-Type-Options"] == "nosniff" + assert headers["Cache-Control"] == "no-store" + plain = {"Content-Type": "text/plain"} + assert call(running, "/api/save", {"fields": {}}, headers=plain)[0] == 415 + big = {"fields": {"notes": "x" * 70_000}} + assert call(running, "/api/save", big)[0] == 413 + assert call(running, "/api/save", [1, 2])[0] == 400 + + +def test_save_resume_and_finalize_over_http(running: dict[str, Any]) -> None: + state = call(running, "/api/state")[1] + assert state["reviewer"] == "A" + assert state["decisions"] == {} + for it in state["items"]: + status, res, _ = call( + running, + "/api/save", + {"fields": fields(it["item"], it["victim_event_id"]), "expected_revision": 0}, + ) + assert status == 200, res + # A stale client is told to reload instead of overwriting. + first = state["items"][0] + stale = { + "fields": fields(first["item"], first["victim_event_id"], INSUFFICIENT_FIELDS), + "expected_revision": 0, + } + assert call(running, "/api/save", stale)[0] == 400 + resumed = ReviewApp(running["pkg"]).state() # what a restarted server would serve + assert len(resumed["decisions"]) == len(state["items"]) + status, fin, _ = call(running, "/api/finalize", {}) + assert status == 200 + assert len(fin["content_sha256"]) == 64 + stale["expected_revision"] = 1 + status, err, _ = call(running, "/api/save", stale) + assert status == 400 + assert "finalized" in err["error"] + assert (running["pkg"] / "annotations" / "submission.json").exists() + + +def test_invalid_decisions_get_a_useful_error(running: dict[str, Any]) -> None: + f = {**fields(1, _event(running, 1)), "prior_counterparty_address": None} + status, err, _ = call(running, "/api/save", {"fields": f}) + assert status == 400 + assert "imitated earlier counterparty" in err["error"] + + +def test_a_second_server_cannot_open_the_same_store(running: dict[str, Any]) -> None: + from cryptoguard.ml.annotation import AnnotationError + + other = ReviewApp(running["pkg"]) + with pytest.raises(AnnotationError, match="another review session"), other.store: + pass + + +def test_a_tampered_sheet_will_not_be_served(running: dict[str, Any]) -> None: + from cryptoguard.ml.review_server import PackageError + + sheet = running["pkg"] / rs.SHEET + sheet.write_bytes(sheet.read_bytes() + b"\n") + with pytest.raises(PackageError, match="frozen sheet"): + ReviewApp(running["pkg"]) diff --git a/tests/unit/test_ml_unblind.py b/tests/unit/test_ml_unblind.py new file mode 100644 index 0000000..3e82a7f --- /dev/null +++ b/tests/unit/test_ml_unblind.py @@ -0,0 +1,278 @@ +"""Agreement statistics, replacements, the unblinding gate and the pre-specified analysis. + +All reviewer decisions are synthetic software inputs; no real label is created. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import unblind as ub +from cryptoguard.ml.agreement import BINARY, agreement +from cryptoguard.ml.annotation import ( + AdjudicationRecord, + AnnotationError, + ReviewerStore, + load_submission, +) +from cryptoguard.ml.review_server import REPLACEMENT_SHEET, ReviewApp +from tests.review_fixtures import INSUFFICIENT_FIELDS, fields, frozen + +# --- agreement ----------------------------------------------------------------------------- + + +def labels(pairs: list[tuple[str, str]]) -> tuple[dict[str, str], dict[str, str]]: + return ({str(i): a for i, (a, _) in enumerate(pairs)}, + {str(i): b for i, (_, b) in enumerate(pairs)}) # fmt: skip + + +def test_kappa_and_ac1_match_hand_computation() -> None: + # 2x2 table [[20, 5], [10, 15]]: po = 0.7, pe = 0.5, kappa = 0.4. + pairs = ( + [("attempt", "attempt")] * 20 + + [("attempt", "not_attempt")] * 5 + + [("not_attempt", "attempt")] * 10 + + [("not_attempt", "not_attempt")] * 15 + ) + a, b = labels(pairs) + r = agreement(a, b, BINARY) + assert r["observed_agreement"] == pytest.approx(0.7) + assert r["cohen_kappa"] == pytest.approx(0.4) + # AC1: pi = (0.55, 0.45), pe = 2 * 0.55 * 0.45 / 1 = 0.495. + assert r["gwet_ac1"] == pytest.approx((0.7 - 0.495) / (1 - 0.495)) + assert r["confusion"]["not_attempt"]["attempt"] == 10 + assert r["disagreements"] == 15 + + +def test_kappa_is_undefined_not_zero_when_both_use_one_category() -> None: + a, b = labels([("attempt", "attempt")] * 6) + r = agreement(a, b, BINARY) + assert r["cohen_kappa"] is None + assert "single" in r["kappa_note"] + assert r["gwet_ac1"] == pytest.approx(1.0) + empty = agreement({}, {}, BINARY) + assert empty["cohen_kappa"] is None + assert empty["observed_agreement"] is None + + +def test_unpaired_items_and_foreign_labels_are_reported() -> None: + r = agreement({"1": "attempt", "2": "attempt"}, {"1": "attempt"}, BINARY) + assert r["unpaired"] == {"only_a": 1, "only_b": 0} + assert r["paired_items"] == 1 + with pytest.raises(ValueError, match="outside"): + agreement({"1": "benign"}, {"1": "attempt"}, BINARY) + + +# --- workflow helpers -------------------------------------------------------------------------- + + +def review(pkg: Path, decide: Any) -> Path: + """Save one synthetic decision per item through the store, then finalize.""" + app = ReviewApp(pkg) + with app.store: + for it in app.state()["items"]: + app.store.save(fields(it["item"], it["victim_event_id"], decide(it["item"]))) + app.finalize() + return pkg / "annotations" / "submission.json" + + +def attempt(_: int) -> dict[str, Any]: + from tests.review_fixtures import ATTEMPT_FIELDS + + return ATTEMPT_FIELDS + + +@pytest.fixture +def study(tmp_path: Path, monkeypatch) -> dict[str, Any]: + _, sample, manifest = frozen(tmp_path, monkeypatch) + work = tmp_path / "work" + pkgs = {r: ub.make_package(sample, work, r, tmp_path / f"pkg-{r}") for r in ("A", "B")} + return {"sample": sample, "work": work, "pkgs": pkgs, "manifest": manifest, "tmp": tmp_path} + + +# --- gate -------------------------------------------------------------------------------------- + + +def test_gate_refuses_before_two_finalized_reviewers(study: dict[str, Any]) -> None: + a = review(study["pkgs"]["A"], attempt) + with pytest.raises(ub.UnblindingRefused, match="two finalized"): + ub.unblind(study["sample"], study["work"], [a]) + with pytest.raises(ub.UnblindingRefused, match="submitted twice"): + ub.unblind(study["sample"], study["work"], [a, a]) + missing = study["tmp"] / "pkg-B" / "annotations" / "submission.json" + with pytest.raises(ub.UnblindingRefused): + ub.unblind(study["sample"], study["work"], [a, missing]) + assert not (study["work"] / ub.ACCESS_LOG).exists() # the key was never opened + + +def test_gate_refuses_incomplete_or_edited_submissions(study: dict[str, Any]) -> None: + a = review(study["pkgs"]["A"], attempt) + app = ReviewApp(study["pkgs"]["B"]) + with app.store: + it = app.state()["items"][0] + app.store.save(fields(it["item"], it["victim_event_id"])) + with pytest.raises(AnnotationError, match="no decision"), app.store: + app.finalize() + b = review(study["pkgs"]["B"], attempt) + body = json.loads(b.read_text(encoding="utf-8")) + body["decisions"][0]["decision"] = "insufficient_evidence" + b.write_text(json.dumps(body), encoding="utf-8") + with pytest.raises(ub.UnblindingRefused, match="edited"): + ub.unblind(study["sample"], study["work"], [a, b]) + + +def test_gate_refuses_a_modified_key(study: dict[str, Any]) -> None: + a = review(study["pkgs"]["A"], attempt) + b = review(study["pkgs"]["B"], attempt) + key = study["sample"] / rs.KEY + key.write_bytes(key.read_bytes().replace(b"tsuchiya-payoff:confirmed", b"x", 1)) + with pytest.raises(ub.UnblindingRefused, match="unblinding_key"): + ub.unblind(study["sample"], study["work"], [a, b]) + + +def test_unblinding_reports_agreement_estimates_and_source_comparison( + study: dict[str, Any], +) -> None: + a = review(study["pkgs"]["A"], attempt) + b = review(study["pkgs"]["B"], lambda i: INSUFFICIENT_FIELDS if i % 6 == 0 else attempt(i)) + report = ub.unblind(study["sample"], study["work"], [a, b]) + n = len(study["manifest"]["selected"]) + disagree = n // 6 + assert report["items_reviewed_by_all"] == n + primary = report["primary_all_reviewers_attempt"]["overall"] + lenient = report["sensitivity_any_reviewer_attempt"]["overall"] + assert primary["positives"] == n - disagree + assert lenient["positives"] == n + assert primary["estimate"] < lenient["estimate"] == 1.0 + assert report["agreement"]["binary"]["disagreements"] == disagree + lo, hi = report["primary_all_reviewers_attempt"]["attempt_level_bounds"] + assert lo <= primary["estimate"] <= hi + cats = report["source_comparison"]["categories"] + assert cats == {"full_agreement": n - disagree, "insufficient_evidence": disagree} + log = (study["work"] / ub.ACCESS_LOG).read_text(encoding="utf-8").splitlines() + assert json.loads(log[-1])["purpose"] == "unblind" + rows = (study["work"] / "unblinded_items.jsonl").read_text(encoding="utf-8").splitlines() + assert len(rows) == n # row-level table stays in the git-ignored work directory + assert "0x" not in json.dumps(report) # the aggregate report carries no addresses + + +def test_adjudication_is_separate_and_by_a_third_person(study: dict[str, Any]) -> None: + a = review(study["pkgs"]["A"], attempt) + b = review(study["pkgs"]["B"], lambda i: INSUFFICIENT_FIELDS if i == 1 else attempt(i)) + sub_b = load_submission(b) + item1 = next(x for x in sub_b.decisions if x.item == 1).victim_event_id + rec = { + "victim_event_id": item1, + "reviewer_decisions": {"A": "confirmed_poisoning_attempt", "B": "insufficient_evidence"}, + "final_decision": "likely_poisoning_attempt", + "rationale": "Counterparty found in the earlier history.", + "additional_evidence_used": True, + "saw_source_labels": False, + "adjudicated_at": "2026-11-03T00:00:00+00:00", + } + path = study["tmp"] / "adj.jsonl" + path.write_text(AdjudicationRecord(adjudicator="A", **rec).model_dump_json(), encoding="utf-8") + with pytest.raises(ub.UnblindingRefused, match="one of the reviewers"): + ub.unblind(study["sample"], study["work"], [a, b], path) + path.write_text(AdjudicationRecord(adjudicator="C", **rec).model_dump_json(), encoding="utf-8") + report = ub.unblind(study["sample"], study["work"], [a, b], path) + primary = report["primary_all_reviewers_attempt"]["overall"]["positives"] + adjudicated = report["secondary_adjudicated"]["overall"]["positives"] + assert adjudicated == primary + 1 # the original disagreement still counts in primary + + +# --- replacements ------------------------------------------------------------------------------ + + +def test_replacement_takes_the_next_reserve_and_reaches_packages_blinded( + study: dict[str, Any], +) -> None: + m = study["manifest"] + first = m["selected"][0] + rec = ub.record_replacement( + study["sample"], + study["work"], + original_event_id=first["victim_event_id"], + reason="transaction_not_found", + evidence="No explorer or archive node returns the transaction.", + exposed=["A"], + recorded_by="maintainer", + ) + assert rec.replacement_event_id == m["reserves"][first["stratum"]][0] + assert rec.replacement_item == len(m["selected"]) + 1 + pkg = ub.make_package(study["sample"], study["work"], "C", study["tmp"] / "pkg-C") + line = (pkg / REPLACEMENT_SHEET).read_text(encoding="utf-8") + assert first["stratum"].split("|")[0] not in line # no stratum or subtype in the package + state = ReviewApp(pkg).state() + ids = {i["victim_event_id"] for i in state["items"]} + assert rec.replacement_event_id in ids + assert first["victim_event_id"] not in ids + with pytest.raises(AnnotationError, match="not an active"): + ub.record_replacement( + study["sample"], + study["work"], + original_event_id=first["victim_event_id"], + reason="transaction_not_found", + evidence="Replacing it a second time must fail.", + exposed=[], + recorded_by="maintainer", + ) + + +def test_replaced_originals_are_nonresponse_in_the_sensitivity_bounds( + study: dict[str, Any], +) -> None: + first = study["manifest"]["selected"][0] + ub.record_replacement( + study["sample"], + study["work"], + original_event_id=first["victim_event_id"], + reason="chain_data_unavailable", + evidence="The block is not served by any reachable source.", + exposed=[], + recorded_by="maintainer", + ) + pkgs = {r: ub.make_package(study["sample"], study["work"], r, study["tmp"] / f"r-{r}") + for r in ("A", "B")} # fmt: skip + subs = [review(pkgs[r], attempt) for r in ("A", "B")] + report = ub.unblind(study["sample"], study["work"], subs) + sens = report["replacement_sensitivity"]["overall"] + assert sens["missing"] == 1 + lo, hi = sens["bounds_missing_as_false_true"] + assert lo < hi == 1.0 + assert report["replacements"][0]["reason"] == "chain_data_unavailable" + + +def test_out_of_order_replacements_are_rejected(study: dict[str, Any]) -> None: + from cryptoguard.ml.annotation import ReplacementRecord, validate_replacements + + m = study["manifest"] + first = m["selected"][0] + reserves = m["reserves"][first["stratum"]] + rec = ReplacementRecord( + original_event_id=first["victim_event_id"], + original_item=1, + replacement_event_id=reserves[1], # skips the first reserve + replacement_item=99, + sheet_line={"victim_event_id": reserves[1]}, + stratum=first["stratum"], + reserve_position=1, + reason="transaction_not_found", + inaccessibility_evidence="not retrievable anywhere", + reviewers_exposed_to_original=(), + recorded_by="m", + recorded_at="t", + ) + problems = validate_replacements(m, [rec]) + assert any("next reserve" in p for p in problems) + + +def test_reviewer_store_rejects_items_outside_the_package(study: dict[str, Any]) -> None: + s = ReviewerStore(study["tmp"] / "x", "A", {1: "00000000000000aa"}) + with s, pytest.raises(AnnotationError, match="unknown item"): + s.save(fields(2, "00000000000000bb")) From c6d91e0ddb225edbac949a0e7cf8b8e6005e7506 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 11:13:16 +0300 Subject: [PATCH 23/92] feat(ml): benchmark readiness and review-holdout guard Versioned benchmark manifest, the ten readiness criteria (built on events.quality_gates), and a guard that refuses training events sharing an event, wallet, lookalike or planting tx with the reviewed holdout; development use is recorded permanently. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/benchmark.py | 155 ++++++++++++++++++++++++++++++++ tests/unit/test_ml_benchmark.py | 98 ++++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 src/cryptoguard/ml/benchmark.py create mode 100644 tests/unit/test_ml_benchmark.py diff --git a/src/cryptoguard/ml/benchmark.py b/src/cryptoguard/ml/benchmark.py new file mode 100644 index 0000000..82bdd4a --- /dev/null +++ b/src/cryptoguard/ml/benchmark.py @@ -0,0 +1,155 @@ +"""Benchmark readiness for ``poisoning-attempt/1`` and protection of the review holdout. + +- ``benchmark_manifest`` pins every component a result depends on. Its versions are: + - candidate generation; + - source and human labels; + - the feature schema; + - the split policy; + - the evaluation protocol. + A result is comparable only with others that share it. +- ``Holdout`` holds the reviewed sample's events and entities (wallets, lookalikes, + planting transactions). ``check_training_events`` refuses a training set that touches + any of them. Once the holdout is used for development, ``mark_development`` records it + for good. From then on it can no longer be reported as independent evaluation. +- ``readiness`` lists the ten criteria a supervised benchmark must meet. It reuses + ``events.quality_gates`` for the label and split gates, so the two cannot disagree. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +from cryptoguard.ml.events import ( + EVENT_SCHEMA_VERSION, + TASK_ID, + LabelTier, + PoisoningEvent, + quality_gates, +) + +BENCHMARK_VERSION = "poisoning-benchmark/0" # 0: not yet a valid benchmark +SPLIT_POLICY = "grouped-temporal/1" # events.grouped_temporal_split +EVALUATION_PROTOCOL = None # undefined until verified negatives exist (gate B) + + +class HoldoutLeakError(ValueError): + pass + + +def component_versions() -> dict[str, str | None]: + from cryptoguard.ml.annotation import PROTOCOL + from cryptoguard.ml.candidates import CANDIDATE_VERSION, EVENT_FEATURE_VERSION + from cryptoguard.ml.reconcile import RECONCILE_VERSION + from cryptoguard.ml.review_sample import SAMPLE_VERSION + from cryptoguard.ml.tsuchiya import SOURCE_VERSION + from cryptoguard.ml.tsuchiya_archive import PARSER_VERSION + + return { + "task": TASK_ID, + "event_schema": EVENT_SCHEMA_VERSION, + "candidate_generation": CANDIDATE_VERSION, + "feature_schema": EVENT_FEATURE_VERSION, + "source_labels": f"{PARSER_VERSION}+{SOURCE_VERSION}+{RECONCILE_VERSION}", + "human_labels": f"{SAMPLE_VERSION}+{PROTOCOL}", + "split_policy": SPLIT_POLICY, + "evaluation_protocol": EVALUATION_PROTOCOL, + } + + +def benchmark_manifest( + events: Sequence[PoisoningEvent], labels: Mapping[str, LabelTier] +) -> dict[str, Any]: + body = { + "benchmark": BENCHMARK_VERSION, + "components": component_versions(), + "events": sorted(e.victim_event_id for e in events), + "labels": dict(sorted(labels.items())), + } + digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest() + return {**body, "events": len(events), "labels": len(labels), "sha256": digest} + + +@dataclass +class Holdout: + event_ids: frozenset[str] + entities: frozenset[str] # lowercase wallets, lookalikes and planting transactions + status: Literal["untouched", "development"] = "untouched" + history: list[dict[str, str]] = field(default_factory=list) + + +def holdout_from_sheet(sheet: Path, state: Path | None = None) -> Holdout: + """Build the holdout from the blinded sheet (no key needed). ``state`` is an optional + JSON file that records development use.""" + from cryptoguard.ml.review_sample import read_sheet + + rows = read_sheet(sheet) + entities = { + str(r[k]).lower() for r in rows for k in ("wallet", "address_under_review", "transaction") + } + h = Holdout(frozenset(r["victim_event_id"] for r in rows), frozenset(entities)) + if state is not None and state.exists(): + saved = json.loads(state.read_text(encoding="utf-8")) + h.status, h.history = saved["status"], saved["history"] + return h + + +def mark_development(h: Holdout, state: Path, reason: str, when: str) -> None: + """Irreversible: the reviewed sample has influenced development.""" + h.status = "development" + h.history.append({"at": when, "reason": reason}) + state.write_text(json.dumps({"status": h.status, "history": h.history}, indent=1) + "\n") + + +def check_training_events(events: Sequence[PoisoningEvent], h: Holdout) -> None: + """Refuse training data that shares an event, wallet, lookalike or planting transaction + with the reviewed holdout (the same entity-level rule as the grouped split).""" + hits = [ + e.victim_event_id + for e in events + if e.victim_event_id in h.event_ids + or {e.victim.lower(), e.lookalike.lower(), e.planting_tx.lower()} & h.entities + ] + if hits: + raise HoldoutLeakError( + f"{len(hits)} training event(s) overlap the review holdout, e.g. {hits[:3]}" + ) + + +def readiness( + events: Sequence[PoisoningEvent], + labels: Mapping[str, LabelTier], + holdout: Holdout, + *, + license_ok: bool, + candidate_recall_measured: bool, +) -> list[dict[str, Any]]: + """The ten criteria. ``passed`` is None where only a person can judge.""" + gates = {g.gate: g for g in quality_gates(events, dict(labels), license_ok=license_ok)} + versions = component_versions() + return [ + {"criterion": "1 prediction unit", "passed": True, + "detail": f"victim-event at a cutoff ({TASK_ID}, {EVENT_SCHEMA_VERSION})"}, + {"criterion": "2 reliable source labels", "passed": False, + "detail": "source categories are heuristics (ML_CROSS_DATASET_VALIDATION.md §17)"}, + {"criterion": "3 independent review evidence", "passed": gates["B_label_validity"].passed, + "detail": gates["B_label_validity"].detail}, + {"criterion": "4 suitable negatives", "passed": gates["B_label_validity"].passed, + "detail": "verified_legitimate matched candidates (ML_BENCHMARK_READINESS.md §4)"}, + {"criterion": "5 point-in-time features", "passed": True, + "detail": f"{versions['feature_schema']}: features use data up to the planting only"}, + {"criterion": "6 candidate-generation coverage", "passed": candidate_recall_measured, + "detail": "needs full wallet histories; reported apart from classifier metrics"}, + {"criterion": "7 entity-aware splitting", "passed": gates["D_split_validity"].passed, + "detail": gates["D_split_validity"].detail}, + {"criterion": "8 temporal validation", "passed": gates["C_temporal_validity"].passed, + "detail": gates["C_temporal_validity"].detail}, + {"criterion": "9 untouched final holdout", "passed": holdout.status == "untouched", + "detail": f"{len(holdout.event_ids)} reviewed items, status {holdout.status}"}, + {"criterion": "10 stable evaluation protocol", "passed": EVALUATION_PROTOCOL is not None, + "detail": "not defined until 3 and 4 pass"}, + ] # fmt: skip diff --git a/tests/unit/test_ml_benchmark.py b/tests/unit/test_ml_benchmark.py new file mode 100644 index 0000000..3d98629 --- /dev/null +++ b/tests/unit/test_ml_benchmark.py @@ -0,0 +1,98 @@ +"""Benchmark readiness and protection of the reviewed holdout (Phase 11.4). + +Synthetic events only. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from cryptoguard.ml import benchmark as bm +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.events import PoisoningEvent, quality_gates +from cryptoguard.ml.review import DECISION_TIER +from tests.review_fixtures import addr, frozen + + +def event(n: int, *, victim: str | None = None, tx: str | None = None) -> PoisoningEvent: + return PoisoningEvent( + chain_id=1, + victim=victim or addr(70_000 + n), + lookalike=addr(80_000 + n), + imitated=addr(90_000 + n), + planting_tx=tx or "0x" + f"{900_000 + n:064x}", + planting_block=17_000_000 + n, + planting_tx_index=None, + planting_log_index=None, + observation_timestamp=None, + subtype="fake_token", + tx_signer=None, + log_contract=None, + token_contract=None, + candidate_method="synthetic", + ) + + +@pytest.fixture +def holdout(tmp_path: Path, monkeypatch) -> bm.Holdout: + _, sample, _ = frozen(tmp_path, monkeypatch) + return bm.holdout_from_sheet(sample / rs.SHEET) + + +def test_training_data_touching_the_holdout_is_refused(holdout: bm.Holdout, tmp_path) -> None: + sheet = rs.read_sheet(tmp_path / "sample" / rs.SHEET) + clean = [event(i) for i in range(5)] + bm.check_training_events(clean, holdout) + same_wallet = event(99, victim=sheet[0]["wallet"].upper().replace("0X", "0x")) + same_tx = event(98, tx=sheet[1]["transaction"]) + for bad in (same_wallet, same_tx): + with pytest.raises(bm.HoldoutLeakError, match="overlap"): + bm.check_training_events([*clean, bad], holdout) + + +def test_development_use_is_recorded_and_fails_the_holdout_criterion( + holdout: bm.Holdout, tmp_path: Path +) -> None: + state = tmp_path / "holdout_state.json" + ready = bm.readiness([event(1)], {}, holdout, license_ok=False, candidate_recall_measured=False) + assert next(c for c in ready if c["criterion"].startswith("9"))["passed"] is True + bm.mark_development(holdout, state, "detector retuned after reading review errors", "t") + again = bm.holdout_from_sheet(tmp_path / "sample" / rs.SHEET, state) + assert again.status == "development" + ready = bm.readiness([event(1)], {}, again, license_ok=False, candidate_recall_measured=False) + assert next(c for c in ready if c["criterion"].startswith("9"))["passed"] is False + assert json.loads(state.read_text())["history"][0]["reason"].startswith("detector") + + +def test_current_state_is_not_a_benchmark(holdout: bm.Holdout) -> None: + """With no verified labels the label, negative and protocol criteria fail.""" + events = [event(i) for i in range(10)] + labels = {e.victim_event_id: "weak_attempt" for e in events} + ready = {c["criterion"][:2].strip(): c["passed"] for c in bm.readiness( + events, labels, holdout, license_ok=False, candidate_recall_measured=False)} # fmt: skip + assert ready["3"] is False + assert ready["4"] is False + assert ready["10"] is False + assert bm.component_versions()["evaluation_protocol"] is None + + +def test_unknown_and_insufficient_are_never_negatives() -> None: + assert DECISION_TIER["insufficient_evidence"] == "unknown" + assert DECISION_TIER["conflicting_evidence"] == "conflicting" + events = [event(i) for i in range(40)] + labels = {e.victim_event_id: "unknown" for e in events} + gate = next(g for g in quality_gates(events, labels, license_ok=False) + if g.gate == "B_label_validity") # fmt: skip + assert "verified negatives 0" in gate.detail + + +def test_manifest_pins_components_and_changes_with_labels() -> None: + events = [event(i) for i in range(3)] + a = bm.benchmark_manifest(events, {events[0].victim_event_id: "weak_attempt"}) + b = bm.benchmark_manifest(events, {events[0].victim_event_id: "verified_attempt"}) + assert a["sha256"] != b["sha256"] + assert a["components"]["task"] == "poisoning-attempt/1" + assert a["components"]["human_labels"].startswith("review-sample/1+review-protocol/1") From 59c82078113942cbfc3d26021a34cd42adfc0306 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 11:13:19 +0300 Subject: [PATCH 24/92] docs(ml): Phase 11.4 annotation audit, protocol amendment 1, benchmark readiness Amendment 1 was written before any review and leaves the frozen sample unchanged: campaign-level primary estimand, design-based intervals (the 0.94/0.86 figures assumed simple random sampling; all-confirmed design bound 0.929), collapse rule, structured evidence and exposure. Adds the reviewer guide, maintainer checklist and negative-data collection plan (not authorized). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 +++ ML.md | 7 +- ML_ANNOTATION_AUDIT.md | 325 +++++++++++++++++++++++++++++++++ ML_BENCHMARK_READINESS.md | 132 +++++++++++++ ML_CROSS_DATASET_VALIDATION.md | 13 ++ ML_RESEARCH_PLAN.md | 5 +- README.md | 2 +- docs/ml/review-protocol.md | 94 ++++++++++ docs/ml/reviewer-guide.md | 89 +++++++++ 9 files changed, 690 insertions(+), 3 deletions(-) create mode 100644 ML_ANNOTATION_AUDIT.md create mode 100644 ML_BENCHMARK_READINESS.md create mode 100644 docs/ml/reviewer-guide.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f56865b..41addf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,32 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Independent annotation and benchmark validation (Phase 11.4) +- Verified the frozen review sample against its committed hashes (`ml review verify`) and + audited its design (`ml review audit`). Every uniqueness, separation, allocation, weight + and reserve check passes; nothing was regenerated. The 1,401 versus 1,395 group count is + explained: an exploratory count without the imitated-address link. +- Protocol amendment 1, written before any review: + - campaign-level primary estimand; attempt level as bounds only; + - design-based intervals (the earlier 0.94 and 0.86 assumed simple random sampling; the + all-confirmed design bound is 0.929); + - a pre-specified collapse rule for single-item strata; + - structured evidence and exposure fields. +- Added the review workflow: + - per-reviewer packages holding only the blinded sheet; + - a local review app (loopback only, session token, Host check, strict CSP, no data in + static files); + - a hash-chained, atomically written reviewer store with finalization; + - replacements in frozen reserve order; + - agreement statistics (kappa undefined rather than 0; Gwet's AC1); + - an unblinding gate with no override, and a key-access log. +- Added benchmark readiness (`ml/benchmark.py`): versioned benchmark manifest, a guard that + refuses training data touching the review holdout, and the ten criteria. Not a benchmark + yet: no human decisions and no verified negatives. The negative-data collection plan + needs a separately approved RPC cap. +- Docs: ML_ANNOTATION_AUDIT.md, ML_BENCHMARK_READINESS.md, docs/ml/reviewer-guide.md, and + protocol amendment 1. + ### Cross-dataset validation of poisoning research data (Phase 11.3) - Added a verified, resumable downloader for one approved file at a time (`ml fetch-file`). Resume needs a matching `206`, the file is renamed only after size, diff --git a/ML.md b/ML.md index ca9906c..d9fea88 100644 --- a/ML.md +++ b/ML.md @@ -44,7 +44,12 @@ method and decision log. (`cryptoguard ml scan-archive`, `cryptoguard ml cross-dataset-report`), `ml/review_sample.py` (frozen, blinded review sample: `cryptoguard ml freeze-review-sample`; protocol in - [docs/ml/review-protocol.md](docs/ml/review-protocol.md)). + [docs/ml/review-protocol.md](docs/ml/review-protocol.md)); + - Phase 11.4: `ml/sample_design.py` (design audit and estimators), `ml/annotation.py` + (decision schema, hash-chained reviewer store, finalization), `ml/review_server.py` + (local, blinded review app), `ml/agreement.py`, `ml/unblind.py` (gated unblinding and + analysis), `ml/benchmark.py` (readiness and holdout guard); commands under + `cryptoguard ml review` ([ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md)). - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. diff --git a/ML_ANNOTATION_AUDIT.md b/ML_ANNOTATION_AUDIT.md new file mode 100644 index 0000000..ec4c293 --- /dev/null +++ b/ML_ANNOTATION_AUDIT.md @@ -0,0 +1,325 @@ +# Annotation audit: the frozen review sample (Phase 11.4) + +Status: **review-ready. No human decision exists yet.** Two independent human reviewers are +needed. Nothing below is a reviewed result. + +- Every number comes from `cryptoguard ml review audit`, which is offline, makes 0 RPC + requests and writes aggregate-only JSON to `data/ml/poisoning/review/design_audit.json`. +- Code: + - `ml/review_sample.py` (verification); + - `ml/sample_design.py` (design and estimators); + - `ml/annotation.py`, `ml/review_server.py`, `ml/agreement.py`, `ml/unblind.py` + (workflow). +- Protocol: [docs/ml/review-protocol.md](docs/ml/review-protocol.md), with amendment 1. + +## 1. Frozen sample identity + +Re-verified on 2026-11-02 from the raw bytes (`cryptoguard ml review verify`). All five +committed hashes in ML_CROSS_DATASET_VALIDATION.md §26 match: + +| Item | SHA-256 | Basis | +|---|---|---| +| review queue (input) | `84f8268e…b42e83` | raw bytes | +| selection | `e368beb4…85a62` | SHA-256 of compact, key-sorted JSON of the selection fields (`review_sample._canonical`) | +| `reviewer_sheet.jsonl` | `a0ec4b6e…814027` | raw bytes (LF line endings, key-sorted JSON lines) | +| `unblinding_key.jsonl` | `407b412f…03bb2d` | raw bytes | +| `sample_manifest.json` | `c38ae31d…dbdc3` | raw bytes | + +**How verification works:** +- It recomputes the selection hash from the manifest instead of trusting the recorded + value. It also checks the manifest's own file hashes and that the selected ids equal the + sheet ids. +- It never writes. A mismatch is reported, and the file is left as found. +- **No canonicalization was changed.** The hash bases above are the ones used at freezing. +- Redrawing from the queue with the frozen code gives the identical selection. +- No frozen file was modified, regenerated or reordered in this phase. + +## 2. Dataset provenance + +- **Frame:** the 1,469 payoff-linked attempt packets, built by `ml/reconcile.py` + (`reconcile/1`) from Tsuchiya et al.'s attempt archive and payoff list + (CC BY-NC-ND 4.0). See ML_CROSS_DATASET_VALIDATION.md §11. +- **Who is in it:** each packet is the latest source-labelled attempt by a lookalike + against a victim before that victim paid that lookalike. + +## 3. Sampling frame and units + +| Unit | Count | Meaning | +|---|---|---| +| attempt (packet) | 1,469 | one payoff-linked planting attempt | +| victims | 1,407 | distinct victim wallets | +| campaign group | 1,395 | attempts linked by victim, lookalike, planting tx or imitated address | +| representative | 1,395 | one attempt per group: the lowest `sha256(seed\|rep\|id)` | +| item | 60 | representatives drawn into the sample | + +- 62 groups hold more than one attempt (136 attempts, at most 6 per group). +- 26 groups span more than one stratum. +- 12 groups hold two victims. +- **74 attempts are not representatives** and could never be selected. +- All 60 items come from single-attempt groups. + +## 4. Campaign grouping and the 1,401 versus 1,395 discrepancy + +- **Where each number came from:** + - **1,401** appeared only in a chat progress message during Phase 11.3. It was the output + of an exploratory profiling script, run before the sampler was written, that linked + attempts by victim, lookalike and planting transaction only. + - **1,395** is the frozen design. It also links by imitated address, because attempts + imitating the same counterparty were treated as one campaign. That merges 12 of the + exploratory groups into 6. +- **No defect in the frozen draw:** the manifest, §26 and the code agree on 1,395, and the + 1,401 figure was never committed. The audit recomputes both counts on every run. +- **When the rule was chosen:** after seeing aggregate group and subtype counts, before any + review existed. No outcome information was available or used. + +## 5. Sampling strata + +- **Definition:** subtype × block-height period × rival lookalike present. The strata are + mutually exclusive and cover all 1,395 representatives (audit checks + `strata_partition_representatives` and `strata_counts_match_queue`). +- **Year names are approximate:** the year boundaries (blocks 16,308,190 and 18,908,895) + were entered from memory and could not be checked offline, because the archive has no + timestamps. The strata are exact as block ranges. 15 attempts lie within 7,200 blocks + (about a day) of a boundary. + +| Stratum | Attempts | Groups N | Ideal share | Selected n | π | Weight N/n | Reserves | +|---|---|---|---|---|---|---|---| +| dust, 2023, no rival | 8 | 8 | 1.44 | 1 | 1/8 | 8.0 | 7 | +| dust, 2023, rival | 29 | 25 | 4.50 | 5 | 5/25 | 5.0 | 20 | +| dust, 2024, no rival | 8 | 8 | 1.44 | 1 | 1/8 | 8.0 | 7 | +| dust, 2024, rival | 14 | 9 | 1.62 | 2 | 2/9 | 4.5 | 7 | +| fake token, 2023, no rival | 305 | 293 | 9.63 | 10 | 10/293 | 29.3 | 283 | +| fake token, 2023, rival | 363 | 339 | 11.15 | 11 | 11/339 | 30.82 | 328 | +| fake token, 2024, no rival | 39 | 39 | 1.28 | 1 | 1/39 | 39.0 | 38 | +| fake token, 2024, rival | 62 | 59 | 1.94 | 2 | 2/59 | 29.5 | 57 | +| spoofed transferFrom, 2022, no rival | 111 | 103 | 4.04 | 4 | 4/103 | 25.75 | 99 | +| spoofed transferFrom, 2022, rival | 59 | 58 | 2.28 | 2 | 2/58 | 29.0 | 56 | +| spoofed transferFrom, 2023, no rival | 105 | 103 | 4.04 | 4 | 4/103 | 25.75 | 99 | +| spoofed transferFrom, 2023, rival | 344 | 330 | 12.94 | 12 | 12/330 | 27.5 | 318 | +| spoofed transferFrom, 2024, no rival | 1 | 1 | 0.04 | 1 | 1/1 | 1.0 | 0 | +| spoofed transferFrom, 2024, rival | 18 | 17 | 0.67 | 1 | 1/17 | 17.0 | 16 | +| zero-value, 2023, rival | 3 | 3 | 3 | 3 | 3/3 | 1.0 | 0 | + +- **Rounding.** The allocation was recomputed independently and matches. The minimum of + one per stratum gave the single-group stratum (spoofed, 2024, no rival) one item, so the + largest spoofed stratum got 12 instead of 13. The weights account for this. +- **Zero-value is a census of the frame only.** Its 3 groups are all the zero-value + attempts in the payoff-linked frame, not all zero-value poisoning. + - Here, zero-value means a zero-value transfer *to* the victim. + - A zero-value `transferFrom` that shows the victim as sender is labelled "spoofed + transferFrom". + +## 6. Selection probabilities + +- **Exact part:** given the representatives, an item's inclusion probability is exactly + `n_c / N_c` (stratified sampling without replacement, keyed-hash ranking treated as a + random permutation). +- **The attempt level needs a model:** `(1/m_g)·n_c/N_c` holds only if the representative + is considered random within its group. Under the fixed hash, the 74 non-representatives + have probability zero. +- **No label influenced selection beyond the strata.** The rival flag comes from the + source archive, as preregistered. + +## 7. Weighting and estimands + +| Estimand | Definition | How it is estimated | +|---|---|---| +| A, campaign (primary) | share of the 1,395 campaign groups whose representative attempt reviewers support as an attempt | stratified (Hájek) estimator, weights `N_c/n_c` | +| B, attempt | share of the 1,469 attempts supported | **bounds only**: `[L·1395/1469, (U·1395+74)/1469]` from A's interval | +| C, agreement | consistency between two reviewers on the 60 items | unweighted (it describes the sample) | +| D, subtype | A within each subtype | same estimator; zero-value is a frame census | +| victim level | – | **not estimated**: victims are nested in groups, and 12 groups hold two | + +- **Weights:** exact rationals in the analysis. The manifest's rounded values differ by at + most 1.8×10⁻⁷. They sum to 1,395. +- **Kish design effect:** 1.20 overall (effective n ≈ 50), 1.00–1.06 within subtypes. + +## 8. Confidence-interval assumptions + +- **What the original protocol's bounds were.** "0.94 overall, 0.86 per 24-item subtype" + are the lower ends of **two-sided unweighted Wilson 95%** intervals (0.9398 and 0.8620), + which assume a simple random sample of items. They are reproduced exactly, and they do + not describe the weighted design. +- **Design-based interval (amendment 1).** It is a Wilson interval on the effective sample + size: + - `n_eff = p(1−p)/v̂`; + - `v̂` is the stratified variance with finite-population correction, using pre-specified + collapsed strata for the four single-item strata; + - when `p` is 0 or 1, it uses `n / deff_Kish` instead. +- **If all 60 were confirmed**, the lower bounds would be: + + | Scope | Lower bound | + |---|---| + | overall | **0.929** | + | fake token | 0.862 | + | spoofed transferFrom | 0.856 | + | dust | 0.689 | + | zero-value | 1.0 (frame census, no sampling error) | + +- **These intervals are approximate.** For dust (9) and zero-value (3), raw counts are the + primary report. + +## 9. Reviewer blinding + +| Hidden from the reviewer (never sent by the server) | Still visible | +|---|---| +| subtype, source labels, imitated address, payoff, rival lookalikes, evidence summary, strata, weights, model score | wallet, address under review, planting transaction, block | + +**How it is enforced:** +- The server reads only the reviewer package: the sheet and the reviewer's own store. The + package never contains the key or the manifest. +- Static files hold no data. +- A test searches every response (HTML, JS, CSS, state, saves and errors) for every value + only the key holds. +- Drafts in browser storage hold only the reviewer's own input. The session token stays in + the tab's session storage. + +**What stays visible:** a block explorer shows later activity, including the payment, and +explorer labels such as phishing tags. This is partial blinding. Amendment 1 records it +per item: explorer use, viewing after the cutoff, external labels, source or model output. + +**Evidence sufficiency:** +- Hiding the imitated address does not prevent judgement. Reviewers find the earlier + counterparty in the wallet's history before the cutoff, and record it with the matched + characters. +- At unblinding, their counterparty is compared with the source's imitated address, + giving an independent check of the source's matching. +- An offline evidence packet was **not** built. The only local pre-cutoff history is the + source's own intended-transfer matching, which would reveal the answer. + +## 10. Reviewer independence + +- Each reviewer gets a separate package (`cryptoguard ml review package`) and store, and + can open no one else's. +- A second server on the same store is refused (OS lock). +- The maintainer combines submissions only after both are finalized. +- On a shared computer, independence is procedural, not technical. The guide asks for + separate machines or accounts. +- The two reviewers must be **two distinct people**. Two model sessions, prompts or + classifier outputs are not reviewers. +- The maintainer who built the sample has seen the source information and must not review. + +## 11. Evidence requirements + +Amendment 1 adds structured checks to each decision (`poisoning-annotation/1`): +- planting transfer, earlier counterparty (address and matched characters), token, value, + initiator and legitimate explanation; +- each with an evidence state: observed / looked for and absent / not available / not + looked at / not applicable / contradictory. + +Strong decisions are refused without their evidence (`annotation.evidence_problems`). +Missing data is never read as negative evidence. Later theft is not required for an +attempt. + +## 12. Replacement policy + +**Allowed reasons:** technical inaccessibility only (`transaction_not_found`, +`chain_data_unavailable`, `sheet_record_malformed`). + +**Rules:** +- The replacement is the next reserve of the same stratum, in frozen order, enforced by + `validate_replacements`. +- Each record keeps the original and the replacement (event and item), the stratum, the + reserve position, the reason, the evidence, which reviewers were exposed to the + original, who recorded it and when, and the protocol version. +- A replacement never edits the frozen files. It goes into + `data/ml/poisoning/review/replacements.jsonl`, and the reviewer package receives only + the blinded line. +- **Statistics:** the replacement takes its original's design slot (missing at random + within the stratum is assumed). A sensitivity analysis treats each replaced original as + missing, with bounds at 0 and 1. + +## 13. Submission freeze + +- **The log:** each reviewer's log is append-only and hash-chained. Every save rewrites + the file atomically (temporary file, fsync, replace). +- **Revisions:** a revision appends, and the earlier record stays. An identical resubmit + is a no-op. A save based on an older revision is refused. +- **Finalizing** needs a decision for every item. It writes `submission.json` with a + content hash, then refuses further edits; changes need an amendment. +- **Tampering:** edited logs and submissions are detected (hash chain, content hash). + +## 14. Agreement analysis + +`ml/agreement.py` reports: +- paired and unpaired items; +- per-reviewer counts; +- the confusion matrix and number of disagreements; +- observed agreement; +- Cohen's kappa (`None`, with a reason, when undefined); +- Gwet's AC1, because one category is expected to dominate. + +It covers both the five decisions and attempt versus not-attempt. Subgroups (subtype, year, +rival) are reported only with 10 or more items. Weighted kappa is not used, because the +categories have no order. + +## 15. Adjudication + +- **Optional, and never a replacement.** A third person's decision is recorded beside the + two originals, never instead of them. +- **Who may adjudicate:** the adjudicator must differ from both reviewers, and the recorded + originals must equal the submissions. Agreed items cannot be adjudicated. +- **How it is reported:** the primary result keeps the disagreement (an item counts only if + both reviewers say "attempt"). The sensitivity result counts an item if either says so. + The adjudicated result is secondary. + +## 16. Unblinding + +`cryptoguard ml review unblind` runs these checks first: +- frozen hashes; +- valid replacements; +- two distinct finalized submissions, with valid content hashes, for this sample, sheet and + protocol, covering exactly the active items; +- valid adjudications. + +On any failure it opens nothing. There is no override flag. Each key access is appended to +`key_access.log.jsonl`. + +**Outputs:** +- an aggregate report; +- a row-level item table (local, git-ignored); +- source comparison categories: full agreement, partial agreement, reviewer disagreement, + insufficient evidence, source disagreement, unresolved ambiguity. + +Source labels never overwrite reviewer decisions. + +## 17. Outcome leakage + +The frame is payoff-linked, so a reviewer may see the later payment. + +- **Two separate questions:** *attempt validity* (was the planting an attempt?) and the + *subsequent outcome* (did a payment follow?). The protocol asks only the first. +- **What is recorded:** exposure is recorded per decision. +- **Exploratory comparison:** the report compares attempt decisions with and without + after-cutoff viewing, per reviewer. This is not preregistered and not causal. + +## 18. Statistical limitations + +- **Population.** The estimates describe payoff-linked campaign groups from one source's + detector, over July 2022 to June 2024, for ERC-20 tokens. They do not give global + poisoning prevalence, detector precision, recall or false-positive rates. +- **Positive frame only.** With no legitimate items in the sample, reviewers know almost + everything is a candidate, so acquiescence is possible. Agreement and rationales are the + safeguard. Negatives come later (ML_BENCHMARK_READINESS.md). +- **Small strata.** Four strata have one item, and dust and zero-value are small. Their + intervals are approximate, and counts are primary. +- **Licensing.** Review decisions are keyed by event ids derived from CC BY-NC-ND data. + Whether derived per-item labels may be published is unresolved, so submissions and item + tables stay local. This is not legal advice. + +## 19. Audit register (Phase 11.4) + +| ID | Pri | Finding | Status | +|---|---|---|---| +| 21 | P1 | **Estimand unit mismatch.** Protocol §7 asked for a design-weighted estimate "for the queue" (1,469 attempts), but the weights are campaign-level, and 74 attempts have zero inclusion probability | Amendment 1: campaign estimand primary; attempt level as bounds; victim level not estimated | +| 22 | P1 | **Protocol bounds assumed simple random sampling.** 0.94 and 0.86 are unweighted two-sided Wilson; the design-based all-confirmed bound is 0.929 overall | Amendment 1: design-based interval primary; unweighted labelled illustrative | +| 23 | P1 | **No variance rule for single-item strata** (four strata) | Amendment 1: pre-specified collapse rule (`collapse_partners`), fixed before any review | +| 24 | P1 | **No exposure recording.** The explorer reveals later payments and phishing tags | Amendment 1: exposure fields per decision; exploratory comparison | +| 25 | P1 | **Free-text rationale only.** Strong labels could not be checked against evidence | Amendment 1: structured checks with validation | +| 26 | P1 | **No mechanics for finalization, unblinding or replacement** | Implemented: hash-chained store, finalization, gated unblinding, replacement log | +| 27 | P2 | **Year boundaries described as "from a block explorer"** but entered from memory | Comment corrected; strata are exact block ranges; values unchanged | +| 28 | P2 | **1,401 versus 1,395 groups** | Explained (§4): exploratory count without the imitated-address link; never committed | +| 29 | P2 | **Manifest weights rounded to 6 decimals** | The analysis uses exact `N_c/n_c` | +| 30 | P2 | **"Zero-value" naming** covers only zero-value transfers to the victim | Documented (§5) | + +No P0 finding: every hash, uniqueness, separation, allocation and reserve-order check passes. diff --git a/ML_BENCHMARK_READINESS.md b/ML_BENCHMARK_READINESS.md new file mode 100644 index 0000000..b7a0f10 --- /dev/null +++ b/ML_BENCHMARK_READINESS.md @@ -0,0 +1,132 @@ +# Benchmark readiness: `poisoning-attempt/1` (Phase 11.4) + +**Verdict: not a benchmark yet. Supervised training is not justified.** +- The review sample is ready, but no human decision exists. +- There are no verified negatives anywhere. +- No collection is authorized. + +Code: `ml/benchmark.py`, which builds on `events.quality_gates`, so the two cannot +disagree. Annotation design: [ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md). + +## 1. Readiness criteria + +| # | Criterion | Now | Evidence | +|---|---|---|---| +| 1 | Clear prediction unit | pass | victim-event at a cutoff (`poisoning-event/1`) | +| 2 | Reliable source labels | fail | archive categories are the source's heuristics | +| 3 | Independent review evidence | **fail: waiting on people** | 60-item sample frozen and tooling ready; 0 decisions | +| 4 | Suitable negatives | fail | 0 `verified_legitimate` events | +| 5 | Point-in-time features | pass | `event-features/1` uses data up to the planting only | +| 6 | Candidate-generation coverage | fail | needs full wallet histories (§3) | +| 7 | Entity-aware splitting | infrastructure only | `grouped-temporal/1`; nothing labelled to split | +| 8 | Temporal validation | partial | block-level order; no within-block order in the archive | +| 9 | Untouched final holdout | pass | the 60 reviewed items are guarded (§6) | +| 10 | Stable evaluation protocol | fail | deliberately undefined until 3 and 4 pass | + +## 2. Labels: available and missing + +| Have | Tier | Usable for | +|---|---|---| +| 1,469 payoff-linked attempts | review candidates, no label | the frozen review sample | +| Poison-Hunter rows | `weak_attempt` | descriptive only | +| Tsuchiya categories (17.4 M rows) | source heuristics, not loaded as labels | agreement analysis | +| Verified attempts | 0 (60 to be reviewed) | — | +| Verified negatives | **0** | — | + +`insufficient_evidence` maps to `unknown` and `conflicting_evidence` to `conflicting`. +Neither ever becomes a negative (tested). + +## 3. Candidate-generation coverage + +- **Two separate measures.** Candidate recall (did `candidates/1` emit the event at all?) + is kept apart from classifier performance. A model cannot score what the generator never + emits. +- **What would measure recall:** running the generator over complete wallet histories + around reviewed attempts. Those histories do not exist locally. +- **What has been measured:** the archive agreement in ML_CROSS_DATASET_VALIDATION.md §16 + measures agreement with the source's own definitions, not recall. + +## 4. Negative-data protocol (proposal; nothing collected) + +**What a negative is.** A candidate event that `candidates/1` emits on an ordinary wallet, +and that two independent reviewers mark `confirmed_legitimate_interaction`, with the +legitimate explanation observed. + +**Candidate categories to look for** (these are where to look, not labels): +- a counterparty's own second address; +- similar vanity or exchange deposit addresses; +- first-time counterparties; +- legitimate airdrops and dust; +- router and aggregator transfers; +- ordinary low-value transfers. + +**Matching.** Draw negatives through the same generator, from wallets matched to the +reviewed victims on: +- period; +- activity band (nonce range); +- token class; +- transaction shape; +- coverage. + +Never compare specialist-source attacks with random unrelated transactions. + +**Unknown stays unknown.** A wallet with no published theft is not benign. + +**Sample size.** Gate B needs at least 30 verified per class from 5 or more campaign +groups. Allow for: +- candidates per wallet-week, which are unknown and possibly below 1; +- reviewer yield. + +The proposal is therefore 120 wallet-weeks: +- the 60 reviewed victims, in the week before their planting; +- 60 matched ordinary wallets. + +Collection stops at the cap, whatever has been found by then. + +| Item | Estimate (`cryptoguard ml plan-collection`, no requests sent) | +|---|---| +| Window | 50,400 blocks (about 7 days) per wallet | +| Requests at 100-block log ranges (free endpoint used in the pilot) | 1,978 per wallet; **237,360 for 120 wallets**; about 16.5 h at 4 requests/s | +| Requests at 2,000-block log ranges | 927 per wallet; 111,240 total | +| Retry allowance | +10% (included) | +| Expected fully resolved wallets | 96 of 120 (80% coverage assumption) | +| Disk and memory | not measured: the pilot's recorded fixtures were lost (ML_PILOT_AUDIT.md §4). Measure on the first 5 wallets before continuing | +| Review cost | 2 reviewers × every emitted candidate; about 5 minutes each (an estimate) | +| Hard cap to request | the plan's total, enforced by `RequestLedger`; the plan hash is recorded before any run | + +**Approval.** +- This needs **separate, explicit approval** of a request cap and a provider. None is given. +- The pilot's 364 leftover requests are not usable for this. +- Paid providers are excluded unless you decide otherwise. + +## 5. Evaluation task (when gates pass) + +- **Classification.** Score each emitted candidate event at its cutoff. +- **Primary metric.** Precision-recall on a grouped, time-ordered test split. +- **Reported separately:** + - candidate recall; + - alert volume per wallet-week, from the matched ordinary wallets. +- **Baselines:** the existing rules detector and a trivial classifier. + +## 6. Splits and leakage + +- **Splits.** `grouped-temporal/1` puts whole campaign groups on one side, with the latest + groups as the test set. +- **Review holdout.** `benchmark.check_training_events` refuses any training event that + shares an event, wallet, lookalike or planting transaction with the 60 reviewed items. +- **If the reviewed items are used in development** (for example, retuning the detector + after reading review errors), `mark_development` records it permanently. They are then + development evidence, not an independent evaluation. +- **Never train on the 60 and report on the 60.** +- **Versioned manifest.** `benchmark_manifest` pins task, event schema, candidate + generation, features, source and human label versions, split policy and evaluation + protocol. Results are comparable only under the same hash. + +## 7. Isolation from the existing classifier + +- **Separate tasks.** The PTXPhish transaction classifier stays a different task, and the + shadow scorer refuses a model card for `poisoning-attempt/1` + (`tests/unit/test_ml_pipeline.py`). +- **Never loaded by production.** The review and annotation modules are research-only, and + `tests/unit/test_ml_reconcile.py` checks that they load neither the application database + nor the API. Wallet scans and findings are unchanged. diff --git a/ML_CROSS_DATASET_VALIDATION.md b/ML_CROSS_DATASET_VALIDATION.md index 9f093d7..fabf41d 100644 --- a/ML_CROSS_DATASET_VALIDATION.md +++ b/ML_CROSS_DATASET_VALIDATION.md @@ -552,3 +552,16 @@ same time: [docs/ml/review-protocol.md](docs/ml/review-protocol.md). - The review itself: two independent reviewers, per the protocol. - The matched negatives from §25, which need a separately approved RPC cap. - No label exists until reviewed decisions are imported. + +## 27. Phase 11.4: verification and annotation workflow (0 RPC requests) + +- **Hashes.** All five §26 hashes were re-verified from the raw bytes; no file changed. The + selection was recomputed and redrawn identically. +- **Design audit.** It passes every check. +- **Grouping count.** The 1,401 group count mentioned during Phase 11.3 came from an + exploratory script without the imitated-address link; the frozen design has 1,395. +- **Protocol amendment 1** was made before any review. It fixes the estimand and the + interval method; the earlier bounds assumed simple random sampling. +- **Reviews.** No review has taken place. Details: + [ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md) and + [ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md). diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 133eb57..66c7e2f 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -4,7 +4,10 @@ Status: infrastructure done, gates B and D fail (no verified labels), and no mod for this task. The Tsuchiya et al. payoff cross-check (§6) and the attempt-archive reconciliation (§7, Phase 11.3) are done. The next experiment is in [ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md) §25; its review sample of -60 is frozen and waiting for reviewers (§26). Data model and labels: +60 is frozen (§26). Phase 11.4 verified it, audited its design and built the independent +annotation workflow; it now waits for two human reviewers +([ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md), +[ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md)). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). diff --git a/README.md b/README.md index 9f55852..2095337 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ evidence of common ownership ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). | Network, structural and activity-rate analyses (graph propagation, spectral features, robust burst statistics) over stored observations, coverage-aware and point in time | Experimental, **off by default**: evaluated with no measurable gain over the existing detector; available in shadow mode only (see [DETECTION_METHODS.md](DETECTION_METHODS.md)) | | Wallet-signed transactions (incl. native-ETH payments) located by nonce search in snapshots and scans; used by the poisoning detector and the graph; degrades to explicit "unlocated" counts without archive state | Implemented | | Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, approval-gated model registry, offline generalization audit, wallet-history feature infrastructure ([ML.md](ML.md), [ML_GENERALIZATION_AUDIT.md](ML_GENERALIZATION_AUDIT.md)) | Experimental, **research-only** (`ml` extra): AP 0.999 on a development benchmark (not an untouched holdout), false-positive rate 7/43 from 12 benign senders (cluster interval 4% to 36%); the API does not score with it; never creates findings | -| Wallet-centric address-poisoning research: typed event and label model, offline payment verification, candidate rules, point-in-time features, review workflow, and a safe streaming reconciliation of the Poison-Hunter and Tsuchiya et al. (USENIX Security 2025) datasets ([ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md)) | Experimental, **research-only**: no model, because the available labels cannot support a valid supervised benchmark; third-party data stays local (CC BY-NC-ND / unlicensed) | +| Wallet-centric address-poisoning research: typed event and label model, offline payment verification, candidate rules, point-in-time features, a safe streaming reconciliation of the Poison-Hunter and Tsuchiya et al. (USENIX Security 2025) datasets, and a frozen 60-item sample with a local, blinded two-reviewer annotation workflow ([ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md), [ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md)) | Experimental, **research-only**: no model, because the available labels cannot support a valid supervised benchmark; no human review has happened yet; third-party data stays local (CC BY-NC-ND / unlicensed) | | Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals | Not yet | ## Quick start diff --git a/docs/ml/review-protocol.md b/docs/ml/review-protocol.md index cf2d872..d117aa9 100644 --- a/docs/ml/review-protocol.md +++ b/docs/ml/review-protocol.md @@ -99,3 +99,97 @@ Each reviewer returns one line per item in `poisoning-review/1` format descriptive only. - **Not concluded from this review:** detector precision or recall, theft probability, or any population rate. + +--- + +# Amendment 1 (2026-11-02, before any review) + +**Status when written:** +- No reviewer had been recruited. +- No decision existed. +- No reviewer package had been issued. +- The unblinding key was not opened. Its bytes were hashed only. +- No outcome data was inspected. The only data examined were the frozen manifest's + aggregate design counts and the review queue (the sampling frame), both seen earlier by + the maintainer while building the sample. +- The frozen sample and the hashes in §2 are unchanged and remain usable. +- No new data is needed. + +The text above stays as written. This amendment replaces the clauses it names. +Background: [ML_ANNOTATION_AUDIT.md](../../ML_ANNOTATION_AUDIT.md) §19. + +## A1. Defects in the original protocol + +1. **§7 asked for a design-weighted estimate "for the queue"** (1,469 attempts). The design + samples campaign groups through one fixed representative each, so 74 attempts could + never be selected. +2. **The §7 scale figures (0.94 and 0.86)** are unweighted two-sided Wilson bounds. They + assume simple random sampling. +3. **No rule existed for variance in strata with one item.** +4. **§6 named the exposure problem but recorded nothing.** +5. **Decisions carried only free text**, so strong labels could not be checked. +6. **Finalization, unblinding and replacement had no mechanics.** + +## A2. Corrections + +- **Decision format.** Decisions use `poisoning-annotation/1` (`ml/annotation.py`): + - the §4 decision and a confidence level; + - the §3 checks as structured evidence states, including the earlier counterparty + address the reviewer found and the matched characters; + - exposure: explorer use, viewing after the cutoff block, external labels, source or + model output; + - a rationale, and optional notes. + + Every record converts to `poisoning-review/1` for `review.import_reviews`. +- **Evidence rules:** + - `confirmed_poisoning_attempt` requires the planting observed, the imitated earlier + counterparty observed and recorded with its matched characters, a legitimate + explanation looked for and absent, and a rationale of at least five words; + - `likely` requires the planting observed; + - `confirmed_legitimate_interaction` requires the legitimate explanation observed; + - `conflicting_evidence` requires one check marked contradictory. + + Missing evidence is never negative evidence. +- **Estimands.** The primary estimand is the campaign-level share (ML_ANNOTATION_AUDIT.md + §7). Attempt-level results are bounds only. Victim level is not estimated. +- **Primary statistic.** It is unchanged: an item counts only if both reviewers mark it + confirmed or likely. + - The estimate is stratified (weights `N_c/n_c`). + - Its interval is a two-sided Wilson 95% on the effective sample size, with variance from + pre-specified collapsed strata (`sample_design.collapse_partners`). + - Unweighted Wilson intervals are reported, labelled illustrative. + - For dust and zero-value, raw counts are primary. +- **Sensitivity and secondary results:** + - counting an item if either reviewer says attempt; + - an adjudicated result (secondary); + - replaced originals treated as missing, with bounds. +- **Agreement.** Cohen's kappa (undefined, never 0, when only one category is used) and + Gwet's AC1, on the five decisions and on attempt versus not. Subgroups are reported only + with 10 or more items. +- **Exploratory only.** Attempt decisions with and without after-cutoff viewing. +- **Mechanics:** + - one package and store per reviewer; + - append-only hash-chained log; + - finalization with a content hash, after which no edits are possible; + - replacements only for technical inaccessibility, the next reserve in frozen order, + logged separately; + - unblinding only after two distinct finalized submissions pass every check, with each + key access logged. + +## A3. Maintainer checklist + +1. `cryptoguard ml review verify`: all five hashes match. +2. Recruit two people with Ethereum explorer experience who did not build the sample. Give + each a pseudonym (`A`, `B`). Keep any identifying details outside the repository. +3. `cryptoguard ml review package --reviewer A --out `, and the same for B. Hand each + reviewer only their own directory and [reviewer-guide.md](reviewer-guide.md). Never + hand over the key, the manifest, this protocol's analysis sections or the other + reviewer's directory. +4. If an item cannot be shown at all, run `cryptoguard ml review replace`, then remake the + packages. Never replace for difficulty. +5. Collect both `annotations/submission.json` files, and record their content hashes in + the run notes. +6. Optional: adjudication by a third person, recorded as `poisoning-adjudication/1`. +7. `cryptoguard ml review unblind --submission A.json --submission B.json`. +8. Report from `unblinded_report.json` (aggregate). Keep `unblinded_items.jsonl` and the + submissions local. diff --git a/docs/ml/reviewer-guide.md b/docs/ml/reviewer-guide.md new file mode 100644 index 0000000..e353fc5 --- /dev/null +++ b/docs/ml/reviewer-guide.md @@ -0,0 +1,89 @@ +# Reviewer guide: CryptoGuard poisoning review + +Thank you for reviewing. You will judge 60 Ethereum transactions, independently. Please do +not discuss items with the other reviewer until you have both submitted. + +## Setup (once) + +1. Get your personal review folder from the maintainer. It contains `reviewer_sheet.jsonl` + and `reviewer.json`, and nothing else is needed. +2. From the CryptoGuard repository, with Python 3.12 and `uv`, run: + + ```bash + uv run cryptoguard ml review serve --package + ``` + +3. Your browser opens the review page. If it does not, open the exact address the command + prints. That address contains a session key, so do not share it. +4. Your work is saved in `/annotations/` on every Save. You can close the + window and run the command again at any time to continue. + +The page runs only on your computer (127.0.0.1). Nothing is uploaded. + +## What you decide + +For each item: **was this transaction an address-poisoning attempt against the wallet?** +A poisoning attempt plants a look-alike address in the wallet's history, so the owner +later copies it by mistake. + +Use only evidence up to the item's block (the observation cutoff). Whether money was lost +later does not decide whether this was an attempt. + +| Key | Decision | Use when | +|---|---|---| +| 1 | Confirmed poisoning attempt | the address under review imitates a real earlier counterparty of the wallet, and you found no legitimate relationship | +| 2 | Likely poisoning attempt | the pattern fits, but one element cannot be checked | +| 3 | Confirmed legitimate interaction | you found evidence of a genuine relationship | +| 4 | Insufficient evidence | the data does not allow a decision; this is a valid answer | +| 5 | Conflicting evidence | observations point both ways | + +## Checklist per item + +1. **Planting transfer.** Open the transaction. Did it move a token, or record a zero-value + transfer, between the wallet and the address under review? +2. **Earlier counterparty.** In the wallet's history *before the block*, find an address it + really dealt with that shares the first and last characters of the address under + review. Paste it in. The page counts the matching characters. +3. **Token and value.** Is it a widely used token or an imitation contract? Is the value + zero, dust or ordinary? +4. **Initiator.** Did the wallet send it, or a third party (for example through + `transferFrom`)? +5. **Legitimate explanation.** Could the address be the wallet's own, or a known partner's? + +For each check, say what you found: observed / looked for and absent / data not available +/ not looked at / not applicable / contradictory. "Not available" is not evidence against +an attempt. + +## Be honest about what you saw + +Block explorers show later activity and sometimes labels such as "Phishing". That is fine. +Just record it: +- whether you used an explorer; +- whether you viewed activity after the cutoff block; +- whether you saw a third-party label; +- whether you saw any source label, payoff record or model output. + +These answers are not judged. + +## Keyboard + +| Key | Action | +|---|---| +| 1–5 | choose a decision | +| Ctrl+S | save | +| `[` and `]` | previous and next item | + +The numbered buttons show which items are saved. + +## Problems + +- **A transaction cannot be found anywhere:** do not guess. Tell the maintainer, who can + replace the item. Do not ask for a replacement because an item is hard; use + "Insufficient evidence" instead. +- **Save fails:** your input is kept as a draft in the browser. Fix the message shown, or + restart the command, and save again. + +## Finishing + +When all items are saved, press **Finalize submission**. After that, nothing can be +changed. Send `/annotations/submission.json` to the maintainer. From 6287f4e4ffc9ce541b0b4e0050d4559fd9c3474d Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 12:58:09 +0300 Subject: [PATCH 25/92] feat(ml): generic frozen review cohorts in the existing review workflow cohort.py generalizes the frozen-sample design (one representative per group, stratified keyed-hash selection, reserves, hash-committed manifest) with its own version, seed and directory per cohort; the Phase 11.4 sample is untouched. Reviewer packages name no cohort: the server identifies it by the sheet hash, so a cohort's purpose never reaches reviewers. Sheet v2 adds a neutral description, a coverage note and pre-cutoff context, rendered as text only. Unblinding takes the cohort, reads both key formats and adds an all-reviewers-legitimate estimand; subgroup names come from the manifest design. Co-Authored-By: Claude Opus 5.5 --- docs/ml/reviewer-guide.md | 9 ++ src/cryptoguard/ml/cohort.py | 190 +++++++++++++++++++++++ src/cryptoguard/ml/review_app/app.css | 4 + src/cryptoguard/ml/review_app/app.js | 20 +++ src/cryptoguard/ml/review_sample.py | 18 ++- src/cryptoguard/ml/review_server.py | 23 ++- src/cryptoguard/ml/sample_design.py | 8 +- src/cryptoguard/ml/unblind.py | 90 ++++++++--- tests/unit/test_ml_cohort.py | 211 ++++++++++++++++++++++++++ 9 files changed, 533 insertions(+), 40 deletions(-) create mode 100644 src/cryptoguard/ml/cohort.py create mode 100644 tests/unit/test_ml_cohort.py diff --git a/docs/ml/reviewer-guide.md b/docs/ml/reviewer-guide.md index e353fc5..acdb34e 100644 --- a/docs/ml/reviewer-guide.md +++ b/docs/ml/reviewer-guide.md @@ -54,6 +54,15 @@ For each check, say what you found: observed / looked for and absent / data not / not looked at / not applicable / contradictory. "Not available" is not evidence against an attempt. +Some folders show items titled **"Candidate for independent security review"**. They may +also show: +- a coverage note: how much of the wallet's history was recorded; +- an expandable table of the wallet's recorded activity before the cutoff. + +Judge them exactly like any other item. Any of the five decisions may be right, including +"Confirmed poisoning attempt". The table is a convenience: it shows only what was +recorded, so check an explorer when the note says history is missing. + ## Be honest about what you saw Block explorers show later activity and sometimes labels such as "Phishing". That is fine. diff --git a/src/cryptoguard/ml/cohort.py b/src/cryptoguard/ml/cohort.py new file mode 100644 index 0000000..bdae1cc --- /dev/null +++ b/src/cryptoguard/ml/cohort.py @@ -0,0 +1,190 @@ +"""Generic frozen review cohorts (Phase 11.5). The design matches ``review_sample`` (one +representative per group, stratified sampling without replacement by keyed SHA-256 rank, +ordered reserves, a hash-committed manifest), but every cohort has its own version, seed, +frame, strata and output directory. The Phase 11.4 sample is never touched. + +The manifest uses the same keys as ``review_sample``, so ``sample_design.design`` and the +review workflow read both. ``queue_sha256`` is the hash of the cohort's eligible frame. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter, defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.annotation import atomic_write + +SHEET_SCHEMA_V2 = "review-sheet/2" # adds neutral description, context and coverage notes +NEUTRAL = "Candidate for independent security review" + + +@dataclass(frozen=True) +class FrameItem: + """One eligible unit. ``sheet`` is the blinded reviewer view (no label, frame, category, + screening result or score); ``key`` is everything else, maintainer-only.""" + + event_id: str + stratum: str # "||", parsed by sample_design.parse_stratum + group: str + sheet: Mapping[str, Any] + key: Mapping[str, Any] + + +@dataclass(frozen=True) +class CohortDesign: + version: str + seed: str + quota: Mapping[str, int] # per stratum prefix (the frame); allocation within it + strata_names: tuple[str, str, str] + notes: str + + +def _rank(seed: str, *parts: str) -> str: + return hashlib.sha256("|".join((seed, *parts)).encode()).hexdigest() + + +def frame_sha256(items: Sequence[FrameItem]) -> str: + rows = sorted( + json.dumps( + {"id": i.event_id, "stratum": i.stratum, "group": i.group, "key": i.key}, + sort_keys=True, + default=str, + ) + for i in items + ) + return hashlib.sha256("\n".join(rows).encode()).hexdigest() + + +def draw(items: Sequence[FrameItem], design: CohortDesign) -> dict[str, Any]: + ids = [i.event_id for i in items] + if len(set(ids)) != len(ids): + raise rs.ReviewSampleError("frame repeats an event id") + if not items: + raise rs.ReviewSampleError("empty frame: nothing to sample") + by_id = {i.event_id: i for i in items} + members: dict[str, list[str]] = defaultdict(list) + for i in items: + members[i.group].append(i.event_id) + reps = [min(v, key=lambda e: _rank(design.seed, "rep", e)) for v in members.values()] + group_size = {e: len(members[by_id[e].group]) for e in reps} + cells: dict[str, list[str]] = defaultdict(list) + for e in reps: + cells[by_id[e].stratum].append(e) + for v in cells.values(): + v.sort(key=lambda e: _rank(design.seed, "select", e)) + alloc: dict[str, int] = {} + for frame in sorted({s.split("|")[0] for s in cells}): + sizes = {(s,): len(v) for s, v in cells.items() if s.split("|")[0] == frame} + quota = design.quota.get(frame, 0) + got = rs.allocate(sizes, quota) if quota else dict.fromkeys(sizes, 0) + alloc |= {k[0]: n for k, n in got.items()} + packets = Counter(i.stratum for i in items) + selected: list[dict[str, Any]] = [] + reserves: dict[str, list[str]] = {} + table: list[dict[str, Any]] = [] + for s in sorted(cells): + v, n = cells[s], alloc[s] + w = round(len(v) / n, 6) if n else None + table.append( + {"stratum": s, "packets": packets[s], "groups": len(v), "selected": n, "weight": w} + ) + selected += [ + {"victim_event_id": e, "stratum": s, "group_size": group_size[e], "weight": w} + for e in v[:n] + ] + reserves[s] = v[n:] + order = sorted( + (r["victim_event_id"] for r in selected), key=lambda e: _rank(design.seed, "order", e) + ) + sheet = [ + { + "schema_version": SHEET_SCHEMA_V2, + "item": n, + "victim_event_id": e, + "description": NEUTRAL, + **{k: v for k, v in by_id[e].sheet.items() if k not in ("item", "victim_event_id")}, + } + for n, e in enumerate(order, start=1) + ] + role = {r["victim_event_id"]: ("selected", r["stratum"]) for r in selected} + for s, v in reserves.items(): + role |= {e: ("reserve", s) for e in v} + key = [ + { + "role": role[e][0], + "stratum": role[e][1], + "group": by_id[e].group, + "candidate": {"event_id": e, **by_id[e].key}, + "sheet": { + "schema_version": SHEET_SCHEMA_V2, + "victim_event_id": e, + "description": NEUTRAL, + **by_id[e].sheet, + }, + } + for e in sorted(role) + ] + selection = { + "sample_version": design.version, + "queue_sha256": frame_sha256(items), + "design": { + "seed": design.seed, + "quota": dict(design.quota), + "strata": list(design.strata_names), + "allocation": "quota per frame; proportional within it, at least 1 per non-empty " + "stratum, largest remainder", + "ranking": "sha256(seed|purpose|event id), lowest first; one representative per group", + "notes": design.notes, + }, + "selected": selected, + "reserves": reserves, + } + sizes_hist = Counter(len(v) for v in members.values()) + manifest = { + **selection, + "selection_sha256": rs.selection_sha256(selection), + "queue_packets": len(items), + "groups": { + "count": len(members), + "multi_packet": sum(v for k, v in sizes_hist.items() if k > 1), + "largest": max(sizes_hist), + }, + "strata_table": table, + "rpc_requests": 0, + } + return {"manifest": manifest, "sheet": sheet, "key": key} + + +def freeze( + items: Sequence[FrameItem], design: CohortDesign, out_dir: Path +) -> tuple[dict[str, Any], bool]: + """Write once; later calls verify the recomputed selection and refuse a different one.""" + from cryptoguard.ml.cross_dataset import git_state + + sample = draw(items, design) + manifest = sample["manifest"] + path = out_dir / rs.MANIFEST + if path.exists(): + old = json.loads(path.read_text(encoding="utf-8")) + if old.get("queue_sha256") != manifest["queue_sha256"]: + raise rs.SampleFrozenError(f"{path}: the eligible frame changed after freezing") + if old.get("selection_sha256") != manifest["selection_sha256"]: + raise rs.SampleFrozenError(f"{path}: a different cohort is already frozen") + return old, False + out_dir.mkdir(parents=True, exist_ok=True) + sheet, key = rs._jsonl(sample["sheet"]), rs._jsonl(sample["key"]) + manifest["files"] = { + rs.SHEET: hashlib.sha256(sheet).hexdigest(), + rs.KEY: hashlib.sha256(key).hexdigest(), + } + manifest["git"] = git_state() + atomic_write(out_dir / rs.SHEET, sheet) + atomic_write(out_dir / rs.KEY, key) + atomic_write(path, json.dumps(manifest, indent=1, sort_keys=True).encode() + b"\n") + return manifest, True diff --git a/src/cryptoguard/ml/review_app/app.css b/src/cryptoguard/ml/review_app/app.css index 39c34ec..a187397 100644 --- a/src/cryptoguard/ml/review_app/app.css +++ b/src/cryptoguard/ml/review_app/app.css @@ -53,3 +53,7 @@ button.copy { font-size: 12px; padding: 1px 6px; } main { grid-template-columns: 1fr; padding: 10px 16px; } .facts { grid-template-columns: 1fr; } } +.coverage { color: var(--muted); margin: 10px 0 0; } +details.context { margin-top: 10px; } +details.context table { border-collapse: collapse; width: 100%; font-size: 13px; display: block; overflow-x: auto; } +details.context th, details.context td { border-bottom: 1px solid var(--line); padding: 3px 8px; text-align: left; } diff --git a/src/cryptoguard/ml/review_app/app.js b/src/cryptoguard/ml/review_app/app.js index 02e47ff..f7b0e75 100644 --- a/src/cryptoguard/ml/review_app/app.js +++ b/src/cryptoguard/ml/review_app/app.js @@ -193,6 +193,7 @@ function render() { $(".cutoff", frag).textContent = `Judge the planting with evidence up to block ${it.block}. If you look at later activity ` + "(an explorer shows it), record that below; it is not hidden from you, only from this sheet."; + if (it.description) $(".item-title", frag).textContent = `${it.description}: item ${it.item} of ${state.items.length}`; const dl = $(".facts", frag); for (const [k, label] of FACTS) { const dd = el("dd"); @@ -200,6 +201,25 @@ function render() { dd.append(copyButton(it[k])); dl.append(el("dt", label), dd); } + const card = $(".card", frag); + if (it.coverage_note) card.append(el("p", it.coverage_note, "coverage")); + if (Array.isArray(it.context) && it.context.length) { + const details = el("details", undefined, "context"); + details.append(el("summary", `Recorded wallet activity before the cutoff (last ${it.context.length})`)); + const table = el("table"); + const head = el("tr"); + for (const h of ["Block", "Direction", "Counterparty", "Value (base units)"]) head.append(el("th", h)); + table.append(head); + for (const row of it.context) { + const tr = el("tr"); + tr.append(el("td", row.block), el("td", row.direction)); + const td = el("td"); td.append(el("code", row.counterparty)); tr.append(td); + tr.append(el("td", row.value)); + table.append(tr); + } + details.append(table); + card.append(details); + } const form = $("form", frag); const fs = $(".decision", form); DECISIONS.forEach(([v, label], n) => { diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py index 174d582..86e9401 100644 --- a/src/cryptoguard/ml/review_sample.py +++ b/src/cryptoguard/ml/review_sample.py @@ -316,6 +316,13 @@ class FrozenIntegrityError(ReviewSampleError): MANIFEST: "c38ae31d598bb58c33fcd2d6553823fc1880b25a4b49b8764d32a290bc7dbdc3", } SELECTION_FIELDS = ("sample_version", "queue_sha256", "design", "selected", "reserves") +# Every frozen cohort and its committed hashes. A reviewer package names no cohort: the +# server finds it by the sheet's hash, so a cohort's purpose is never shown to reviewers. +COHORTS: dict[str, dict[str, str]] = {SAMPLE_VERSION: FROZEN_V1} + + +def cohort_for_sheet(sheet_sha256: str) -> str | None: + return next((c for c, h in COHORTS.items() if h[SHEET] == sheet_sha256), None) def file_sha256(path: Path) -> str: @@ -330,12 +337,15 @@ def verify_frozen( sample_dir: Path, *, queue: Path | None = None, - expected: dict[str, str] = FROZEN_V1, + expected: dict[str, str] | None = None, with_key: bool = True, + cohort: str = SAMPLE_VERSION, ) -> dict[str, Any]: """Check every frozen file against ``expected`` and the manifest's own records; return the manifest. Raises ``FrozenIntegrityError`` naming every mismatch. ``with_key=False`` - skips the unblinding key (for a reviewer package, which does not contain it).""" + skips the unblinding key (for a reviewer package, which does not contain it). + ``cohort`` selects the committed hashes (``COHORTS``) and the expected version.""" + expected = expected if expected is not None else COHORTS[cohort] problems: list[str] = [] names = [MANIFEST, SHEET] + ([KEY] if with_key else []) got: dict[str, str] = {} @@ -350,7 +360,7 @@ def verify_frozen( if problems: raise FrozenIntegrityError("; ".join(problems)) manifest: dict[str, Any] = json.loads((sample_dir / MANIFEST).read_text(encoding="utf-8")) - if manifest.get("sample_version") != SAMPLE_VERSION: + if manifest.get("sample_version") != cohort: problems.append(f"sample_version {manifest.get('sample_version')!r}") if selection_sha256(manifest) != expected["selection"]: problems.append("selection hash does not match the committed value") @@ -375,6 +385,6 @@ def verify_frozen( def read_sheet(path: Path) -> list[dict[str, Any]]: rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line] for r in rows: - if r.get("schema_version") != SHEET_SCHEMA: + if r.get("schema_version") not in (SHEET_SCHEMA, "review-sheet/2"): raise ReviewSampleError(f"{path}: unexpected sheet schema {r.get('schema_version')!r}") return rows diff --git a/src/cryptoguard/ml/review_server.py b/src/cryptoguard/ml/review_server.py index 9bbc8fc..d2dfcb8 100644 --- a/src/cryptoguard/ml/review_server.py +++ b/src/cryptoguard/ml/review_server.py @@ -47,20 +47,28 @@ ) SHEET_FIELDS = ("item", "victim_event_id", "chain_id", "wallet", "address_under_review", "transaction", "block") # fmt: skip +OPTIONAL_FIELDS = ("description", "coverage_note", "context") # sheet v2 (later cohorts) + + +def _view(r: dict[str, Any]) -> dict[str, Any]: + """The reviewer's view of one sheet line: required fields plus whitelisted extras.""" + return {k: r[k] for k in SHEET_FIELDS} | {k: r[k] for k in OPTIONAL_FIELDS if k in r} class PackageError(ValueError): pass -def load_package(package: Path, expected_sheet_sha256: str) -> dict[str, Any]: - """Verify the package and return its reviewer, sample hashes and active items.""" +def load_package(package: Path, expected_sheet_sha256: str | None = None) -> dict[str, Any]: + """Verify the package and return its reviewer, sample hashes and active items. The + cohort is found by the sheet's hash among the committed cohorts (``rs.COHORTS``).""" info = json.loads((package / PACKAGE_INFO).read_text(encoding="utf-8")) sheet_path = package / rs.SHEET got = rs.file_sha256(sheet_path) - if got != info["sheet_sha256"] or got != expected_sheet_sha256: - raise PackageError(f"{sheet_path}: sha256 {got} is not the frozen sheet") - items = {r["item"]: {k: r[k] for k in SHEET_FIELDS} for r in rs.read_sheet(sheet_path)} + known = expected_sheet_sha256 == got if expected_sheet_sha256 else rs.cohort_for_sheet(got) + if got != info["sheet_sha256"] or not known: + raise PackageError(f"{sheet_path}: sha256 {got} is not a frozen sheet") + items = {r["item"]: _view(r) for r in rs.read_sheet(sheet_path)} replaced: list[int] = [] rep_path = package / REPLACEMENT_SHEET if rep_path.exists(): @@ -72,7 +80,7 @@ def load_package(package: Path, expected_sheet_sha256: str) -> dict[str, Any]: raise PackageError(f"{rep_path}: bad replacement for item {r['replaces_item']}") del items[r["replaces_item"]] replaced.append(r["replaces_item"]) - items[r["item"]] = {k: r[k] for k in SHEET_FIELDS} + items[r["item"]] = _view(r) return { "reviewer": info["reviewer"], "selection_sha256": info["selection_sha256"], @@ -84,8 +92,7 @@ def load_package(package: Path, expected_sheet_sha256: str) -> dict[str, Any]: class ReviewApp: def __init__(self, package: Path, expected_sheet_sha256: str | None = None) -> None: - expected = expected_sheet_sha256 or rs.FROZEN_V1[rs.SHEET] - self.pkg = load_package(package, expected) + self.pkg = load_package(package, expected_sheet_sha256) ids = {i: v["victim_event_id"] for i, v in self.pkg["items"].items()} self.store = ReviewerStore(package / STORE_DIR, self.pkg["reviewer"], ids) self.token = secrets.token_urlsafe(24) diff --git a/src/cryptoguard/ml/sample_design.py b/src/cryptoguard/ml/sample_design.py index ae5f0ea..5c2f095 100644 --- a/src/cryptoguard/ml/sample_design.py +++ b/src/cryptoguard/ml/sample_design.py @@ -78,10 +78,12 @@ def weight(self, event_id: str) -> Fraction: def parse_stratum(name: str) -> tuple[str, int, bool]: - subtype, year, rival = name.split("|") - if rival not in ("rival", "no_rival"): + # The flag is rival/no_rival (Phase 11.4 sample) or yes/no (later cohorts; its meaning + # is in the manifest's design["strata"]). + subtype, year, flag = name.split("|") + if flag not in ("rival", "no_rival", "yes", "no"): raise ValueError(f"bad stratum name {name!r}") - return subtype, int(year), rival == "rival" + return subtype, int(year), flag in ("rival", "yes") def design(manifest: Mapping[str, Any]) -> Design: diff --git a/src/cryptoguard/ml/unblind.py b/src/cryptoguard/ml/unblind.py index e121066..c635337 100644 --- a/src/cryptoguard/ml/unblind.py +++ b/src/cryptoguard/ml/unblind.py @@ -56,12 +56,24 @@ def _log_access(work: Path, purpose: str, detail: Mapping[str, Any]) -> None: fh.write(line) +def record_of(row: Mapping[str, Any]) -> Mapping[str, Any]: + """The source record in a key line: a review packet (Phase 11.4 sample) or a candidate + record (later cohorts).""" + rec: Mapping[str, Any] = row.get("packet") or row["candidate"] + return rec + + +def _id(row: Mapping[str, Any]) -> str: + rec = record_of(row) + return str(rec.get("victim_event_id") or rec["event_id"]) + + def _key_rows(sample_dir: Path, wanted: set[str]) -> dict[str, dict[str, Any]]: out: dict[str, dict[str, Any]] = {} for line in (sample_dir / rs.KEY).read_text(encoding="utf-8").splitlines(): row = json.loads(line) - if row["packet"]["victim_event_id"] in wanted: - out[row["packet"]["victim_event_id"]] = row + if _id(row) in wanted: + out[_id(row)] = row return out @@ -73,14 +85,16 @@ def replacements(work: Path) -> list[ReplacementRecord]: # --- reviewer packages ------------------------------------------------------------------- -def make_package(sample_dir: Path, work: Path, reviewer: str, out: Path) -> Path: +def make_package( + sample_dir: Path, work: Path, reviewer: str, out: Path, *, cohort: str = rs.SAMPLE_VERSION +) -> Path: """Copy what one reviewer needs and nothing else: the blinded sheet (byte for byte), any blinded replacement lines and a small info file. Never the key or the manifest.""" from cryptoguard.ml.annotation import REVIEWER_ID if not REVIEWER_ID.match(reviewer): raise AnnotationError(f"invalid reviewer pseudonym {reviewer!r}") - manifest = rs.verify_frozen(sample_dir) + manifest = rs.verify_frozen(sample_dir, cohort=cohort) info_path = out / PACKAGE_INFO if info_path.exists(): existing = json.loads(info_path.read_text(encoding="utf-8")) @@ -119,10 +133,11 @@ def record_replacement( evidence: str, exposed: Sequence[str], recorded_by: str, + cohort: str = rs.SAMPLE_VERSION, ) -> ReplacementRecord: """Append the next frozen reserve of the original's stratum. Only for technical inaccessibility; the log keeps every replacement with its reason.""" - manifest = rs.verify_frozen(sample_dir) + manifest = rs.verify_frozen(sample_dir, cohort=cohort) recs = replacements(work) active = {r["victim_event_id"]: r["stratum"] for r in manifest["selected"]} items = {r["victim_event_id"]: r["item"] for r in rs.read_sheet(sample_dir / rs.SHEET)} @@ -141,16 +156,20 @@ def record_replacement( raise AnnotationError(f"{stratum}: no reserve left (nonresponse; see protocol §5)") new_id = reserves[pos] _log_access(work, "replacement sheet line", {"event": new_id}) - packet = _key_rows(sample_dir, {new_id})[new_id]["packet"] - from cryptoguard.ml.review import ReviewPacket - + row = _key_rows(sample_dir, {new_id})[new_id] item = max(items.values()) + 1 + if "packet" in row: + from cryptoguard.ml.review import ReviewPacket + + line = rs.blind(ReviewPacket.model_validate(row["packet"]), item) + else: # later cohorts keep the blinded line in the frozen key's sheet copy + line = {**row["sheet"], "item": item} rec = ReplacementRecord( original_event_id=original_event_id, original_item=items[original_event_id], replacement_event_id=new_id, replacement_item=item, - sheet_line=rs.blind(ReviewPacket.model_validate(packet), item), + sheet_line=line, stratum=stratum, reserve_position=pos, reason=reason, @@ -176,13 +195,15 @@ def preflight( work: Path, submission_paths: Sequence[Path], adjudication_path: Path | None = None, + *, + cohort: str = rs.SAMPLE_VERSION, ) -> dict[str, Any]: """Every check that must pass before the key may be opened. Raises ``UnblindingRefused`` listing all failures. Never reads the key's contents (only its hash).""" problems: list[str] = [] try: - manifest = rs.verify_frozen(sample_dir) + manifest = rs.verify_frozen(sample_dir, cohort=cohort) except rs.ReviewSampleError as exc: raise UnblindingRefused(f"frozen sample: {exc}") from None recs = replacements(work) @@ -205,7 +226,7 @@ def preflight( for s in subs: if s.selection_sha256 != manifest["selection_sha256"]: problems.append(f"{s.reviewer}: submission is for another sample") - if s.sheet_sha256 != rs.FROZEN_V1[rs.SHEET]: + if s.sheet_sha256 != rs.COHORTS[cohort][rs.SHEET]: problems.append(f"{s.reviewer}: submission is for another reviewer sheet") if s.protocol != PROTOCOL: problems.append(f"{s.reviewer}: protocol {s.protocol}") @@ -248,10 +269,12 @@ def unblind( work: Path, submission_paths: Sequence[Path], adjudication_path: Path | None = None, + *, + cohort: str = rs.SAMPLE_VERSION, ) -> dict[str, Any]: """Run the gate, open the key, write the local item table and return the aggregate report. Reviewer decisions are never overwritten by source labels.""" - pre = preflight(sample_dir, work, submission_paths, adjudication_path) + pre = preflight(sample_dir, work, submission_paths, adjudication_path, cohort=cohort) active: set[str] = pre["active"] subs: list[Submission] = pre["submissions"] _log_access( @@ -288,7 +311,7 @@ def item_table( adj = {a.victim_event_id: a for a in adjudications} rows = [] for e in sorted(key): - packet = key[e]["packet"] + packet = record_of(key[e]) reviews = {s.reviewer: next(a for a in s.decisions if a.victim_event_id == e) for s in subs} found = { r: a.prior_counterparty_address.lower() @@ -300,9 +323,12 @@ def item_table( { "victim_event_id": e, "stratum": key[e]["stratum"], - "source_subtype": packet["subtype"], - "source_labels": packet["source_labels"], - "rival_lookalikes": len(packet["competing_lookalikes"]), + "source_subtype": packet.get("subtype"), + "source_labels": packet.get("source_labels"), + "frame": packet.get("frame"), + "categories": packet.get("categories"), + "screen_status": packet.get("screen_status"), + "rival_lookalikes": len(packet.get("competing_lookalikes", ())), "reviewer_decisions": {r: a.decision for r, a in reviews.items()}, "reviewer_counterparty_matches_source_imitated": { r: addr == imitated for r, addr in found.items() @@ -351,15 +377,16 @@ def analyse( reviewers = sorted(decisions) items = sorted(set.intersection(*(set(v) for v in decisions.values()))) - def outcome(rule: str) -> dict[str, bool | None]: + def outcome(rule: str, positive: frozenset[str] = ATTEMPT) -> dict[str, bool | None]: out: dict[str, bool | None] = dict.fromkeys(d.item_cell) for e in items: labels = [decisions[r][e] for r in reviewers] - flags = [x in ATTEMPT for x in labels] + flags = [x in positive for x in labels] out[slot.get(e, e)] = all(flags) if rule == "all" else any(flags) return out primary, lenient = outcome("all"), outcome("any") + legitimate = outcome("all", frozenset({"confirmed_legitimate_interaction"})) adjudicated = dict(primary) for a in adjudications: adjudicated[slot.get(a.victim_event_id, a.victim_event_id)] = a.final_decision in ATTEMPT @@ -388,7 +415,7 @@ def block(o: Mapping[str, bool | None]) -> dict[str, Any]: ), "by_subgroup": {}, } - for name, member in _subgroups(stratum_of).items(): + for name, member in _subgroups(stratum_of, manifest["design"].get("strata")).items(): ids = [e for e in items if e in member] if len(ids) < MIN_CELL: agree["by_subgroup"][name] = {"items": len(ids), "note": f"fewer than {MIN_CELL}"} @@ -435,6 +462,9 @@ def block(o: Mapping[str, bool | None]) -> dict[str, Any]: "primary_all_reviewers_attempt": block(primary), "sensitivity_any_reviewer_attempt": block(lenient), "secondary_adjudicated": block(adjudicated) if adjudications else None, + # Share every reviewer judged a confirmed legitimate interaction (the hard-negative + # cohort's primary quantity; reported for every cohort). + "all_reviewers_legitimate": block(legitimate), "replacement_sensitivity": block( { **primary, @@ -454,7 +484,7 @@ def block(o: Mapping[str, bool | None]) -> dict[str, Any]: cats = Counter(_source_category([decisions[r][e] for r in reviewers]) for e in items) matched: Counter[str] = Counter() for e in items: - imitated = (key[e]["packet"].get("imitated") or "").lower() + imitated = (record_of(key[e]).get("imitated") or "").lower() for s in subs: ann = next(x for x in s.decisions if x.victim_event_id == e) if ann.prior_counterparty_address: @@ -464,16 +494,26 @@ def block(o: Mapping[str, bool | None]) -> dict[str, Any]: report["source_comparison"] = { "categories": dict(cats), "reviewer_counterparty_vs_source_imitated": dict(matched), - "note": "the source labels every item a poisoning attempt; reviewer decisions are " - "never overwritten by it", + "note": ( + "the source labels every item a poisoning attempt" + if manifest["sample_version"] == rs.SAMPLE_VERSION + else "items are unlabeled candidates; no source label exists" + ) + + "; reviewer decisions are never overwritten by source information", } return report -def _subgroups(stratum_of: Mapping[str, str]) -> dict[str, set[str]]: +def _subgroups( + stratum_of: Mapping[str, str], names: Sequence[str] | None = None +) -> dict[str, set[str]]: + first, _, third = names if names and len(names) == 3 else ("subtype", "year", "rival") + third = "rival" if third == "rival_lookalike" else third + first = first.split("_")[0] if first != "frame" else "frame" groups: dict[str, set[str]] = {} for e, name in stratum_of.items(): - subtype, year, rival = sd.parse_stratum(name) - for g in (f"subtype={subtype}", f"year={year}", f"rival={'yes' if rival else 'no'}"): + head, year, flag = sd.parse_stratum(name) + head = head.split(":")[0] # one recorded wallet per stratum: report by frame + for g in (f"{first}={head}", f"year={year}", f"{third}={'yes' if flag else 'no'}"): groups.setdefault(g, set()).add(e) return dict(sorted(groups.items())) diff --git a/tests/unit/test_ml_cohort.py b/tests/unit/test_ml_cohort.py new file mode 100644 index 0000000..f03ee1c --- /dev/null +++ b/tests/unit/test_ml_cohort.py @@ -0,0 +1,211 @@ +"""Generic review cohorts (Phase 11.5): deterministic stratified draw, freeze-once, and the +existing review workflow running a second, separately frozen cohort without revealing its +purpose. + +Synthetic items and synthetic reviewer decisions only. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import cohort as ch +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import unblind as ub +from cryptoguard.ml.review_server import ReviewApp +from tests.review_fixtures import ATTEMPT_FIELDS, addr, fields + +COHORT = "hard-negative-candidates/1" +LEGIT = { + **ATTEMPT_FIELDS, + "decision": "confirmed_legitimate_interaction", + "prior_counterparty": "not_observed", + "prior_counterparty_address": None, + "matched_leading": None, + "matched_trailing": None, + "legitimate_explanation": "observed", + "rationale": "The address is the wallet owner's own exchange deposit address.", +} + + +def items(n_arc: int = 40, wallets: int = 3, per_wallet: int = 5) -> list[ch.FrameItem]: + out = [] + k = 0 + for i in range(n_arc): + k += 1 + out.append( + _item( + k, + f"archive_uncategorized|{2023 if i % 2 else 2022}|{'yes' if i % 7 == 0 else 'no'}", + group=f"a/{i // 2}", + ) + ) + for w in range(wallets): + for _ in range(per_wallet): + k += 1 + out.append(_item(k, f"fixture_background:w{w}|2024|no", group=f"f/{k}")) + return out + + +def _item(k: int, stratum: str, *, group: str) -> ch.FrameItem: + return ch.FrameItem( + event_id=f"{k:016x}", + stratum=stratum, + group=group, + sheet={ + "chain_id": 1, + "wallet": addr(1000 + k), + "address_under_review": addr(2000 + k), + "transaction": "0x" + f"{k:064x}", + "block": 17_000_000 + k, + "coverage_note": "No wallet history is included.", + "context": [ + {"block": 1, "direction": "out", "counterparty": addr(3000 + k), "value": "5"} + ], + }, + key={ + "frame": stratum.split("|")[0], + "categories": ["A_similarity_ordinary_value"], + "screen_status": "no_known_overlap", + "label_status": "unlabeled_candidate", + "imitated": addr(4000 + k), + }, + ) + + +def design(quota: dict[str, int] | None = None) -> ch.CohortDesign: + q = quota or {"archive_uncategorized": 6} | {f"fixture_background:w{w}": 2 for w in range(3)} + return ch.CohortDesign(COHORT, "seed", q, ("frame", "year", "potential_positive_overlap"), "t") + + +def test_draw_is_deterministic_stratified_and_one_per_group() -> None: + a = ch.draw(items(), design()) + b = ch.draw(list(reversed(items())), design()) + assert a == b + m = a["manifest"] + assert len(m["selected"]) == 12 + by_item = {i.event_id: i for i in items()} + groups = [by_item[r["victim_event_id"]].group for r in m["selected"]] + assert len(set(groups)) == len(groups) + table = {r["stratum"]: r for r in m["strata_table"]} + assert sum(r["groups"] for r in table.values()) == m["groups"]["count"] # every rep counted + for r in table.values(): + if r["selected"]: + got = sum(x["weight"] for x in m["selected"] if x["stratum"] == r["stratum"]) + assert got == pytest.approx(r["groups"]) # weights are N/n + + +def test_sheet_is_neutral_and_key_holds_the_rest() -> None: + s = ch.draw(items(), design()) + for line in s["sheet"]: + assert line["description"] == ch.NEUTRAL + text = json.dumps(line) + for word in ( + "archive", + "fixture", + "uncategorized", + "negative", + "categor", + "screen", + "label", + "imitated", + ): + assert word not in text + assert all("candidate" in k and "sheet" in k for k in s["key"]) + + +def test_empty_or_duplicate_frames_are_refused() -> None: + with pytest.raises(rs.ReviewSampleError, match="empty"): + ch.draw([], design()) + dup = items()[:2] + with pytest.raises(rs.ReviewSampleError, match="repeats"): + ch.draw([dup[0], dup[0]], design()) + + +def test_small_strata_take_everything_they_have() -> None: + m = ch.draw(items(per_wallet=1), design())["manifest"] + fixture_rows = [r for r in m["strata_table"] if r["stratum"].startswith("fixture")] + assert all(r["selected"] == r["groups"] == 1 for r in fixture_rows) # census + + +def test_freeze_once_and_refuse_a_changed_frame(tmp_path: Path) -> None: + out = tmp_path / "cohort" + m, written = ch.freeze(items(), design(), out) + assert written + before = {p.name: p.read_bytes() for p in out.iterdir()} + again, written = ch.freeze(items(), design(), out) + assert not written + assert again["selection_sha256"] == m["selection_sha256"] + with pytest.raises(rs.SampleFrozenError, match="frame changed"): + ch.freeze(items()[:-1], design(), out) + assert {p.name: p.read_bytes() for p in out.iterdir()} == before + + +# --- the review workflow on a second cohort ---------------------------------------------------- + + +@pytest.fixture +def frozen_cohort(tmp_path: Path, monkeypatch) -> dict[str, Any]: + out = tmp_path / "cohort" + m, _ = ch.freeze(items(), design(), out) + hashes = {name: rs.file_sha256(out / name) for name in (rs.SHEET, rs.KEY, rs.MANIFEST)} + monkeypatch.setitem( + rs.COHORTS, + COHORT, + hashes | {"selection": m["selection_sha256"], "queue": m["queue_sha256"]}, + ) + return {"dir": out, "manifest": m, "tmp": tmp_path} + + +def test_package_names_no_cohort_and_server_hides_the_key(frozen_cohort: dict[str, Any]) -> None: + t = frozen_cohort["tmp"] + pkg = ub.make_package(frozen_cohort["dir"], t / "work", "A", t / "pkg", cohort=COHORT) + info = (pkg / "reviewer.json").read_text(encoding="utf-8") + assert "negative" not in info + assert COHORT not in info + state = ReviewApp(pkg).state() + text = json.dumps(state) + for word in ("negative", "archive_uncategorized", "fixture", "screen", "unlabeled", "categor"): + assert word not in text + hidden = {i.key["imitated"] for i in items()} + assert not any(h in text for h in hidden) # key-only addresses are never sent + first = state["items"][0] + assert first["description"] == ch.NEUTRAL + assert first["context"][0]["direction"] == "out" + + +def test_verification_of_one_cohort_does_not_accept_another(frozen_cohort: dict[str, Any]) -> None: + with pytest.raises(rs.FrozenIntegrityError): + rs.verify_frozen(frozen_cohort["dir"]) # checked against the Phase 11.4 hashes + assert rs.verify_frozen(frozen_cohort["dir"], cohort=COHORT)["sample_version"] == COHORT + + +def _review(pkg: Path, decide) -> Path: + app = ReviewApp(pkg) + with app.store: + for it in app.state()["items"]: + app.store.save(fields(it["item"], it["victim_event_id"], decide(it["item"]))) + app.finalize() + return pkg / "annotations" / "submission.json" + + +def test_unblinding_a_candidate_cohort_reports_the_legitimate_share( + frozen_cohort: dict[str, Any], +) -> None: + t, d = frozen_cohort["tmp"], frozen_cohort["dir"] + pkgs = {r: ub.make_package(d, t / "work", r, t / f"pkg-{r}", cohort=COHORT) for r in "AB"} + a = _review(pkgs["A"], lambda i: LEGIT) + b = _review(pkgs["B"], lambda i: ATTEMPT_FIELDS if i == 1 else LEGIT) + with pytest.raises(ub.UnblindingRefused): + ub.unblind(d, t / "work", [a, b]) # the default cohort's hashes do not match + report = ub.unblind(d, t / "work", [a, b], cohort=COHORT) + n = len(frozen_cohort["manifest"]["selected"]) + legit = report["all_reviewers_legitimate"]["overall"] + assert legit["positives"] == n - 1 # one item disputed + assert report["agreement"]["binary"]["disagreements"] == 1 + assert any(k.startswith("frame=") for k in report["agreement"]["by_subgroup"]) + assert "no source label" in report["source_comparison"]["note"] From c68d3a467dc63b1911d089540198367b66b3aa9f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 12:58:11 +0300 Subject: [PATCH 26/92] feat(ml): offline hard-negative discovery, contamination screen and evaluation contract candidates/2: a counterparty counts as chosen only with a verified wallet signature (candidates/1 also used unknown-signer transfers), and generation is one pass instead of one history scan per transfer; identical output on all 13 recorded windows. Adds the archive's uncategorized-row extraction (two streaming passes, never executes SQL), the hard-negative pool with structural categories (every item unlabeled_candidate), a contamination screen against every local known positive with match levels and statuses, typed campaign grouping that never links through common tokens, coarsened exact matching with balance diagnostics, source-separability diagnostics, a benchmark data contract and metrics that refuse unverified negatives, a data inventory, and the hard-negative-study command. Offline, 0 RPC requests. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/candidates.py | 37 +- src/cryptoguard/ml/cli.py | 100 +++- src/cryptoguard/ml/contamination.py | 170 ++++++ src/cryptoguard/ml/evaluation.py | 310 +++++++++++ src/cryptoguard/ml/grouping.py | 129 +++++ src/cryptoguard/ml/hard_negative_archive.py | 144 +++++ src/cryptoguard/ml/hard_negatives.py | 451 +++++++++++++++ src/cryptoguard/ml/hn_study.py | 531 ++++++++++++++++++ src/cryptoguard/ml/inventory.py | 109 ++++ src/cryptoguard/ml/matching.py | 134 +++++ tests/unit/test_ml_hard_negatives.py | 581 ++++++++++++++++++++ tests/unit/test_ml_reconcile.py | 9 + 12 files changed, 2687 insertions(+), 18 deletions(-) create mode 100644 src/cryptoguard/ml/contamination.py create mode 100644 src/cryptoguard/ml/evaluation.py create mode 100644 src/cryptoguard/ml/grouping.py create mode 100644 src/cryptoguard/ml/hard_negative_archive.py create mode 100644 src/cryptoguard/ml/hard_negatives.py create mode 100644 src/cryptoguard/ml/hn_study.py create mode 100644 src/cryptoguard/ml/inventory.py create mode 100644 src/cryptoguard/ml/matching.py create mode 100644 tests/unit/test_ml_hard_negatives.py diff --git a/src/cryptoguard/ml/candidates.py b/src/cryptoguard/ml/candidates.py index f65b5bb..ca294a2 100644 --- a/src/cryptoguard/ml/candidates.py +++ b/src/cryptoguard/ml/candidates.py @@ -21,6 +21,18 @@ the same block (``history.Boundary`` ``pre_execution``, with the event's transaction excluded). Features see only strictly earlier positions; the cross-wallet index sees only earlier blocks. + +``candidates/2`` (Phase 11.5) counts a counterparty as *chosen* only when the wallet's +signature is verified (``wallet_signed is True``). ``candidates/1`` also counted outgoing +transfers whose signer was unknown, so under partial coverage a spoofed transfer to a +lookalike could become the "imitated" counterparty. No recorded fixture has such a +transfer, so no published number changes. The generator is now one pass instead of one +history scan per transfer. + +Known breadth (documented, not a defect): ``spoofed_out`` also fires on legitimate +transfers pulled by an approved spender (routers, settlement contracts, Permit2), and +``dust_in`` on genuine small test payments. These are hard-negative candidates, never +labels. """ from __future__ import annotations @@ -42,7 +54,7 @@ from cryptoguard.ml.payments import TRUSTED_TOKENS from cryptoguard.replay.models import ReplayFixture -CANDIDATE_VERSION = "candidates/1" +CANDIDATE_VERSION = "candidates/2" EVENT_FEATURE_VERSION = "event-features/1" MIN_AFFIX = 6 MIN_SUFFIX = 3 @@ -96,34 +108,43 @@ class Candidate: def _chosen_before(events: list[WalletEvent], position: tuple[int, int, int]) -> dict[str, int]: - """Counterparties the wallet chose (signed outgoing events) strictly before ``position``, - with the block they were last chosen.""" + """Counterparties the wallet chose (outgoing events it verifiably signed) strictly before + ``position``, with the block they were last chosen.""" chosen: dict[str, int] = {} - for e in events: - if e.position < position and e.direction == "out" and e.wallet_signed is not False: + for e in sorted(events, key=lambda e: e.position): + if e.position < position and _chose(e): chosen[e.counterparty.lower()] = e.block return chosen +def _chose(e: WalletEvent) -> bool: + return e.direction == "out" and e.wallet_signed is True + + def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: """Candidate events from one recorded wallet window, in chain order.""" wallet = fixture.wallet.lower() events, coverage = events_from_fixture(fixture) - events.sort(key=lambda e: e.position) + choices = sorted((e for e in events if _chose(e)), key=lambda e: e.position) status = "complete" if coverage.complete else "partial" out: list[Candidate] = [] + chosen: dict[str, int] = {} # grows as the pass moves forward: strictly earlier choices + next_choice = 0 for t in sorted( fixture.transfers, key=lambda t: (t.block_number, t.transaction_index, t.log_index) ): + position = (t.block_number, t.transaction_index, t.log_index) + while next_choice < len(choices) and choices[next_choice].position < position: + e = choices[next_choice] + chosen[e.counterparty.lower()] = e.block + next_choice += 1 incoming = t.recipient.lower() == wallet outgoing = t.sender.lower() == wallet if not (incoming or outgoing): continue - position = (t.block_number, t.transaction_index, t.log_index) token = t.token.lower() value = int(t.value) party = (t.sender if incoming else t.recipient).lower() - chosen = _chosen_before(events, position) match = max( ((k, m) for k in chosen if (m := similar(party, k)) is not None), key=lambda km: (sum(km[1]), km[1][1], km[0]), diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 0e17762..78aab97 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -93,6 +93,23 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ) fr.add_argument("--out", type=Path, default=ML_DIR / "poisoning" / "review_sample") _add_review_parser(ml) + iv = ml.add_parser("inventory", help="hash and describe every local research data file") + iv.add_argument("--root", type=Path, default=Path(".")) + iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") + hx = ml.add_parser( + "hard-negative-extract", + help="two offline passes over the local archive for uncategorized lookalike transfers", + ) + hx.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + hx.add_argument("--out", type=Path, default=ML_DIR / "poisoning" / "hard_negative") + hs = ml.add_parser( + "hard-negative-study", + help="candidate pool, contamination screen, matching, separability, cohort (offline)", + ) + hs.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + hs.add_argument("--poisoning-dir", type=Path, default=ML_DIR / "poisoning") + hs.add_argument("--tables", type=Path, default=Path("ML_HARD_NEGATIVE_TABLES.md")) + hs.add_argument("--no-freeze", action="store_true", help="draw without freezing") bz = ml.add_parser("bench-archive", help="archive-scanner scaling on synthetic dumps") bz.add_argument("sizes", type=int, nargs="+") bz.add_argument("--work", type=Path, default=ML_DIR / "bench") @@ -138,6 +155,51 @@ def run(args: argparse.Namespace) -> int: return _freeze_review_sample(args) if args.ml_command == "review": return _review(args) + if args.ml_command == "inventory": + import json + + from cryptoguard.ml.inventory import inventory + + inv = inventory(args.root) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(inv, indent=1) + "\n", encoding="utf-8") + unregistered = [f["path"] for f in inv["files"] if f["source"] == "unregistered"] + print(f"{len(inv['files'])} files described in {args.out}; unregistered: {unregistered}") + return 0 + if args.ml_command == "hard-negative-extract": + import json + + from cryptoguard.ml.hard_negative_archive import context_scan, extract_uncategorized + + try: + first = extract_uncategorized(args.data_dir, args.out) + second = context_scan(args.data_dir, args.out) + except FileNotFoundError as exc: + print(f"error [FileNotFoundError]: {exc}") + return 1 + print(json.dumps({"extract": first, "context_rows": second.get("stored_rows")}, indent=1)) + return 0 + if args.ml_command == "hard-negative-study": + from cryptoguard.ml.hn_study import run + + try: + report = run( + args.data_dir, + args.poisoning_dir, + args.poisoning_dir / "hard_negative", + args.tables, + freeze_cohort=not args.no_freeze, + ) + except FileNotFoundError as exc: + print(f"error [FileNotFoundError]: {exc} (run `cryptoguard ml hard-negative-extract`)") + return 1 + c = report["cohort"] + print( + f"Pool: {sum(f['candidates'] for f in report['pool']['frames'].values()):,} " + f"unlabeled candidates; cohort {c['version']}: {c['selected']} items " + f"(selection {c['selection_sha256'][:12]}); wrote {args.tables} (0 RPC requests)." + ) + return 0 if args.ml_command == "bench-archive": import json @@ -297,6 +359,9 @@ def _freeze_review_sample(args: argparse.Namespace) -> int: SAMPLE_DIR = ML_DIR / "poisoning" / "review_sample" REVIEW_WORK = ML_DIR / "poisoning" / "review" +HN_DIR = ML_DIR / "poisoning" / "hard_negative" +COHORT_DIRS = {"review-sample/1": SAMPLE_DIR, "hard-negative-candidates/1": HN_DIR / "cohort_v1"} +COHORT_WORK = {"review-sample/1": REVIEW_WORK, "hard-negative-candidates/1": HN_DIR / "review"} QUEUE = ML_DIR / "poisoning" / "review_packets_payoff_linked.jsonl" @@ -308,14 +373,14 @@ def _add_review_parser(ml: argparse._SubParsersAction[argparse.ArgumentParser]) ("audit", "recompute and check the sampling design; aggregate JSON"), ): p = sub.add_parser(name, help=text) - p.add_argument("--sample", type=Path, default=SAMPLE_DIR) + p.add_argument("--sample", type=Path, default=None) p.add_argument("--queue", type=Path, default=QUEUE) sub.choices["audit"].add_argument("--out", type=Path, default=REVIEW_WORK / "design_audit.json") pk = sub.add_parser("package", help="make one reviewer's package (blinded sheet only)") pk.add_argument("--reviewer", required=True, help="pseudonym, e.g. A") pk.add_argument("--out", type=Path, required=True) - pk.add_argument("--sample", type=Path, default=SAMPLE_DIR) - pk.add_argument("--work", type=Path, default=REVIEW_WORK) + pk.add_argument("--sample", type=Path, default=None) + pk.add_argument("--work", type=Path, default=None) sv = sub.add_parser("serve", help="run the local review app for one reviewer package") sv.add_argument("--package", type=Path, required=True) sv.add_argument("--port", type=int, default=0) @@ -332,13 +397,19 @@ def _add_review_parser(ml: argparse._SubParsersAction[argparse.ArgumentParser]) rp.add_argument("--evidence", required=True) rp.add_argument("--exposed", default="", help="reviewers who already saw the original") rp.add_argument("--by", required=True) - rp.add_argument("--sample", type=Path, default=SAMPLE_DIR) - rp.add_argument("--work", type=Path, default=REVIEW_WORK) + rp.add_argument("--sample", type=Path, default=None) + rp.add_argument("--work", type=Path, default=None) ub = sub.add_parser("unblind", help="gate, then compare reviews with the source (maintainer)") ub.add_argument("--submission", type=Path, action="append", required=True) ub.add_argument("--adjudication", type=Path) - ub.add_argument("--sample", type=Path, default=SAMPLE_DIR) - ub.add_argument("--work", type=Path, default=REVIEW_WORK) + ub.add_argument("--sample", type=Path, default=None) + ub.add_argument("--work", type=Path, default=None) + for p in (sub.choices["verify"], pk, rp, ub): + p.add_argument( + "--cohort", + default="review-sample/1", + choices=["review-sample/1", "hard-negative-candidates/1"], + ) def _review(args: argparse.Namespace) -> int: @@ -348,9 +419,15 @@ def _review(args: argparse.Namespace) -> int: from cryptoguard.ml.annotation import AnnotationError cmd = args.review_command + cohort = getattr(args, "cohort", rs.SAMPLE_VERSION) + if getattr(args, "sample", "unset") is None: + args.sample = COHORT_DIRS[cohort] + if getattr(args, "work", "unset") is None: + args.work = COHORT_WORK[cohort] try: if cmd == "verify": - manifest = rs.verify_frozen(args.sample, queue=args.queue) + queue = args.queue if cohort == rs.SAMPLE_VERSION else None + manifest = rs.verify_frozen(args.sample, queue=queue, cohort=cohort) print( f"Frozen sample verified: {len(manifest['selected'])} items, selection " f"{manifest['selection_sha256']}; all five committed hashes match." @@ -369,7 +446,7 @@ def _review(args: argparse.Namespace) -> int: if cmd == "package": from cryptoguard.ml.unblind import make_package - out = make_package(args.sample, args.work, args.reviewer, args.out) + out = make_package(args.sample, args.work, args.reviewer, args.out, cohort=cohort) print(f"Reviewer package for {args.reviewer} in {out} (blinded sheet only).") return 0 if cmd == "serve": @@ -394,6 +471,7 @@ def _review(args: argparse.Namespace) -> int: evidence=args.evidence, exposed=[x for x in args.exposed.split(",") if x], recorded_by=args.by, + cohort=cohort, ) print( f"Item {rec.original_item} replaced by item {rec.replacement_item} (reserve " @@ -403,7 +481,9 @@ def _review(args: argparse.Namespace) -> int: if cmd == "unblind": from cryptoguard.ml.unblind import unblind - report = unblind(args.sample, args.work, args.submission, args.adjudication) + report = unblind( + args.sample, args.work, args.submission, args.adjudication, cohort=cohort + ) primary = report["primary_all_reviewers_attempt"]["overall"] keys = ("items", "positives", "estimate", "wilson95_design") print(json.dumps({k: primary.get(k) for k in keys}, indent=1)) diff --git a/src/cryptoguard/ml/contamination.py b/src/cryptoguard/ml/contamination.py new file mode 100644 index 0000000..d444c23 --- /dev/null +++ b/src/cryptoguard/ml/contamination.py @@ -0,0 +1,170 @@ +"""Screen hard-negative candidates against every locally known poisoning record (Phase 11.5). + +A candidate that overlaps a known attack must never be used as a negative. A candidate +with no known overlap is **not** benign: it is only unscreened-positive. + +Match levels, strongest first: + +1. ``exact_event``: same victim, lookalike and transaction as a known attempt; +2. ``exact_tx``: same planting transaction; +3. ``victim_lookalike``: the same victim-lookalike pair, another transaction; +4. ``shared_infrastructure``: the lookalike (or a counterfeit token contract) is a known + attacker address elsewhere; +5. ``related_campaign``: the same victim was attacked with a lookalike of the same + imitated counterparty; +6. ``weak_similarity``: nothing above, but the candidate's lookalike resembles a known + lookalike of the same victim (similarity is not evidence of malice); +7. ``none``. + +Statuses: levels 1-4 give ``known_positive_overlap``, level 5 gives +``potential_positive_overlap``, and level 6 or 7 gives ``no_known_overlap``, or +``insufficient_information`` when no screening source covers the candidate's block. +Neither of the last two means verified benign. +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Literal + +from cryptoguard.ml.candidates import similar + +SCREEN_VERSION = "contamination/1" +Level = Literal[ + "exact_event", + "exact_tx", + "victim_lookalike", + "shared_infrastructure", + "related_campaign", + "weak_similarity", + "none", +] +Status = Literal[ + "known_positive_overlap", + "potential_positive_overlap", + "no_known_overlap", + "insufficient_information", +] +LEVEL_STATUS: dict[str, Status] = { + "exact_event": "known_positive_overlap", + "exact_tx": "known_positive_overlap", + "victim_lookalike": "known_positive_overlap", + "shared_infrastructure": "known_positive_overlap", + "related_campaign": "potential_positive_overlap", + "weak_similarity": "no_known_overlap", + "none": "no_known_overlap", +} + + +@dataclass(frozen=True) +class KnownAttack: + """One known poisoning record from any source (no label strength implied beyond the + source's own).""" + + source: str # e.g. "tsuchiya-archive", "poison-hunter", "tsuchiya-payoff", "incident" + victim: str | None + lookalike: str + tx: str | None + imitated: str | None = None + token: str | None = None # a counterfeit token contract, when the source says so + + +@dataclass(frozen=True) +class Coverage: + """Block range a source screened; a candidate outside every range cannot be screened.""" + + source: str + from_block: int + to_block: int + + +@dataclass +class KnownIndex: + coverage: list[Coverage] = field(default_factory=list) + events: dict[tuple[str, str, str], set[str]] = field(default_factory=lambda: defaultdict(set)) + txs: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set)) + pairs: dict[tuple[str, str], set[str]] = field(default_factory=lambda: defaultdict(set)) + lookalikes: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set)) + counterfeit: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set)) + imitated_by_victim: dict[tuple[str, str], set[str]] = field( + default_factory=lambda: defaultdict(set) + ) + lookalikes_by_victim: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set)) + + def add(self, k: KnownAttack) -> None: + look = k.lookalike.lower() + self.lookalikes[look].add(k.source) + if k.token: + self.counterfeit[k.token.lower()].add(k.source) + if k.tx: + self.txs[k.tx.lower()].add(k.source) + if k.victim: + v = k.victim.lower() + self.pairs[(v, look)].add(k.source) + self.lookalikes_by_victim[v].add(look) + if k.tx: + self.events[(v, look, k.tx.lower())].add(k.source) + if k.imitated: + self.imitated_by_victim[(v, k.imitated.lower())].add(k.source) + + def extend(self, attacks: Iterable[KnownAttack]) -> KnownIndex: + for k in attacks: + self.add(k) + return self + + +@dataclass(frozen=True) +class Screened: + level: Level + status: Status + sources: tuple[str, ...] + + +def screen( + *, + victim: str, + lookalike: str, + tx: str, + block: int, + imitated: str | None, + token: str | None, + index: KnownIndex, +) -> Screened: + v, look, t = victim.lower(), lookalike.lower(), tx.lower() + checks: list[tuple[Level, set[str]]] = [ + ("exact_event", index.events.get((v, look, t), set())), + ("exact_tx", index.txs.get(t, set())), + ("victim_lookalike", index.pairs.get((v, look), set())), + ( + "shared_infrastructure", + index.lookalikes.get(look, set()) | index.counterfeit.get((token or "").lower(), set()), + ), + ( + "related_campaign", + index.imitated_by_victim.get((v, imitated.lower()), set()) if imitated else set(), + ), + ] + for level, sources in checks: + if sources: + return Screened(level, LEVEL_STATUS[level], tuple(sorted(sources))) + covered = any(c.from_block <= block <= c.to_block for c in index.coverage) + status: Status = "no_known_overlap" if covered else "insufficient_information" + if any(similar(look, k) for k in index.lookalikes_by_victim.get(v, ())): + return Screened("weak_similarity", status, ()) + return Screened("none", status, ()) + + +def summary(results: Sequence[Screened]) -> dict[str, object]: + return { + "screen_version": SCREEN_VERSION, + "candidates": len(results), + "by_level": dict(Counter(r.level for r in results)), + "by_status": dict(Counter(r.status for r in results)), + "by_source": dict(Counter(s for r in results for s in r.sources)), + } + + +def by_level_counts(results: Mapping[str, Screened]) -> dict[str, int]: + return dict(Counter(r.level for r in results.values())) diff --git a/src/cryptoguard/ml/evaluation.py b/src/cryptoguard/ml/evaluation.py new file mode 100644 index 0000000..9c87059 --- /dev/null +++ b/src/cryptoguard/ml/evaluation.py @@ -0,0 +1,310 @@ +"""Benchmark data contract and label-aware evaluation for ``poisoning-attempt/1`` (Phase 11.5). + +``BenchmarkExample`` keeps seven layers apart: +1. the raw observation; +2. the candidate-generation result; +3. the feature vector; +4. the source label; +5. the human-reviewed label; +6. the later victim outcome; +7. the model prediction. + +Features never contain an outcome, label or score field. A missing feature is ``None``, +never 0. + +The metrics refuse what the data cannot support. +- Only ``verified_attempt`` (1) and ``verified_legitimate`` (0) count as truth. +- Weak, unknown, conflicting and unlabeled examples are excluded and counted, never + turned into negatives. +- Precision needs reviewed positives and negatives; a false-positive rate needs reviewed + negatives. +- Every result names its population, weights and exclusions. +""" + +from __future__ import annotations + +import math +from collections import Counter +from collections.abc import Mapping, Sequence +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +CONTRACT_VERSION = "benchmark-example/1" +TRUTH = {"verified_attempt": 1, "verified_legitimate": 0} +FORBIDDEN_FEATURE_WORDS = ("label", "outcome", "payoff", "loss", "score", "prediction", "paid") +Split = Literal["train", "validation", "test"] + + +class Observation(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + chain_id: int + wallet: str + candidate_address: str + transaction: str + block: int + observation_cutoff: str # e.g. "after tx, before the rest of the block" + source_manifest: str # hash of the input data + + +class Generation(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + candidate_version: str + methods: tuple[str, ...] + eligible: bool + eligibility_flags: tuple[str, ...] = () + + +class Features(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + feature_version: str + values: dict[str, float | None] + missing: tuple[str, ...] = () # names whose input was unavailable (not zero) + + @model_validator(mode="after") + def _no_post_cutoff_fields(self) -> Features: + bad = [k for k in self.values if any(w in k.lower() for w in FORBIDDEN_FEATURE_WORDS)] + if bad: + raise ValueError(f"label, outcome or score data in features: {bad}") + unflagged = [k for k, v in self.values.items() if v is None and k not in self.missing] + if unflagged: + raise ValueError(f"missing values must be listed in `missing`: {unflagged}") + return self + + +class SourceLabel(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + source: str | None + status: Literal["source_positive", "unlabeled_candidate", "none"] + + +class HumanLabel(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + tier: Literal[ + "verified_attempt", "weak_attempt", "verified_legitimate", "unknown", "conflicting" + ] + provenance: tuple[str, ...] # submission content hashes + reviewers: int = Field(ge=0) + + +class Outcome(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + later_loss: bool | None # never an input; for outcome analyses only + + +class Prediction(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + model: str + score: float + + +class BenchmarkExample(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + contract: Literal["benchmark-example/1"] = "benchmark-example/1" + task: Literal["poisoning-attempt/1"] = "poisoning-attempt/1" + event_id: str + group_id: str + split: Split | None = None + observation: Observation + generation: Generation + features: Features | None = None + source_label: SourceLabel + human_label: HumanLabel | None = None + outcome: Outcome | None = None + prediction: Prediction | None = None + weight: float = Field(default=1.0, gt=0) # inverse inclusion probability + + @model_validator(mode="after") + def _consistent(self) -> BenchmarkExample: + if self.split is not None and not self.generation.eligible: + raise ValueError("an ineligible candidate cannot be assigned to a split") + return self + + @property + def truth(self) -> int | None: + return TRUTH.get(self.human_label.tier) if self.human_label else None + + +class MetricRefused(ValueError): + """The labels or population cannot support the requested metric.""" + + +def label_accounting(examples: Sequence[BenchmarkExample]) -> dict[str, int]: + c: Counter[str] = Counter() + for e in examples: + c[e.human_label.tier if e.human_label else f"no_review:{e.source_label.status}"] += 1 + return dict(sorted(c.items())) + + +def _auc(pos: Sequence[float], neg: Sequence[float]) -> float: + """Mann-Whitney AUC with ties counted as one half.""" + wins = sum((p > n) + 0.5 * (p == n) for p in pos for n in neg) + return wins / (len(pos) * len(neg)) + + +def _average_precision(scores: Sequence[tuple[float, int, float]]) -> float: + """Weighted AP: the step-wise precision at each positive, ties broken pessimistically.""" + ranked = sorted(scores, key=lambda s: (-s[0], s[1])) + tp = fp = ap = 0.0 + total_pos = sum(w for _, y, w in ranked if y == 1) + for _, y, w in ranked: + if y == 1: + tp += w + ap += w * tp / (tp + fp) + else: + fp += w + return ap / total_pos + + +def evaluate( + examples: Sequence[BenchmarkExample], + *, + threshold: float, + fpr_budget: float | None = None, + review_capacity: int | None = None, + split: Split = "test", +) -> dict[str, Any]: + """Metrics on the reviewed, eligible, predicted examples of one split. Raises + ``MetricRefused`` when the population cannot support them.""" + scope = [e for e in examples if e.split == split] + if not scope: + raise MetricRefused(f"no examples assigned to the {split} split") + usable = [e for e in scope if e.truth is not None and e.prediction is not None] + excluded = { + "unreviewed_or_unverified": sum(1 for e in scope if e.truth is None), + "no_prediction": sum(1 for e in scope if e.truth is not None and e.prediction is None), + } + pos = [e for e in usable if e.truth == 1] + neg = [e for e in usable if e.truth == 0] + if not neg: + raise MetricRefused( + "no verified_legitimate examples: precision, FPR and AUC are undefined; weak, " + "unknown and unlabeled examples are never negatives" + ) + if not pos: + raise MetricRefused("no verified_attempt examples: recall and AP are undefined") + + def w(es: Sequence[BenchmarkExample]) -> float: + return sum(e.weight for e in es) + + def score(e: BenchmarkExample) -> float: + assert e.prediction is not None + return e.prediction.score + + tp = w([e for e in pos if score(e) >= threshold]) + fp = w([e for e in neg if score(e) >= threshold]) + out: dict[str, Any] = { + "split": split, + "population": "reviewed candidates in this split; not natural prevalence unless the " + "sample was drawn to represent it", + "labels": label_accounting(scope), + "excluded": excluded, + "positives": len(pos), + "negatives": len(neg), + "weighted": any(e.weight != 1.0 for e in usable), + "threshold": threshold, + "precision": tp / (tp + fp) if tp + fp else None, + "recall": tp / w(pos), + "fpr": fp / w(neg), + "average_precision": _average_precision( + [(score(e), e.truth or 0, e.weight) for e in usable] + ), + "roc_auc": _auc([score(e) for e in pos], [score(e) for e in neg]) + if len(pos) * len(neg) <= 4_000_000 + else None, + } + if fpr_budget is not None: + cuts = sorted({score(e) for e in usable}, reverse=True) + best = 0.0 + for t in cuts: + if w([e for e in neg if score(e) >= t]) / w(neg) <= fpr_budget: + best = max(best, w([e for e in pos if score(e) >= t]) / w(pos)) + out["recall_at_fpr_budget"] = {"budget": fpr_budget, "recall": best} + if review_capacity is not None: + top = sorted(usable, key=lambda e: -score(e))[:review_capacity] + out["precision_at_capacity"] = { + "capacity": review_capacity, + "precision": sum(1 for e in top if e.truth == 1) / len(top) if top else None, + } + return out + + +def candidate_recall( + known_event_ids: Sequence[str], generated_ids: Sequence[str] +) -> dict[str, Any]: + """Share of known attempts the generator emitted at all, reported apart from classifier + metrics. A model cannot score what the generator never produced.""" + known = set(known_event_ids) + if not known: + raise MetricRefused("no known attempts: candidate recall is undefined") + hit = known & set(generated_ids) + return {"known": len(known), "generated": len(hit), "recall": len(hit) / len(known)} + + +def alerts_per_1000_wallet_days( + alerts: int, wallet_days: float, *, reviewed: bool, representative: bool +) -> dict[str, Any]: + if wallet_days <= 0: + raise MetricRefused("no observed wallet-days") + kind = "confirmed false alerts" if reviewed else "unlabeled candidate volume (not false alerts)" + return { + "per_1000_wallet_days": 1000 * alerts / wallet_days, + "measure": kind, + "generalizes": representative, + "note": None if representative else "convenience sample: not an Ethereum-wide rate", + } + + +def precision_under_prevalence(tpr: float, fpr: float, prevalence: float) -> dict[str, Any]: + """HYPOTHETICAL scenario, not an observed measurement.""" + for name, v in (("tpr", tpr), ("fpr", fpr), ("prevalence", prevalence)): + if not 0 <= v <= 1 or math.isnan(v): + raise MetricRefused(f"{name} must be in [0, 1]") + denom = tpr * prevalence + fpr * (1 - prevalence) + return { + "scenario": "hypothetical", + "tpr": tpr, + "fpr": fpr, + "prevalence": prevalence, + "precision": tpr * prevalence / denom if denom else None, + } + + +def split_report(examples: Sequence[BenchmarkExample], events: Mapping[str, Any]) -> dict[str, Any]: + """Rows, labels, groups and entity overlap per split. ``events`` maps event id to its + ``PoisoningEvent`` (for the typed-entity overlap check).""" + from cryptoguard.ml.grouping import overlapping + + by_split: dict[str, list[BenchmarkExample]] = {} + for e in examples: + by_split.setdefault(e.split or "unassigned", []).append(e) + report: dict[str, Any] = {} + for s, es in sorted(by_split.items()): + blocks = [e.observation.block for e in es] + report[s] = { + "rows": len(es), + "labels": label_accounting(es), + "groups": len({e.group_id for e in es}), + "wallets": len({e.observation.wallet for e in es}), + "blocks": [min(blocks), max(blocks)], + } + names = [s for s in ("train", "validation", "test") if s in by_split] + leaks = {} + for i, a in enumerate(names): + for b in names[i + 1 :]: + shared_groups = {e.group_id for e in by_split[a]} & {e.group_id for e in by_split[b]} + shared_entities = overlapping( + [events[e.event_id] for e in by_split[a]], [events[e.event_id] for e in by_split[b]] + ) + leaks[f"{a}/{b}"] = {"groups": len(shared_groups), "entities": len(shared_entities)} + report["overlap"] = leaks + report["valid"] = bool(names) and all(v == {"groups": 0, "entities": 0} for v in leaks.values()) + return report diff --git a/src/cryptoguard/ml/grouping.py b/src/cryptoguard/ml/grouping.py new file mode 100644 index 0000000..2acf206 --- /dev/null +++ b/src/cryptoguard/ml/grouping.py @@ -0,0 +1,129 @@ +"""Typed entity relationships for campaign isolation (Phase 11.5). + +Every relationship between two events has a type. Only some types are evidence of one +campaign. + +Isolating (they link events into one group): +- ``shared_planting_tx``: one transaction plants every victim it touches; +- ``shared_lookalike``: the lookalike is the attacker's address; +- ``shared_planting_signer``: unless the signer is public infrastructure (a relayer or + router signs for everyone); +- ``shared_victim``: one wallet's events must not straddle a split; +- ``shared_imitated``: unless public infrastructure (an exchange hot wallet is imitated by + unrelated attackers); +- ``shared_counterfeit_token``: a counterfeit token contract is attack infrastructure, + whatever its degree; +- ``shared_verified_infra``: caller-supplied, independently verified attack addresses. + +Not isolating: +- ``shared_token_contract``: USDT, USDC, DAI; everyone uses them; +- ``shared_recipient``: an ordinary or public counterparty says nothing about an attacker. + +High degree alone never exempts an address. Exemption needs membership of the reviewed +public-infrastructure list (``dataset.PUBLIC_INFRASTRUCTURE``) or the trusted-token list. +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field + +from cryptoguard.ml.dataset import PUBLIC_INFRASTRUCTURE +from cryptoguard.ml.events import PoisoningEvent, _UnionFind +from cryptoguard.ml.payments import TRUSTED_TOKENS + +GROUPING_VERSION = "typed-groups/1" +ISOLATING = frozenset( + { + "shared_planting_tx", + "shared_lookalike", + "shared_planting_signer", + "shared_victim", + "shared_imitated", + "shared_counterfeit_token", + "shared_verified_infra", + } +) +NON_ISOLATING = frozenset({"shared_token_contract", "shared_recipient"}) + + +@dataclass(frozen=True) +class GroupingPolicy: + public: frozenset[str] = field(default_factory=lambda: frozenset(PUBLIC_INFRASTRUCTURE)) + trusted_tokens: frozenset[str] = field(default_factory=lambda: frozenset(TRUSTED_TOKENS)) + verified_infra: frozenset[str] = frozenset() # independently verified attack addresses + # Edge types not used for this grouping (e.g. ``shared_victim`` when sampling within one + # wallet's candidates, where the wallet is already its own stratum). + exclude: frozenset[str] = frozenset() + + +def _lower(v: str | None) -> str | None: + return v.lower() if v else None + + +def edge_keys(e: PoisoningEvent, policy: GroupingPolicy) -> list[tuple[str, str]]: + """``(edge type, entity)`` pairs of one event, isolating or not.""" + public = {a.lower() for a in policy.public} + verified = {v.lower() for v in policy.verified_infra} + trusted_tokens = {t.lower() for t in policy.trusted_tokens} + keys: list[tuple[str, str]] = [ + ("shared_planting_tx", e.planting_tx_id), + ("shared_lookalike", e.lookalike.lower()), + ("shared_victim", e.victim.lower()), + ] + signer = _lower(e.tx_signer) + if signer and signer != e.victim.lower(): + keys.append(("shared_recipient" if signer in public else "shared_planting_signer", signer)) + imitated = _lower(e.imitated) + if imitated: + keys.append(("shared_recipient" if imitated in public else "shared_imitated", imitated)) + token = _lower(e.log_contract) + if token: + trusted = token in trusted_tokens or token in public + keys.append(("shared_token_contract" if trusted else "shared_counterfeit_token", token)) + for addr in (signer, e.lookalike.lower(), token): + if addr and addr in verified: + keys.append(("shared_verified_infra", addr)) + return keys + + +@dataclass(frozen=True) +class Grouping: + group: dict[str, str] # victim_event_id -> group id + edges_used: dict[str, int] # isolating edge type -> events carrying it + edges_ignored: dict[str, int] # non-isolating edge type -> events carrying it + linking: dict[str, int] # isolating edge type -> entities shared by 2+ events + + +def typed_groups( + events: Sequence[PoisoningEvent], policy: GroupingPolicy | None = None +) -> Grouping: + policy = policy or GroupingPolicy() + uf = _UnionFind() + used: Counter[str] = Counter() + ignored: Counter[str] = Counter() + members: dict[tuple[str, str], set[str]] = defaultdict(set) + for e in events: + node = "e:" + e.victim_event_id + uf.find(node) + for kind, key in edge_keys(e, policy): + if kind in ISOLATING and kind not in policy.exclude: + used[kind] += 1 + members[(kind, key)].add(e.victim_event_id) + uf.union(node, f"{kind}:{key}") + else: + ignored[kind] += 1 + roots = {e.victim_event_id: uf.find("e:" + e.victim_event_id) for e in events} + names = {r: f"t{i:05d}" for i, r in enumerate(sorted(set(roots.values())))} + linking: Counter[str] = Counter(k for (k, _), ids in members.items() if len(ids) > 1) + return Grouping( + {e: names[r] for e, r in roots.items()}, dict(used), dict(ignored), dict(linking) + ) + + +def overlapping(a: Iterable[PoisoningEvent], b: Iterable[PoisoningEvent]) -> set[str]: + """Isolating entities shared between two event sets (for split-leakage checks).""" + policy = GroupingPolicy() + left = {k for e in a for k in edge_keys(e, policy) if k[0] in ISOLATING} + return {f"{k}:{v}" for k, v in left & {k for e in b for k in edge_keys(e, policy)}} diff --git a/src/cryptoguard/ml/hard_negative_archive.py b/src/cryptoguard/ml/hard_negative_archive.py new file mode 100644 index 0000000..bee037e --- /dev/null +++ b/src/cryptoguard/ml/hard_negative_archive.py @@ -0,0 +1,144 @@ +"""Offline extraction of hard-negative *candidates* from the local Tsuchiya attempt archive +(Phase 11.5, 0 RPC requests). Nothing here assigns a label. + +The archive's ``uncategorized`` rows are transfers between an address and a lookalike of +one of its counterparties that the source placed in none of its poisoning categories: +not zero-value, not tiny, not counterfeit. In the local subset they are genuine-token, +ordinary-value transfers to the wallet. They are the closest available frame to +"legitimate activity that looks like poisoning", and also possibly value-bearing +poisoning, so they stay ``unlabeled_candidate``. + +Two streaming passes; neither decompresses to disk or executes SQL: + +1. ``extract_uncategorized`` keeps every uncategorized row (bounded at ``MAX_ROWS``). +2. ``context_scan`` reruns the verified scanner with the candidates' lookalikes and + transactions as targets. This finds every archive row in which those addresses or + transactions also appear, including as source-labelled poisoning lookalikes, for + the contamination screen. +""" + +from __future__ import annotations + +import json +import time +from collections import Counter +from pathlib import Path +from typing import Any + +from cryptoguard.ml.annotation import atomic_write +from cryptoguard.ml.fetch import TSUCHIYA_FILES, verify_local +from cryptoguard.ml.tsuchiya_archive import ( + PARSER_VERSION, + UNCATEGORIZED, + ArchiveReader, + ArchiveTransfer, + build_targets, + load_targets, + peak_rss_bytes, + scan, +) + +EXTRACT_VERSION = "hn-archive-extract/1" +ARCHIVE = "address_poisoning_ethereum.sql.gz" +MAX_ROWS = 50_000 # the publisher reports 8,651; anything far above means a parser fault +ROWS = "uncategorized_rows.jsonl" +SUMMARY = "extract_summary.json" +CONTEXT_DB = "context_subset.sqlite" +CONTEXT_TARGETS = "context_targets.json" +FIELDS = ( + "line", + "block", + "tx", + "token", + "sender", + "receiver", + "sender_is_victim", + "value", + "value_usd", + "flags", + "intended", + "first_digits", + "last_digits", +) + + +class ExtractError(RuntimeError): + pass + + +def row_dict(t: ArchiveTransfer) -> dict[str, Any]: + return {k: getattr(t, k) for k in FIELDS} + + +def extract_uncategorized(data_dir: Path, out_dir: Path, *, progress: Any = None) -> dict[str, Any]: + """Pass 1: every row flagged uncategorized, written atomically with a summary.""" + archive = data_dir / "tsuchiya2025" / ARCHIVE + if not archive.exists(): + raise FileNotFoundError(f"{archive} is missing; it is never downloaded automatically") + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + t0 = time.perf_counter() + reader = ArchiveReader(archive) + rows: list[dict[str, Any]] = [] + flags: Counter[int] = Counter() + for i, t in enumerate(reader, start=1): + if t.flags & UNCATEGORIZED: + flags[t.flags] += 1 + rows.append(row_dict(t)) + if len(rows) > MAX_ROWS: + raise ExtractError(f"more than {MAX_ROWS} uncategorized rows: parser fault?") + if progress is not None and i % 1_000_000 == 0: + progress(i, len(rows)) + out_dir.mkdir(parents=True, exist_ok=True) + data = b"".join(json.dumps(r, sort_keys=True).encode() + b"\n" for r in rows) + atomic_write(out_dir / ROWS, data) + import hashlib + + summary = { + "version": EXTRACT_VERSION, + "parser_version": PARSER_VERSION, + "source_sha256": source["sha256"], + "rows_scanned": reader.stats.valid_rows, + "malformed": reader.stats.data_rows - reader.stats.valid_rows, + "uncategorized_rows": len(rows), + "flag_combinations": {str(k): v for k, v in sorted(flags.items())}, + "rows_sha256": hashlib.sha256(data).hexdigest(), + "runtime_seconds": round(time.perf_counter() - t0, 1), + "peak_rss_bytes": peak_rss_bytes(), + "rpc_requests": 0, + } + atomic_write(out_dir / SUMMARY, json.dumps(summary, indent=1).encode() + b"\n") + return summary + + +def load_rows(out_dir: Path) -> list[dict[str, Any]]: + import hashlib + + summary = json.loads((out_dir / SUMMARY).read_text(encoding="utf-8")) + data = (out_dir / ROWS).read_bytes() + if hashlib.sha256(data).hexdigest() != summary["rows_sha256"]: + raise ExtractError(f"{out_dir / ROWS}: content differs from its summary; re-extract") + return [json.loads(line) for line in data.splitlines() if line] + + +def context_scan(data_dir: Path, out_dir: Path, *, progress: Any = None) -> dict[str, Any]: + """Pass 2: every archive row touching a candidate's lookalike or transaction.""" + rows = load_rows(out_dir) + manifest = build_targets( + { + "hn_lookalikes": { + r["sender"] if not r["sender_is_victim"] else r["receiver"] for r in rows + }, + "hn_txs": {r["tx"] for r in rows}, + } + ) + atomic_write(out_dir / CONTEXT_TARGETS, json.dumps(manifest).encode()) + archive = data_dir / "tsuchiya2025" / ARCHIVE + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + return scan( + archive, + load_targets(out_dir / CONTEXT_TARGETS), + out_dir / CONTEXT_DB, + work_dir=out_dir / "spill", + source_sha256=source["sha256"], + progress=progress, + ) diff --git a/src/cryptoguard/ml/hard_negatives.py b/src/cryptoguard/ml/hard_negatives.py new file mode 100644 index 0000000..3fd3081 --- /dev/null +++ b/src/cryptoguard/ml/hard_negatives.py @@ -0,0 +1,451 @@ +"""Hard-negative candidate pool, contamination screen, matching design and review cohort +(Phase 11.5, offline, 0 RPC requests). + +**Every candidate is ``unlabeled_candidate``.** A low score, absence from a threat list or +the absence of a later loss is not a benign label. Categories describe structure, never +intent: + +| Category | Structural meaning | +|---|---| +| A_similarity_ordinary_value | lookalike of a prior counterparty, genuine token, above dust | +| B_first_time_counterparty | the counterparty never appears earlier in the observed window | +| C_low_value | dust-range or at most 1 USD | +| D_token_ambiguity | zero-value genuine token, or a token outside the reviewed list | +| E_contract_mediated | moved out of the wallet by a transaction it did not sign | +| F_shared_infrastructure | signed by an address on the reviewed public-infrastructure list | +| G_incomplete_observation | partial or no wallet history, or an unknown receipt status | +| H_near_threshold | similarity within one character of the rule's threshold | + +**Frames.** +- ``fixture_background:`` and ``fixture_incident:``: generator outputs on the + recorded replay windows. These are public chain data, recorded once. +- ``archive_uncategorized``: the source's uncategorized lookalike transfers (CC BY-NC-ND; + local only). +""" + +from __future__ import annotations + +import json +import sqlite3 +from collections import Counter +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +from cryptoguard.ml import candidates as cg +from cryptoguard.ml.cohort import CohortDesign, FrameItem +from cryptoguard.ml.contamination import Coverage, KnownAttack, KnownIndex, Screened, screen +from cryptoguard.ml.dataset import PUBLIC_INFRASTRUCTURE +from cryptoguard.ml.events import PoisoningEvent +from cryptoguard.ml.grouping import GroupingPolicy, typed_groups +from cryptoguard.ml.payments import TRUSTED_TOKENS + +HN_VERSION = "hard-negatives/1" +COHORT_VERSION = "hard-negative-candidates/1" +COHORT_SEED = "cryptoguard-hard-negative-candidates/1" # fixed before the only draw +Frame = Literal["fixture_background", "fixture_incident", "archive_uncategorized"] +LabelStatus = Literal["unlabeled_candidate"] +ARCHIVE_RANGE = (15_053_226, 20_208_032) # blocks in the Tsuchiya archive (Phase 11.3 scan) +NEAR = 1 # characters above the rule's threshold that count as "near" + + +@dataclass(frozen=True) +class HNCandidate: + event: PoisoningEvent + frame: str # Frame, optionally ":" + methods: tuple[str, ...] + categories: tuple[str, ...] + token_trusted: bool + value_base_units: float | None + value_usd: float | None + similarity: tuple[int, int] | None # (prefix, suffix) matched characters + coverage: str + first_time_counterparty: bool | None + receipt_known: bool | None + context: tuple[Mapping[str, Any], ...] = () # pre-cutoff observations for reviewers + label_status: LabelStatus = "unlabeled_candidate" + screened: Screened | None = field(default=None, compare=False) + + @property + def year(self) -> int: + from cryptoguard.ml.review_sample import year + + return year(self.event.planting_block) + + +def categories( + *, + similarity: tuple[int, int] | None, + threshold: int, + token_trusted: bool, + value_usd: float | None, + methods: Sequence[str], + signer: str | None, + token: str, + coverage: str, + first_time: bool | None, + receipt_known: bool | None, + value_base_units: float | None, +) -> tuple[str, ...]: + public = {a.lower() for a in PUBLIC_INFRASTRUCTURE} + dustish = "dust_in" in methods or (value_usd is not None and 0 < value_usd <= 1) + zero = value_base_units == 0 or "zero_value_in" in methods + out = [] + if similarity and token_trusted and not dustish and not zero: + out.append("A_similarity_ordinary_value") + if first_time: + out.append("B_first_time_counterparty") + if dustish: + out.append("C_low_value") + if (zero and token_trusted) or not token_trusted: + out.append("D_token_ambiguity") + if "spoofed_out" in methods: + out.append("E_contract_mediated") + if signer and signer.lower() in public: # common tokens alone are not infrastructure + out.append("F_shared_infrastructure") + if coverage != "complete" or receipt_known is False: + out.append("G_incomplete_observation") + if similarity and sum(similarity) <= threshold + NEAR: + out.append("H_near_threshold") + return tuple(out) + + +# --- frame 1: generator outputs on recorded wallet windows --------------------------------- + + +def fixture_candidates() -> list[HNCandidate]: + from cryptoguard.ml.history import events_from_fixture + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + + fixtures: list[tuple[str, Any]] = [ + (f"fixture_incident:{c.manifest.case_id}", c.fixture) for c in load_cases() if c.fixture + ] + [ + (f"fixture_background:{b.manifest.case_id}", b.fixture) + for b in load_background() + if b.fixture + ] + out: list[HNCandidate] = [] + for frame, fx in fixtures: + events, _ = events_from_fixture(fx) + events.sort(key=lambda e: e.position) + for c in cg.generate(fx): + e = c.event + pos = (e.planting_block, e.planting_tx_index or 0, e.planting_log_index or 0) + earlier = [x for x in events if x.position < pos] + first = all(x.counterparty.lower() != e.lookalike for x in earlier) + trusted = e.log_contract in TRUSTED_TOKENS + out.append( + HNCandidate( + event=e, + frame=frame, + methods=c.methods, + categories=categories( + similarity=c.best_match, + threshold=cg.MIN_AFFIX, + token_trusted=trusted, + value_usd=None, + methods=c.methods, + signer=e.tx_signer, + token=e.log_contract or "", + coverage=e.coverage, + first_time=first, + receipt_known=True, # a recorded Transfer log implies success + value_base_units=float(c.value), + ), + token_trusted=trusted, + value_base_units=float(c.value), + value_usd=None, + similarity=c.best_match, + coverage=e.coverage, + first_time_counterparty=first, + receipt_known=True, + context=tuple( + { + "block": x.block, + "direction": x.direction, + "counterparty": x.counterparty.lower(), + "value": str(x.value), + } + for x in earlier[-25:] + ), + ) + ) + return out + + +# --- frame 2: the archive's uncategorized lookalike transfers ------------------------------- + + +def archive_candidates(rows: Iterable[Mapping[str, Any]]) -> list[HNCandidate]: + out: list[HNCandidate] = [] + for r in rows: + victim, look = ( + (r["sender"], r["receiver"]) if r["sender_is_victim"] else (r["receiver"], r["sender"]) + ) + token = r["token"].lower() + trusted = token in TRUSTED_TOKENS + sim = ( + (r["first_digits"], r["last_digits"]) + if r["first_digits"] is not None and r["last_digits"] is not None + else None + ) + e = PoisoningEvent( + chain_id=1, + victim=victim, + lookalike=look, + imitated=r["intended"], + planting_tx=r["tx"], + planting_block=r["block"], + planting_tx_index=None, + planting_log_index=r["line"], # the archive has no log index: its line number + observation_timestamp=None, + subtype="other", + tx_signer=None, + log_contract=token, + token_contract=token if trusted else None, + candidate_method="tsuchiya-archive:uncategorized", + coverage="unavailable", + ) + usd = r["value_usd"] + out.append( + HNCandidate( + event=e, + frame="archive_uncategorized", + methods=("source_uncategorized",), + categories=categories( + similarity=sim, + threshold=7, # the source's 3+4 rule + token_trusted=trusted, + value_usd=usd, + methods=(), + signer=None, + token=token, + coverage="unavailable", + first_time=None, + receipt_known=True, # the archive is built from emitted logs + value_base_units=r["value"], + ), + token_trusted=trusted, + value_base_units=r["value"], + value_usd=usd, + similarity=sim, + coverage="unavailable", + first_time_counterparty=None, + receipt_known=True, + ) + ) + return out + + +# --- known positives ------------------------------------------------------------------------ + + +def known_index(data_dir: Path, poisoning_dir: Path) -> tuple[KnownIndex, dict[str, int]]: + """Every locally known poisoning record. Archive rows are streamed from SQLite. + + Screening *coverage* (a range in which absence of a match means something) comes only + from the Tsuchiya archive, the one chain-wide detector here. Poison-Hunter is a sample, + and the incidents are single cases: they can confirm an overlap but never vouch for its + absence.""" + from cryptoguard.ml.poison_hunter import parse_sample + from cryptoguard.ml.tsuchiya import parse_payoffs + from cryptoguard.ml.tsuchiya_archive import COUNTERFEIT, PAYOFF_UNCONFIRMED, POISONING + from cryptoguard.replay.models import load_cases + + ix = KnownIndex() + added: Counter[str] = Counter() + + def add(k: KnownAttack) -> None: + ix.add(k) + added[k.source] += 1 + + for db in ( + poisoning_dir / "archive_subset.sqlite", + poisoning_dir / "hard_negative" / "context_subset.sqlite", + ): + if not db.exists(): + continue + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + query = ( + "select sender, receiver, sender_is_victim, tx, intended, token, flags " + "from transfers where flags & ?" + ) + for s, r, sv, tx, intended, token, flags in con.execute( + query, (POISONING | PAYOFF_UNCONFIRMED,) + ): + victim, look = (s, r) if sv else (r, s) + src = "tsuchiya-archive" if flags & POISONING else "tsuchiya-archive-unconfirmed-payoff" + add( + KnownAttack(src, victim, look, tx, intended, token if flags & COUNTERFEIT else None) + ) + con.close() + ix.coverage.append(Coverage("tsuchiya-archive", *ARCHIVE_RANGE)) + payoffs = parse_payoffs(data_dir / "tsuchiya2025" / "payoff_transfers_ethereum.csv").valid + for p in payoffs: + add(KnownAttack("tsuchiya-payoff", p.payer, p.lookalike, p.tx_hash)) + ph = parse_sample(data_dir / "poison-hunter" / "phishing_transfers_sample.csv").valid + for r in ph: + add(KnownAttack("poison-hunter", r.victim, r.lookalike, r.planting_tx, r.imitated)) + for case in load_cases(): + m = case.manifest + add( + KnownAttack( + "incident", + m.victim, + m.harm.recipient, + m.harm.transaction_hash, + m.intended_recipient, + ) + ) + return ix, dict(added) + + +def screen_all(cands: Sequence[HNCandidate], ix: KnownIndex) -> list[HNCandidate]: + from dataclasses import replace + + return [ + replace( + c, + screened=screen( + victim=c.event.victim, + lookalike=c.event.lookalike, + tx=c.event.planting_tx, + block=c.event.planting_block, + imitated=c.event.imitated, + token=None if c.token_trusted else c.event.log_contract, + index=ix, + ), + ) + for c in cands + ] + + +# --- matching covariates -------------------------------------------------------------------- + + +def value_bin(usd: float | None) -> str: + if usd is None: + return "missing" + if usd == 0: + return "zero" + return "<=1" if usd <= 1 else "<=100" if usd <= 100 else ">100" + + +def similarity_bin(sim: tuple[int, int] | None) -> str: + if sim is None: + return "missing" + total = sum(sim) + return "7" if total <= 7 else "8-9" if total <= 9 else "10+" + + +# --- cohort --------------------------------------------------------------------------------- + + +def cohort_items(cands: Sequence[HNCandidate]) -> tuple[list[FrameItem], dict[str, int]]: + """Eligible frame: every screened candidate except known-positive overlaps. Potential + overlaps stay eligible, in their own stratum, so they are not silently dropped.""" + eligible = [c for c in cands if c.screened and c.screened.status != "known_positive_overlap"] + excluded = Counter(c.frame.split(":")[0] for c in cands if c not in eligible) + items: list[FrameItem] = [] + for frame in sorted({c.frame for c in eligible}): + members = [c for c in eligible if c.frame == frame] + policy = GroupingPolicy( + exclude=frozenset({"shared_victim"}) if frame.startswith("fixture") else frozenset() + ) + grouping = typed_groups([c.event for c in members], policy) + for c in members: + flag = ( + "yes" if c.screened and c.screened.status == "potential_positive_overlap" else "no" + ) + items.append( + FrameItem( + event_id=c.event.victim_event_id, + stratum=f"{frame}|{c.year}|{flag}", + group=f"{frame}/{grouping.group[c.event.victim_event_id]}", + sheet={ + "chain_id": 1, + "wallet": c.event.victim, + "address_under_review": c.event.lookalike, + "transaction": c.event.planting_tx, + "block": c.event.planting_block, + "coverage_note": _coverage_note(c), + "context": [dict(x) for x in c.context], + }, + key=key_record(c), + ) + ) + return items, dict(excluded) + + +def _coverage_note(c: HNCandidate) -> str: + if c.coverage == "complete": + return ( + "The wallet's transfers in the recorded window are complete; earlier history was " + "not recorded." + ) + if c.coverage == "partial": + return "The recorded window is incomplete: some transfers may be missing." + return "No wallet history is included: use a block explorer, up to the block above." + + +def key_record(c: HNCandidate) -> dict[str, Any]: + return { + "event_id": c.event.victim_event_id, + "frame": c.frame, + "methods": list(c.methods), + "categories": list(c.categories), + "token": c.event.log_contract, + "token_trusted": c.token_trusted, + "value_usd": c.value_usd, + "similarity": list(c.similarity) if c.similarity else None, + "imitated": c.event.imitated, + "screen_level": c.screened.level if c.screened else None, + "screen_status": c.screened.status if c.screened else None, + "screen_sources": list(c.screened.sources) if c.screened else [], + "label_status": c.label_status, + } + + +def cohort_design(items: Sequence[FrameItem]) -> CohortDesign: + """Quotas fixed before the draw: 24 from the archive frame, 2 per recorded wallet.""" + quota: dict[str, int] = {"archive_uncategorized": 24} + for frame in {i.stratum.split("|")[0] for i in items if i.stratum.startswith("fixture")}: + quota[frame] = 2 + return CohortDesign( + version=COHORT_VERSION, + seed=COHORT_SEED, + quota=quota, + strata_names=("frame", "year", "potential_positive_overlap"), + notes="Known-positive overlaps excluded; potential overlaps kept as their own stratum. " + "Recorded-wallet frames are one stratum per wallet; the archive frame takes one item " + "per typed campaign group.", + ) + + +def pool_summary(cands: Sequence[HNCandidate]) -> dict[str, Any]: + by_frame: dict[str, Any] = {} + for frame in sorted({c.frame.split(":")[0] for c in cands}): + cs = [c for c in cands if c.frame.split(":")[0] == frame] + by_frame[frame] = { + "candidates": len(cs), + "wallets": len({c.event.victim for c in cs}), + "blocks": [ + min(c.event.planting_block for c in cs), + max(c.event.planting_block for c in cs), + ], + "categories": dict(sorted(Counter(k for c in cs for k in c.categories).items())), + "methods": dict(sorted(Counter(m for c in cs for m in c.methods).items())), + "screen_level": dict(Counter(c.screened.level for c in cs if c.screened)), + "screen_status": dict(Counter(c.screened.status for c in cs if c.screened)), + "token_trusted": sum(c.token_trusted for c in cs), + "value_usd_bins": dict(Counter(value_bin(c.value_usd) for c in cs)), + "similarity_bins": dict(Counter(similarity_bin(c.similarity) for c in cs)), + "duplicate_event_ids": len(cs) - len({c.event.victim_event_id for c in cs}), + } + return {"version": HN_VERSION, "label_status": "unlabeled_candidate", "frames": by_frame} + + +def dump(obj: Any) -> str: + return json.dumps(obj, indent=1, sort_keys=True, default=str) diff --git a/src/cryptoguard/ml/hn_study.py b/src/cryptoguard/ml/hn_study.py new file mode 100644 index 0000000..03e8229 --- /dev/null +++ b/src/cryptoguard/ml/hn_study.py @@ -0,0 +1,531 @@ +"""Phase 11.5 hard-negative study: one reproducible offline run (``cryptoguard ml +hard-negative-study``), 0 RPC requests. + +The run: +1. builds the candidate pool from the recorded wallet windows and the archive's + uncategorized rows; +2. screens every candidate against all local known-positive records; +3. matches the archive candidates to the payoff-linked source positives (excluding the + 60 reserved review items) and reports balance; +4. measures how easily the two frames are told apart (source separability, not fraud + detection); +5. freezes the review cohort, once; +6. writes aggregate JSON and a Markdown table file. + +Nothing it writes assigns a label. +""" + +from __future__ import annotations + +import json +import math +import sqlite3 +import time +from collections import Counter +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +from cryptoguard.ml import hard_negatives as hn +from cryptoguard.ml.annotation import atomic_write +from cryptoguard.ml.matching import Unit, cem +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.ml.tsuchiya_archive import POISONING, peak_rss_bytes + +STUDY_VERSION = "hn-study/1" + + +def positive_units(poisoning_dir: Path) -> list[dict[str, Any]]: + """Covariates of the payoff-linked source positives, from the archive row of each + packet's planting. The 60 items reserved for the human-review study are excluded.""" + import hashlib + + from cryptoguard.ml.review_sample import read_sheet + + packets = [ + json.loads(line) + for line in (poisoning_dir / "review_packets_payoff_linked.jsonl") + .read_text(encoding="utf-8") + .splitlines() + ] + reserved = { + r["victim_event_id"] + for r in read_sheet(poisoning_dir / "review_sample" / "reviewer_sheet.jsonl") + } + con = sqlite3.connect(f"file:{poisoning_dir / 'archive_subset.sqlite'}?mode=ro", uri=True) + out = [] + for p in packets: + if p["victim_event_id"] in reserved: + continue + row = con.execute( + "select block, token, sender_is_victim, value_usd, first_digits, last_digits " + "from transfers where tx = ? and (sender = ? or receiver = ?) and flags & ? limit 1", + (p["planting_tx"], p["lookalike"], p["lookalike"], POISONING), + ).fetchone() + if row is None: + continue + block, token, sv, usd, fd, ld = row + out.append( + { + "id": "p:" + hashlib.sha256(p["victim_event_id"].encode()).hexdigest()[:16], + "block": block, + "token": token, + "victim_sends": bool(sv), + "value_usd": usd, + "similarity": (fd, ld) if fd is not None and ld is not None else None, + "subtype": p["subtype"], + } + ) + con.close() + return out + + +def _unit( + uid: str, + *, + block: int, + trusted: bool, + victim_sends: bool, + usd: float | None, + sim: tuple[int, int] | None, +) -> Unit: + from cryptoguard.ml.review_sample import year + + nan = usd is not None and math.isnan(usd) + usd = None if nan else usd + return Unit( + uid, + { + "year": year(block), + "victim_sends": victim_sends, + "token_trusted": trusted, + "value_bin": hn.value_bin(usd), + "similarity_bin": hn.similarity_bin(sim), + }, + { + "log10_value_usd": None if usd is None else math.log10(usd + 1e-6), + "similarity_total": None if sim is None else float(sum(sim)), + "token_trusted": float(trusted), + "victim_sends": float(victim_sends), + "block_millions": block / 1e6, + }, + ) + + +def univariate_auc(pos: Sequence[float], neg: Sequence[float]) -> float | None: + """How well one covariate alone separates the frames (0.5 = not at all).""" + if not pos or not neg: + return None + ranked = sorted([(v, 1) for v in pos] + [(v, 0) for v in neg]) + rank_sum, i = 0.0, 0 + while i < len(ranked): + j = i + while j < len(ranked) and ranked[j][0] == ranked[i][0]: + j += 1 + avg = (i + j + 1) / 2 + rank_sum += avg * sum(1 for k in range(i, j) if ranked[k][1] == 1) + i = j + auc = (rank_sum - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)) + return max(auc, 1 - auc) # separability, direction-free + + +def separability(pos: Sequence[Unit], neg: Sequence[Unit]) -> dict[str, Any]: + names = sorted({k for u in (*pos, *neg) for k in u.numeric}) + uni = {} + for k in names: + a = [v for u in pos if (v := u.numeric.get(k)) is not None] + b = [v for u in neg if (v := u.numeric.get(k)) is not None] + miss_a, miss_b = len(pos) - len(a), len(neg) - len(b) + uni[k] = { + "auc_separability": univariate_auc(a, b), + "missing_share_source_positive": round(miss_a / len(pos), 3) if pos else None, + "missing_share_candidate": round(miss_b / len(neg), 3) if neg else None, + } + out: dict[str, Any] = { + "task": "predict which frame a row came from (NOT fraud detection)", + "univariate": uni, + } + try: # optional: the ml extra + import numpy as np + from sklearn.linear_model import LogisticRegression + from sklearn.model_selection import StratifiedKFold, cross_val_score + except ImportError: + out["multivariate"] = "scikit-learn not installed (ml extra): skipped" + return out + families = { + "value_only": ["log10_value_usd"], + "similarity_only": ["similarity_total"], + "token_only": ["token_trusted"], + "direction_only": ["victim_sends"], + "time_only": ["block_millions"], + "all_without_value": [ + "similarity_total", + "token_trusted", + "victim_sends", + "block_millions", + ], + } + multi = {} + rows = [*pos, *neg] + y = np.array([1] * len(pos) + [0] * len(neg)) + for fam, cols in families.items(): + x = np.array( + [ + [u.numeric.get(c) if u.numeric.get(c) is not None else -99.0 for c in cols] + for u in rows + ], + dtype=float, + ) + miss = np.array([[float(u.numeric.get(c) is None) for c in cols] for u in rows]) + x = np.hstack([x, miss]) + cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0) + scores = cross_val_score(LogisticRegression(max_iter=1000), x, y, cv=cv, scoring="roc_auc") + multi[fam] = { + "cv_roc_auc_mean": round(float(scores.mean()), 4), + "cv_roc_auc_sd": round(float(scores.std()), 4), + } + out["multivariate"] = multi + out["multivariate_note"] = ( + "5-fold stratified CV, logistic regression with missingness indicators; rows are not " + "grouped by campaign, so these AUCs are optimistic; diagnostic only" + ) + return out + + +def run( + data_dir: Path, + poisoning_dir: Path, + out_dir: Path, + tables: Path | None, + *, + freeze_cohort: bool = True, +) -> dict[str, Any]: + from cryptoguard.ml import cohort as ch + from cryptoguard.ml.contamination import summary + from cryptoguard.ml.cross_dataset import git_state + from cryptoguard.ml.hard_negative_archive import load_rows + + t0 = time.perf_counter() + timings: dict[str, float] = {} + hn_dir = poisoning_dir / "hard_negative" + rows = load_rows(hn_dir) + extract = json.loads((hn_dir / "extract_summary.json").read_text(encoding="utf-8")) + t = time.perf_counter() + fixture = hn.fixture_candidates() + timings["fixture_candidates_s"] = round(time.perf_counter() - t, 2) + t = time.perf_counter() + archive = hn.archive_candidates(rows) + timings["archive_candidates_s"] = round(time.perf_counter() - t, 2) + t = time.perf_counter() + index, known_counts = hn.known_index(data_dir, poisoning_dir) + timings["known_index_s"] = round(time.perf_counter() - t, 2) + t = time.perf_counter() + pool = hn.screen_all([*fixture, *archive], index) + timings["screen_s"] = round(time.perf_counter() - t, 2) + screened = [c.screened for c in pool if c.screened] + + # Matching: archive candidates (screened, not known positive) vs source positives. + t = time.perf_counter() + positives = positive_units(poisoning_dir) + pos_units = [ + _unit( + p["id"], + block=p["block"], + trusted=p["token"] in TRUSTED_TOKENS, + victim_sends=p["victim_sends"], + usd=p["value_usd"], + sim=p["similarity"], + ) + for p in positives + ] + eligible_arc = [ + c + for c in pool + if c.frame == "archive_uncategorized" + and c.screened + and c.screened.status != "known_positive_overlap" + ] + cand_units = [ + _unit( + "c:" + c.event.victim_event_id, + block=c.event.planting_block, + trusted=c.token_trusted, + victim_sends=False, + usd=c.value_usd, + sim=c.similarity, + ) + for c in eligible_arc + ] + strict_keys = ["year", "victim_sends", "token_trusted", "value_bin", "similarity_bin"] + strict = cem(pos_units, cand_units, keys=strict_keys) + relaxed = cem(pos_units, cand_units, keys=["year", "similarity_bin"]) + timings["matching_s"] = round(time.perf_counter() - t, 2) + sep = separability(pos_units, cand_units) + + items, excluded = hn.cohort_items(pool) + design = hn.cohort_design(items) + cohort_dir = poisoning_dir / "hard_negative" / "cohort_v1" + if freeze_cohort: + manifest, written = ch.freeze(items, design, cohort_dir) + else: + manifest, written = ch.draw(items, design)["manifest"], False + + def drop_pairs(m: dict[str, Any]) -> dict[str, Any]: + return { + k: v + for k, v in m.items() + if k not in ("pairs", "unmatched_positives", "unmatched_candidates") + } | { + "unmatched_positive_count": len(m["unmatched_positives"]), + "unmatched_candidate_count": len(m["unmatched_candidates"]), + } + + bg = [c for c in pool if c.frame.startswith("fixture_background")] + from cryptoguard.replay.background import load_background + + windows = [b.fixture for b in load_background() if b.fixture] + wallet_days = sum(f.to_block - f.from_block for f in windows) / 7_200 + report = { + "study_version": STUDY_VERSION, + "git": git_state(), + "inputs": { + "archive_extract": { + k: extract[k] + for k in ( + "version", + "source_sha256", + "rows_scanned", + "uncategorized_rows", + "rows_sha256", + ) + }, + "known_positive_records": known_counts, + "screen_coverage": [c.__dict__ for c in index.coverage], + }, + "pool": hn.pool_summary(pool), + "contamination": summary(screened), + "contamination_by_frame": { + f: summary([c.screened for c in pool if c.frame.split(":")[0] == f and c.screened]) + for f in sorted({c.frame.split(":")[0] for c in pool}) + }, + "operational_background": { + "recorded_windows": len(windows), + "windows_with_candidates": len({c.frame for c in bg}), + "wallet_days": round(wallet_days, 1), + "candidates": len(bg), + "per_1000_wallet_days": round(1000 * len(bg) / wallet_days, 1) if wallet_days else None, + "note": "unlabeled candidate volume on randomly drawn recorded wallets; not false " + "alerts and not an Ethereum-wide rate", + }, + "matching": { + "positives_frame": "payoff-linked source positives minus the 60 reserved review items", + "positives": len(pos_units), + "candidates": len(cand_units), + "strict": drop_pairs(strict), + "relaxed_year_similarity": drop_pairs(relaxed), + }, + "separability": sep, + "cohort": { + "version": manifest["sample_version"], + "frame_sha256": manifest["queue_sha256"], + "selection_sha256": manifest["selection_sha256"], + "frame_items": manifest["queue_packets"], + "excluded_known_positive": excluded, + "groups": manifest["groups"], + "strata_table": manifest["strata_table"], + "selected": len(manifest["selected"]), + "files": manifest.get("files"), + "newly_frozen": written, + }, + "timings": timings | {"total_s": round(time.perf_counter() - t0, 1)}, + "peak_rss_bytes": peak_rss_bytes(), + "rpc_requests": 0, + } + out_dir.mkdir(parents=True, exist_ok=True) + atomic_write(out_dir / "hn-study.json", hn.dump(report).encode() + b"\n") + if tables is not None: + tables.write_text(render(report), encoding="utf-8", newline="\n") + return report + + +def _fmt(v: Any) -> str: + if v is None: + return "n/a" + if isinstance(v, float): + return f"{v:.3f}" + return str(v) + + +def render(r: dict[str, Any]) -> str: + """Aggregate-only tables (no address, transaction or event id).""" + lines = [ + "# Hard-negative study tables (generated)", + "", + f"Generated by `cryptoguard ml hard-negative-study` ({r['study_version']}) at commit " + f"`{(r['git'].get('commit') or '')[:7]}`" + f"{' (dirty tree)' if r['git'].get('dirty') else ''}. " + "0 RPC requests. Every candidate is `unlabeled_candidate`.", + "", + "## Candidate pool", + "", + "| Frame | Candidates | Wallets | Block range | Trusted token |", + "|---|---|---|---|---|", + ] + for f, v in r["pool"]["frames"].items(): + lines.append( + f"| {f} | {v['candidates']:,} | {v['wallets']:,} | {v['blocks'][0]:,}-" + f"{v['blocks'][1]:,} | {v['token_trusted']:,} |" + ) + lines += [ + "", + "### Structural categories (multi-label; not intent)", + "", + "| Frame | " + " | ".join("ABCDEFGH") + " |", + "|---|" + "---|" * 8, + ] + for f, v in r["pool"]["frames"].items(): + cats = v["categories"] + row = [str(sum(n for k, n in cats.items() if k.startswith(x + "_"))) for x in "ABCDEFGH"] + lines.append(f"| {f} | " + " | ".join(row) + " |") + lines += [ + "", + "## Contamination screen", + "", + "| Frame | " + + " | ".join( + ( + "exact_event", + "exact_tx", + "victim_lookalike", + "shared_infrastructure", + "related_campaign", + "weak_similarity", + "none", + ) + ) + + " |", + "|---|" + "---|" * 7, + ] + for f, s in r["contamination_by_frame"].items(): + lv = s["by_level"] + lines.append( + f"| {f} | " + + " | ".join( + str(lv.get(k, 0)) + for k in ( + "exact_event", + "exact_tx", + "victim_lookalike", + "shared_infrastructure", + "related_campaign", + "weak_similarity", + "none", + ) + ) + + " |" + ) + lines += [ + "", + "| Frame | known_positive_overlap | potential_positive_overlap | " + "no_known_overlap | insufficient_information |", + "|---|---|---|---|---|", + ] + for f, s in r["contamination_by_frame"].items(): + st = s["by_status"] + lines.append( + f"| {f} | " + + " | ".join( + str(st.get(k, 0)) + for k in ( + "known_positive_overlap", + "potential_positive_overlap", + "no_known_overlap", + "insufficient_information", + ) + ) + + " |" + ) + m = r["matching"] + lines += [ + "", + "## Matching (archive candidates vs source positives)", + "", + f"Positives: {m['positives']:,} ({m['positives_frame']}); candidates: {m['candidates']:,}.", + "", + "| Design | Keys | Matched positives | Matched candidates | Candidates without support |", + "|---|---|---|---|---|", + ] + for name in ("strict", "relaxed_year_similarity"): + d = m[name] + lines.append( + f"| {name} | {', '.join(d['keys'])} | {d['matched_positives']:,} | " + f"{d['matched_candidates']:,} | {d['candidates_without_support']:,} |" + ) + lines += [ + "", + "Standardized mean differences (before matching):", + "", + "| Covariate | SMD | Missing (positives) | Missing (candidates) |", + "|---|---|---|---|", + ] + for k, v in m["strict"]["balance_before"].items(): + if isinstance(v, dict): + lines.append( + f"| {k} | {_fmt(v['smd'])} | {v['missing_positive']} | {v['missing_candidate']} |" + ) + s = r["separability"] + lines += [ + "", + "## Source separability (which frame a row came from; NOT fraud detection)", + "", + "| Covariate | Univariate separability AUC |", + "|---|---|", + ] + for k, v in s["univariate"].items(): + lines.append(f"| {k} | {_fmt(v['auc_separability'])} |") + if isinstance(s.get("multivariate"), dict): + lines += ["", "| Feature family | CV ROC-AUC (mean ± sd) |", "|---|---|"] + for k, v in s["multivariate"].items(): + lines.append(f"| {k} | {v['cv_roc_auc_mean']:.3f} ± {v['cv_roc_auc_sd']:.3f} |") + lines += ["", s["multivariate_note"] + "."] + c = r["cohort"] + lines += [ + "", + "## Review cohort", + "", + f"`{c['version']}`: {c['selected']} of {c['frame_items']:,} eligible items " + f"({c['groups']['count']:,} groups). Frame SHA-256 `{c['frame_sha256']}`, " + f"selection SHA-256 `{c['selection_sha256']}`.", + "", + "| Stratum | Items | Groups | Selected | Weight |", + "|---|---|---|---|---|", + ] + for row in c["strata_table"]: + frame, period, flag = row["stratum"].split("|") + name, wallet = ( + (frame.split(":")[0], " (one recorded wallet)") if ":" in frame else (frame, "") + ) + lines.append( + f"| {name}{wallet}, {period}, potential overlap {flag} | {row['packets']:,} | " + f"{row['groups']:,} | {row['selected']} | {_fmt(row['weight'])} |" + ) + o = r["operational_background"] + lines += [ + "", + "## Background candidate volume (unlabeled)", + "", + f"{o['candidates']} candidates on {o['recorded_windows']} recorded random wallets " + f"({o['wallet_days']} wallet-days; {o['windows_with_candidates']} wallets with any): " + f"{o['per_1000_wallet_days']} per 1,000 wallet-days. {o['note']}.", + ] + t = r["timings"] + lines += [ + "", + f"Runtime {t['total_s']} s; peak RSS {(r['peak_rss_bytes'] or 0) / 2**20:.0f} MiB.", + "", + ] + return "\n".join(lines) + + +def counts(items: Sequence[Any]) -> dict[str, int]: + return dict(Counter(items)) diff --git a/src/cryptoguard/ml/inventory.py b/src/cryptoguard/ml/inventory.py new file mode 100644 index 0000000..27d47a4 --- /dev/null +++ b/src/cryptoguard/ml/inventory.py @@ -0,0 +1,109 @@ +"""Offline inventory of local research data (``cryptoguard ml inventory``), 0 RPC requests. + +For every file under ``data/`` and the recorded replay fixtures it records: +- path, format, size and SHA-256; +- the record count, where the format makes it cheap; +- source, licence and whether it may be redistributed; +- label status. + +Files are hashed in 1 MiB chunks and never loaded whole. The registry below is the single +place where provenance is declared. A file it does not know is reported as +``unregistered``, never guessed. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +INVENTORY_VERSION = "inventory/1" +CHUNK = 1 << 20 + +# (path prefix, source, licence, redistributable, label status) +REGISTRY: tuple[tuple[str, str, str, str, str], ...] = ( + ("data/external/tsuchiya2025/", "Tsuchiya et al., USENIX Security 2025 (KiltHub " + "10.1184/R1/29212703.v1)", "CC BY-NC-ND 4.0", "no (non-commercial, no derivatives)", + "source heuristics: attempt categories and confirmed payoffs"), + ("data/external/poison-hunter/", "Poison-Hunter (published sample)", "none published", + "no", "source pipeline detections (weak_attempt)"), + ("data/external/ptxphish/", "PTXPhish (Chen et al., NDSS 2025)", "none published", "no", + "expert-reviewed phishing/benign transactions (separate task)"), + ("data/external/forta/", "Forta labelled datasets", "see data/external/forta/LICENSE", + "per licence", "address labels (separate task)"), + ("data/ml/poisoning/review_sample/", "derived: frozen Phase 11.4 review sample", + "derived from CC BY-NC-ND", "no", "unlabeled until human review"), + ("data/ml/poisoning/hard_negative/", "derived: Phase 11.5 hard-negative pool and cohort", + "derived from CC BY-NC-ND and public chain data", "no", "unlabeled_candidate"), + ("data/ml/poisoning/", "derived: Phase 11.2-11.4 reconciliation outputs", + "derived from CC BY-NC-ND", "no (aggregate tables only)", "source-derived"), + ("data/ml/pilot/", "option A pilot (eth.drpc.org, 2026-11-01)", "public chain data", "yes", + "pilot outcomes; unknown is never benign"), + ("data/ml/chain/", "PTXPhish chain features (collected)", "public chain data + PTXPhish", + "no (contains PTXPhish labels)", "PTXPhish labels"), + ("data/ml/", "derived: Phase 11 classifier runs, splits, registry", "derived", "no", + "PTXPhish labels (separate task)"), + ("src/cryptoguard/replay/cases/", "recorded incident fixtures (public chain data)", + "public chain data; committed", "yes", "incident case studies (used in development)"), + ("src/cryptoguard/replay/background_cases/", "recorded random background wallets", + "public chain data; committed", "yes", "unlabelled_background"), +) # fmt: skip + + +def _hash(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as fh: + while block := fh.read(CHUNK): + h.update(block) + return h.hexdigest() + + +def _records(path: Path) -> int | None: + suffix = path.suffix.lower() + if suffix in (".jsonl", ".csv", ".txt"): + with path.open("rb") as fh: + lines = sum(1 for _ in fh) + return lines - 1 if suffix == ".csv" else lines + if suffix in (".sqlite", ".db"): + import sqlite3 + + try: + con = sqlite3.connect(f"file:{path}?mode=ro", uri=True) + n = con.execute("select count(*) from transfers").fetchone()[0] + con.close() + return int(n) + except sqlite3.Error: + return None + return None + + +def _files(root: Path, rels: tuple[str, ...]) -> Iterator[Path]: + for rel in rels: + base = root / rel + if base.exists(): + yield from sorted( + p + for p in base.rglob("*") + if p.is_file() and not {"spill", "__pycache__"} & set(p.parts) + ) + + +def inventory(root: Path) -> dict[str, Any]: + rows = [] + for p in _files(root, ("data", "src/cryptoguard/replay/cases", + "src/cryptoguard/replay/background_cases")): # fmt: skip + rel = p.relative_to(root).as_posix() + reg = next((r for r in REGISTRY if rel.startswith(r[0])), None) + rows.append({ + "path": rel, + "format": p.suffix.lstrip(".") or "none", + "bytes": p.stat().st_size, + "sha256": _hash(p), + "records": _records(p), + "source": reg[1] if reg else "unregistered", + "licence": reg[2] if reg else "unknown", + "redistributable": reg[3] if reg else "unknown", + "label_status": reg[4] if reg else "unknown", + }) # fmt: skip + return {"version": INVENTORY_VERSION, "files": rows, "rpc_requests": 0} diff --git a/src/cryptoguard/ml/matching.py b/src/cryptoguard/ml/matching.py new file mode 100644 index 0000000..3241558 --- /dev/null +++ b/src/cryptoguard/ml/matching.py @@ -0,0 +1,134 @@ +"""Deterministic coarsened exact matching between source-labelled positive candidates and +unlabeled hard-negative candidates, with balance diagnostics (Phase 11.5). + +Matching describes *comparability*, never labels. + +- Units match only when every coarsened covariate is equal. A missing covariate is its + own level and never imputed. +- Matches are drawn without replacement, up to ``ratio`` candidates per positive, in + keyed-hash order, so ties break deterministically. +- Positives and candidates without support are reported as unmatched, not forced. + +Only information available at the observation cutoff may be a covariate. Outcomes, +future campaign membership, final labels and model scores are refused by name. +""" + +from __future__ import annotations + +import hashlib +import math +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +MATCH_VERSION = "cem/1" +FORBIDDEN = frozenset( + { + "payoff", + "paid", + "loss", + "outcome", + "label", + "source_label", + "score", + "prediction", + "campaign_after", + "later_payment", + } +) +Value = str | int | float | bool | None + + +class MatchingError(ValueError): + pass + + +@dataclass(frozen=True) +class Unit: + id: str + covariates: Mapping[str, Value] # coarsened values used for exact matching + numeric: Mapping[str, float | None] # raw values for balance diagnostics + + +def _rank(seed: str, unit_id: str) -> str: + return hashlib.sha256(f"{seed}|{unit_id}".encode()).hexdigest() + + +def cem( + positives: Sequence[Unit], + candidates: Sequence[Unit], + *, + keys: Sequence[str], + ratio: int = 1, + seed: str = MATCH_VERSION, +) -> dict[str, Any]: + bad = [k for k in keys if any(f in k.lower() for f in FORBIDDEN)] + if bad: + raise MatchingError(f"refusing post-cutoff or label covariates: {bad}") + if ratio < 1: + raise MatchingError("ratio must be at least 1") + ids = [u.id for u in (*positives, *candidates)] + if len(set(ids)) != len(ids): + raise MatchingError("unit ids repeat across or within the two sets") + + def cell(u: Unit) -> tuple[Value, ...]: + return tuple(u.covariates.get(k) for k in keys) + + pool: dict[tuple[Value, ...], list[Unit]] = defaultdict(list) + for c in sorted(candidates, key=lambda u: _rank(seed, u.id)): + pool[cell(c)].append(c) + pairs: list[tuple[str, str]] = [] + unmatched_pos: list[str] = [] + for p in sorted(positives, key=lambda u: _rank(seed, u.id)): + bucket = pool.get(cell(p), []) + take, pool[cell(p)] = bucket[:ratio], bucket[ratio:] + if not take: + unmatched_pos.append(p.id) + pairs += [(p.id, c.id) for c in take] + matched_c = {c for _, c in pairs} + matched_p = {p for p, _ in pairs} + pos_cells = {cell(p) for p in positives} + return { + "match_version": MATCH_VERSION, + "keys": list(keys), + "ratio": ratio, + "pairs": pairs, + "matched_positives": len(matched_p), + "unmatched_positives": unmatched_pos, + "matched_candidates": len(matched_c), + "unmatched_candidates": [c.id for c in candidates if c.id not in matched_c], + "candidates_without_support": sum(1 for c in candidates if cell(c) not in pos_cells), + "balance_before": balance(positives, candidates), + "balance_after": balance( + [p for p in positives if p.id in matched_p], + [c for c in candidates if c.id in matched_c], + ), + } + + +def smd(a: Sequence[float], b: Sequence[float]) -> float | None: + """Standardized mean difference (pooled SD). None when undefined.""" + if len(a) < 2 or len(b) < 2: + return None + ma, mb = sum(a) / len(a), sum(b) / len(b) + va = sum((x - ma) ** 2 for x in a) / (len(a) - 1) + vb = sum((x - mb) ** 2 for x in b) / (len(b) - 1) + sd = math.sqrt((va + vb) / 2) + if sd == 0: + return 0.0 if ma == mb else None + return (ma - mb) / sd + + +def balance(positives: Sequence[Unit], candidates: Sequence[Unit]) -> dict[str, Any]: + names = sorted({k for u in (*positives, *candidates) for k in u.numeric}) + out: dict[str, Any] = {"positives": len(positives), "candidates": len(candidates)} + for k in names: + a = [v for u in positives if (v := u.numeric.get(k)) is not None] + b = [v for u in candidates if (v := u.numeric.get(k)) is not None] + out[k] = { + "smd": smd(a, b), + "missing_positive": len(positives) - len(a), + "missing_candidate": len(candidates) - len(b), + } + return out diff --git a/tests/unit/test_ml_hard_negatives.py b/tests/unit/test_ml_hard_negatives.py new file mode 100644 index 0000000..104128d --- /dev/null +++ b/tests/unit/test_ml_hard_negatives.py @@ -0,0 +1,581 @@ +"""Phase 11.5: candidate-generator audit, hard-negative categories, contamination screen, +typed grouping, matching and the evaluation contract. + +Synthetic fixtures only. Nothing here measures fraud-detection accuracy. +""" + +from __future__ import annotations + +import random + +import pytest + +from cryptoguard.ml import candidates as cand +from cryptoguard.ml import contamination as ct +from cryptoguard.ml import evaluation as ev +from cryptoguard.ml import grouping as gp +from cryptoguard.ml import hard_negatives as hn +from cryptoguard.ml.events import PoisoningEvent +from cryptoguard.ml.history import events_from_fixture +from cryptoguard.ml.matching import MatchingError, Unit, cem, smd +from tests.unit.test_ml_poisoning import ( + FAKE, + FRIEND, + LOOKALIKE, + STRANGER, + USDT, + WALLET, + eth_tx, + fixture, + transfer, +) + +ROUTER = "0x7a250d5630b4cf539739df2c5dacb4c659f2488d" # on the public-infrastructure list +OTHER = "0x" + "44" * 20 + +# --- generator audit ------------------------------------------------------------------------- + + +def methods_at(fx, block: int) -> set[str]: + return {m for c in cand.generate(fx) if c.event.planting_block == block for m in c.methods} + + +def test_legitimate_looking_similarity_is_a_candidate_not_a_label() -> None: + """A genuine-token, ordinary-value transfer from a lookalike fires only lookalike_in: + the generator flags shape, not intent.""" + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 100, tx_sender=WALLET, idx=1), + transfer(900, LOOKALIKE, WALLET, 5_000_000_000, idx=1), + ], + [], + ) + assert methods_at(fx, 900) == {"lookalike_in"} + + +def test_repeated_and_unknown_counterparties() -> None: + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 100, tx_sender=WALLET, idx=1), + transfer(600, FRIEND, WALLET, 5_000_000_000, idx=1), # the real friend + transfer(700, STRANGER, WALLET, 5_000_000_000, idx=1), + ], + [], + ) + assert methods_at(fx, 600) == set() # exact earlier counterparty: not a lookalike + assert methods_at(fx, 700) == set() # unrelated stranger: no rule fires + + +def test_unverified_signer_is_not_a_chosen_counterparty() -> None: + """candidates/2: an outgoing transfer with an unknown signer (possibly a spoof) does + not become the 'imitated' counterparty.""" + fx = fixture( + [ + transfer(500, WALLET, LOOKALIKE, 0, tx_sender=None, idx=1), + transfer(900, FRIEND, WALLET, 5_000_000_000, idx=1), + ], + [], + transfer_scan_complete=False, + ) + assert methods_at(fx, 900) == set() + signed = fixture( + [ + transfer(500, WALLET, LOOKALIKE, 1, tx_sender=WALLET, idx=1), + transfer(900, FRIEND, WALLET, 5_000_000_000, idx=1), + ], + [], + ) + assert methods_at(signed, 900) == {"lookalike_in"} + + +def test_router_pull_is_a_spoofed_out_candidate() -> None: + """A legitimate transferFrom by an approved spender looks like a spoofed transfer: the + rule's documented breadth (category E), never a label.""" + fx = fixture([transfer(800, WALLET, OTHER, 10**9, tx_sender=ROUTER, idx=1)], []) + assert methods_at(fx, 800) == {"spoofed_out"} + + +def test_duplicate_logs_in_one_transaction_get_distinct_identities() -> None: + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 1, tx_sender=WALLET, idx=1), + transfer(900, LOOKALIKE, WALLET, 0, idx=1, log=1), + transfer(900, LOOKALIKE, WALLET, 0, token=FAKE, idx=1, log=2), + ], + [], + ) + ids = [c.event.victim_event_id for c in cand.generate(fx)] + assert len(ids) == len(set(ids)) == 2 + + +def test_failed_payments_still_count_as_chosen_and_are_documented() -> None: + """A reverted ETH send still appears in the wallet's history, so its destination is a + plausible copy source.""" + fx = fixture( + [transfer(900, LOOKALIKE, WALLET, 0, idx=1)], [eth_tx(500, FRIEND, 10**18, succeeded=False)] + ) + assert "lookalike_in" in methods_at(fx, 900) + + +def _brute_force(fx) -> list[tuple[str, tuple[str, ...], tuple[int, int] | None]]: + events, _ = events_from_fixture(fx) + out = [] + wallet = fx.wallet.lower() + for t in sorted(fx.transfers, key=lambda t: (t.block_number, t.transaction_index, t.log_index)): + incoming, outgoing = t.recipient.lower() == wallet, t.sender.lower() == wallet + if not (incoming or outgoing): + continue + pos = (t.block_number, t.transaction_index, t.log_index) + chosen = cand._chosen_before(events, pos) + party = (t.sender if incoming else t.recipient).lower() + match = max( + ((k, m) for k in chosen if (m := cand.similar(party, k))), + key=lambda km: (sum(km[1]), km[1][1], km[0]), + default=None, + ) + methods = cand.transfer_methods( + incoming=incoming, + outgoing=outgoing, + value=int(t.value), + token=t.token.lower(), + wallet_signed=None if t.tx_sender is None else t.tx_sender.lower() == wallet, + matched=match is not None, + ) + if methods: + out.append((t.transaction_hash, tuple(methods), match[1] if match else None)) + return out + + +def test_single_pass_generator_equals_the_per_transfer_definition() -> None: + rng = random.Random(7) + parties = [FRIEND, LOOKALIKE, STRANGER, OTHER, "0xd29" + "9" * 33 + "d7d5"] + for _ in range(30): + ts = [] + for i in range(25): + block = rng.randrange(100, 2_000) + if rng.random() < 0.4: + ts.append( + transfer( + block, + WALLET, + rng.choice(parties), + rng.choice([0, 5, 10**9]), + tx_sender=rng.choice([WALLET, None, STRANGER]), + idx=i, + ) + ) + else: + ts.append( + transfer( + block, + rng.choice(parties), + WALLET, + rng.choice([0, 5, 10**9]), + token=rng.choice([USDT, FAKE]), + idx=i, + ) + ) + fx = fixture(ts, [eth_tx(rng.randrange(100, 2_000), FRIEND, 1, idx=99)]) + got = [(c.event.planting_tx, c.methods, c.best_match) for c in cand.generate(fx)] + assert got == _brute_force(fx) + + +# --- categories ------------------------------------------------------------------------------ + + +def test_categories_are_structural_and_multi_label() -> None: + cats = hn.categories( + similarity=(3, 4), + threshold=6, + token_trusted=True, + value_usd=None, + methods=("lookalike_in",), + signer=None, + token=USDT, + coverage="partial", + first_time=True, + receipt_known=True, + value_base_units=5e9, + ) + assert set(cats) == { + "A_similarity_ordinary_value", + "B_first_time_counterparty", + "G_incomplete_observation", + "H_near_threshold", + } + dust = hn.categories( + similarity=None, + threshold=6, + token_trusted=True, + value_usd=0.5, + methods=("dust_in",), + signer=ROUTER, + token=USDT, + coverage="complete", + first_time=False, + receipt_known=True, + value_base_units=500, + ) + assert "C_low_value" in dust + assert "F_shared_infrastructure" in dust + assert "A_similarity_ordinary_value" not in dust + + +def test_every_pool_candidate_is_unlabeled() -> None: + rows = [ + { + "line": 7, + "block": 17_000_000, + "tx": "0x" + "ab" * 32, + "token": USDT, + "sender": LOOKALIKE, + "receiver": WALLET, + "sender_is_victim": False, + "value": 1e7, + "value_usd": 10.0, + "flags": 64, + "intended": FRIEND, + "first_digits": 4, + "last_digits": 4, + } + ] + (c,) = hn.archive_candidates(rows) + assert c.label_status == "unlabeled_candidate" + assert c.event.victim == WALLET + assert c.event.lookalike == LOOKALIKE + assert c.event.imitated == FRIEND + assert "A_similarity_ordinary_value" in c.categories + assert "G_incomplete_observation" in c.categories # no wallet history in the archive + + +# --- contamination --------------------------------------------------------------------------- + + +def known() -> ct.KnownIndex: + ix = ct.KnownIndex(coverage=[ct.Coverage("archive", 0, 10_000)]) + return ix.extend( + [ + ct.KnownAttack("archive", WALLET, LOOKALIKE, "0xt1", FRIEND), + ct.KnownAttack("archive", OTHER, "0x" + "55" * 20, "0xt2", None, token=FAKE), + ct.KnownAttack("unconfirmed", None, "0x" + "66" * 20, None), + ] + ) + + +@pytest.mark.parametrize( + ("kw", "level", "status"), + [ + ({"lookalike": LOOKALIKE, "tx": "0xt1"}, "exact_event", "known_positive_overlap"), + ( + {"victim": STRANGER, "lookalike": STRANGER, "tx": "0xt1"}, + "exact_tx", + "known_positive_overlap", + ), + ({"lookalike": LOOKALIKE, "tx": "0xnew"}, "victim_lookalike", "known_positive_overlap"), + ( + {"victim": STRANGER, "lookalike": "0x" + "55" * 20}, + "shared_infrastructure", + "known_positive_overlap", + ), + ( + {"victim": STRANGER, "lookalike": STRANGER, "token": FAKE}, + "shared_infrastructure", + "known_positive_overlap", + ), + ( + {"lookalike": "0x" + "77" * 20, "imitated": FRIEND}, + "related_campaign", + "potential_positive_overlap", + ), + ({"lookalike": "0xd296" + "0" * 32 + "d7d5"}, "weak_similarity", "no_known_overlap"), + ( + {"lookalike": "0xd296" + "0" * 32 + "d7d5", "block": 99_999}, + "weak_similarity", + "insufficient_information", + ), + ({"victim": STRANGER, "lookalike": STRANGER}, "none", "no_known_overlap"), + ( + {"victim": STRANGER, "lookalike": STRANGER, "block": 99_999}, + "none", + "insufficient_information", + ), + ], +) +def test_screen_levels_and_statuses(kw: dict, level: str, status: str) -> None: + args = { + "victim": WALLET, + "lookalike": STRANGER, + "tx": "0xother", + "block": 500, + "imitated": None, + "token": None, + **kw, + } + got = ct.screen(index=known(), **args) + assert (got.level, got.status) == (level, status) + + +def test_a_common_token_is_not_attack_infrastructure() -> None: + """Sharing USDT with a known attack is not an overlap: trusted tokens are never passed + as counterfeit infrastructure.""" + ix = known() + got = ct.screen( + victim=STRANGER, lookalike=STRANGER, tx="0xz", block=5, imitated=None, token=None, index=ix + ) + assert got.status == "no_known_overlap" + + +def test_conflicting_sources_are_all_recorded() -> None: + ix = known().extend([ct.KnownAttack("poison-hunter", WALLET, LOOKALIKE, "0xt1")]) + got = ct.screen( + victim=WALLET, lookalike=LOOKALIKE, tx="0xt1", block=1, imitated=None, token=None, index=ix + ) + assert got.sources == ("archive", "poison-hunter") + + +# --- typed grouping -------------------------------------------------------------------------- + + +def ev_( + n: int, + *, + victim: str, + look: str, + signer: str | None = None, + token: str = USDT, + imitated: str | None = None, + tx: str | None = None, +) -> PoisoningEvent: + return PoisoningEvent( + chain_id=1, + victim=victim, + lookalike=look, + imitated=imitated, + planting_tx=tx or "0x" + f"{n:064x}", + planting_block=100 + n, + planting_tx_index=0, + planting_log_index=n, + observation_timestamp=None, + subtype="fake_token", + tx_signer=signer, + log_contract=token, + token_contract=None, + candidate_method="t", + ) + + +def a(n: int) -> str: + return "0x" + f"{n:040x}" + + +def same_group(events: list[PoisoningEvent], policy: gp.GroupingPolicy | None = None) -> bool: + g = gp.typed_groups(events, policy).group + return len({g[e.victim_event_id] for e in events}) == 1 + + +def test_typed_grouping_follows_the_threat_model() -> None: + usdt = [ev_(1, victim=a(1), look=a(11)), ev_(2, victim=a(2), look=a(12))] + assert not same_group(usdt) # two unrelated wallets that both use USDT + signer = [ + ev_(3, victim=a(3), look=a(13), signer=a(99)), + ev_(4, victim=a(4), look=a(14), signer=a(99)), + ] + assert same_group(signer) # one planting signer, two victims + router = [ + ev_(5, victim=a(5), look=a(15), signer=ROUTER), + ev_(6, victim=a(6), look=a(16), signer=ROUTER), + ] + assert not same_group(router) # a public router signs for everyone + fake = [ + ev_(7, victim=a(7), look=a(17), token=FAKE), + ev_(8, victim=a(8), look=a(18), token=FAKE), + ] + assert same_group(fake) # a counterfeit token contract, whatever its degree + repeat = [ev_(9, victim=a(9), look=a(19)), ev_(10, victim=a(10), look=a(19))] + assert same_group(repeat) # a repeated lookalike + imitated = [ + ev_(11, victim=a(21), look=a(31), imitated=a(77)), + ev_(12, victim=a(22), look=a(32), imitated=a(77)), + ] + assert same_group(imitated) # the same imitated recipient + unknown = [ + ev_(13, victim=a(23), look=a(33), token=a(500)), + ev_(14, victim=a(24), look=a(34), token=USDT), + ] + assert not same_group(unknown) # unknown contracts do not link to common tokens + batch = [ + ev_(15, victim=a(25), look=a(35), tx="0x" + "bb" * 32), + ev_(16, victim=a(26), look=a(36), tx="0x" + "bb" * 32), + ] + assert same_group(batch) # a multi-victim planting transaction + + +def test_verified_infrastructure_links_and_exclusions_apply() -> None: + pair = [ + ev_(1, victim=a(1), look=a(11), signer=ROUTER), + ev_(2, victim=a(2), look=a(12), signer=ROUTER), + ] + assert same_group(pair, gp.GroupingPolicy(verified_infra=frozenset({ROUTER}))) + same_wallet = [ev_(3, victim=a(3), look=a(13)), ev_(4, victim=a(3), look=a(14))] + assert same_group(same_wallet) + assert not same_group(same_wallet, gp.GroupingPolicy(exclude=frozenset({"shared_victim"}))) + stats = gp.typed_groups(pair) + assert stats.edges_ignored["shared_token_contract"] == 2 + + +# --- matching -------------------------------------------------------------------------------- + + +def U(i: str, **cov: object) -> Unit: + return Unit(i, cov, {"x": float(len(i))}) + + +def test_exact_match_no_match_and_explicit_unmatched() -> None: + pos = [U("p1", year=2023, bin="a"), U("p2", year=2024, bin="b")] + cands = [U("c1", year=2023, bin="a"), U("c2", year=2022, bin="a")] + r = cem(pos, cands, keys=["year", "bin"]) + assert r["pairs"] == [("p1", "c1")] + assert r["unmatched_positives"] == ["p2"] # temporal mismatch is not forced + assert r["unmatched_candidates"] == ["c2"] + assert r["candidates_without_support"] == 1 + + +def test_one_to_many_is_deterministic_and_missing_is_its_own_level() -> None: + pos = [U("p1", bin=None)] + cands = [U(f"c{i}", bin=None) for i in range(5)] + [U("c9", bin="a")] + a1 = cem(pos, cands, keys=["bin"], ratio=3) + a2 = cem(pos, list(reversed(cands)), keys=["bin"], ratio=3) + assert a1["pairs"] == a2["pairs"] + assert len(a1["pairs"]) == 3 + assert "c9" not in {c for _, c in a1["pairs"]} # a missing value never matches a present one + + +def test_matching_refuses_outcome_covariates_and_duplicate_ids() -> None: + with pytest.raises(MatchingError, match="post-cutoff"): + cem([U("p")], [U("c")], keys=["later_payment"]) + with pytest.raises(MatchingError, match="repeat"): + cem([U("x")], [U("x")], keys=[]) + assert smd([1.0, 2.0], [1.0, 2.0]) == 0.0 + assert smd([1.0], [2.0, 3.0]) is None # insufficient support + + +# --- evaluation contract ----------------------------------------------------------------------- + + +def example( + i: int, tier: str | None, score: float | None, *, split: str = "test", weight: float = 1.0 +) -> ev.BenchmarkExample: + return ev.BenchmarkExample( + event_id=f"{i:016x}", + group_id=f"g{i}", + split=split, + observation=ev.Observation( + chain_id=1, + wallet=a(i), + candidate_address=a(100 + i), + transaction="0x" + f"{i:064x}", + block=i, + observation_cutoff="after tx", + source_manifest="m", + ), + generation=ev.Generation( + candidate_version="candidates/2", methods=("lookalike_in",), eligible=True + ), + source_label=ev.SourceLabel(source=None, status="unlabeled_candidate"), + human_label=None + if tier is None + else ev.HumanLabel(tier=tier, provenance=("h",), reviewers=2), + prediction=None if score is None else ev.Prediction(model="m", score=score), + weight=weight, + ) + + +def test_unlabeled_and_weak_are_never_negatives() -> None: + data = [ + example(1, "verified_attempt", 0.9), + example(2, "weak_attempt", 0.1), + example(3, None, 0.2), + example(4, "unknown", 0.3), + ] + with pytest.raises(ev.MetricRefused, match="no verified_legitimate"): + ev.evaluate(data, threshold=0.5) + + +def test_metrics_on_reviewed_examples_name_their_exclusions() -> None: + data = [ + example(1, "verified_attempt", 0.9), + example(2, "verified_attempt", 0.4), + example(3, "verified_legitimate", 0.6), + example(4, "verified_legitimate", 0.1), + example(5, None, 0.95), + example(6, "conflicting", 0.5), + ] + r = ev.evaluate(data, threshold=0.5, fpr_budget=0.0, review_capacity=2) + assert r["precision"] == 0.5 + assert r["recall"] == 0.5 + assert r["fpr"] == 0.5 + assert r["roc_auc"] == 0.75 + assert r["average_precision"] == pytest.approx((1 / 1 + 2 / 3) / 2) + assert r["recall_at_fpr_budget"]["recall"] == 0.5 + assert r["excluded"]["unreviewed_or_unverified"] == 2 + assert r["labels"]["no_review:unlabeled_candidate"] == 1 + + +def test_contract_refuses_outcomes_in_features_and_unflagged_missing() -> None: + with pytest.raises(ValueError, match="outcome"): + ev.Features(feature_version="f", values={"later_payoff_usd": 1.0}) + with pytest.raises(ValueError, match="missing"): + ev.Features(feature_version="f", values={"prior_payments": None}) + ok = ev.Features( + feature_version="f", values={"prior_payments": None}, missing=("prior_payments",) + ) + assert ok.values["prior_payments"] is None # missing stays missing, never 0 + + +def test_split_report_finds_entity_leakage() -> None: + e1 = ev_(1, victim=a(1), look=a(11)) + e2 = ev_(2, victim=a(1), look=a(12)) # same wallet in another split + data = [example(1, None, None, split="train"), example(2, None, None, split="test")] + events = {data[0].event_id: e1, data[1].event_id: e2} + r = ev.split_report(data, events) + assert r["valid"] is False + assert r["overlap"]["train/test"]["entities"] >= 1 + + +def test_operational_measures_are_labelled_for_what_they_are() -> None: + r = ev.alerts_per_1000_wallet_days(8, 27, reviewed=False, representative=False) + assert r["per_1000_wallet_days"] == pytest.approx(296.3, abs=0.1) + assert "not false alerts" in r["measure"] + h = ev.precision_under_prevalence(0.9, 0.01, 0.001) + assert h["scenario"] == "hypothetical" + with pytest.raises(ev.MetricRefused): + ev.precision_under_prevalence(1.2, 0.0, 0.1) + with pytest.raises(ev.MetricRefused, match="no known attempts"): + ev.candidate_recall([], ["x"]) + + +# --- inventory and separability diagnostics ---------------------------------------------------- + + +def test_inventory_hashes_files_and_never_guesses_provenance(tmp_path) -> None: + from cryptoguard.ml.inventory import inventory + + (tmp_path / "data/external/tsuchiya2025").mkdir(parents=True) + (tmp_path / "data/external/tsuchiya2025/x.csv").write_text("h\n1\n2\n", encoding="utf-8") + (tmp_path / "data/mystery").mkdir(parents=True) + (tmp_path / "data/mystery/y.bin").write_bytes(b"\x00") + rows = {r["path"]: r for r in inventory(tmp_path)["files"]} + known = rows["data/external/tsuchiya2025/x.csv"] + assert known["records"] == 2 + assert known["licence"] == "CC BY-NC-ND 4.0" + assert len(known["sha256"]) == 64 + assert rows["data/mystery/y.bin"]["source"] == "unregistered" + + +def test_separability_auc_is_direction_free() -> None: + from cryptoguard.ml.hn_study import univariate_auc + + assert univariate_auc([5.0, 6.0], [1.0, 2.0]) == 1.0 + assert univariate_auc([1.0, 2.0], [5.0, 6.0]) == 1.0 + assert univariate_auc([1.0, 2.0], [1.0, 2.0]) == 0.5 + assert univariate_auc([], [1.0]) is None diff --git a/tests/unit/test_ml_reconcile.py b/tests/unit/test_ml_reconcile.py index b6c670e..3bbfa61 100644 --- a/tests/unit/test_ml_reconcile.py +++ b/tests/unit/test_ml_reconcile.py @@ -332,6 +332,15 @@ def test_counterfeit_rows_are_attempts() -> None: "cryptoguard.ml.review_server", "cryptoguard.ml.unblind", "cryptoguard.ml.benchmark", + "cryptoguard.ml.hard_negative_archive", + "cryptoguard.ml.hard_negatives", + "cryptoguard.ml.contamination", + "cryptoguard.ml.grouping", + "cryptoguard.ml.matching", + "cryptoguard.ml.cohort", + "cryptoguard.ml.evaluation", + "cryptoguard.ml.hn_study", + "cryptoguard.ml.inventory", ) # The pure lookalike predicates live in detectors.poisoning, whose base module imports type # definitions from history/services/risk. Persistence and the API are what could create, From 732e560b796ae93a3d5cf6809eca63423eed29ae Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 13:13:58 +0300 Subject: [PATCH 27/92] feat(ml): register the frozen hard-negative cohort; skip bytecode in the inventory Commits the five hashes of hard-negative-candidates/1 (frozen at c68d3a4, clean tree, before any review) to review_sample.COHORTS so verify, package, serve and unblind recognise it; the Phase 11.4 sample's hashes are unchanged. The inventory no longer lists __pycache__ files. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/review_sample.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py index 86e9401..34bd417 100644 --- a/src/cryptoguard/ml/review_sample.py +++ b/src/cryptoguard/ml/review_sample.py @@ -319,6 +319,15 @@ class FrozenIntegrityError(ReviewSampleError): # Every frozen cohort and its committed hashes. A reviewer package names no cohort: the # server finds it by the sheet's hash, so a cohort's purpose is never shown to reviewers. COHORTS: dict[str, dict[str, str]] = {SAMPLE_VERSION: FROZEN_V1} +# Phase 11.5 hard-negative candidate cohort, frozen at c68d3a4 before any review +# (ML_HARD_NEGATIVE_STUDY.md section 12). +COHORTS["hard-negative-candidates/1"] = { + "queue": "881f2faebdf3669d659cfb2a3fbbd87f27a50cd71e92c6889e34427c2ef3feea", + "selection": "ae9df36ab99750a35e884bf487e117e1f5c99f555a2beaf5ab2f30c11f6ddb57", + SHEET: "121c112d291e5397c378cddd2a27b2e081404aa8a57b5d73325556b7d94ca108", + KEY: "f333386d20ce327df27c2747aef317e96e030c61650f3f20b60d06f038802ad9", + MANIFEST: "05dc1b1679f9fdce7560ff5da1f9a869fd84c8617646410e56aa3cbce59e3868", +} def cohort_for_sheet(sheet_sha256: str) -> str | None: From 98874461ef50fa34c6a01f265135c9cb2f20f06d Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 13:14:01 +0300 Subject: [PATCH 28/92] docs(ml): Phase 11.5 hard-negative study, readiness gates A-J, generated tables Documents the offline hard-negative pool (8,877 unlabeled candidates), the contamination screen (42% of the archive's uncategorized rows overlap known attacks), matching and source-separability results (value alone separates the frames), the frozen 35-item cohort and its first, superseded draw, and the readiness gates. ML_POISONING_TABLES.md is regenerated with candidates/2: only the commit line changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 21 ++ ML.md | 6 + ML_ANNOTATION_AUDIT.md | 11 + ML_BENCHMARK_READINESS.md | 18 ++ ML_HARD_NEGATIVE_STUDY.md | 442 +++++++++++++++++++++++++++++++++++++ ML_HARD_NEGATIVE_TABLES.md | 100 +++++++++ ML_POISONING_TABLES.md | 2 +- ML_RESEARCH_PLAN.md | 7 +- README.md | 2 +- 9 files changed, 605 insertions(+), 4 deletions(-) create mode 100644 ML_HARD_NEGATIVE_STUDY.md create mode 100644 ML_HARD_NEGATIVE_TABLES.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 41addf3..0ba08e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,27 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Hard-negative discovery and benchmark contract (Phase 11.5) +- `candidates/2`: a counterparty counts as chosen only with a verified wallet signature, + and generation is a single pass. The output is identical on all 13 recorded windows and + the published tables are unchanged. +- Added `ml hard-negative-extract` and `ml hard-negative-study` (offline, 0 RPC): + - 8,651 uncategorized archive transfers (the publisher's count) plus 226 recorded-window + candidates, every one `unlabeled_candidate`; + - a contamination screen against every local known positive. 3,632 archive candidates + (42%) overlap known attacks; none is called benign; + - typed campaign grouping that never links through common tokens or routers; + - coarsened exact matching with balance diagnostics (strict: 17 of 1,409 positives + matched); + - source-separability diagnostics: value alone separates the frames, AUC 1.0. +- Added a second frozen review cohort (`hard-negative-candidates/1`, 35 items) in the same + review app. Packages name no cohort, and the page shows a neutral title and pre-cutoff + context. +- Added the `benchmark-example/1` contract and metrics that refuse unverified negatives + (`ml/evaluation.py`), plus a data inventory (`ml inventory`). +- Docs: ML_HARD_NEGATIVE_STUDY.md, generated ML_HARD_NEGATIVE_TABLES.md, and readiness gates + A-J in ML_BENCHMARK_READINESS.md §8. + ### Independent annotation and benchmark validation (Phase 11.4) - Verified the frozen review sample against its committed hashes (`ml review verify`) and audited its design (`ml review audit`). Every uniqueness, separation, allocation, weight diff --git a/ML.md b/ML.md index d9fea88..b842212 100644 --- a/ML.md +++ b/ML.md @@ -50,6 +50,12 @@ method and decision log. (local, blinded review app), `ml/agreement.py`, `ml/unblind.py` (gated unblinding and analysis), `ml/benchmark.py` (readiness and holdout guard); commands under `cryptoguard ml review` ([ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md)). + - Phase 11.5: `ml/hard_negative_archive.py` and `ml/hard_negatives.py` (unlabeled + hard-negative pool), `ml/contamination.py` (known-positive screen), + `ml/grouping.py` (typed campaign edges), `ml/matching.py` (coarsened exact + matching), `ml/cohort.py` (generic frozen cohorts), `ml/evaluation.py` (benchmark + contract and metrics that refuse unverified negatives), `ml/hn_study.py` and + `ml/inventory.py` ([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. diff --git a/ML_ANNOTATION_AUDIT.md b/ML_ANNOTATION_AUDIT.md index ec4c293..b90cf89 100644 --- a/ML_ANNOTATION_AUDIT.md +++ b/ML_ANNOTATION_AUDIT.md @@ -323,3 +323,14 @@ The frame is payoff-linked, so a reviewer may see the later payment. | 30 | P2 | **"Zero-value" naming** covers only zero-value transfers to the victim | Documented (§5) | No P0 finding: every hash, uniqueness, separation, allocation and reserve-order check passes. + +## 20. Second cohort (Phase 11.5) + +- **The cohort.** A separately frozen cohort, `hard-negative-candidates/1` (35 unlabeled + candidates), uses the same app, store, finalization and unblinding gate. +- **How cohorts are kept apart:** + - each cohort has its own committed hashes in `review_sample.COHORTS`; + - a reviewer package names no cohort, so the server finds the cohort by the sheet's hash; + - items carry the neutral title "Candidate for independent security review". +- **The Phase 11.4 sample is unchanged** (re-verified). +- Design and hashes: [ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md) §12. diff --git a/ML_BENCHMARK_READINESS.md b/ML_BENCHMARK_READINESS.md index b7a0f10..85d3d34 100644 --- a/ML_BENCHMARK_READINESS.md +++ b/ML_BENCHMARK_READINESS.md @@ -130,3 +130,21 @@ Collection stops at the cap, whatever has been found by then. - **Never loaded by production.** The review and annotation modules are research-only, and `tests/unit/test_ml_reconcile.py` checks that they load neither the application database nor the API. Wallet scans and findings are unchanged. + +## 8. Phase 11.5 readiness gates + +Evidence: [ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md). Status values: pass, fail, +blocked by missing evidence, not yet evaluated. Infrastructure alone never passes a gate. + +| Gate | Status | Why | +|---|---|---| +| A Candidate validity | **pass** | `candidates/2` is deterministic, versioned and audited. It equals its per-transfer definition on random fixtures and gives identical output to `candidates/1` on all 13 recorded windows | +| B Historical correctness | **pass** (for implemented features) | features use only strictly earlier positions (tested: future events, input order, same-block, unknown vs empty history). The archive frame has no wallet history at all | +| C Positive-label provenance | blocked by missing evidence | positives are source labels with known provenance tiers; the 60-item independent review has not happened | +| D Negative-label validity | blocked by missing evidence | 0 candidates reviewed; 35 are frozen for review | +| E Source independence | **pass** (identified, not resolved) | contamination and shortcuts measured: 42% of the archive frame overlaps known attacks; value alone separates frames perfectly | +| F Leakage-safe splitting | blocked by missing evidence | typed grouping, holdout guard and split overlap report exist; nothing labelled to split | +| G Statistical adequacy | **fail** | 0 independent labels; gate B in `events.quality_gates` needs 30 per class | +| H Baseline comparability | blocked by missing evidence | the detector needs wallet histories; only the recorded-window frame has them, and it has no labels | +| I Operational relevance | not yet evaluated | unlabeled candidate volume only (8 on 27 wallet-days); no reviewed false alerts | +| J Deployment safety | **pass** | research modules load neither database nor API (tested); no production finding changes | diff --git a/ML_HARD_NEGATIVE_STUDY.md b/ML_HARD_NEGATIVE_STUDY.md new file mode 100644 index 0000000..3875219 --- /dev/null +++ b/ML_HARD_NEGATIVE_STUDY.md @@ -0,0 +1,442 @@ +# Hard-negative study (Phase 11.5) + +Status: **offline groundwork done; nothing is labelled.** +- 8,877 hard-negative *candidates* were extracted and screened. +- A 35-item review cohort is frozen. +- No human has reviewed it. +- No model was trained. 0 RPC requests. 0 downloads. + +Generated numbers: [ML_HARD_NEGATIVE_TABLES.md](ML_HARD_NEGATIVE_TABLES.md). Regenerate with: + +```bash +cryptoguard ml hard-negative-extract # two offline passes over the local archive (~50 min) +cryptoguard ml hard-negative-study # pool, screen, matching, diagnostics, cohort (~2 min) +cryptoguard ml inventory # hashes and provenance of every local data file +``` + +## 1. Executive summary + +- **The question.** Can CryptoGuard tell real address-poisoning attempts from legitimate + activity that looks like poisoning, using only information available before harm? It + cannot be answered yet, because no independently labelled legitimate example exists. +- **What exists now:** + - a reproducible candidate pool; + - a screen that removes known attacks; + - a matching design; + - a frozen, blinded review cohort; + - evaluation code that refuses unsupported metrics. +- **Finding 1: "uncategorized" is not "benign".** The archive's 8,651 uncategorized + lookalike transfers are the closest local frame to legitimate look-alike activity. + **3,632 of them (42%) overlap known attacks:** + - 2,136 share the victim and the lookalike with a source-labelled attempt; + - 1,495 come from a lookalike known as an attacker elsewhere; + - 1 is the same event. +- **Finding 2: naive negatives would be a shortcut.** Source positives and archive + candidates are separable by data source alone: + - transfer value separates them perfectly (AUC 1.000); + - direction alone gives 0.982; + - everything except value gives 0.993. + + The source defined its categories by these very covariates. Training on them would + learn the source's rules, not malice (hypothesis H5). +- **Finding 3: strict matching finds almost no support.** Matching on transaction shape + pairs only 17 of 1,409 positives. Matching on period and similarity alone pairs 806. + "Hard negatives that look like positives" barely exist in this archive, by + construction. +- **Random wallets.** On 9 randomly drawn recorded wallets (27 wallet-days), the generator + emits 8 candidates (296 per 1,000 wallet-days, unlabeled). Most look like real + fake-token spoofs rather than legitimate activity. + +## 2. Scientific objectives + +| Hypothesis | Testable now? | What this phase adds | +|---|---|---| +| H1 Similarity alone is insufficient | no (needs labels) | 8,651 similarity-matched, uncategorized transfers across 4,190 wallets, 42% attack-linked: a frame in which to test it | +| H2 Wallet history helps | no | history exists only for the recorded windows (226 candidates) | +| H3 Transaction semantics matter | descriptively | categories A-H; frames differ sharply by value, token and direction | +| H4 Graph context helps | no | typed grouping and contamination edges give the needed relations | +| H5 Hard negatives are necessary | **supported descriptively** | separability diagnostics (§19): naive negatives are trivially separable | + +## 3. Existing data inventory + +- **Coverage.** `cryptoguard ml inventory` hashes and describes every file under `data/` + and the recorded fixtures (`data/ml/inventory.json`, local). +- **Provenance.** Every file maps to a declared source, and no file is unregistered. + +| Source | Files (examples) | Records | Licence | Redistributable | Label status | +|---|---|---|---|---|---| +| Tsuchiya et al. 2025 | `address_poisoning_ethereum.sql.gz` (2,316,354,530 B, SHA-256 `270211ac…`), payoff CSV (1,738) | 34,905,969 rows | CC BY-NC-ND 4.0 | no | source heuristics | +| Poison-Hunter sample | `phishing_transfers_sample.csv` | 150 (149 valid) | none published | no | source detections (weak) | +| PTXPhish | `PTXPHISH.xlsx` | 18,555 transactions | none published | no | separate task (Track A) | +| Forta labels | 3 CSVs | 15,259 | per its LICENSE | per licence | address labels, separate task | +| Recorded incident fixtures | 4 `fixture.json` (committed) | 411 transfers | public chain data | yes | case studies (used in development) | +| Recorded background wallets | 9 `fixture.json` (committed) | 27 wallet-days | public chain data | yes | `unlabelled_background` | +| Derived (local) | archive subset, context subset, review cohorts | 301,370 / 210,478 rows | derived from CC BY-NC-ND | no | source-derived / unlabeled | + +- **Missing:** none of the files the docs mention. The Phase 11 pilot's three cost-phase + wallet-days were lost earlier (ML_PILOT_AUDIT.md §4). + +## 4. Candidate-generation rules (`candidates/2`) + +**Audit findings:** +- **Inputs.** Recorded transfers and wallet transactions only. No production findings, no + labels, no scores. +- **Rules.** `zero_value_in`, `spoofed_out`, `lookalike_in` (6 or more prefix+suffix + characters, of which at least 3 suffix), `untrusted_token_in`, `dust_in`. +- **Cutoff.** Strictly earlier positions only; no future information. +- **Dependence on the source.** The generator's lookalike rule is looser than the source's + 3+4 rule. The source rule is a subset of it (ML_CROSS_DATASET_VALIDATION.md §16). + +**Changes:** + +| ID | Pri | Finding | Fix | +|---|---|---|---| +| 31 | P2 | **Unverified choices.** `candidates/1` counted outgoing transfers with an *unknown* signer as counterparties the wallet chose. Under partial coverage, a spoofed transfer to a lookalike could become the "imitated" address | `candidates/2` requires a verified wallet signature. No recorded transfer has an unknown signer, so the output on all 13 windows is identical (tested), and ML_POISONING_TABLES.md is unchanged | +| 32 | P2 | **Quadratic scan.** The history was rescanned per transfer | Single forward pass; a property test checks equality with the per-transfer definition on 30 random fixtures | + +**Documented breadth (not defects):** +- `spoofed_out` also fires on legitimate pulls by an approved spender: routers, Permit2, + settlement contracts. +- `dust_in` fires on genuine small test payments. +- A reverted ETH send still counts as a chosen counterparty, because it appears in the + wallet's history. +- Duplicate logs get distinct identities (the log index is part of the identity). + +All of these are tested. + +## 5. Candidate eligibility + +- **What enters the frame.** Every candidate enters the pool. The review frame excludes + only `known_positive_overlap` (§7). +- **Potential overlaps stay in**, as their own stratum. +- **No candidate was dropped for being hard.** + +## 6. Source overlap + +| Known-positive source | Records indexed | +|---|---| +| Tsuchiya archive (poisoning rows touching the targets) | 198,903 | +| Tsuchiya archive, unconfirmed payoffs | 1,113 | +| Tsuchiya payoffs | 1,738 | +| Poison-Hunter | 149 | +| Incidents | 4 | + +- **Coverage counts only where absence means something.** Only the archive is chain-wide + for its block range (15,053,226–20,208,032). Poison-Hunter is a sample and the incidents + are single cases: they can confirm an overlap, never vouch for its absence. +- **Consequence.** A candidate outside the archive range is `insufficient_information`, + not "no known overlap". + +## 7. Positive contamination + +**Match levels** (`ml/contamination.py`), strongest first: +1. exact event; +2. exact transaction; +3. same victim and lookalike; +4. shared attack infrastructure: a known lookalike, or a counterfeit token contract; +5. related campaign: the same victim and the same imitated counterparty; +6. weak similarity; +7. none. + +| Frame | Known positive | Potential | No known overlap | Insufficient information | +|---|---|---|---|---| +| archive uncategorized (8,651) | **3,632** (exact event 1, victim–lookalike 2,136, shared infrastructure 1,495) | 79 | 4,940 | 0 | +| recorded incident wallets (218) | 13 (victim–lookalike) | 32 | 168 | 5 | +| recorded background wallets (8) | 0 | 0 | 0 | 8 (2026 blocks: no chain-wide screen) | + +- **Known-positive overlaps** (3,645) are excluded from review and from any future negative + set. +- **Potential overlaps** (111) are kept as a stratum. +- **"No known overlap" and "insufficient information"** are not benign. +- **A common token never counts as infrastructure:** shared USDT is not an overlap (tested). + +## 8. Hard-negative candidate categories + +The categories are structural, multi-label and never labels: + +| Category | Archive (8,651) | Background (8) | Incident wallets (218) | +|---|---|---|---| +| A lookalike, genuine token, ordinary value | 8,651 | 0 | 1 | +| B first-time counterparty in the window | n/a (no history) | 6 | 35 | +| C low value | 0 | 0 | 3 | +| D token ambiguity (zero-value genuine, or untrusted token) | 0 | 8 | 46 | +| E moved out by a transaction the wallet did not sign | 0 | 7 | 213 | +| F signed by public infrastructure | 0 | 0 | 0 | +| G incomplete observation | 8,651 | 0 | 0 | +| H within one character of the similarity threshold | 6,070 | 2 | 5 | + +- **Category F is empty.** No recorded candidate was signed by a listed router. +- **Category E is not mostly spoofs.** 168 of its 213 incident candidates are non-zero, + genuine-token transfers out of the WBTC victim's wallet, in transactions it did not + sign (33 distinct signers in all). That is the shape of approved-spender pulls such as + solver-settled swaps. + - They are the most plausible *legitimate* look-alikes in the local data, and the cohort + samples from them. + - The rest of E is zero-value or untrusted-token spoofs (45). +- **Background candidates have attack shapes.** 7 of the 8 are attack-shaped: 6 + untrusted-token spoofs and 1 zero-value `transferFrom` spoof. +- **The WBTC wallet dominates** the incident frame: 169 of its 218 candidates. + +## 9. Matching design + +**Method.** Coarsened exact matching (`cem/1`), 1:1, deterministic keyed-hash order, +explicit unmatched units. +- **Positives:** the 1,409 payoff-linked source positives, excluding the 60 reserved review + items. +- **Candidates:** the 5,019 archive candidates not known to overlap a positive. + +| Design | Keys | Matched positives | Candidates without support | +|---|---|---|---| +| strict | year, direction, token class, value bin, similarity bin | **17** | 1,121 | +| relaxed | year, similarity bin | 806 | 0 | + +**Balance before matching** (standardized mean difference): + +| Covariate | SMD | +|---|---| +| victim sends (direction) | 7.22 | +| log value | −6.13 (745 positives have no USD value) | +| block | −2.48 | +| token class | −1.51 | +| similarity | 0.48 | + +**Reading.** +- Strict matching fails by design. The source's categories (zero, tiny, counterfeit) are + the shape covariates, so its positives and its uncategorized rows almost never share a + cell. +- Relaxed matching balances period and similarity, but not shape. +- Neither yields negatives. They show which comparisons the data can support. Outcomes, + labels and scores are refused as covariates by name (tested). + +## 10. Historical feature availability + +| Frame | Wallet history | Features available | +|---|---|---| +| recorded windows (226) | complete within a 21,600-block window; earlier history not recorded | all `event-features/1` | +| archive (8,651) | none (the archive keeps only source-selected rows) | similarity, value, token, block only | + +**Point-in-time guarantees, all tested:** +- future events, losses, labels and same-block later transactions do not change past + features; +- input order does not matter; +- unknown history is `partial`/`unavailable`, never zero; +- known-empty history gives real zeros. + +The contract keeps missing values as `None` with a `missing` list. Features may not carry +label, outcome, payoff or score fields (`ml/evaluation.py`). + +## 11. Sampling frame + +- **Eligible frame:** 5,232 items in 2,664 typed groups. + - Archive frame: one representative per typed campaign group (victim, lookalike, tx, + signer, imitated and counterfeit-token edges). + - Recorded-wallet frames: one stratum per wallet, with victim edges excluded (the wallet + is already the stratum). +- **Typed grouping never links through USDT, USDC, DAI or a listed router** (tested with + the cases the brief lists). + +## 12. Frozen candidate sample (`hard-negative-candidates/1`) + +**Design** (fixed before the draw): +- 24 items from the archive frame, allocated across period × potential-overlap strata; +- 2 per recorded wallet; +- seed `cryptoguard-hard-negative-candidates/1`. + +**Result:** 35 items: +- 24 from the archive; +- 3 from background wallets; +- 8 from incident wallets. + +| Item | SHA-256 | +|---|---| +| eligible frame | `881f2faebdf3669d659cfb2a3fbbd87f27a50cd71e92c6889e34427c2ef3feea` | +| selection | `ae9df36ab99750a35e884bf487e117e1f5c99f555a2beaf5ab2f30c11f6ddb57` | +| `reviewer_sheet.jsonl` | `121c112d291e5397c378cddd2a27b2e081404aa8a57b5d73325556b7d94ca108` | +| `unblinding_key.jsonl` | `f333386d20ce327df27c2747aef317e96e030c61650f3f20b60d06f038802ad9` | +| `sample_manifest.json` | `05dc1b1679f9fdce7560ff5da1f9a869fd84c8617646410e56aa3cbce59e3868` | + +- **Frozen** at commit `c68d3a4` on a clean tree. The files are local + (`data/ml/poisoning/hard_negative/cohort_v1/`) and the hashes are registered in + `review_sample.COHORTS`. +- **First draw, set aside.** It was frozen minutes earlier on an uncommitted tree. Weak- + similarity candidates outside the screened block range were then marked "no known + overlap" instead of "insufficient information" (3 items). + - It was set aside to `superseded/cohort_v1_first_draw/` before any package was issued. + - The redraw selected **the same 35 items**, and the reviewer sheet is byte-identical. + Only the answer key's screening statuses changed. +- **"2024" in the strata names means "2024 or later".** The year boundaries stop at 2024. +- **The Phase 11.4 sample is unchanged:** all five hashes re-verified. + +## 13. Human-review protocol + +- **Same rules as the first sample:** the protocol (with amendment 1) and the review app + are reused. +- **What reviewers see:** + - a neutral title, "Candidate for independent security review"; + - a coverage note; + - for recorded wallets, the last 25 pre-cutoff observations. +- **What they never see:** the frame, categories, screening result, cohort name or any + score. The package's info file names no cohort; the server identifies it by the sheet's + hash. +- **Every decision stays possible**, including "confirmed poisoning attempt". +- **Primary quantity:** the share of items both reviewers mark + `confirmed_legitimate_interaction`, design-weighted within the frame. The attempt + share and agreement are also reported (`ub.analyse`). + +## 14. Label validity + +| Have | Status | +|---|---| +| Independent human labels | **0** | +| Candidates | `unlabeled_candidate` | +| Overlaps | known-positive, used only to exclude | + +Nothing here is a negative. + +## 15. Statistical limitations + +- **Small cohort.** 35 items across 14 strata. Several recorded-wallet strata have one + item, and archive strata carry weights up to 197.5. Archive-frame estimates will be + wide; recorded-wallet results are case-level. +- **No population rate.** Neither frame is a random sample of Ethereum activity, so no + population false-positive rate can follow. + +## 16. Source-selection bias + +- **The archive frame is the source's leftover category.** It is selected by the source's + pipeline (lookalike rule, payoff-linked victims and their counterparties), then + restricted to what the source did not categorize. +- **The recorded-wallet frame is not representative either.** Four of its seven wallets + are publicly reported theft victims, and three are random wallets. +- **Consequence.** Proportions from either frame describe that frame only. + +## 17. Operational candidate volume + +| Measure | Value | +|---|---| +| Recorded random wallets | 9 (27.0 wallet-days) | +| Candidates | 8, on 3 of the 9 wallets | +| Rate | 296.3 per 1,000 wallet-days, unlabeled | + +These are not false alerts and not an Ethereum-wide rate. `ml/evaluation.py` labels +alert-volume results as *unlabeled* or *reviewed*, and *representative* or not, and marks +prevalence scenarios as hypothetical. + +## 18. Model-evaluation design + +**Ready:** `ml/evaluation.py`. +- The `benchmark-example/1` contract keeps seven layers apart: observation, generation, + features, source label, human label, outcome and prediction. +- **Metrics:** precision, recall, FPR, AP, ROC-AUC, recall at an FPR budget, and precision + at a review capacity. Candidate recall is a separate function. + +**Refusals:** +- no `verified_legitimate` examples means no precision, FPR or AUC; +- weak, unknown and unlabeled examples are never negatives; +- an ineligible candidate cannot enter a split. + +**Splits:** the split report checks entity overlap with the typed grouping. + +**Baselines ready to plug in:** the deterministic detector (replay), the similarity rule +and the generator. Logistic regression and LightGBM only once labels exist. + +## 19. Experiment results + +**Source separability:** predicting which *frame* a row came from. This is not fraud +detection. + +| Covariate or family | AUC | +|---|---| +| value (univariate / LR) | 1.000 / 1.000 | +| direction (victim sends) | 0.982 | +| block (time) | 0.943 | +| token class | 0.766 | +| similarity | 0.629 | +| everything except value (LR, 5-fold) | 0.993 | + +The cross-validation is not grouped by campaign, so these values are optimistic. The +conclusion does not depend on that: almost every shape covariate alone nearly separates +the frames. + +## 20. Negative results + +- **Similarity does not separate the frames** (0.63), so it is not a shortcut here. +- **No usable hard negatives** exist under strict matching: 17 pairs. +- **The background frame looks like real attacks.** 7 of its 8 candidates have attack + signatures, so it is a poor source of legitimate examples. The plausible legitimate + shapes sit in one incident wallet (category E), which limits how far any result + generalizes. +- **The pool contains no candidate with a router signer** (category F is empty), so router + false positives cannot be studied locally. + +## 21. Resource usage + +| Step | Runtime | Peak RSS | Disk | +|---|---|---|---| +| Extraction pass 1 (uncategorized rows) | 734 s | 46 MiB | 4.0 MB of rows | +| Extraction pass 2 (context scan) | 2,350 s | 280 MiB | 102.5 MB SQLite (210,478 rows) | +| Study (pool, screen, matching, diagnostics, cohort) | 120 s | 418 MiB | 3.0 MB key + 0.03 MB sheet | + +RPC requests: **0**. Downloads: **0**. + +## 22. Data licensing + +**Kept local** (git-ignored): +- the archive-derived rows, context subset, cohort key and sheet; +- the study JSON. + +**Committed:** only code, tests and aggregate tables. + +**Open question:** whether per-item review labels or a matched benchmark built from +CC BY-NC-ND rows would be an adaptation. It remains unresolved, so everything per-item +stays local. This is not legal advice. + +## 23. Benchmark readiness + +See [ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md) §8. + +| Gate | Status | +|---|---| +| A candidate validity | pass | +| B historical correctness | pass for implemented features | +| C positive provenance | blocked by missing evidence | +| D negative-label validity | blocked by missing evidence | +| E source independence | pass (shortcuts identified, not resolved) | +| F leakage-safe splitting | blocked by missing evidence | +| G statistical adequacy | fail | +| H baseline comparability | blocked by missing evidence | +| I operational relevance | not yet evaluated | +| J deployment safety | pass | + +**Supervised training is not justified.** + +## 24. Remaining blockers + +| Blocker | Kind | +|---|---| +| No independent positive review (60 frozen items) | needs human reviewers | +| No confirmed legitimate examples (35 frozen candidates) | needs human reviewers | +| No wallet history for the archive frame | historical evidence (explorer at review time; no RPC authorized) | +| CC BY-NC-ND adaptation question | restricted source data | +| 95 review items cannot support per-subtype precision claims | statistical power | +| Engineering defects | none open (one test flaked once under load, see the final report) | + +## 25. Next scientific experiment + +**Experiment.** Two independent human reviewers review both frozen cohorts: the 60 +source positives and the 35 hard-negative candidates. They use the existing local app. +Packages: `cryptoguard ml review package --cohort … --reviewer A|B`. + +**Evidence it adds:** +- the first independently reviewed positives; +- the first independently reviewed legitimate look-alikes, if any exist; +- inter-reviewer agreement on both; +- how often the generator and source frames hold real attacks. + +**Cost:** 95 items × 2 reviewers at about 5 minutes each, about 16 reviewer-hours. 0 RPC +requests, no download. + +**What it cannot do:** reach gate G's 30 verified negatives on its own. If fewer than 30 +legitimate examples come back, the next step is a negative-only cohort drawn from the +4,940 unscreened archive candidates, using the same frozen procedure. That also needs no +RPC. diff --git a/ML_HARD_NEGATIVE_TABLES.md b/ML_HARD_NEGATIVE_TABLES.md new file mode 100644 index 0000000..0d7f397 --- /dev/null +++ b/ML_HARD_NEGATIVE_TABLES.md @@ -0,0 +1,100 @@ +# Hard-negative study tables (generated) + +Generated by `cryptoguard ml hard-negative-study` (hn-study/1) at commit `c68d3a4` (dirty tree). 0 RPC requests. Every candidate is `unlabeled_candidate`. + +## Candidate pool + +| Frame | Candidates | Wallets | Block range | Trusted token | +|---|---|---|---|---| +| archive_uncategorized | 8,651 | 4,190 | 15,063,932-20,207,934 | 8,651 | +| fixture_background | 8 | 3 | 23,881,913-24,184,546 | 2 | +| fixture_incident | 218 | 4 | 19,774,080-24,344,845 | 185 | + +### Structural categories (multi-label; not intent) + +| Frame | A | B | C | D | E | F | G | H | +|---|---|---|---|---|---|---|---|---| +| archive_uncategorized | 8651 | 0 | 0 | 0 | 0 | 0 | 8651 | 6070 | +| fixture_background | 0 | 6 | 0 | 8 | 7 | 0 | 0 | 2 | +| fixture_incident | 1 | 35 | 3 | 46 | 213 | 0 | 0 | 5 | + +## Contamination screen + +| Frame | exact_event | exact_tx | victim_lookalike | shared_infrastructure | related_campaign | weak_similarity | none | +|---|---|---|---|---|---|---|---| +| archive_uncategorized | 1 | 0 | 2136 | 1495 | 79 | 0 | 4940 | +| fixture_background | 0 | 0 | 0 | 0 | 0 | 0 | 8 | +| fixture_incident | 0 | 0 | 13 | 0 | 32 | 3 | 170 | + +| Frame | known_positive_overlap | potential_positive_overlap | no_known_overlap | insufficient_information | +|---|---|---|---|---| +| archive_uncategorized | 3632 | 79 | 4940 | 0 | +| fixture_background | 0 | 0 | 0 | 8 | +| fixture_incident | 13 | 32 | 168 | 5 | + +## Matching (archive candidates vs source positives) + +Positives: 1,409 (payoff-linked source positives minus the 60 reserved review items); candidates: 5,019. + +| Design | Keys | Matched positives | Matched candidates | Candidates without support | +|---|---|---|---|---| +| strict | year, victim_sends, token_trusted, value_bin, similarity_bin | 17 | 17 | 1,121 | +| relaxed_year_similarity | year, similarity_bin | 806 | 806 | 0 | + +Standardized mean differences (before matching): + +| Covariate | SMD | Missing (positives) | Missing (candidates) | +|---|---|---|---| +| block_millions | -2.477 | 0 | 0 | +| log10_value_usd | -6.134 | 745 | 0 | +| similarity_total | 0.484 | 0 | 0 | +| token_trusted | -1.506 | 0 | 0 | +| victim_sends | 7.222 | 0 | 0 | + +## Source separability (which frame a row came from; NOT fraud detection) + +| Covariate | Univariate separability AUC | +|---|---| +| block_millions | 0.943 | +| log10_value_usd | 1.000 | +| similarity_total | 0.629 | +| token_trusted | 0.766 | +| victim_sends | 0.982 | + +| Feature family | CV ROC-AUC (mean ± sd) | +|---|---| +| value_only | 1.000 ± 0.000 | +| similarity_only | 0.629 ± 0.010 | +| token_only | 0.766 ± 0.008 | +| direction_only | 0.982 ± 0.005 | +| time_only | 0.943 ± 0.005 | +| all_without_value | 0.993 ± 0.003 | + +5-fold stratified CV, logistic regression with missingness indicators; rows are not grouped by campaign, so these AUCs are optimistic; diagnostic only. + +## Review cohort + +`hard-negative-candidates/1`: 35 of 5,232 eligible items (2,664 groups). Frame SHA-256 `881f2faebdf3669d659cfb2a3fbbd87f27a50cd71e92c6889e34427c2ef3feea`, selection SHA-256 `ae9df36ab99750a35e884bf487e117e1f5c99f555a2beaf5ab2f30c11f6ddb57`. + +| Stratum | Items | Groups | Selected | Weight | +|---|---|---|---|---| +| archive_uncategorized, 2022, potential overlap no | 48 | 9 | 1 | 9.000 | +| archive_uncategorized, 2023, potential overlap no | 700 | 395 | 2 | 197.500 | +| archive_uncategorized, 2023, potential overlap yes | 25 | 20 | 1 | 20.000 | +| archive_uncategorized, 2024, potential overlap no | 4,192 | 2,195 | 19 | 115.526 | +| archive_uncategorized, 2024, potential overlap yes | 54 | 32 | 1 | 32.000 | +| fixture_background (one recorded wallet), 2024, potential overlap no | 1 | 1 | 1 | 1.000 | +| fixture_background (one recorded wallet), 2024, potential overlap no | 5 | 1 | 1 | 1.000 | +| fixture_background (one recorded wallet), 2024, potential overlap no | 2 | 1 | 1 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap no | 2 | 2 | 2 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap no | 1 | 1 | 1 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap yes | 30 | 1 | 1 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap no | 2 | 1 | 1 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap yes | 2 | 1 | 1 | 1.000 | +| fixture_incident (one recorded wallet), 2024, potential overlap no | 168 | 4 | 2 | 2.000 | + +## Background candidate volume (unlabeled) + +8 candidates on 9 recorded random wallets (27.0 wallet-days; 3 wallets with any): 296.3 per 1,000 wallet-days. unlabeled candidate volume on randomly drawn recorded wallets; not false alerts and not an Ethereum-wide rate. + +Runtime 119.9 s; peak RSS 418 MiB. diff --git a/ML_POISONING_TABLES.md b/ML_POISONING_TABLES.md index 235fde1..73227e9 100644 --- a/ML_POISONING_TABLES.md +++ b/ML_POISONING_TABLES.md @@ -1,7 +1,7 @@ # ML Phase 11.2 tables Generated by `cryptoguard ml poisoning-report` from local artifacts (0 RPC requests). -Git `873169068909dbdf70d07a8b3cb27079aa9ec311`; runtime 5.74 s (per-window generation memory is in the JSON report). +Git `c68d3a467dc63b1911d089540198367b66b3aa9f`; runtime 6.08 s (per-window generation memory is in the JSON report). ## Poison-Hunter sample diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 66c7e2f..d22e456 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -7,7 +7,10 @@ reconciliation (§7, Phase 11.3) are done. The next experiment is in 60 is frozen (§26). Phase 11.4 verified it, audited its design and built the independent annotation workflow; it now waits for two human reviewers ([ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md), -[ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md)). Data model and labels: +[ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md)). Phase 11.5 added a screened +pool of 8,877 unlabeled hard-negative candidates and a second frozen cohort of 35 +([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). Both cohorts wait for the same +two reviewers. Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). @@ -39,7 +42,7 @@ See ML_POISONING_DATASET.md §2: - **Output:** an experimental ranking with coverage, not a theft probability, never a finding. -## 3. Candidate generation (`ml/candidates.py`, `candidates/1`) +## 3. Candidate generation (`ml/candidates.py`, `candidates/1`; now `candidates/2`) **Rules.** The rules are structural and independent of the production detector and of any model: diff --git a/README.md b/README.md index 2095337..3804b3a 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ evidence of common ownership ([CAMPAIGN_EVALUATION.md](CAMPAIGN_EVALUATION.md)). | Network, structural and activity-rate analyses (graph propagation, spectral features, robust burst statistics) over stored observations, coverage-aware and point in time | Experimental, **off by default**: evaluated with no measurable gain over the existing detector; available in shadow mode only (see [DETECTION_METHODS.md](DETECTION_METHODS.md)) | | Wallet-signed transactions (incl. native-ETH payments) located by nonce search in snapshots and scans; used by the poisoning detector and the graph; degrades to explicit "unlocated" counts without archive state | Implemented | | Phishing-transaction classifier (LightGBM) trained on independently labelled public data (PTXPhish, NDSS 2025) with point-in-time chain features, time-ordered and account-disjoint splits, rule and trivial baselines, run ledger, approval-gated model registry, offline generalization audit, wallet-history feature infrastructure ([ML.md](ML.md), [ML_GENERALIZATION_AUDIT.md](ML_GENERALIZATION_AUDIT.md)) | Experimental, **research-only** (`ml` extra): AP 0.999 on a development benchmark (not an untouched holdout), false-positive rate 7/43 from 12 benign senders (cluster interval 4% to 36%); the API does not score with it; never creates findings | -| Wallet-centric address-poisoning research: typed event and label model, offline payment verification, candidate rules, point-in-time features, a safe streaming reconciliation of the Poison-Hunter and Tsuchiya et al. (USENIX Security 2025) datasets, and a frozen 60-item sample with a local, blinded two-reviewer annotation workflow ([ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md), [ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md)) | Experimental, **research-only**: no model, because the available labels cannot support a valid supervised benchmark; no human review has happened yet; third-party data stays local (CC BY-NC-ND / unlicensed) | +| Wallet-centric address-poisoning research: typed event and label model, offline payment verification, candidate rules, point-in-time features, a safe streaming reconciliation of the Poison-Hunter and Tsuchiya et al. (USENIX Security 2025) datasets, a frozen 60-item sample with a local, blinded two-reviewer annotation workflow, and a screened pool of unlabeled hard-negative candidates with a second frozen cohort ([ML_CROSS_DATASET_VALIDATION.md](ML_CROSS_DATASET_VALIDATION.md), [ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md), [ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)) | Experimental, **research-only**: no model, because the available labels cannot support a valid supervised benchmark; no human review has happened yet; third-party data stays local (CC BY-NC-ND / unlicensed) | | Scheduled monitoring loop, native ETH *received*, NFT/Permit2 approvals | Not yet | ## Quick start From 3774c7011e2e22282eecf3a265b87505ff925999 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 13:59:52 +0300 Subject: [PATCH 29/92] fix(db): report a locked lease table as retryable LeaseBusyError When other writers kept SQLite locked past the driver's busy timeout, LeaseStore.acquire let a raw OperationalError escape: indistinguishable from a crash (HTTP 500), and the most plausible way a contender exits non-zero under heavy I/O. It now raises LeaseBusyError (503, retryable); 'held' still returns None and at most one owner wins. The contention test reports each child's outcome or exception and asserts safety (never two owners) separately from liveness; a deterministic test holds a write lock and checks the busy path. The original flake was not reproduced in 16 rounds under CPU and fsync-heavy disk load. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/database/leases.py | 30 +++++++++++++++-- tests/integration/test_leases.py | 52 +++++++++++++++++++++++++----- 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/src/cryptoguard/database/leases.py b/src/cryptoguard/database/leases.py index b5df74b..55edf85 100644 --- a/src/cryptoguard/database/leases.py +++ b/src/cryptoguard/database/leases.py @@ -27,7 +27,7 @@ from datetime import UTC, datetime, timedelta from sqlalchemy import delete, select, update -from sqlalchemy.exc import IntegrityError +from sqlalchemy.exc import IntegrityError, OperationalError from sqlalchemy.orm import Session from cryptoguard.core.errors import CryptoGuardError @@ -43,6 +43,21 @@ class LeaseLostError(CryptoGuardError): retryable = True +class LeaseBusyError(CryptoGuardError): + """The database stayed locked by other writers past the driver's busy timeout, so it is + unknown whether the lease is free. Distinct from "held" (``acquire`` returns None) and + from a crash; the caller may retry.""" + + code = "operation_lease_busy" + http_status = 503 + retryable = True + + +def _locked(exc: OperationalError) -> bool: + text = str(exc.orig if exc.orig is not None else exc).lower() + return "database is locked" in text or "database is busy" in text + + @dataclass(frozen=True) class Lease: key: str @@ -56,7 +71,18 @@ def __init__(self, repository: ObservationRepository) -> None: self._sessions = repository._sessions def acquire(self, key: str, ttl_seconds: float, *, now: datetime | None = None) -> Lease | None: - """Take the lease for ``key``, or return None if another live owner holds it.""" + """Take the lease for ``key``, or return None if another live owner holds it. Raises + ``LeaseBusyError`` when the database stays locked past the busy timeout.""" + try: + return self._acquire(key, ttl_seconds, now=now) + except OperationalError as exc: + if _locked(exc): + raise LeaseBusyError( + "The lease table is locked by other writers; retry shortly." + ) from exc + raise + + def _acquire(self, key: str, ttl_seconds: float, *, now: datetime | None) -> Lease | None: now = now or datetime.now(UTC) expires = now + timedelta(seconds=ttl_seconds) token = uuid.uuid4().hex diff --git a/tests/integration/test_leases.py b/tests/integration/test_leases.py index 8087e5f..ed348cd 100644 --- a/tests/integration/test_leases.py +++ b/tests/integration/test_leases.py @@ -30,11 +30,14 @@ def _repo(url: str) -> HistoryRepository: def _contend(url: str, start: float, results: mp.Queue) -> None: # runs in a child process - repo = _repo(url) - while time.time() < start: # line every process up on the same instant - time.sleep(0.001) - lease = LeaseStore(repo).acquire(KEY, 30) - results.put(os.getpid() if lease is not None else None) + try: + repo = _repo(url) + while time.time() < start: # line every process up on the same instant + time.sleep(0.001) + lease = LeaseStore(repo).acquire(KEY, 30) + results.put(("won" if lease is not None else "lost", os.getpid())) + except Exception as exc: # reported to the parent: a failure must say what happened + results.put(("error", f"{type(exc).__name__}: {exc}")) CRASH_TTL = 8.0 # generous: process teardown on a loaded machine can take seconds @@ -61,9 +64,42 @@ def test_only_one_process_wins_a_simultaneous_acquire(db_url: str) -> None: p.start() for p in procs: p.join(timeout=60) - assert p.exitcode == 0 - winners = [r for r in (results.get(timeout=5) for _ in procs) if r is not None] - assert len(winners) == 1 + outcomes = [results.get(timeout=5) for _ in procs] + winners = [o for o in outcomes if o[0] == "won"] + assert len(winners) <= 1, outcomes # safety: never two owners, whatever else happens + errors = [o for o in outcomes if o[0] == "error"] + assert not errors, errors # liveness: every contender got an answer + assert len(winners) == 1, outcomes + assert all(p.exitcode == 0 for p in procs), [p.exitcode for p in procs] + + +def test_a_locked_database_is_reported_as_busy_not_as_free_or_held(tmp_path: Path) -> None: + """When other writers keep the database locked past the busy timeout, acquire raises the + retryable LeaseBusyError instead of returning None ("held") or crashing.""" + import sqlite3 + + from sqlalchemy import create_engine + + from cryptoguard.database.leases import LeaseBusyError + from cryptoguard.database.repository import _transactional_sqlite + + path = tmp_path / "busy.db" + _repo(f"sqlite:///{path.as_posix()}") # schema + engine = create_engine( + f"sqlite:///{path.as_posix()}", connect_args={"timeout": 0.2, "check_same_thread": False} + ) + _transactional_sqlite(engine) + store = LeaseStore(HistoryRepository(engine)) + blocker = sqlite3.connect(path, isolation_level=None) + blocker.execute("BEGIN IMMEDIATE") # another writer holds the write lock + try: + with pytest.raises(LeaseBusyError) as err: + store.acquire(KEY, 30) + assert err.value.retryable + finally: + blocker.execute("ROLLBACK") + blocker.close() + assert store.acquire(KEY, 30) is not None # free again once the writer is gone def test_lease_of_a_crashed_process_is_recovered_after_expiry(db_url: str) -> None: From 240ba9b132537d8e60f7faf159266227a5068b15 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 13:59:56 +0300 Subject: [PATCH 30/92] feat(ml): offline evidence packets, protocol amendment 2, training cohort, label policy evidence.py builds deterministic pre-cutoff packets from local data only (sheet in, never the key; no flags, intended address or payoffs; no similarity computed so reviewers identify the counterparty themselves); the review app serves them only when their hash is registered. Amendment-2 decisions record later-payment and third-party-label exposure, offline-panel use, reason codes and evidence citations. Adds a synthetic training cohort, sessions that expire, submission checks and a key-free agreement report, the label policy (seven statuses, strict binary eligibility), an inactive pre-registered experiment spec, FPR power planning, both cohorts as one protected holdout, and source identifiers refused as features. candidates/2 now buckets chosen counterparties by suffix (exact): 10,000 transfers in 0.13 s instead of 13 s, identical output. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/annotation.py | 50 ++- src/cryptoguard/ml/benchmark.py | 13 + src/cryptoguard/ml/candidates.py | 9 +- src/cryptoguard/ml/cli.py | 41 +- src/cryptoguard/ml/evaluation.py | 18 +- src/cryptoguard/ml/evidence.py | 362 +++++++++++++++++ src/cryptoguard/ml/experiment_spec.py | 139 +++++++ src/cryptoguard/ml/label_policy.py | 75 ++++ src/cryptoguard/ml/power.py | 55 +++ src/cryptoguard/ml/review_app/app.css | 10 + src/cryptoguard/ml/review_app/app.js | 107 +++++ src/cryptoguard/ml/review_app/index.html | 21 + src/cryptoguard/ml/review_server.py | 38 +- src/cryptoguard/ml/submissions.py | 111 ++++++ src/cryptoguard/ml/training.py | 228 +++++++++++ src/cryptoguard/ml/unblind.py | 11 + tests/review_fixtures.py | 5 + tests/unit/test_ml_cohort.py | 1 + tests/unit/test_ml_validation_readiness.py | 443 +++++++++++++++++++++ 19 files changed, 1725 insertions(+), 12 deletions(-) create mode 100644 src/cryptoguard/ml/evidence.py create mode 100644 src/cryptoguard/ml/experiment_spec.py create mode 100644 src/cryptoguard/ml/label_policy.py create mode 100644 src/cryptoguard/ml/power.py create mode 100644 src/cryptoguard/ml/submissions.py create mode 100644 src/cryptoguard/ml/training.py create mode 100644 tests/unit/test_ml_validation_readiness.py diff --git a/src/cryptoguard/ml/annotation.py b/src/cryptoguard/ml/annotation.py index 7c6fa0c..91a6260 100644 --- a/src/cryptoguard/ml/annotation.py +++ b/src/cryptoguard/ml/annotation.py @@ -32,7 +32,8 @@ ANNOTATION_SCHEMA = "poisoning-annotation/1" SUBMISSION_SCHEMA = "poisoning-submission/1" -PROTOCOL = "review-protocol/1+amendment-1" +PROTOCOL = "review-protocol/1+amendment-2" +Protocol = Literal["review-protocol/1+amendment-1", "review-protocol/1+amendment-2"] LOG = "annotations.log.jsonl" SUBMISSION = "submission.json" LOCK = ".lock" @@ -51,6 +52,22 @@ Initiator = Literal["wallet", "third_party", "unknown"] Exposure = Literal["no", "yes", "unsure"] Confidence = Literal["high", "medium", "low"] +ReasonCode = Literal[ + "lookalike_of_earlier_counterparty", + "imitation_token_contract", + "zero_value_transfer", + "dust_value", + "third_party_initiated_transfer", + "wallet_initiated_transfer", + "known_relationship", + "same_owner_evidence", + "ordinary_payment_pattern", + "no_earlier_counterparty_found", + "history_unavailable", + "contradictory_observations", + "other", +] +REF = re.compile(r"^0x([0-9a-fA-F]{40}|[0-9a-fA-F]{64})$") REVIEWER_ID = re.compile(r"^[A-Za-z0-9_-]{1,32}$") ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$") @@ -73,7 +90,7 @@ class Annotation(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) schema_version: Literal["poisoning-annotation/1"] = "poisoning-annotation/1" - protocol: Literal["review-protocol/1+amendment-1"] = "review-protocol/1+amendment-1" + protocol: Protocol = "review-protocol/1+amendment-2" item: int = Field(ge=1) victim_event_id: str = Field(pattern=r"^[0-9a-f]{16}$") reviewer: str @@ -96,6 +113,12 @@ class Annotation(BaseModel): viewed_after_cutoff: Exposure saw_external_label: Exposure saw_source_or_model_output: bool + # Amendment 2: required from then on (None only in amendment-1 records). + used_offline_evidence: bool | None = None + saw_later_victim_payment: Exposure | None = None + third_party_label_influenced: Exposure | None = None + reason_codes: tuple[ReasonCode, ...] = () + evidence_refs: tuple[str, ...] = Field(default=(), max_length=20) # tx hashes, addresses rationale: str = Field(min_length=1, max_length=4000) notes: str = Field(default="", max_length=4000) @@ -129,6 +152,25 @@ def evidence_problems(a: Annotation) -> list[str]: out.append( "a prior counterparty address needs prior_counterparty observed or contradictory" ) + if a.protocol == "review-protocol/1+amendment-2": + missing = [ + name + for name in ( + "used_offline_evidence", + "saw_later_victim_payment", + "third_party_label_influenced", + ) + if getattr(a, name) is None + ] + if missing: + out.append(f"amendment 2 requires: {', '.join(missing)}") + if a.decision in ("confirmed_poisoning_attempt", "confirmed_legitimate_interaction") and ( + not a.reason_codes + ): + out.append("a confirmed decision needs at least one reason code") + bad = [r for r in a.evidence_refs if not REF.match(r)] + if bad: + out.append(f"evidence references must be 0x addresses or tx hashes: {bad[:3]}") words = len(a.rationale.split()) d = a.decision if d == "confirmed_poisoning_attempt": @@ -354,7 +396,7 @@ class Submission(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) schema_version: Literal["poisoning-submission/1"] - protocol: Literal["review-protocol/1+amendment-1"] + protocol: Protocol reviewer: str selection_sha256: str sheet_sha256: str @@ -410,7 +452,7 @@ class ReplacementRecord(BaseModel): reviewers_exposed_to_original: tuple[str, ...] recorded_by: str recorded_at: str - protocol: Literal["review-protocol/1+amendment-1"] = "review-protocol/1+amendment-1" + protocol: Protocol = "review-protocol/1+amendment-2" def validate_replacements( diff --git a/src/cryptoguard/ml/benchmark.py b/src/cryptoguard/ml/benchmark.py index 82bdd4a..14cf737 100644 --- a/src/cryptoguard/ml/benchmark.py +++ b/src/cryptoguard/ml/benchmark.py @@ -153,3 +153,16 @@ def readiness( {"criterion": "10 stable evaluation protocol", "passed": EVALUATION_PROTOCOL is not None, "detail": "not defined until 3 and 4 pass"}, ] # fmt: skip + + +def holdout_from_sheets(sheets: list[Path], state: Path | None = None) -> Holdout: + """Both frozen review cohorts (or any set of sheets) as one protected holdout.""" + parts = [holdout_from_sheet(s) for s in sheets] + h = Holdout( + frozenset().union(*(p.event_ids for p in parts)), + frozenset().union(*(p.entities for p in parts)), + ) + if state is not None and state.exists(): + saved = json.loads(state.read_text(encoding="utf-8")) + h.status, h.history = saved["status"], saved["history"] + return h diff --git a/src/cryptoguard/ml/candidates.py b/src/cryptoguard/ml/candidates.py index ca294a2..adc6de3 100644 --- a/src/cryptoguard/ml/candidates.py +++ b/src/cryptoguard/ml/candidates.py @@ -128,7 +128,9 @@ def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: choices = sorted((e for e in events if _chose(e)), key=lambda e: e.position) status = "complete" if coverage.complete else "partial" out: list[Candidate] = [] - chosen: dict[str, int] = {} # grows as the pass moves forward: strictly earlier choices + # Strictly earlier choices, bucketed by their last MIN_SUFFIX characters: ``similar`` + # needs at least that suffix in common, so no other bucket can ever match (exact). + chosen: dict[str, dict[str, int]] = defaultdict(dict) next_choice = 0 for t in sorted( fixture.transfers, key=lambda t: (t.block_number, t.transaction_index, t.log_index) @@ -136,7 +138,8 @@ def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: position = (t.block_number, t.transaction_index, t.log_index) while next_choice < len(choices) and choices[next_choice].position < position: e = choices[next_choice] - chosen[e.counterparty.lower()] = e.block + k = e.counterparty.lower() + chosen[k[-MIN_SUFFIX:]][k] = e.block next_choice += 1 incoming = t.recipient.lower() == wallet outgoing = t.sender.lower() == wallet @@ -146,7 +149,7 @@ def generate(fixture: ReplayFixture, *, chain_id: int = 1) -> list[Candidate]: value = int(t.value) party = (t.sender if incoming else t.recipient).lower() match = max( - ((k, m) for k in chosen if (m := similar(party, k)) is not None), + ((k, m) for k in chosen.get(party[-MIN_SUFFIX:], {}) if (m := similar(party, k))), key=lambda km: (sum(km[1]), km[1][1], km[0]), default=None, ) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 78aab97..ca17f5b 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -404,7 +404,19 @@ def _add_review_parser(ml: argparse._SubParsersAction[argparse.ArgumentParser]) ub.add_argument("--adjudication", type=Path) ub.add_argument("--sample", type=Path, default=None) ub.add_argument("--work", type=Path, default=None) - for p in (sub.choices["verify"], pk, rp, ub): + be = sub.add_parser("build-evidence", help="offline pre-cutoff evidence packets (maintainer)") + be.add_argument("--sample", type=Path, default=None) + be.add_argument("--work", type=Path, default=None) + tp = sub.add_parser("training-package", help="synthetic training items for a reviewer") + tp.add_argument("--reviewer", required=True) + tp.add_argument("--out", type=Path, required=True) + ag = sub.add_parser("agreement", help="agreement between finalized submissions (no key)") + ag.add_argument("--submission", type=Path, action="append", required=True) + ag.add_argument("--sample", type=Path, default=None) + ck = sub.add_parser("check-submission", help="validate one submission file (no key)") + ck.add_argument("submission", type=Path) + ck.add_argument("--sample", type=Path, default=None) + for p in (sub.choices["verify"], pk, rp, ub, be, ag, ck): p.add_argument( "--cohort", default="review-sample/1", @@ -451,6 +463,33 @@ def _review(args: argparse.Namespace) -> int: return 0 if cmd == "serve": return _review_serve(args) + if cmd == "build-evidence": + from cryptoguard.ml.evidence import build_cohort + + dbs = [ML_DIR / "poisoning" / "archive_subset.sqlite", + HN_DIR / "context_subset.sqlite"] # fmt: skip + m = build_cohort(args.sample, args.work / "evidence", archive_dbs=dbs, cohort=cohort) + print(f"{m['items']} packets for {cohort}; sha256 {m['packets_sha256']} " + f"(0 RPC requests).") # fmt: skip + return 0 + if cmd == "training-package": + from cryptoguard.ml.training import make_package as training_package + + out = training_package(args.reviewer, args.out) + print(f"Training package for {args.reviewer} in {out} (synthetic items only).") + return 0 + if cmd == "agreement": + from cryptoguard.ml.submissions import agreement_report + + report = agreement_report(args.submission, args.sample, cohort=cohort) + print(json.dumps(report, indent=1)) + return 0 + if cmd == "check-submission": + from cryptoguard.ml.submissions import check_submission + + problems = check_submission(args.submission, args.sample, cohort=cohort) + print("valid" if not problems else "\n".join(problems)) + return 0 if not problems else 1 if cmd == "status": from cryptoguard.ml.review_server import ReviewApp diff --git a/src/cryptoguard/ml/evaluation.py b/src/cryptoguard/ml/evaluation.py index 9c87059..6db9460 100644 --- a/src/cryptoguard/ml/evaluation.py +++ b/src/cryptoguard/ml/evaluation.py @@ -32,7 +32,23 @@ CONTRACT_VERSION = "benchmark-example/1" TRUTH = {"verified_attempt": 1, "verified_legitimate": 0} -FORBIDDEN_FEATURE_WORDS = ("label", "outcome", "payoff", "loss", "score", "prediction", "paid") +FORBIDDEN_FEATURE_WORDS = ( + "label", + "outcome", + "payoff", + "loss", + "score", + "prediction", + "paid", + # source construction, not behaviour (Phase 11.5 separability findings) + "source", + "dataset", + "cohort", + "frame", + "row_index", + "line_number", + "file", +) Split = Literal["train", "validation", "test"] diff --git a/src/cryptoguard/ml/evidence.py b/src/cryptoguard/ml/evidence.py new file mode 100644 index 0000000..ee29c07 --- /dev/null +++ b/src/cryptoguard/ml/evidence.py @@ -0,0 +1,362 @@ +"""Offline, pre-cutoff evidence packets for reviewers (``evidence-packets/1``, Phase 11.6). + +For each item of a frozen reviewer sheet, the builder gathers what the *local* recorded +data show strictly before the item's block. The block is the observation cutoff; a +same-block row is included only when the recorded order proves it came first. + +The builder reads the reviewer sheet, never the unblinding key. From the archive it reads +only block, transaction, token, sender, receiver and value. It never reads the source's +category flags, its ``intended`` (imitated) address or its payoff markings. It computes no +similarity: reviewers find the imitated counterparty themselves, so their identification +stays independent of the source's matching. No network access. + +Sections: +1. candidate event; +2. address relationship; +3. transaction semantics; +4. wallet history; +5. token provenance; +6. historical graph context; +7. coverage and uncertainty. + +Unknown values are ``None`` or an explicit status, never 0 or False. +""" + +from __future__ import annotations + +import hashlib +import json +import sqlite3 +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal + +from cryptoguard.ml.payments import TRUSTED_TOKENS + +EVIDENCE_VERSION = "evidence-packets/1" +MAX_HISTORY = 50 +PACKETS = "evidence_packets.jsonl" +Status = Literal[ + "complete_for_declared_scope", + "partial_history", + "source_selected_rows_only", + "missing_transaction_details", + "missing_receipt", + "unknown_signer", + "unknown_token_legitimacy", + "unsupported_contract_execution", + "insufficient_evidence", +] +ARCHIVE_COLUMNS = "line, block, tx, token, sender, receiver, value" # never flags or intended + + +class EvidenceError(ValueError): + """The requested cutoff or item disagrees with the recorded data.""" + + +@dataclass(frozen=True) +class Row: + """One recorded transfer, label-free. ``order`` sorts rows within a block when the + source records it (fixtures: transaction and log index); the archive leaves it None.""" + + block: int + order: tuple[int, int] | None + tx: str + token: str + sender: str + receiver: str + value: str + signer: str | None + source: str # "recorded_window" or "archive" + + +def _archive_rows(dbs: Sequence[Path], where: str, args: Sequence[Any]) -> list[Row]: + seen: dict[int, Row] = {} + for db in dbs: + if not db.exists(): + continue + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + for line, block, tx, token, s, r, value in con.execute( + f"select {ARCHIVE_COLUMNS} from transfers where {where}", # noqa: S608 - fixed text + args, + ): + seen.setdefault( + line, + Row( + block, + None, + tx, + token.lower(), + s.lower(), + r.lower(), + _num(value), + None, + "archive", + ), + ) + con.close() + return sorted(seen.values(), key=lambda x: (x.block, x.tx, x.sender, x.receiver)) + + +def _num(v: Any) -> str: + if v is None or (isinstance(v, float) and v != v): + return "unknown" + return format(v, ".10g") if isinstance(v, float) else str(v) + + +def _fixture_rows(fx: Any) -> list[Row]: + rows = [ + Row( + t.block_number, + (t.transaction_index, t.log_index), + t.transaction_hash.lower(), + t.token.lower(), + t.sender.lower(), + t.recipient.lower(), + str(t.value), + t.tx_sender.lower() if t.tx_sender else None, + "recorded_window", + ) + for t in fx.transfers + ] + rows += [ + Row( + t.block_number, + (t.transaction_index, -1), + t.transaction_hash.lower(), + "native-eth", + fx.wallet.lower(), + (t.to or "").lower(), + str(t.value), + fx.wallet.lower(), + "recorded_window", + ) + for t in fx.wallet_transactions + if t.to + ] + return sorted(rows, key=lambda x: (x.block, x.order or (0, 0), x.tx)) + + +def _before(r: Row, cutoff: int, position: tuple[int, int] | None) -> bool: + if r.block != cutoff: + return r.block < cutoff + return position is not None and r.order is not None and r.order < position + + +def packet( + item: Mapping[str, Any], + *, + rows: Sequence[Row], + source: str | None, + window: tuple[int, int] | None, + max_history: int = MAX_HISTORY, +) -> dict[str, Any]: + """One item's packet from rows already restricted to its wallet and address.""" + wallet, addr = item["wallet"].lower(), item["address_under_review"].lower() + tx, cutoff = item["transaction"].lower(), int(item["block"]) + candidate = [r for r in rows if r.tx == tx and {wallet, addr} <= {r.sender, r.receiver}] + statuses: list[Status] = [] + if candidate: + blocks = {r.block for r in candidate} + if blocks != {cutoff}: + raise EvidenceError( + f"item {item['item']}: transaction at blocks {sorted(blocks)}, " + f"sheet cutoff {cutoff}" + ) + position = candidate[0].order + else: + statuses.append("missing_transaction_details") + position = None + history = [r for r in rows if wallet in (r.sender, r.receiver) and _before(r, cutoff, position)] + graph = [ + r + for r in rows + if addr in (r.sender, r.receiver) + and wallet not in (r.sender, r.receiver) + and _before(r, cutoff, position) + ] + prior_pair = [r for r in history if addr in (r.sender, r.receiver)] + signers = {r.signer for r in candidate} + if candidate and None in signers: + statuses.append("unknown_signer") + tokens = sorted({r.token for r in candidate}) + if any(t not in TRUSTED_TOKENS for t in tokens): + statuses.append("unknown_token_legitimacy") + if source == "archive": + statuses.append("source_selected_rows_only") + if not history: + statuses.append("partial_history") # no row of this wallet before the cutoff + elif source == "recorded_window": + statuses.append("complete_for_declared_scope") + if source is None: + statuses.append("insufficient_evidence") + + def view(r: Row) -> dict[str, Any]: + return { + "block": r.block, + "transaction": r.tx, + "token": r.token, + "from": r.sender, + "to": r.receiver, + "value_base_units": r.value, + } + + return { + "schema_version": EVIDENCE_VERSION, + "item": item["item"], + "victim_event_id": item["victim_event_id"], + "cutoff": { + "block": cutoff, + "rule": "rows strictly before this block; same-block rows only when the recorded " + "order proves they came earlier", + }, + "candidate_event": [ + view(r) | {"direction": "wallet sends" if r.sender == wallet else "wallet receives"} + for r in candidate + ], + "address_relationship": { + "earlier_rows_between_wallet_and_address": len(prior_pair), + "note": "find the earlier counterparty yourself in the wallet history below; no " + "similarity is computed here", + }, + "transaction_semantics": { + "execution": "succeeded (a Transfer log was recorded)" if candidate else None, + "signer": ( + None + if not candidate or None in signers + else ("the wallet" if signers == {wallet} else sorted(signers)) + ), + "zero_value": any(r.value == "0" for r in candidate) if candidate else None, + }, + "token_provenance": [ + {"token": t, "on_reviewed_token_list": True if t in TRUSTED_TOKENS else None} + for t in tokens + ], + "wallet_history": { + "rows_before_cutoff": len(history), + "shown": [view(r) for r in history[-max_history:]], + "window": list(window) if window else None, + }, + "graph_context": ( + { + "earlier_rows_of_address_with_other_wallets": len(graph), + "distinct_other_wallets": len( + {r.receiver if r.sender == addr else r.sender for r in graph} + ), + } + if source == "archive" + else None # a recorded window holds only this wallet's transfers + ), + "coverage": { + "source": source, + "statuses": statuses, + "explanation": _explain(source), + }, + } + + +def _explain(source: str | None) -> str: + if source == "recorded_window": + return ( + "Every transfer of this wallet inside the recorded block window, and nothing " + "before the window." + ) + if source == "archive": + return ( + "Only rows the research dataset kept (those involving look-alike addresses): " + "ordinary activity is missing. Use a block explorer for the full history, up " + "to the cutoff block." + ) + return "No local record of this wallet. Use a block explorer, up to the cutoff block." + + +def build( + sheet: Iterable[Mapping[str, Any]], + *, + archive_dbs: Sequence[Path], + fixtures: Sequence[Any], + max_history: int = MAX_HISTORY, +) -> list[dict[str, Any]]: + """Packets for every sheet item, in item order. Deterministic; reads no key.""" + out = [] + for item in sorted(sheet, key=lambda i: i["item"]): + wallet, addr = item["wallet"].lower(), item["address_under_review"].lower() + block = int(item["block"]) + fx = next( + ( + f + for f in fixtures + if f.wallet.lower() == wallet and f.from_block <= block <= f.to_block + ), + None, + ) + if fx is not None: + rows = [r for r in _fixture_rows(fx) if {wallet, addr} & {r.sender, r.receiver}] + out.append( + packet( + item, + rows=rows, + source="recorded_window", + window=(fx.from_block, fx.to_block), + max_history=max_history, + ) + ) + continue + rows = _archive_rows( + archive_dbs, "sender in (?, ?) or receiver in (?, ?)", (wallet, addr, wallet, addr) + ) + out.append( + packet( + item, + rows=rows, + source="archive" if rows else None, + window=None, + max_history=max_history, + ) + ) + return out + + +def dumps(packets: Sequence[Mapping[str, Any]]) -> bytes: + return b"".join(json.dumps(p, sort_keys=True).encode() + b"\n" for p in packets) + + +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def build_cohort( + sample_dir: Path, out_dir: Path, *, archive_dbs: Sequence[Path], cohort: str +) -> dict[str, Any]: + """Build, write and describe the packets of one frozen cohort. The frozen sheet is + verified first; the output goes to ``out_dir``, never into the frozen directory.""" + from cryptoguard.ml import review_sample as rs + from cryptoguard.ml.annotation import atomic_write + from cryptoguard.ml.cross_dataset import git_state + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + + rs.verify_frozen(sample_dir, cohort=cohort, with_key=False) + fixtures = [c.fixture for c in load_cases() if c.fixture] + [ + b.fixture for b in load_background() if b.fixture + ] + packets = build( + rs.read_sheet(sample_dir / rs.SHEET), archive_dbs=archive_dbs, fixtures=fixtures + ) + data = dumps(packets) + out_dir.mkdir(parents=True, exist_ok=True) + atomic_write(out_dir / PACKETS, data) + manifest = { + "version": EVIDENCE_VERSION, + "cohort": cohort, + "sheet_sha256": rs.COHORTS[cohort][rs.SHEET], + "packets_sha256": sha256(data), + "inputs": {db.name: rs.file_sha256(db) for db in archive_dbs if db.exists()} + | {f"fixture:{f.case_id}": f.sha256() for f in fixtures}, + "items": len(packets), + "git": git_state(), + "rpc_requests": 0, + } + atomic_write(out_dir / "evidence_manifest.json", json.dumps(manifest, indent=1).encode()) + return manifest diff --git a/src/cryptoguard/ml/experiment_spec.py b/src/cryptoguard/ml/experiment_spec.py new file mode 100644 index 0000000..a9bbd78 --- /dev/null +++ b/src/cryptoguard/ml/experiment_spec.py @@ -0,0 +1,139 @@ +"""Pre-registered specification of the first supervised ``poisoning-attempt/1`` experiment +(Phase 11.6). It stays **inactive** until ``activation_check`` passes on real, independently +reviewed labels. Synthetic labels may exercise the code but never activate it. + +Everything a result depends on is fixed here, before any label exists: +- the prediction unit, cutoff, target and eligibility; +- the split, threshold rule, metrics and calibration; +- the baselines, feature groups and resource budget. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from cryptoguard.ml.label_policy import POLICY_VERSION + +SPEC_VERSION = "poisoning-attempt-supervised/1" +MIN_PER_CLASS = 30 # events.quality_gates gate B +MIN_GROUPS_PER_CLASS = 5 # gate D +FORBIDDEN_COLUMN_WORDS = ( + "label", + "source", + "dataset", + "cohort", + "frame", + "row", + "line", + "file", + "outcome", + "payoff", + "loss", + "score", + "screen", +) + +FEATURE_GROUPS: dict[str, tuple[str, ...]] = { + "similarity_only": ( + "prefix_to_imitated", + "suffix_to_imitated", + "plausible_impersonated", + "recipient_lookalike_of_known", + "recipient_max_affix_to_known", + ), + "transaction_only": ( + "value_is_zero", + "token_trusted", + "subtype_dust", + "subtype_fake_token", + "subtype_other", + "subtype_spoofed_transfer_from", + "subtype_zero_value", + ), + "wallet_history_only": ( + "prior_payments_to_recipient", + "prior_interactions_with_recipient", + "distinct_prior_recipients", + "recent_new_recipient_share", + "unsolicited_events_with_recipient", + "history_available", + "history_partial", + "observed_blocks", + ), + "temporal_only": ( + "blocks_since_first_interaction", + "blocks_since_last_interaction", + "blocks_since_imitated_chosen", + "recent_unsolicited_in", + ), + "graph_context_only": ( + "lookalike_victims_before", + "signer_victims_before", + "lookalike_plantings_observed", + ), +} +FEATURE_GROUPS["combined"] = tuple(c for g in list(FEATURE_GROUPS.values()) for c in g) + +SPEC: dict[str, Any] = { + "version": SPEC_VERSION, + "status": "inactive", + "prediction_unit": "victim-event: one candidate transfer to or from one wallet", + "cutoff": "after the candidate's transaction executes, before anything later in its block", + "target": f"{POLICY_VERSION} strict binary: reviewed_attack=1, reviewed_legitimate=0", + "eligibility": "candidates/2 outputs with complete or partial recorded history; " + "known-positive overlaps never serve as negatives", + "populations": { + "train": "reviewed items outside both frozen review cohorts", + "validation": "grouped-temporal split of the training population", + "test": "a later, untouched set; the frozen cohorts count only if never used in " + "development (benchmark.Holdout)", + }, + "split": "grouped-temporal/1 with typed-groups/1 entities (victim, lookalike, planting " + "tx, signer, imitated, counterfeit token); public tokens and routers never link", + "threshold": "chosen on validation only: the highest recall with FPR <= 5%", + "primary_metric": "average precision on test, reported with recall at FPR <= 5%", + "secondary_metrics": [ + "precision", + "recall", + "FPR", + "ROC-AUC", + "precision at review capacity 50", + "candidate recall (separately)", + "latency", + ], + "calibration": "reliability curve and Brier score only with >= 100 reviewed items per class", + "baselines": [ + "detectors.poisoning (production rule)", + "similarity heuristic (candidates.similar)", + "transaction-shape heuristic (subtype)", + "wallet-history heuristic (no prior payment to the recipient)", + "logistic regression", + "LightGBM", + ], + "feature_groups": FEATURE_GROUPS, + "resource_budget": "CPU only, < 2 GB RAM, < 2 minutes per fit (larger needs approval)", + "no_gnn": "graph context enters as tabular features; no GNN without a new hypothesis", +} + + +def forbidden_columns(columns: tuple[str, ...]) -> list[str]: + return [c for c in columns if any(w in c.lower() for w in FORBIDDEN_COLUMN_WORDS)] + + +def activation_check(labels: Mapping[str, int], groups: Mapping[str, str]) -> dict[str, Any]: + """``labels``: strict binary labels from ``label_policy.strict_benchmark``; ``groups``: + campaign group per event. Returns ``active`` and every unmet requirement.""" + reasons = [] + pos = [e for e, y in labels.items() if y == 1] + neg = [e for e, y in labels.items() if y == 0] + for name, ids in (("reviewed_attack", pos), ("reviewed_legitimate", neg)): + if len(ids) < MIN_PER_CLASS: + reasons.append(f"{len(ids)} {name} labels; need {MIN_PER_CLASS}") + n_groups = len({groups.get(e, e) for e in ids}) + if n_groups < MIN_GROUPS_PER_CLASS: + reasons.append(f"{n_groups} {name} campaign groups; need {MIN_GROUPS_PER_CLASS}") + bad = forbidden_columns(FEATURE_GROUPS["combined"]) + if bad: + reasons.append(f"forbidden feature columns: {bad}") + return {"spec": SPEC_VERSION, "active": not reasons, "unmet": reasons} diff --git a/src/cryptoguard/ml/label_policy.py b/src/cryptoguard/ml/label_policy.py new file mode 100644 index 0000000..563f907 --- /dev/null +++ b/src/cryptoguard/ml/label_policy.py @@ -0,0 +1,75 @@ +"""Benchmark label policy for ``poisoning-attempt/1`` (Phase 11.6). + +Seven statuses stay distinct and are never collapsed automatically: + +- ``external_source_assertion``: a research source calls it an attempt (source data); +- ``reviewed_attack``: every reviewer (2 or more) chose *confirmed poisoning attempt*; +- ``reviewed_legitimate``: every reviewer chose *confirmed legitimate interaction*; +- ``likely_attack``: every reviewer chose confirmed or likely attempt, not all confirmed; +- ``unknown``: not reviewed, or a reviewer found the evidence insufficient; +- ``conflicting``: reviewers disagree across attack and legitimate, or chose conflicting + evidence; +- ``later_victim_loss``: a payment to the lookalike followed (an outcome, never a feature). + +A strict binary benchmark admits only ``reviewed_attack`` (1) and ``reviewed_legitimate`` +(0). Everything else is excluded *and counted*. Reviewed labels are evidence-based +judgments, not proof of intent. An adjudicated label is a separate, secondary layer and +never replaces the reviewers' own. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Mapping, Sequence +from typing import Any, Literal + +POLICY_VERSION = "label-policy/1" +Status = Literal[ + "external_source_assertion", + "reviewed_attack", + "reviewed_legitimate", + "likely_attack", + "unknown", + "conflicting", + "later_victim_loss", +] +ATTACKISH = frozenset({"confirmed_poisoning_attempt", "likely_poisoning_attempt"}) +MIN_REVIEWERS = 2 + + +def resolve(decisions: Sequence[str]) -> Status: + """Status from the reviewers' own decisions (adjudication is handled separately).""" + if len(decisions) < MIN_REVIEWERS: + return "unknown" + s = set(decisions) + if "conflicting_evidence" in s: + return "conflicting" + if s & ATTACKISH and "confirmed_legitimate_interaction" in s: + return "conflicting" + if "insufficient_evidence" in s: + return "unknown" + if s == {"confirmed_poisoning_attempt"}: + return "reviewed_attack" + if s == {"confirmed_legitimate_interaction"}: + return "reviewed_legitimate" + if s <= ATTACKISH: + return "likely_attack" + return "conflicting" + + +def binary_target(status: Status) -> int | None: + return {"reviewed_attack": 1, "reviewed_legitimate": 0}.get(status) + + +def strict_benchmark(reviews: Mapping[str, Sequence[str]]) -> dict[str, Any]: + """Eligible labels and the count of every exclusion, for a set of reviewed items.""" + statuses = {e: resolve(d) for e, d in reviews.items()} + labels = {e: t for e, s in statuses.items() if (t := binary_target(s)) is not None} + return { + "policy": POLICY_VERSION, + "eligible": len(labels), + "positives": sum(labels.values()), + "negatives": len(labels) - sum(labels.values()), + "excluded": dict(Counter(s for e, s in statuses.items() if e not in labels)), + "labels": labels, + } diff --git a/src/cryptoguard/ml/power.py b/src/cryptoguard/ml/power.py new file mode 100644 index 0000000..6ec13b4 --- /dev/null +++ b/src/cryptoguard/ml/power.py @@ -0,0 +1,55 @@ +"""Sample-size planning for false-positive-rate claims (Phase 11.6). Planning only: +nothing here collects data. + +Question: how many independently reviewed *legitimate* events are needed so that the +upper bound of a two-sided 95% Wilson interval on the FPR falls below a target? The +assumption is that the true FPR is a stated fraction of the target. + +Clustering inflates the need. Events from one wallet or campaign are correlated, so the +effective sample size is ``n / deff`` with ``deff = 1 + (m - 1) * icc`` (``m`` events per +cluster, ``icc`` the intra-cluster correlation). The required ``n`` is multiplied by +``deff``. +""" + +from __future__ import annotations + +import math +from typing import Any + +from cryptoguard.ml.sample_design import wilson + + +def negatives_needed(target_fpr: float, true_fpr: float, *, max_n: int = 1_000_000) -> int | None: + """Smallest n whose expected Wilson 95% upper bound (at the true FPR) is below target.""" + if not 0 <= true_fpr < target_fpr <= 1: + raise ValueError("need 0 <= true_fpr < target_fpr <= 1") + lo, hi = 1, max_n + if (wilson(true_fpr, hi) or (0, 1))[1] >= target_fpr: + return None + while lo < hi: + mid = (lo + hi) // 2 + if (wilson(true_fpr, mid) or (0, 1))[1] < target_fpr: + hi = mid + else: + lo = mid + 1 + return lo + + +def design_effect(per_cluster: float, icc: float) -> float: + return 1 + (per_cluster - 1) * icc + + +def plan_table(targets: tuple[float, ...] = (0.10, 0.05, 0.01), + ratios: tuple[float, ...] = (0.0, 0.5), + deffs: tuple[float, ...] = (1.0, 1.5, 2.0)) -> list[dict[str, Any]]: # fmt: skip + rows = [] + for target in targets: + for ratio in ratios: + n = negatives_needed(target, target * ratio) + rows.append({ + "target_fpr": target, + "assumed_true_fpr": target * ratio, + "negatives_iid": n, + **{f"negatives_deff_{d}": (math.ceil(n * d) if n else None) for d in deffs}, + }) # fmt: skip + return rows diff --git a/src/cryptoguard/ml/review_app/app.css b/src/cryptoguard/ml/review_app/app.css index a187397..a6014c1 100644 --- a/src/cryptoguard/ml/review_app/app.css +++ b/src/cryptoguard/ml/review_app/app.css @@ -57,3 +57,13 @@ button.copy { font-size: 12px; padding: 1px 6px; } details.context { margin-top: 10px; } details.context table { border-collapse: collapse; width: 100%; font-size: 13px; display: block; overflow-x: auto; } details.context th, details.context td { border-bottom: 1px solid var(--line); padding: 3px 8px; text-align: left; } +.evidence h3 { margin: 0 0 4px; font-size: 16px; } +.evidence h4 { margin: 12px 0 4px; font-size: 14px; } +.evidence table { border-collapse: collapse; font-size: 13px; display: block; overflow-x: auto; max-width: 100%; } +.evidence th, .evidence td { border-bottom: 1px solid var(--line); padding: 3px 8px; text-align: left; white-space: nowrap; } +ul.chips { list-style: none; padding: 0; margin: 6px 0; display: flex; flex-wrap: wrap; gap: 6px; } +ul.chips li { border-radius: 10px; padding: 2px 10px; font-size: 12px; } +ul.chips li.ok { background: var(--okbg); color: var(--ok); } +ul.chips li.warn, p.warn { background: var(--errbg); color: var(--err); } +fieldset.reasons { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 2px 12px; } +details.checklist { margin-top: 10px; } diff --git a/src/cryptoguard/ml/review_app/app.js b/src/cryptoguard/ml/review_app/app.js index f7b0e75..3aebf22 100644 --- a/src/cryptoguard/ml/review_app/app.js +++ b/src/cryptoguard/ml/review_app/app.js @@ -23,6 +23,32 @@ const CHOICES = { initiator: [["unknown", "unknown"], ["wallet", "the wallet"], ["third_party", "a third party"]], }; +const REASONS = [ + ["lookalike_of_earlier_counterparty", "Look-alike of an earlier counterparty"], + ["imitation_token_contract", "Imitation token contract"], + ["zero_value_transfer", "Zero-value transfer"], + ["dust_value", "Dust value"], + ["third_party_initiated_transfer", "Initiated by a third party"], + ["wallet_initiated_transfer", "Initiated by the wallet"], + ["known_relationship", "Known relationship"], + ["same_owner_evidence", "Same-owner evidence"], + ["ordinary_payment_pattern", "Ordinary payment pattern"], + ["no_earlier_counterparty_found", "No earlier counterparty found"], + ["history_unavailable", "History unavailable"], + ["contradictory_observations", "Contradictory observations"], + ["other", "Other (explain)"], +]; +const STATUS_TEXT = { + complete_for_declared_scope: ["ok", "Complete for the recorded window"], + partial_history: ["warn", "No earlier rows of this wallet are available locally"], + source_selected_rows_only: ["warn", "Only rows a research dataset kept: ordinary activity is missing"], + missing_transaction_details: ["warn", "The listed transaction is not in the local data"], + missing_receipt: ["warn", "Receipt not recorded"], + unknown_signer: ["warn", "Signer not recorded"], + unknown_token_legitimacy: ["warn", "Token not on the reviewed list (unknown, not necessarily fake)"], + unsupported_contract_execution: ["warn", "Contract execution not interpretable offline"], + insufficient_evidence: ["warn", "No local evidence"], +}; const FACTS = [ ["wallet", "Wallet"], ["address_under_review", "Address under review"], @@ -156,11 +182,24 @@ function formFields(form) { saw_source_or_model_output: f.get("saw_source_or_model_output") === "on", rationale: (f.get("rationale") || "").trim(), notes: (f.get("notes") || "").trim(), + used_offline_evidence: f.get("used_offline_evidence") === "on", + saw_later_victim_payment: f.get("saw_later_victim_payment"), + third_party_label_influenced: f.get("third_party_label_influenced"), + reason_codes: f.getAll("reason_codes"), + evidence_refs: (f.get("evidence_refs") || "").split(/\s+/).filter(Boolean), }; } function setFields(form, v) { + for (const box of form.querySelectorAll('input[name="reason_codes"]')) { + box.checked = (v.reason_codes || []).includes(box.value); + } for (const [k, val] of Object.entries(v)) { + if (k === "reason_codes") continue; + if (k === "evidence_refs") { + form.elements.namedItem("evidence_refs").value = (val || []).join("\n"); + continue; + } const input = form.elements.namedItem(k); if (!input || k === "decision") continue; if (input.type === "checkbox") input.checked = Boolean(val); @@ -177,6 +216,65 @@ function matchCounts(a, b) { return [lead, trail]; } +function table(headers, rows) { + const t = el("table"); + const head = el("tr"); + for (const h of headers) head.append(el("th", h)); + t.append(head); + for (const r of rows) { + const tr = el("tr"); + for (const cell of r) { + const td = el("td"); + if (typeof cell === "string" && cell.startsWith("0x")) td.append(el("code", cell)); + else td.textContent = cell === null || cell === undefined ? "unknown" : String(cell); + tr.append(td); + } + t.append(tr); + } + return t; +} + +function renderEvidence(box, ev) { + if (!ev) return; + box.hidden = false; + box.append(el("h3", `Offline evidence before block ${ev.cutoff.block}`)); + box.append(el("p", ev.coverage.explanation, "muted")); + const chips = el("ul", undefined, "chips"); + for (const s of ev.coverage.statuses) { + const [kind, text] = STATUS_TEXT[s] || ["warn", s]; + chips.append(el("li", text, kind)); + } + box.append(chips); + const row = (r) => [r.block, r.transaction, r.token, r.from, r.to, r.value_base_units]; + const heads = ["Block", "Transaction", "Token", "From", "To", "Value (base units)"]; + box.append(el("h4", "1. Candidate event")); + if (ev.candidate_event.length) { + box.append(table([...heads, "Direction"], ev.candidate_event.map((r) => [...row(r), r.direction]))); + } else { + box.append(el("p", "Not in the local data.", "warn")); + } + const sem = ev.transaction_semantics; + const signer = Array.isArray(sem.signer) ? sem.signer.join(", ") : sem.signer; + box.append(el("h4", "2. Transaction semantics")); + box.append(table(["Execution", "Signer", "Zero value"], [[sem.execution, signer, sem.zero_value]])); + box.append(el("h4", "3. Token")); + box.append(table(["Token", "On the reviewed list"], + ev.token_provenance.map((t) => [t.token, t.on_reviewed_token_list ? "yes" : "unknown"]))); + box.append(el("h4", "4. Address relationship")); + const rel = ev.address_relationship; + box.append(el("p", `${rel.earlier_rows_between_wallet_and_address} earlier row(s) between the wallet and this address. ${rel.note}.`)); + const hist = ev.wallet_history; + const d = el("details"); + d.append(el("summary", `5. Wallet history before the cutoff: ${hist.rows_before_cutoff} row(s), showing the last ${hist.shown.length}`)); + if (hist.shown.length) d.append(table(heads, hist.shown.map(row))); + box.append(d); + if (ev.graph_context) { + const g = ev.graph_context; + box.append(el("h4", "6. This address with other wallets before the cutoff")); + box.append(el("p", `${g.earlier_rows_of_address_with_other_wallets} row(s) with ${g.distinct_other_wallets} other wallet(s) in the local data.`)); + } +} + function go(i) { if (dirty && !confirm("This item has unsaved changes (kept as a draft in this browser). Leave it?")) return; index = Math.max(0, Math.min(state.items.length - 1, i)); @@ -201,6 +299,7 @@ function render() { dd.append(copyButton(it[k])); dl.append(el("dt", label), dd); } + renderEvidence($(".evidence", frag), it.evidence); const card = $(".card", frag); if (it.coverage_note) card.append(el("p", it.coverage_note, "coverage")); if (Array.isArray(it.context) && it.context.length) { @@ -230,6 +329,14 @@ function render() { fs.append(l); }); for (const s of form.querySelectorAll("select")) fill(s, s.dataset.kind || s.name); + const reasons = $(".reasons", form); + for (const [v, label] of REASONS) { + const l = el("label", undefined, "check"); + const box = el("input"); + box.type = "checkbox"; box.name = "reason_codes"; box.value = v; + l.append(box, el("span", label)); + reasons.append(l); + } const current = saved(it.item); const draft = readDraft(it.item); if (current) setFields(form, current); diff --git a/src/cryptoguard/ml/review_app/index.html b/src/cryptoguard/ml/review_app/index.html index 93a425c..1455ab7 100644 --- a/src/cryptoguard/ml/review_app/index.html +++ b/src/cryptoguard/ml/review_app/index.html @@ -26,7 +26,19 @@

CryptoGuard review

+
+ Evidence checklist (protocol section 3) +
    +
  1. Did the transaction move a token, or record a zero-value transfer, between the wallet and the address under review?
  2. +
  3. Before the cutoff, did the wallet deal with a different address sharing the first and last characters? Which one?
  4. +
  5. Is the token a widely used one or an imitation? Is the value zero, dust or ordinary?
  6. +
  7. Who initiated it: the wallet, or a third party?
  8. +
  9. Is there a legitimate explanation (the wallet's own address, a known partner)?
  10. +
+

A later theft is not required for an attempt, and shared look-alike shapes alone do not prove a common owner.

+
+
Decision 1–5 @@ -51,7 +63,16 @@

+ + +
+
+ Reasons (at least one for a confirmed decision) +
+ diff --git a/src/cryptoguard/ml/review_server.py b/src/cryptoguard/ml/review_server.py index d2dfcb8..1fcc3e0 100644 --- a/src/cryptoguard/ml/review_server.py +++ b/src/cryptoguard/ml/review_server.py @@ -21,6 +21,7 @@ import hmac import json import secrets +import time from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from importlib import resources @@ -65,10 +66,29 @@ def load_package(package: Path, expected_sheet_sha256: str | None = None) -> dic info = json.loads((package / PACKAGE_INFO).read_text(encoding="utf-8")) sheet_path = package / rs.SHEET got = rs.file_sha256(sheet_path) - known = expected_sheet_sha256 == got if expected_sheet_sha256 else rs.cohort_for_sheet(got) + from cryptoguard.ml import evidence, training + + cohort = rs.cohort_for_sheet(got) + if cohort is None and got == training.sheet_sha256(): + cohort = training.TRAINING_VERSION + known = expected_sheet_sha256 == got if expected_sheet_sha256 else cohort if got != info["sheet_sha256"] or not known: raise PackageError(f"{sheet_path}: sha256 {got} is not a frozen sheet") items = {r["item"]: _view(r) for r in rs.read_sheet(sheet_path)} + packets_path = package / evidence.PACKETS + if packets_path.exists(): + expected = ( + training.packets_sha256() + if cohort == training.TRAINING_VERSION + else rs.COHORTS.get(cohort or "", {}).get("evidence") + ) + if expected is None or rs.file_sha256(packets_path) != expected: + raise PackageError(f"{packets_path}: not the registered evidence for this sheet") + for line in packets_path.read_text(encoding="utf-8").splitlines(): + pk = json.loads(line) + item = items.get(pk["item"]) + if item is not None and pk["victim_event_id"] == item["victim_event_id"]: + item["evidence"] = pk replaced: list[int] = [] rep_path = package / REPLACEMENT_SHEET if rep_path.exists(): @@ -90,9 +110,20 @@ def load_package(package: Path, expected_sheet_sha256: str | None = None) -> dic } +SESSION_TTL_SECONDS = 12 * 3600 # one review sitting; restart the server for a new token + + class ReviewApp: - def __init__(self, package: Path, expected_sheet_sha256: str | None = None) -> None: + def __init__( + self, + package: Path, + expected_sheet_sha256: str | None = None, + *, + session_ttl_seconds: float = SESSION_TTL_SECONDS, + ) -> None: self.pkg = load_package(package, expected_sheet_sha256) + self.started = time.monotonic() + self.session_ttl_seconds = session_ttl_seconds ids = {i: v["victim_event_id"] for i, v in self.pkg["items"].items()} self.store = ReviewerStore(package / STORE_DIR, self.pkg["reviewer"], ids) self.token = secrets.token_urlsafe(24) @@ -158,7 +189,8 @@ def _host_ok(self) -> bool: def _authorized(self) -> bool: token = self.headers.get("X-Review-Token", "") - return hmac.compare_digest(token.encode(), app.token.encode()) + fresh = time.monotonic() - app.started < app.session_ttl_seconds + return fresh and hmac.compare_digest(token.encode(), app.token.encode()) def do_GET(self) -> None: if not self._host_ok(): diff --git a/src/cryptoguard/ml/submissions.py b/src/cryptoguard/ml/submissions.py new file mode 100644 index 0000000..5d9be1f --- /dev/null +++ b/src/cryptoguard/ml/submissions.py @@ -0,0 +1,111 @@ +"""Submission checks and the pre-unblinding agreement report (Phase 11.6). Neither opens +the unblinding key. + +``check_submission`` lists every problem with one reviewer's file instead of stopping at +the first: +- missing or corrupt file; +- edited content (hash); +- schema or stale protocol; +- wrong cohort sheet or sample; +- mixed reviewer ids; +- unknown, missing or repeated items; +- invalid evidence references (checked by the schema). + +``agreement_report`` measures consistency between two finalized submissions. Agreement is +not correctness: two reviewers can agree and both be wrong. +""" + +from __future__ import annotations + +import json +from collections import Counter +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.agreement import BINARY, agreement, binary +from cryptoguard.ml.annotation import PROTOCOL, AnnotationError, Submission, load_submission + + +def _active_ids(sample_dir: Path) -> dict[int, str]: + return {r["item"]: r["victim_event_id"] for r in rs.read_sheet(sample_dir / rs.SHEET)} + + +def check_submission(path: Path, sample_dir: Path, *, cohort: str) -> list[str]: + if not path.is_file(): + return [f"{path}: missing"] + try: + sub = load_submission(path) + except (AnnotationError, OSError, json.JSONDecodeError, UnicodeDecodeError) as exc: + return [str(exc)] + problems: list[str] = [] + expected = rs.COHORTS[cohort] + if sub.sheet_sha256 != expected[rs.SHEET]: + problems.append(f"sheet {sub.sheet_sha256[:12]} is not the {cohort} sheet") + if sub.selection_sha256 != expected["selection"]: + problems.append("submission is for another sample") + if sub.protocol != PROTOCOL: + problems.append(f"stale protocol {sub.protocol}; current is {PROTOCOL}") + if len({a.reviewer for a in sub.decisions} | {sub.reviewer}) != 1: + problems.append("decisions from more than one reviewer id") + ids = _active_ids(sample_dir) + got = Counter((a.item, a.victim_event_id) for a in sub.decisions) + unknown = [i for i, e in got if ids.get(i) != e] + if unknown: + problems.append(f"{len(unknown)} decision(s) for items not on the sheet: {unknown[:5]}") + repeated = [k for k, n in got.items() if n > 1] + if repeated: + problems.append(f"repeated items: {repeated[:5]}") + missing = sorted(set(ids) - {i for i, _ in got}) + if missing: + problems.append(f"{len(missing)} sheet item(s) without a decision: {missing[:10]}") + return problems + + +def agreement_report(paths: Sequence[Path], sample_dir: Path, *, cohort: str) -> dict[str, Any]: + problems = {str(p): check_submission(p, sample_dir, cohort=cohort) for p in paths} + bad = {k: v for k, v in problems.items() if v} + if bad: + raise AnnotationError(f"invalid submissions: {bad}") + subs: list[Submission] = [load_submission(p) for p in paths] + reviewers = [s.reviewer for s in subs] + if len(set(reviewers)) != len(reviewers) or len(reviewers) < 2: + raise AnnotationError("agreement needs finalized submissions from 2+ distinct reviewers") + a, b = sorted(subs, key=lambda s: s.reviewer)[:2] + la = {x.victim_event_id: x.decision for x in a.decisions} + lb = {x.victim_event_id: x.decision for x in b.decisions} + manifest = json.loads((sample_dir / rs.MANIFEST).read_text(encoding="utf-8")) + stratum = {r["victim_event_id"]: r["stratum"] for r in manifest["selected"]} + by_head: dict[str, Any] = {} + for head in sorted({s.split("|")[0].split(":")[0] for s in stratum.values()}): + ids = [e for e in la if stratum.get(e, "").split("|")[0].split(":")[0] == head] + by_head[head] = ( + agreement({e: binary(la[e]) for e in ids}, {e: binary(lb[e]) for e in ids}, BINARY) + if len(ids) >= 10 + else {"items": len(ids), "note": "fewer than 10 items: counts only"} + ) + return { + "cohort": cohort, + "reviewers": [a.reviewer, b.reviewer], + "five_category": agreement(la, lb), + "binary": agreement( + {k: binary(v) for k, v in la.items()}, {k: binary(v) for k, v in lb.items()}, BINARY + ), + "by_stratum_group": by_head, + "per_reviewer": { + s.reviewer: { + "decisions": dict(Counter(x.decision for x in s.decisions)), + "insufficient_rate": sum(x.decision == "insufficient_evidence" for x in s.decisions) + / len(s.decisions), + "conflicting_rate": sum(x.decision == "conflicting_evidence" for x in s.decisions) + / len(s.decisions), + "used_offline_evidence": sum(bool(x.used_offline_evidence) for x in s.decisions), + "saw_later_victim_payment": dict( + Counter(x.saw_later_victim_payment for x in s.decisions) + ), + } + for s in subs + }, + "note": "agreement measures consistency between reviewers, not correctness", + } diff --git a/src/cryptoguard/ml/training.py b/src/cryptoguard/ml/training.py new file mode 100644 index 0000000..ae633e2 --- /dev/null +++ b/src/cryptoguard/ml/training.py @@ -0,0 +1,228 @@ +"""Synthetic reviewer-training cohort (``training/1``, Phase 11.6). + +Ten invented cases let reviewers learn the app and the evidence panels before any real +item. Their addresses and transactions are fabricated and marked as such. They share +nothing with the frozen cohorts, and the unblinding gate refuses them: they are not in +``review_sample.COHORTS``. The teaching notes are separate from the sheet; reviewers read +them *after* trying the cases. +""" + +from __future__ import annotations + +import hashlib +import json +from functools import lru_cache +from pathlib import Path +from typing import Any + +from cryptoguard.ml import evidence as ev + +TRAINING_VERSION = "training/1" +DESCRIPTION = "TRAINING ITEM (synthetic, not real chain data)" +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +FAKE_TOKEN = "0x" + "fa" * 20 +ROUTER = "0x7a250d5630b4cf539739df2c5dacb4c659f2488d" +NOTES = "training_notes.md" + + +def _a(head: str, tail: str, fill: str) -> str: + return "0x" + head + fill * (40 - len(head) - len(tail)) + tail + + +WALLET = _a("7e57", "7e57", "1") +FRIEND = _a("d2962", "5d7d5", "2") +LOOKALIKE = _a("d2962", "5d7d5", "9") # 5 leading + 5 trailing characters shared +WEAK = _a("d29", "d7d5", "4") # 3 + 4 +STRANGER = _a("c0ffee", "c0ffee", "3") + + +def _tx(n: int) -> str: + return "0x" + f"{n:064x}" + + +def _row( + block: int, + sender: str, + receiver: str, + value: str, + *, + token: str = USDT, + tx: int, + signer: str | None, + order: int = 0, +) -> ev.Row: + return ev.Row( + block, (order, 0), _tx(tx), token, sender, receiver, value, signer, "recorded_window" + ) + + +def _history() -> list[ev.Row]: + return [ + _row(1_000, WALLET, FRIEND, "250000000", tx=1, signer=WALLET), + _row(1_400, FRIEND, WALLET, "1000000", tx=2, signer=FRIEND), + _row(1_800, WALLET, FRIEND, "90000000", tx=3, signer=WALLET), + ] + + +# (title, candidate rows, source, extra history, note) +CASES: list[tuple[str, list[ev.Row], str | None, list[ev.Row], str]] = [ + ( + "Clear planting", + [_row(2_000, WALLET, LOOKALIKE, "0", tx=101, signer=STRANGER)], + "recorded_window", + [], + "A zero-value transfer *from* the wallet to an address sharing 5+5 characters with " + "FRIEND, which the wallet paid twice before. A third party signed it, so the wallet " + "did not choose this. Typical: confirmed attempt, with the earlier FRIEND payments " + "cited.", + ), + ( + "Ordinary transfer", + [_row(2_000, FRIEND, WALLET, "5000000", tx=102, signer=FRIEND)], + "recorded_window", + [], + "The sender is FRIEND itself (the exact address seen before), not a look-alike. " + "Similarity rules do not apply. Typical: confirmed legitimate, citing the earlier " + "payments.", + ), + ( + "Ambiguous similarity", + [_row(2_000, WEAK, WALLET, "40000000", tx=103, signer=WEAK)], + "recorded_window", + [], + "Only 3+4 characters match FRIEND, the token is genuine and the value ordinary. " + "Weak similarity alone is not intent. Without more, insufficient evidence or likely " + "is defensible; confirmed is not.", + ), + ( + "Spoofed Transfer log", + [_row(2_000, WALLET, LOOKALIKE, "1000000000", token=FAKE_TOKEN, tx=104, signer=STRANGER)], + "recorded_window", + [], + "An unreviewed token contract emitted a Transfer 'from' the wallet that the wallet " + "never signed. Logs can be forged by their emitting contract. Check the contract on " + "an explorer; an imitation token plus a look-alike recipient supports confirmed.", + ), + ( + "Reverted transaction", + [], + "recorded_window", + [], + "The listed transaction left no Transfer log in the recorded data (for example it " + "reverted). There is nothing to judge: insufficient evidence.", + ), + ( + "Unknown token", + [_row(2_000, LOOKALIKE, WALLET, "1", token=FAKE_TOKEN, tx=106, signer=LOOKALIKE)], + "recorded_window", + [], + "The token is not on the reviewed list, which means only that it is unknown, not " + "that it is fake. Look up the contract before calling it an imitation.", + ), + ( + "Missing history", + [_row(2_000, LOOKALIKE, WALLET, "0", tx=107, signer=None)], + "archive", + [], + "No earlier rows of this wallet are available locally. Find the earlier counterparty " + "on an explorer, up to the cutoff block, or answer insufficient evidence.", + ), + ( + "Contract-mediated transfer", + [_row(2_000, WALLET, STRANGER, "70000000", tx=108, signer=ROUTER)], + "recorded_window", + [], + "Tokens left the wallet in a transaction signed by a public router: usually an " + "approved swap, not a spoof. No look-alike is involved. Typical: confirmed legitimate " + "if the approval is visible, otherwise insufficient evidence.", + ), + ( + "Competing look-alikes", + [_row(2_000, LOOKALIKE, WALLET, "0", tx=109, signer=LOOKALIKE)], + "recorded_window", + [ + _row(1_900, _a("d2962", "5d7d5", "8"), WALLET, "0", tx=110, signer=None), + _row(1_950, _a("d2962", "5d7d5", "7"), WALLET, "0", tx=111, signer=None), + ], + "Several different look-alikes of FRIEND sent zero-value transfers before the cutoff. " + "That supports a campaign against this wallet, but each item is judged on its own " + "evidence. Do not infer that the addresses share an owner from similarity alone.", + ), + ( + "Insufficient evidence", + [], + None, + [], + "No local data at all. Without an explorer check, the only honest answer is " + "insufficient evidence. Do not answer legitimate merely because nothing bad is " + "visible.", + ), +] + + +@lru_cache(maxsize=1) +def build() -> tuple[bytes, bytes, str]: + """(sheet bytes, packet bytes, notes markdown), deterministic.""" + sheet, packets, notes = [], [], ["# Training notes (read after trying the items)", ""] + for n, (title, cand, source, extra, note) in enumerate(CASES, start=1): + address = next((r.sender if r.receiver == WALLET else r.receiver for r in cand), LOOKALIKE) + line = { + "schema_version": "review-sheet/2", + "item": n, + "victim_event_id": f"{0xFEED0000 + n:016x}", + "description": DESCRIPTION, + "chain_id": 1, + "wallet": WALLET, + "address_under_review": address, + "transaction": cand[0].tx if cand else _tx(100 + n), + "block": 2_000, + "coverage_note": "Synthetic case.", + } + rows = [*(_history() if source == "recorded_window" else []), *extra, *cand] + packets.append( + ev.packet( + line, + rows=rows, + source=source, + window=(500, 3_000) if source == "recorded_window" else None, + ) + ) + sheet.append(line) + notes += [f"## {n}. {title}", "", note, ""] + return ev.dumps(sheet), ev.dumps(packets), "\n".join(notes) + + +def sheet_sha256() -> str: + return hashlib.sha256(build()[0]).hexdigest() + + +def packets_sha256() -> str: + return hashlib.sha256(build()[1]).hexdigest() + + +def make_package(reviewer: str, out: Path) -> Path: + from cryptoguard.ml.annotation import PROTOCOL, REVIEWER_ID, AnnotationError, atomic_write + from cryptoguard.ml.review_sample import SHEET + + if not REVIEWER_ID.match(reviewer): + raise AnnotationError(f"invalid reviewer pseudonym {reviewer!r}") + if out.exists() and any(out.iterdir()): + raise AnnotationError(f"{out} is not empty") + sheet, packets, notes = build() + out.mkdir(parents=True, exist_ok=True) + atomic_write(out / SHEET, sheet) + atomic_write(out / ev.PACKETS, packets) + atomic_write(out / NOTES, notes.encode()) + info = { + "reviewer": reviewer, + "protocol": PROTOCOL, + "selection_sha256": TRAINING_VERSION, + "sheet_sha256": sheet_sha256(), + "training": True, + } + atomic_write(out / "reviewer.json", json.dumps(info, indent=1).encode() + b"\n") + return out + + +def info() -> dict[str, Any]: + return {"version": TRAINING_VERSION, "items": len(CASES), "sheet_sha256": sheet_sha256()} diff --git a/src/cryptoguard/ml/unblind.py b/src/cryptoguard/ml/unblind.py index c635337..12f16d5 100644 --- a/src/cryptoguard/ml/unblind.py +++ b/src/cryptoguard/ml/unblind.py @@ -104,6 +104,17 @@ def make_package( raise AnnotationError(f"{out} is not empty") out.mkdir(parents=True, exist_ok=True) shutil.copyfile(sample_dir / rs.SHEET, out / rs.SHEET) + expected_evidence = rs.COHORTS[cohort].get("evidence") + if expected_evidence: # amendment 2: the registered pre-cutoff evidence packets + from cryptoguard.ml.evidence import PACKETS + + src = work / "evidence" / PACKETS + if not src.exists() or rs.file_sha256(src) != expected_evidence: + raise AnnotationError( + f"{src}: registered evidence packets missing or changed; rebuild with " + "`cryptoguard ml review build-evidence`" + ) + shutil.copyfile(src, out / PACKETS) recs = replacements(work) problems = validate_replacements(manifest, recs) if problems: diff --git a/tests/review_fixtures.py b/tests/review_fixtures.py index d301772..343ed02 100644 --- a/tests/review_fixtures.py +++ b/tests/review_fixtures.py @@ -98,6 +98,11 @@ def frozen(tmp: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path, dict "saw_external_label": "no", "saw_source_or_model_output": False, "rationale": "Lookalike of the earlier recipient, imitation token, no relationship found.", + "used_offline_evidence": True, + "saw_later_victim_payment": "no", + "third_party_label_influenced": "no", + "reason_codes": ["lookalike_of_earlier_counterparty", "imitation_token_contract"], + "evidence_refs": [], } INSUFFICIENT_FIELDS: dict[str, Any] = { **ATTEMPT_FIELDS, diff --git a/tests/unit/test_ml_cohort.py b/tests/unit/test_ml_cohort.py index f03ee1c..8e5d135 100644 --- a/tests/unit/test_ml_cohort.py +++ b/tests/unit/test_ml_cohort.py @@ -29,6 +29,7 @@ "matched_trailing": None, "legitimate_explanation": "observed", "rationale": "The address is the wallet owner's own exchange deposit address.", + "reason_codes": ["same_owner_evidence"], } diff --git a/tests/unit/test_ml_validation_readiness.py b/tests/unit/test_ml_validation_readiness.py new file mode 100644 index 0000000..fb70d4f --- /dev/null +++ b/tests/unit/test_ml_validation_readiness.py @@ -0,0 +1,443 @@ +"""Phase 11.6: evidence packets, training cohort, amendment-2 submissions, label policy, +experiment specification, power planning and leakage guards. + +Synthetic data only; no reviewer decision here is real. +""" + +from __future__ import annotations + +import json +import math +import sqlite3 +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import evidence as ev +from cryptoguard.ml import experiment_spec as spec +from cryptoguard.ml import label_policy as lp +from cryptoguard.ml import power, training +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import unblind as ub +from cryptoguard.ml.annotation import Annotation, AnnotationError +from cryptoguard.ml.evaluation import Features +from cryptoguard.ml.review_server import PackageError, ReviewApp +from cryptoguard.ml.submissions import agreement_report, check_submission +from tests.review_fixtures import ATTEMPT_FIELDS, INSUFFICIENT_FIELDS, fields, frozen +from tests.unit.test_ml_poisoning import FRIEND, LOOKALIKE, WALLET, fixture, transfer + +STRANGER = "0x" + "3c" * 20 +TOKEN = "0xdac17f958d2ee523a2206206994597c13d831ec7" + +# --- evidence packets ------------------------------------------------------------------------ + + +def archive_db(path: Path, rows: list[tuple[Any, ...]]) -> Path: + con = sqlite3.connect(path) + con.execute( + "create table transfers (line integer primary key, block integer, tx text, token text, " + "sender text, receiver text, sender_is_victim integer, value real, value_usd real, " + "flags integer, intended text, first_digits integer, last_digits integer)" + ) + con.executemany("insert into transfers values (?,?,?,?,?,?,?,?,?,?,?,?,?)", rows) + con.commit() + con.close() + return path + + +def arow( + line: int, + block: int, + tx: str, + s: str, + r: str, + value: float = 1.0, + *, + flags: int = 1, + intended: str | None = None, +) -> tuple[Any, ...]: + return (line, block, tx, TOKEN, s, r, 0, value, 1.0, flags, intended, 4, 4) + + +ITEM = { + "item": 1, + "victim_event_id": "00000000000000a1", + "wallet": WALLET, + "address_under_review": LOOKALIKE, + "transaction": "0xplant", + "block": 1_000, +} + + +def base_rows() -> list[tuple[Any, ...]]: + return [ + arow(1, 500, "0xa", WALLET, FRIEND, 100.0), # the wallet pays its friend + arow(2, 900, "0xb", LOOKALIKE, STRANGER, 0.0, flags=8), # address elsewhere, earlier + arow(3, 1_000, "0xplant", LOOKALIKE, WALLET, 0.0, flags=2, intended=FRIEND), + ] + + +def build(tmp: Path, rows: list[tuple[Any, ...]], name: str = "a.sqlite") -> list[dict]: + return ev.build([ITEM], archive_dbs=[archive_db(tmp / name, rows)], fixtures=[]) + + +def test_packet_contents_and_no_source_labels(tmp_path: Path) -> None: + (p,) = build(tmp_path, base_rows()) + assert [r["transaction"] for r in p["candidate_event"]] == ["0xplant"] + assert p["wallet_history"]["rows_before_cutoff"] == 1 + assert p["graph_context"] == { + "earlier_rows_of_address_with_other_wallets": 1, + "distinct_other_wallets": 1, + } + assert "source_selected_rows_only" in p["coverage"]["statuses"] + assert "unknown_signer" in p["coverage"]["statuses"] # the archive records no signer + text = json.dumps(p) + for word in ("flags", "intended", "payoff", "categor"): + assert word not in text + assert FRIEND in text # the friend appears only as an observed counterparty + + +def test_future_rows_labels_and_payoffs_never_change_a_packet(tmp_path: Path) -> None: + """Metamorphic: rows at or after the cutoff block, a later payoff and any change to the + source's flags or intended column leave the packet unchanged.""" + before = build(tmp_path, base_rows(), "a.sqlite") + rows = [ + *base_rows(), + arow(4, 1_000, "0xsameblock", WALLET, STRANGER), # same block, order unknown + arow(5, 1_500, "0xpay", WALLET, LOOKALIKE, 5_000.0, flags=16), # later payoff + arow(6, 2_000, "0xlater", LOOKALIKE, STRANGER, 0.0, flags=2), + ] + relabelled = [(*r[:9], 999, STRANGER, *r[11:]) for r in rows] + assert build(tmp_path, rows, "b.sqlite") == before + assert build(tmp_path, relabelled, "c.sqlite") == before + + +def test_inconsistent_cutoff_fails_and_missing_tx_is_reported(tmp_path: Path) -> None: + rows = [r if r[0] != 3 else arow(3, 1_001, "0xplant", LOOKALIKE, WALLET) for r in base_rows()] + with pytest.raises(ev.EvidenceError, match="cutoff"): + build(tmp_path, rows) + (p,) = build(tmp_path, base_rows()[:2], "d.sqlite") + assert p["candidate_event"] == [] + assert "missing_transaction_details" in p["coverage"]["statuses"] + assert p["transaction_semantics"]["zero_value"] is None # unknown, never False + + +def test_recorded_window_uses_exact_order_and_signers() -> None: + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 1, tx_sender=WALLET, idx=1), + transfer(1_000, WALLET, FRIEND, 2, tx_sender=WALLET, idx=1), # same block, earlier + transfer(1_000, LOOKALIKE, WALLET, 0, idx=3), + transfer(1_000, WALLET, FRIEND, 3, tx_sender=WALLET, idx=9), + ], + [], + ) + plant = next(t for t in fx.transfers if t.sender == LOOKALIKE) + item = {**ITEM, "transaction": plant.transaction_hash, "block": 1_000} + (p,) = ev.build([item], archive_dbs=[], fixtures=[fx]) + assert p["wallet_history"]["rows_before_cutoff"] == 2 # idx 1 in-block counts, idx 9 not + assert "complete_for_declared_scope" in p["coverage"]["statuses"] + assert "unknown_signer" in p["coverage"]["statuses"] # incoming log: signer not recorded + assert p["graph_context"] is None + + +def test_packets_are_deterministic_and_history_is_bounded(tmp_path: Path) -> None: + rows = [arow(10 + i, 100 + i, f"0x{i:x}", WALLET, FRIEND) for i in range(80)] + base_rows()[2:] + a = build(tmp_path, rows, "e.sqlite") + b = build(tmp_path, list(reversed(rows)), "f.sqlite") + assert a == b + assert len(a[0]["wallet_history"]["shown"]) == ev.MAX_HISTORY + assert a[0]["wallet_history"]["rows_before_cutoff"] == 80 + + +# --- training cohort ------------------------------------------------------------------------ + + +def test_training_package_is_synthetic_deterministic_and_served(tmp_path: Path) -> None: + pkg = training.make_package("A", tmp_path / "train") + assert training.build() == training.build() + state = ReviewApp(pkg).state() + assert len(state["items"]) == 10 + assert all(i["description"].startswith("TRAINING") for i in state["items"]) + assert all("evidence" in i for i in state["items"]) + assert (pkg / training.NOTES).exists() + assert training.sheet_sha256() not in {h[rs.SHEET] for h in rs.COHORTS.values()} + + +def test_training_submissions_can_never_be_unblinded(tmp_path: Path, monkeypatch) -> None: + _, sample, _ = frozen(tmp_path, monkeypatch) + with pytest.raises(KeyError): + ub.preflight(sample, tmp_path / "w", [], cohort=training.TRAINING_VERSION) + + +def test_unregistered_or_tampered_evidence_is_refused(tmp_path: Path) -> None: + pkg = training.make_package("A", tmp_path / "train") + packets = pkg / ev.PACKETS + packets.write_bytes(packets.read_bytes().replace(b'"block": 2000', b'"block": 1999', 1)) + with pytest.raises(PackageError, match="registered evidence"): + ReviewApp(pkg) + + +def test_sessions_expire(tmp_path: Path) -> None: + from cryptoguard.ml.review_server import make_handler # noqa: F401 - imported for coverage + + app = ReviewApp(training.make_package("A", tmp_path / "t"), session_ttl_seconds=0) + import threading + import urllib.error + import urllib.request + + from cryptoguard.ml.review_server import serve + + with app.store: + httpd, url = serve(app) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + req = urllib.request.Request( # noqa: S310 - loopback test + url.split("/#")[0] + "/api/state", headers={"X-Review-Token": app.token} + ) + try: + with pytest.raises(urllib.error.HTTPError) as err: + urllib.request.urlopen(req, timeout=10) # noqa: S310 - loopback test + assert err.value.code == 403 + finally: + httpd.shutdown() + httpd.server_close() + + +# --- amendment 2 ----------------------------------------------------------------------------- + + +def make(**over: Any) -> Annotation: + return Annotation.model_validate( + {**fields(1, "00000000000000a1"), "reviewer": "A", "revision": 1, "saved_at": "t", **over} + ) + + +def test_amendment_two_requires_exposure_and_reasons() -> None: + make() + with pytest.raises(ValueError, match="saw_later_victim_payment"): + make(saw_later_victim_payment=None) + with pytest.raises(ValueError, match="reason code"): + make(reason_codes=[]) + with pytest.raises(ValueError, match="evidence references"): + make(evidence_refs=["etherscan.io/tx/abc"]) + make(evidence_refs=["0x" + "ab" * 32, FRIEND]) + old = make( + protocol="review-protocol/1+amendment-1", + used_offline_evidence=None, + saw_later_victim_payment=None, + third_party_label_influenced=None, + reason_codes=[], + ) + assert old.protocol.endswith("amendment-1") # earlier records stay loadable + + +# --- submission checks ------------------------------------------------------------------------- + + +def _finalize(pkg: Path, decide) -> Path: + app = ReviewApp(pkg) + with app.store: + for it in app.state()["items"]: + app.store.save(fields(it["item"], it["victim_event_id"], decide(it["item"]))) + app.finalize() + return pkg / "annotations" / "submission.json" + + +def _rehash(path: Path, body: dict[str, Any]) -> None: + from cryptoguard.ml.annotation import _canonical, _sha + + body.pop("content_sha256", None) + body["content_sha256"] = _sha(_canonical(body)) + path.write_text(json.dumps(body), encoding="utf-8") + + +def test_submission_checks_report_every_problem(tmp_path: Path, monkeypatch) -> None: + _, sample, _ = frozen(tmp_path, monkeypatch) + pkg = ub.make_package(sample, tmp_path / "w", "A", tmp_path / "pa") + sub = _finalize(pkg, lambda i: ATTEMPT_FIELDS) + assert check_submission(sub, sample, cohort=rs.SAMPLE_VERSION) == [] + assert check_submission(tmp_path / "nope.json", sample, cohort=rs.SAMPLE_VERSION) + original = json.loads(sub.read_text(encoding="utf-8")) + edited = tmp_path / "edited.json" + + def problems_after(change) -> str: + body = json.loads(json.dumps(original)) + change(body) + _rehash(edited, body) + return " | ".join(check_submission(edited, sample, cohort=rs.SAMPLE_VERSION)) + + def other_reviewer(b: dict) -> None: + b["decisions"][1]["reviewer"] = "B" + + def repeat(b: dict) -> None: + b["decisions"].append(b["decisions"][0]) + + def drop(b: dict) -> None: + b["decisions"].pop() + + def stale(b: dict) -> None: + b["protocol"] = "review-protocol/1+amendment-1" + + assert "another reviewer" in problems_after(other_reviewer) + assert "repeated" in problems_after(repeat) + assert "without a decision" in problems_after(drop) + assert "stale protocol" in problems_after(stale) + edited.write_text("{broken", encoding="utf-8") + assert check_submission(edited, sample, cohort=rs.SAMPLE_VERSION) + + +def test_agreement_report_needs_two_valid_distinct_reviewers(tmp_path: Path, monkeypatch) -> None: + _, sample, m = frozen(tmp_path, monkeypatch) + a = _finalize( + ub.make_package(sample, tmp_path / "w", "A", tmp_path / "pa"), lambda i: ATTEMPT_FIELDS + ) + b = _finalize( + ub.make_package(sample, tmp_path / "w", "B", tmp_path / "pb"), + lambda i: INSUFFICIENT_FIELDS if i <= 6 else ATTEMPT_FIELDS, + ) + with pytest.raises(AnnotationError, match="distinct"): + agreement_report([a], sample, cohort=rs.SAMPLE_VERSION) + r = agreement_report([a, b], sample, cohort=rs.SAMPLE_VERSION) + assert r["binary"]["disagreements"] == 6 + assert r["per_reviewer"]["B"]["insufficient_rate"] == pytest.approx(6 / len(m["selected"])) + assert "consistency" in r["note"] + + +# --- label policy, experiment spec, power ----------------------------------------------------- + + +@pytest.mark.parametrize( + ("decisions", "status"), + [ + (["confirmed_poisoning_attempt"] * 2, "reviewed_attack"), + (["confirmed_legitimate_interaction"] * 2, "reviewed_legitimate"), + (["confirmed_poisoning_attempt", "likely_poisoning_attempt"], "likely_attack"), + (["confirmed_poisoning_attempt", "insufficient_evidence"], "unknown"), + (["confirmed_poisoning_attempt", "confirmed_legitimate_interaction"], "conflicting"), + (["likely_poisoning_attempt", "conflicting_evidence"], "conflicting"), + (["confirmed_poisoning_attempt"], "unknown"), # one reviewer is not enough + ], +) +def test_label_policy(decisions: list[str], status: str) -> None: + assert lp.resolve(decisions) == status + + +def test_strict_benchmark_counts_every_exclusion() -> None: + r = lp.strict_benchmark( + { + "a": ["confirmed_poisoning_attempt"] * 2, + "b": ["confirmed_legitimate_interaction"] * 2, + "c": ["likely_poisoning_attempt"] * 2, + "d": ["insufficient_evidence"] * 2, + } + ) + assert (r["eligible"], r["positives"], r["negatives"]) == (2, 1, 1) + assert r["excluded"] == {"likely_attack": 1, "unknown": 1} + + +def test_spec_feature_groups_exist_and_are_clean() -> None: + from cryptoguard.ml import candidates as cand + from cryptoguard.ml.history import events_from_fixture + + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 1, tx_sender=WALLET, idx=1), + transfer(900, LOOKALIKE, WALLET, 0, idx=2), + ], + [], + ) + events, cov = events_from_fixture(fx) + row = cand.event_features(cand.generate(fx)[0], events, cov).as_model_row() + for name, cols in spec.FEATURE_GROUPS.items(): + assert set(cols) <= set(row), name + assert spec.forbidden_columns(spec.FEATURE_GROUPS["combined"]) == [] + assert spec.forbidden_columns(("source_id", "x")) == ["source_id"] + + +def test_spec_stays_inactive_without_enough_reviewed_labels() -> None: + few = {f"p{i}": 1 for i in range(10)} | {f"n{i}": 0 for i in range(40)} + r = spec.activation_check(few, {}) + assert r["active"] is False + assert any("reviewed_attack" in u for u in r["unmet"]) + one_group = {f"p{i}": 1 for i in range(30)} | {f"n{i}": 0 for i in range(30)} + r = spec.activation_check(one_group, dict.fromkeys(one_group, "g")) + assert r["active"] is False # 60 labels from a single campaign are not 60 observations + + +def test_power_matches_the_closed_form_and_clustering_multiplies() -> None: + # Zero observed false positives: the Wilson upper bound is z^2 / (n + z^2). + z2 = 1.959963984540054**2 + for target in (0.10, 0.05, 0.01): + assert power.negatives_needed(target, 0.0) == math.floor(z2 * (1 - target) / target) + 1 + assert power.design_effect(5, 0.25) == pytest.approx(2.0) + row = next(r for r in power.plan_table() if r["target_fpr"] == 0.05 and r["assumed_true_fpr"]) + assert row["negatives_deff_2.0"] == 2 * row["negatives_iid"] + with pytest.raises(ValueError, match="need"): + power.negatives_needed(0.05, 0.06) + + +def test_contract_refuses_source_identifiers_as_features() -> None: + for bad in ("source_dataset", "cohort_id", "row_index", "frame"): + with pytest.raises(ValueError, match="outcome"): + Features(feature_version="f", values={bad: 1.0}) + + +def test_both_frozen_cohorts_are_one_protected_holdout(tmp_path: Path, monkeypatch) -> None: + from cryptoguard.ml.benchmark import ( + HoldoutLeakError, + check_training_events, + holdout_from_sheets, + ) + from tests.unit.test_ml_benchmark import event + + _, sample, _ = frozen(tmp_path, monkeypatch) + sheet2 = tmp_path / "s2.jsonl" + sheet2.write_text( + json.dumps( + { + "schema_version": "review-sheet/2", + "item": 1, + "victim_event_id": "f" * 16, + "wallet": STRANGER, + "address_under_review": FRIEND, + "transaction": "0x" + "cd" * 32, + "block": 5, + } + ) + + "\n", + encoding="utf-8", + ) + h = holdout_from_sheets([sample / rs.SHEET, sheet2]) + with pytest.raises(HoldoutLeakError): + check_training_events([event(1, victim=STRANGER)], h) + + +# --- candidate generator audit (Phase 11.6 additions) ------------------------------------------ + + +def test_generator_orders_several_transactions_in_one_block() -> None: + """A payment earlier in the same block makes FRIEND a chosen counterparty for a + lookalike later in that block, but not for one earlier in it.""" + from cryptoguard.ml import candidates as cand + + fx = fixture( + [ + transfer(900, LOOKALIKE, WALLET, 0, idx=1), + transfer(900, WALLET, FRIEND, 5, tx_sender=WALLET, idx=2), + transfer(900, LOOKALIKE, WALLET, 0, idx=3, log=1), + ], + [], + ) + by_idx = {c.event.planting_tx_index: set(c.methods) for c in cand.generate(fx)} + assert by_idx[1] == {"zero_value_in"} + assert by_idx[3] == {"zero_value_in", "lookalike_in"} + + +def test_a_duplicated_input_record_is_counted_not_hidden() -> None: + from cryptoguard.ml import candidates as cand + + t = transfer(900, LOOKALIKE, WALLET, 0, idx=1) + _, stats = cand.generate_with_stats(fixture([t, t], [])) + assert stats.candidates == 2 + assert stats.duplicate_identities == 1 From 224665777d290e68d67829bfe0c98c52f7114a49 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 14:13:13 +0300 Subject: [PATCH 31/92] feat(ml): register amendment-2 evidence packets for both cohorts; fix page overflow Registers the SHA-256 of the evidence packets built at 240ba9b on a clean tree (review-sample/1: 68f11afb..., hard-negative-candidates/1: 1c7f32c6...); packages now carry them and the server refuses any other packet file. Frozen sheets, keys and manifests are unchanged. The review page no longer scrolls sideways when the evidence tables are wide. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/review_app/app.css | 2 ++ src/cryptoguard/ml/review_sample.py | 8 ++++++++ tests/review_fixtures.py | 1 + 3 files changed, 11 insertions(+) diff --git a/src/cryptoguard/ml/review_app/app.css b/src/cryptoguard/ml/review_app/app.css index a6014c1..1bbcdce 100644 --- a/src/cryptoguard/ml/review_app/app.css +++ b/src/cryptoguard/ml/review_app/app.css @@ -67,3 +67,5 @@ ul.chips li.ok { background: var(--okbg); color: var(--ok); } ul.chips li.warn, p.warn { background: var(--errbg); color: var(--err); } fieldset.reasons { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 2px 12px; } details.checklist { margin-top: 10px; } +#item { min-width: 0; } +.card { min-width: 0; overflow-wrap: anywhere; } diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py index 34bd417..b144faa 100644 --- a/src/cryptoguard/ml/review_sample.py +++ b/src/cryptoguard/ml/review_sample.py @@ -328,6 +328,14 @@ class FrozenIntegrityError(ReviewSampleError): KEY: "f333386d20ce327df27c2747aef317e96e030c61650f3f20b60d06f038802ad9", MANIFEST: "05dc1b1679f9fdce7560ff5da1f9a869fd84c8617646410e56aa3cbce59e3868", } +# Protocol amendment 2: offline pre-cutoff evidence packets (evidence-packets/1), built at +# 240ba9b on a clean tree before any review. Separate files; the frozen sheets are untouched. +COHORTS[SAMPLE_VERSION]["evidence"] = ( + "68f11afba87266ee393dcf33a84c913c55fca9c01656f7a1b1d6dfc5122d46ae" +) +COHORTS["hard-negative-candidates/1"]["evidence"] = ( + "1c7f32c64c9c2beb0342baf8762d5381a5923f0c04389e83dd5da4919cdc01bf" +) def cohort_for_sheet(sheet_sha256: str) -> str | None: diff --git a/tests/review_fixtures.py b/tests/review_fixtures.py index 343ed02..eba6a5d 100644 --- a/tests/review_fixtures.py +++ b/tests/review_fixtures.py @@ -78,6 +78,7 @@ def frozen(tmp: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path, dict monkeypatch.setitem(rs.FROZEN_V1, name, rs.file_sha256(sample / name)) monkeypatch.setitem(rs.FROZEN_V1, "selection", manifest["selection_sha256"]) monkeypatch.setitem(rs.FROZEN_V1, "queue", rs.file_sha256(q)) + monkeypatch.delitem(rs.FROZEN_V1, "evidence", raising=False) # no packets in synthetic runs return q, sample, manifest From 4fc9d94f011fa36abdcecce76c9cd308fc701957 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 14:13:14 +0300 Subject: [PATCH 32/92] docs(ml): Phase 11.6 human validation readiness, amendment 2, reviewer handoff State: REVIEW_READY - HUMAN ANNOTATION PENDING (0 submissions). Documents the cohort re-verification and Cohort B's superseded-draw history, evidence packet quality and blinding limits, the label policy, estimands, power and cost scenarios, gates A-K, the reviewer invitation draft and maintainer checklist. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 29 +++ ML.md | 7 + ML_ANNOTATION_AUDIT.md | 11 ++ ML_BENCHMARK_READINESS.md | 15 ++ ML_HARD_NEGATIVE_STUDY.md | 12 ++ ML_HUMAN_VALIDATION_READINESS.md | 329 +++++++++++++++++++++++++++++++ ML_RESEARCH_PLAN.md | 6 +- docs/ml/review-protocol.md | 91 +++++++++ docs/ml/reviewer-guide.md | 50 ++++- docs/ml/reviewer-handoff.md | 86 ++++++++ 10 files changed, 628 insertions(+), 8 deletions(-) create mode 100644 ML_HUMAN_VALIDATION_READINESS.md create mode 100644 docs/ml/reviewer-handoff.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ba08e1..5cc8b72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,35 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Human validation readiness (Phase 11.6) +- Both frozen cohorts re-verified byte for byte, and the history of Cohort B's superseded + first draw audited. No reviewer, package or submission exists: state REVIEW_READY. +- Added offline pre-cutoff evidence packets (`ml review build-evidence`). + - They are deterministic, read no key and contain no source flags, payoffs or + similarity scores. + - They are tested so that future rows and labels never change them. + - They are registered by hash and shown in the review page. +- Protocol amendment 2, before any review: + - later-payment and third-party-label exposure, offline-panel use, reason codes and + evidence citations; + - pre-specified exposure sensitivity analyses; + - a synthetic training cohort (`ml review training-package`) that can never be + unblinded; + - review sessions that expire. +- Added submission checks and a key-free agreement report (`ml review check-submission`, + `ml review agreement`). +- Added a label policy with seven statuses and strict binary eligibility. +- Added an inactive, pre-registered experiment spec; it needs 30 reviewed labels per class + from 5 campaign groups each. +- Added FPR power planning; the contract now also refuses source and dataset identifiers + as features. +- Fixed: a locked lease table raised a raw database error. It now raises the retryable + `LeaseBusyError`, and the contention test reports each child's outcome. +- Faster: `candidates/2` buckets counterparties by suffix (exact). 10,000 transfers take + 0.13 s instead of 13 s. +- Docs: ML_HUMAN_VALIDATION_READINESS.md, docs/ml/reviewer-handoff.md, and an updated + reviewer guide and protocol. + ### Hard-negative discovery and benchmark contract (Phase 11.5) - `candidates/2`: a counterparty counts as chosen only with a verified wallet signature, and generation is a single pass. The output is identical on all 13 recorded windows and diff --git a/ML.md b/ML.md index b842212..132d69e 100644 --- a/ML.md +++ b/ML.md @@ -56,6 +56,13 @@ method and decision log. matching), `ml/cohort.py` (generic frozen cohorts), `ml/evaluation.py` (benchmark contract and metrics that refuse unverified negatives), `ml/hn_study.py` and `ml/inventory.py` ([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). + - Phase 11.6: + - `ml/evidence.py`: offline pre-cutoff evidence packets; + - `ml/training.py`: a synthetic training cohort; + - `ml/submissions.py`: submission checks and the key-free agreement report; + - `ml/label_policy.py`, `ml/experiment_spec.py` (inactive) and `ml/power.py`. + + See [ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md). - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. diff --git a/ML_ANNOTATION_AUDIT.md b/ML_ANNOTATION_AUDIT.md index b90cf89..18659f8 100644 --- a/ML_ANNOTATION_AUDIT.md +++ b/ML_ANNOTATION_AUDIT.md @@ -334,3 +334,14 @@ No P0 finding: every hash, uniqueness, separation, allocation and reserve-order - items carry the neutral title "Candidate for independent security review". - **The Phase 11.4 sample is unchanged** (re-verified). - Design and hashes: [ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md) §12. + +## 21. Amendment 2 and evidence packets (Phase 11.6) + +- **Evidence packets.** Both cohorts now carry offline, pre-cutoff evidence packets + (`evidence-packets/1`, hashes registered). The packets never contain source flags, the + intended address, payoffs or similarity scores. +- **New decision fields.** Each decision records later-payment exposure, third-party-label + influence, offline-panel use, reason codes and evidence citations. +- **Calibration.** A synthetic training cohort precedes real review. +- **Sensitivity analyses** are pre-specified in protocol B4. +- **Status:** [ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md). diff --git a/ML_BENCHMARK_READINESS.md b/ML_BENCHMARK_READINESS.md index 85d3d34..5211803 100644 --- a/ML_BENCHMARK_READINESS.md +++ b/ML_BENCHMARK_READINESS.md @@ -148,3 +148,18 @@ blocked by missing evidence, not yet evaluated. Infrastructure alone never passe | H Baseline comparability | blocked by missing evidence | the detector needs wallet histories; only the recorded-window frame has them, and it has no labels | | I Operational relevance | not yet evaluated | unlabeled candidate volume only (8 on 27 wallet-days); no reviewed false alerts | | J Deployment safety | **pass** | research modules load neither database nor API (tested); no production finding changes | + +## 9. Phase 11.6 gates + +[ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md) re-evaluates readiness +as gates A-K. + +| Gate | Status | +|---|---| +| A frozen integrity, G temporal correctness, K production isolation | pass | +| B evidence, C independence, F source bias, H splits | pass with limitations | +| D positive labels, E negative labels, J ML readiness | blocked by missing human evidence | +| I statistical adequacy | fail | + +The pre-registered experiment (`ml/experiment_spec.py`) stays inactive until at least 30 +reviewed labels per class exist, from at least 5 campaign groups each. diff --git a/ML_HARD_NEGATIVE_STUDY.md b/ML_HARD_NEGATIVE_STUDY.md index 3875219..6c900d2 100644 --- a/ML_HARD_NEGATIVE_STUDY.md +++ b/ML_HARD_NEGATIVE_STUDY.md @@ -440,3 +440,15 @@ requests, no download. legitimate examples come back, the next step is a negative-only cohort drawn from the 4,940 unscreened archive candidates, using the same frozen procedure. That also needs no RPC. + +## 26. Phase 11.6 follow-up + +- **Cohort history audited.** The first, superseded draw of Cohort B was compared with the + final one: same items, reserves, strata and sheet bytes, with only 3 screening statuses + changed. No package had been issued. + - Details: [ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md) §3. +- **Evidence packets.** Cohort B's 35 items now have offline evidence packets: 19 archive + items have no local wallet history, and 11 recorded-wallet items have their full window. +- **Generator speed.** `candidates/2` buckets chosen counterparties by their last 3 + characters (an exact shortcut, since the rule requires them). 10,000 transfers take + 0.13 s instead of 13 s, and the output is unchanged. diff --git a/ML_HUMAN_VALIDATION_READINESS.md b/ML_HUMAN_VALIDATION_READINESS.md new file mode 100644 index 0000000..f2e3b95 --- /dev/null +++ b/ML_HUMAN_VALIDATION_READINESS.md @@ -0,0 +1,329 @@ +# Human validation readiness (Phase 11.6) + +**State: REVIEW_READY: HUMAN ANNOTATION PENDING.** +- Finalized human submissions: **0**. Real items reviewed: **0** of 95 (190 planned + decisions). +- No label, benchmark or model exists from this work. 0 RPC requests, 0 downloads. + +## 1. Research objective + +Can a model distinguish genuine address-poisoning attempts from legitimate activity that +looks like poisoning, using only information available at the prediction cutoff? Phase +11.6 builds the bridge between blockchain evidence, independent human judgment and future +evaluation. It does not answer the question. + +## 2. Current annotation status + +| Item | Status | +|---|---| +| Reviewers recruited | none | +| Packages issued | none (verified: no annotation log or submission exists under `data/`) | +| Training cohort | built; synthetic only | +| Cohort A `review-sample/1` | 60 items, frozen, evidence packets registered | +| Cohort B `hard-negative-candidates/1` | 35 items, frozen, evidence packets registered | + +## 3. Frozen cohort verification + +**Both cohorts.** `cryptoguard ml review verify [--cohort …]` re-hashes the raw bytes of +the queue, sheet, key and manifest, recomputes the selection hash and checks ids. Both +pass. Their bytes are unchanged since freezing: + +| | Cohort A | Cohort B | +|---|---|---| +| Selection | `e368beb4…85a62` | `ae9df36a…6ddb57` | +| Sheet | `a0ec4b6e…814027` | `121c112d…ca108` | +| Key | `407b412f…03bb2d` | `f333386d…802ad9` | +| Manifest | `c38ae31d…dbdc3` | `05dc1b16…e3868` | + +**Cohort A.** The design audit reruns clean: unique items, one per campaign and per victim, +allocation reproduced, reserve order, exact weights. + +**Cohort B history**, audited from the files kept in `superseded/cohort_v1_first_draw/`: +- **First draw.** Frozen at 12:45 on 2026-11-02, on commit `59c8207` with uncommitted + code (manifest `git.dirty = true`). +- **Defect.** Minutes later, a weak-similarity candidate outside the screened block range + was found to be marked "no known overlap" instead of "insufficient information". +- **Effect.** Comparing the two draws: identical selected items, reserves, strata, weights + and reviewer sheet bytes. Exactly 3 key rows changed, all `screen_status` of selected + items (`no_known_overlap` → `insufficient_information`). +- **Why the redraw is valid:** + - no package was issued and no label existed or was viewed; + - the frame hash, and therefore the selection hash, changed only through the corrected + statuses; + - the selection itself did not change. +- **Record.** The superseded files are kept, and ML_HARD_NEGATIVE_STUDY.md §12 records the + episode. Independence is not compromised. The one limitation: the design was finalized + minutes after a draw had been seen by the maintainer, who is not a reviewer. + +## 4. Evidence packet quality + +**Builder.** `ml/evidence.py` (`evidence-packets/1`): +- deterministic and offline; +- reads the sheet, never the key, and never the source's flags, intended address or + payoff markings; +- strictly pre-cutoff, with a same-block row included only when the recorded order + proves it came earlier; +- unknowns are explicit; +- a cutoff that contradicts the data raises `EvidenceError`. + +| | Cohort A (60) | Cohort B (35) | +|---|---|---| +| Candidate transfer found locally | 60 | 35 | +| Wallet rows before cutoff | median 22 | none locally for 19 of 24 archive items; the full recorded window for the 11 others (1 of them empty) | +| Earlier rows between wallet and address | 26 items | 3 items | +| Coverage | all `source_selected_rows_only` + `unknown_signer`; 27 also `unknown_token_legitimacy` | 24 archive (19 `partial_history`), 11 `complete_for_declared_scope`; 25 `unknown_signer`, 6 `unknown_token_legitimacy` | +| Packets SHA-256 | `68f11afb…2d46ae` | `1c7f32c6…dc01bf` | + +**Checks on the real served state** (counts only): +- 0 of 60 payoff transactions appear; +- 0 source summaries or category labels appear; +- the field name `zero_value` is the packet's observed value flag, not a label. + +**The imitated address is visible by design.** In all 60 Cohort A packets it appears +among the earlier rows, as a counterparty the wallet really paid before the cutoff. This +is observable pre-cutoff evidence, disclosed in amendment 2. + +**Metamorphic tests.** Future rows, later payoffs and altered source flags or intended +addresses never change a packet. + +## 5. Blinding limitations + +- A block explorer shows later activity and phishing tags; the offline panel reduces the + need for one. +- Each decision records later-payment exposure, third-party-label influence, explorer use + and offline-panel use (amendment 2). Exposed items are kept, and sensitivity analyses + are pre-specified (protocol B4). +- Archive packets are source-selected, which can make attacks look more obvious than a + full history would. The coverage status says so. + +## 6. Reviewer workflow + +**Server.** The local app (loopback only) has: +- a session token in a custom header, and a Host check; +- strict CSP and text-only rendering; +- sessions that expire after 12 hours. + +**The page** adds: +- a cutoff banner and an evidence checklist; +- the offline evidence panel, with coverage warnings; +- reason codes and evidence citations; +- keyboard shortcuts, drafts, resume and mobile layout (all checked in the browser on the + synthetic training package). + +**Saving and finalizing** are hash-chained and atomic. + +**Submission checks** (`ml/submissions.py`, `review check-submission`) report every +problem: +- missing or corrupt file; +- edited content; +- stale protocol; +- wrong cohort or sample; +- mixed reviewer ids; +- unknown, missing or repeated items. + +**Training.** A synthetic cohort of ten cases (`training/1`); it can never be unblinded. + +## 7. Label policy (`ml/label_policy.py`) + +**Seven statuses, never collapsed:** external source assertion, reviewed attack, reviewed +legitimate, likely attack, unknown, conflicting, later victim loss. + +**Strict binary benchmark.** It admits only `reviewed_attack` (two or more reviewers, all +*confirmed attempt*) and `reviewed_legitimate` (all *confirmed legitimate*). Every +exclusion is counted. Adjudication is a separate layer. + +## 8. Statistical design + +**Estimands, never pooled:** + +| Estimand | Cohort | Unit | Weights | +|---|---|---|---| +| Source-positive confirmation rate | A | campaign group (1,395 in the frame) | stratified, `N_c/n_c` | +| Hard-candidate legitimate rate | B | eligible candidate frame (5,232 items in 2,664 groups) | stratified, `N_c/n_c` (up to 197.5) | +| Agreement | each | the items reviewed | unweighted | +| Evidence sufficiency | each | items | unweighted | + +- **Attempt-level (A):** bounds only. **Victim-level:** not estimated. +- **Intervals:** design-based Wilson on the effective sample size, with collapsed strata + (amendment 1). +- **Not a population rate.** Neither cohort's class mix is Ethereum prevalence. +- **Cohort B is too small for a low-FPR claim.** Even if all 35 items were reviewed + legitimate, the zero-error Wilson bound is about 0.10 unweighted and wider with + weights, not 1%. + +## 9. Agreement analysis + +`ml/agreement.py`, `review agreement` (needs no key): +- exact agreement, confusion matrix, disagreement counts; +- Cohen's kappa (`None` with a reason when undefined, never 0); +- Gwet's AC1; +- insufficient- and conflicting-evidence rates per reviewer; +- per-stratum results only with 10 or more items. + +These are tested against hand-computed values. Agreement measures consistency, not truth. + +## 10. Source-selection bias + +The Phase 11.5 findings stand: +- value alone separates the source frames (AUC 1.0); +- direction gives 0.98; +- everything except value gives 0.99. + +**Safeguard.** The benchmark contract refuses feature names containing label, outcome, +payoff, score or prediction, and also source, dataset, cohort, frame, row-index, +line-number or file names. + +**Caveat.** Removing explicit identifiers does not remove selection bias. Reviewed +positives (Cohort A) and reviewed negatives (Cohort B) come from different frames. A +classifier separating them could learn the frames. A benchmark built only from these two +cohorts would be easy and unrepresentative, and the experiment spec forbids that. + +## 11. Negative-data validity + +- **Status.** No reviewed legitimate example exists. +- **Cohort B is a frame of candidates, not of negatives.** 7 of its 8 background-wallet + candidates have attack shapes, and 42% of its archive frame was excluded as known + attacks before sampling. + +## 12. Benchmark leakage protections + +- **Typed grouping.** It links events through planting transactions, lookalikes, signers, + victims, imitated addresses, counterfeit tokens and verified attack infrastructure, but + never through public tokens or routers. +- **Holdout.** `benchmark.holdout_from_sheets` protects *both* cohorts as one holdout, and + any development use is recorded permanently. +- **Point-in-time features.** Tested metamorphically for features and for packets. +- **Split report.** Measures entity overlap between splits. + +## 13. ML experiment specification (`ml/experiment_spec.py`) + +**Status: inactive.** It is pre-registered: +- **Unit and cutoff:** a victim-event, judged at the cutoff. +- **Target:** the strict binary label. +- **Splits:** grouped-temporal. +- **Threshold:** chosen on validation (highest recall with FPR ≤ 5%). +- **Primary metric:** AP, with recall at FPR ≤ 5%. +- **Calibration:** only with 100 or more items per class. +- **Baselines:** the production rule, the similarity, shape and history heuristics, LR and + LightGBM. +- **Feature groups:** similarity, transaction, wallet history, temporal, graph and combined. + Every column is checked against the real feature row. +- **Budget:** CPU only, under 2 GB and 2 minutes. +- **No GNN.** + +**Activation** needs at least 30 reviewed labels per class, from at least 5 campaign groups +each. 60 labels from one campaign are refused (tested). + +## 14. Sample size (`ml/power.py`) + +Reviewed legitimate events needed so the two-sided 95% Wilson upper bound on FPR falls +below the target: + +| Target FPR | True FPR 0 | True FPR = half the target | ×1.5 clustering | ×2 clustering | +|---|---|---|---|---| +| 10% | 35 | 139 | 53 / 209 | 70 / 278 | +| 5% | 73 | 292 | 110 / 438 | 146 / 584 | +| 1% | 381 | 1,522 | 572 / 2,283 | 762 / 3,044 | + +**Choosing a target.** A tool scanning every event of many wallets needs a low FPR to be +usable. Which FPR is acceptable is an operational decision, not a statistical one, and no +evidence for it exists yet. + +## 15. Data acquisition cost (scenarios, nothing collected) + +**Basis:** +- background candidate volume: 8 per 27 wallet-days (unlabeled); +- the legitimate share *f* is unknown; +- the planner gives 1,345 requests per 3-day wallet window (free endpoint, conservative). + +| Reviewed legitimate events | *f* | Wallet-days | Wallets | RPC requests | Items to review (decisions) | +|---|---|---|---|---|---| +| 73 | 0.5 | 493 | 165 | 221,925 | 146 (292) | +| 73 | 0.25 | 986 | 329 | 442,505 | 292 (584) | +| 73 | 0.125 | 1,971 | 657 | 883,665 | 584 (1,168) | + +**Why these are scenarios.** Background candidates looked mostly like attacks, so a low +*f* is plausible. Storage is small: the recorded windows are 1–190 KB each. Any collection +needs a separately approved cap. + +## 16. Licensing restrictions + +- **Kept local:** archive-derived packets, sheets, keys, packages and submissions + (CC BY-NC-ND 4.0). +- **Unresolved:** whether per-item labels or packets may be published. This is not legal + advice. +- **Synthetic and public data:** the training cases are synthetic, and the recorded + fixtures are public chain data. + +## 17. Testing and CI + +See the final report in the PR for the exact counts of this phase's run. + +**New tests cover:** +- evidence packets: cutoff, metamorphic future rows and labels, inconsistent cutoff, + missing transaction, exact in-block order, determinism, bounded history; +- the training cohort and refused unblinding; +- tampered evidence and session expiry; +- amendment-2 validation; +- submission checks and the agreement report; +- the label policy, spec activation, power and leakage guards; +- the generator: same-block order and duplicate input. + +**Lease reliability.** One earlier full run had a lease-contention failure. +- It was not reproduced in 16 rounds under CPU and fsync-heavy disk load. +- The one mechanism found: a locked database raised a raw `OperationalError`. It now raises + a typed, retryable `LeaseBusyError`. +- The contention test reports each child's exception and asserts safety separately from + liveness. +- A deterministic test covers the busy path. + +**Generator.** `candidates/2` now buckets chosen counterparties by suffix (exact). 10,000 +transfers take 0.13 s instead of 13 s, with output identical on all 13 recordings. + +## 18. Remaining blockers (by scientific importance) + +1. **Human:** two independent reviewers for 95 items (190 decisions). +2. **Human:** no reviewed legitimate examples. Gates E, I and J depend on them. +3. **Data:** 19 of 35 Cohort B items have no local wallet history; reviewers need an + explorer. +4. **Statistics:** 35 candidates cannot support low-FPR claims (§14). +5. **Licensing:** the per-item publication question. + +## 19. Human reviewer handoff + +[docs/ml/reviewer-handoff.md](docs/ml/reviewer-handoff.md) has: +- the invitation draft and eligibility; +- the workload, about 9 hours per reviewer (an assumption); +- data handling and independence; +- the maintainer checklist. + +The reviewer guide and protocol amendments 1 and 2 are in `docs/ml/`. + +## 20. Next scientific experiment + +**Experiment.** The two reviewers work through the training package, then both cohorts, +per the checklist. + +**Requirements:** +- **People:** two humans. +- **No new data, no RPC and no new authorization.** +- **No new engineering** beyond fixing what their feedback reveals. + +**Value.** The first independent positives and candidate negatives, agreement on both, and +measured review time, which replaces the 5-minute assumption. + +## Decision gates + +| Gate | Status | +|---|---| +| A Frozen data integrity | **PASS** (both cohorts byte-identical; Cohort B history documented) | +| B Evidence sufficiency | PASS WITH LIMITATIONS (packets for all 95; archive rows are source-selected; 19 B items lack local history) | +| C Reviewer independence | PASS WITH LIMITATIONS (separate packages, stores and finalization; procedural on a shared computer; no humans yet) | +| D Positive-label validation | BLOCKED BY MISSING HUMAN EVIDENCE | +| E Negative-label validation | BLOCKED BY MISSING HUMAN EVIDENCE | +| F Source bias | PASS WITH LIMITATIONS (documented; source identifiers refused as features; selection bias remains) | +| G Temporal correctness | **PASS** (metamorphic tests on features and packets) | +| H Split independence | PASS WITH LIMITATIONS (typed grouping and holdout guards; untested on real labelled splits) | +| I Statistical adequacy | **FAIL** (0 labels; 35 candidates bound FPR at about 10% at best) | +| J ML readiness | BLOCKED BY MISSING HUMAN EVIDENCE (spec inactive) | +| K Production isolation | **PASS** (research modules load neither database nor API; findings unchanged) | diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index d22e456..fd8e0a5 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -9,8 +9,10 @@ annotation workflow; it now waits for two human reviewers ([ML_ANNOTATION_AUDIT.md](ML_ANNOTATION_AUDIT.md), [ML_BENCHMARK_READINESS.md](ML_BENCHMARK_READINESS.md)). Phase 11.5 added a screened pool of 8,877 unlabeled hard-negative candidates and a second frozen cohort of 35 -([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). Both cohorts wait for the same -two reviewers. Data model and labels: +([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). Phase 11.6 made both cohorts +review-ready (evidence packets, protocol amendment 2, training cohort, handoff): status +REVIEW_READY: HUMAN ANNOTATION PENDING +([ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md)). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). diff --git a/docs/ml/review-protocol.md b/docs/ml/review-protocol.md index d117aa9..4b6d46c 100644 --- a/docs/ml/review-protocol.md +++ b/docs/ml/review-protocol.md @@ -193,3 +193,94 @@ Background: [ML_ANNOTATION_AUDIT.md](../../ML_ANNOTATION_AUDIT.md) §19. 7. `cryptoguard ml review unblind --submission A.json --submission B.json`. 8. Report from `unblinded_report.json` (aggregate). Keep `unblinded_items.jsonl` and the submissions local. + +--- + +# Amendment 2 (2026-11-02, before any review; applies to both cohorts) + +**Status when written:** +- No reviewer had been recruited, no package issued and no decision made, in either + cohort. +- No unblinding key was opened. Packets are built from the reviewer sheet and local + recorded data only. +- The frozen sheets, keys and manifests of `review-sample/1` and + `hard-negative-candidates/1` are unchanged. Amendment 2 only *adds* a separate, + hash-registered file. + +## B1. Defect + +Reviewers of the first cohort saw only four facts: +- the wallet; +- the address under review; +- the transaction; +- the block. + +To judge impersonation they had to rebuild the wallet's earlier counterparties on a block +explorer. An explorer also shows the later payment that put every item in this cohort +(hindsight). Where no explorer was used, the protocol gave reviewers too little to work +with. + +## B2. Correction: offline pre-cutoff evidence packets (`evidence-packets/1`) + +**What a packet holds.** For each item (`ml/evidence.py`, built by +`cryptoguard ml review build-evidence`): +- the candidate transfer(s); +- transaction semantics; +- the token and whether it is on CryptoGuard's reviewed list; +- the number of earlier rows between the wallet and the address; +- up to 50 of the wallet's rows *strictly before* the cutoff block; +- for archive data, how often the address appears with other wallets before the cutoff; +- explicit coverage statuses. + +**What it never holds:** +- the source's category flags, its `intended` (imitated) address or its payoff markings; +- any row at or after the cutoff block; +- any model output; +- any similarity score. Reviewers still find the imitated counterparty themselves. + +**Coverage.** Archive packets contain only the rows the research dataset kept, so the +imitated counterparty will usually be visible among the earlier rows, but ordinary activity +is missing. The packet says this (`source_selected_rows_only`). It is observable pre-cutoff +information, not the source's conclusion. + +**Registered hashes:** + +| Cohort | Packets SHA-256 | Items | +|---|---|---| +| `review-sample/1` | `68f11afba87266ee393dcf33a84c913c55fca9c01656f7a1b1d6dfc5122d46ae` | 60 | +| `hard-negative-candidates/1` | `1c7f32c64c9c2beb0342baf8762d5381a5923f0c04389e83dd5da4919cdc01bf` | 35 | + +Built at commit `240ba9b` on a clean tree. The review app refuses a packet file whose hash +is not registered. + +## B3. Correction: recorded exposure, reasons and citations + +Each amendment-2 decision also records: +- `saw_later_victim_payment`: no / yes / unsure; +- `third_party_label_influenced`: no / yes / unsure; +- `used_offline_evidence`: whether the reviewer used the offline panel; +- `reason_codes`: at least one for any confirmed decision; +- `evidence_refs`: transaction hashes or addresses, validated. + +Amendment-1 records stay loadable. New submissions must be amendment 2, or the unblinding +gate refuses them. + +## B4. Pre-specified sensitivity analyses + +1. **Primary results** use every item, whatever the exposure. No item is dropped because + it was exposed. +2. **Exposure sensitivity.** Repeat the primary analysis excluding items where *either* + reviewer answered `yes` to `saw_later_victim_payment` or `third_party_label_influenced`. + Report it beside the primary. +3. **Offline-only sensitivity.** Restrict to items both reviewers judged with + `used_explorer = false`, where available. + +These comparisons are descriptive. Any difference is reported, not "corrected". + +## B5. Training before review + +Each reviewer first works through the synthetic training package +(`cryptoguard ml review training-package`). It has ten invented cases with evidence +packets and separate teaching notes, read afterwards. Training decisions stay in the +training folder and can never be unblinded. The real items are never used for +calibration. diff --git a/docs/ml/reviewer-guide.md b/docs/ml/reviewer-guide.md index acdb34e..bd20a42 100644 --- a/docs/ml/reviewer-guide.md +++ b/docs/ml/reviewer-guide.md @@ -1,12 +1,20 @@ # Reviewer guide: CryptoGuard poisoning review -Thank you for reviewing. You will judge 60 Ethereum transactions, independently. Please do -not discuss items with the other reviewer until you have both submitted. +Thank you for reviewing. You will judge Ethereum transactions independently: two folders, +60 and 35 items. Please do not discuss items with the other reviewer until you have both +submitted. -## Setup (once) +## Before the real items: training (about an hour) -1. Get your personal review folder from the maintainer. It contains `reviewer_sheet.jsonl` - and `reviewer.json`, and nothing else is needed. +Start with the training folder. It holds ten invented cases with the same panels as the +real items. Read `training_notes.md` in that folder *after* trying them. Training answers +are never used as data, and the real items are never used for practice. + +## Setup (once per folder) + +1. Get your personal review folders from the maintainer. Each contains + `reviewer_sheet.jsonl`, `reviewer.json` and usually `evidence_packets.jsonl`, and + nothing else is needed. 2. From the CryptoGuard repository, with Python 3.12 and `uv`, run: ```bash @@ -63,6 +71,31 @@ Judge them exactly like any other item. Any of the five decisions may be right, "Confirmed poisoning attempt". The table is a convenience: it shows only what was recorded, so check an explorer when the note says history is missing. +## The offline evidence panel + +Most items show an **Offline evidence** panel. It lists what this computer's recorded data +show *before the cutoff block*: +- the candidate transfer; +- who signed it (when known); +- the token; +- the wallet's earlier transfers; +- for some items, how often the address appeared with other wallets. + +Read the coloured notes: +- **"Only rows a research dataset kept"**: ordinary activity is missing. Absence of a + payment there does not mean the wallet never paid anyone. +- **"No earlier rows of this wallet are available locally"**: use a block explorer, up to + the cutoff block. +- **"Token not on the reviewed list"**: unknown, not necessarily fake. + +The panel never tells you the answer and computes no similarity. Find the earlier +counterparty yourself and paste it into the form. + +## Reasons and citations + +For a confirmed decision, tick at least one reason. Paste the transaction hashes or +addresses you relied on into **Evidence cited**, one per line. + ## Be honest about what you saw Block explorers show later activity and sometimes labels such as "Phishing". That is fine. @@ -72,7 +105,12 @@ Just record it: - whether you saw a third-party label; - whether you saw any source label, payoff record or model output. -These answers are not judged. +You will also be asked: +- whether you saw a later payment from the wallet to this address; +- whether a third-party label influenced you; +- whether you used the offline panel. + +These answers are not judged, and an item is never removed because of them. ## Keyboard diff --git a/docs/ml/reviewer-handoff.md b/docs/ml/reviewer-handoff.md new file mode 100644 index 0000000..a4fdfe1 --- /dev/null +++ b/docs/ml/reviewer-handoff.md @@ -0,0 +1,86 @@ +# Reviewer handoff (maintainer) + +Materials for recruiting two independent human reviewers. Nothing here has been sent. No +reviewer has been contacted, has agreed or exists yet. + +## 1. Invitation draft (edit before sending; promise nothing not yet decided) + +> **Subject: Independent review of Ethereum transactions (address-poisoning research)** +> +> I am looking for an independent reviewer for a small research study on Ethereum +> address poisoning: attackers planting look-alike addresses in a wallet's history. +> You would judge about 95 historical transactions, plus 10 training cases, using a +> local review page on your own computer and, if you wish, a public block explorer. +> +> What it involves: +> - installing a Python tool from a private repository; +> - working independently, without discussing items with the other reviewer until both +> of you have submitted; +> - recording, for each item, a decision, your reasons and what you saw. +> +> The data come from a licensed research dataset and must stay on your computer. They are +> not to be shared or published. +> +> My rough estimate is [N] hours. This is an assumption, not a measured time. +> +> Would you be willing? + +## 2. Eligibility + +- Comfortable reading Ethereum transactions, token transfers and logs on a block explorer. +- Understands ERC-20 `transfer`/`transferFrom`, zero-value transfers and token contracts. +- Did not build the samples or see their answer keys. The maintainer and any AI assistant + involved are not eligible. +- Two *different people*. Two sessions of one person, or of an AI model, do not count. + +## 3. Workload (assumption, not measured) + +| Part | Items | Decisions (2 reviewers) | Assumed minutes per item | Hours per reviewer | +|---|---|---|---|---| +| Training | 10 | 20 | 5 | about 1 | +| Cohort `review-sample/1` | 60 | 120 | 5 | about 5 | +| Cohort `hard-negative-candidates/1` | 35 | 70 | 5 | about 3 | +| **Total** | 105 | 210 (190 real) | | **about 9** | + +The 5 minutes per item comes from no pilot. Replace it with the median time of the +training cases once a reviewer has done them. + +## 4. Data handling + +- Packages contain addresses derived from CC BY-NC-ND 4.0 research data. Keep them on the + reviewer's computer, use them only for this review, and delete them afterwards if asked. +- Return only `annotations/submission.json`. +- Do not post screenshots or item details anywhere. + +## 5. Independence + +- One package and one store per reviewer, on separate computers or user accounts where + possible. On a shared computer, independence is procedural. +- The reviewers do not see each other's decisions, the answer keys, the manifests or any + model output before both have finalized. +- After finalization nothing can be edited. Changes need a protocol amendment. + +## 6. Maintainer checklist + +1. `cryptoguard ml review verify` and `cryptoguard ml review verify --cohort + hard-negative-candidates/1`: all hashes match. +2. Check the evidence packets are in place. If either command below says they are missing, + rebuild them: + - `cryptoguard ml review build-evidence` + - `cryptoguard ml review build-evidence --cohort hard-negative-candidates/1` + + The printed hashes must equal the registered ones (`review_sample.COHORTS`). +3. For each reviewer R (pseudonyms `A`, `B`): + - `cryptoguard ml review training-package --reviewer R --out /training-R` + - `cryptoguard ml review package --reviewer R --out /sample-R` + - `cryptoguard ml review package --cohort hard-negative-candidates/1 --reviewer R --out + /candidates-R` +4. Send each reviewer only their own three folders, `docs/ml/reviewer-guide.md` and this + repository's setup instructions. +5. When a submission arrives, run + `cryptoguard ml review check-submission [--cohort …]` and fix nothing by hand. A + problem goes back to the reviewer. +6. With both finalized: run `cryptoguard ml review agreement --submission A --submission B + [--cohort …]`. It needs no key. +7. Only then: `cryptoguard ml review unblind …` per cohort. Report aggregates. Keep the + per-item files local. From 1d6f2a090c949e2bf3929e0c7bf9bf42b14cfe8c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 14:53:34 +0300 Subject: [PATCH 33/92] feat(ml): evidence packets v2, review-server hardening, diagnostics, research verification evidence-packets/2 counts same-block rows of unknown order (shown as ambiguous, never silently dropped) and states what 'no earlier interaction' means under complete, source-selected or absent coverage. The review server refuses negative or non-numeric Content-Length (a negative length made it read until the client closed) and requests whose browser Origin is not the app itself. Adds exact Clopper-Pearson FPR bounds by sample size and clustering, a source-proxy-free ablation and fairness/governance fields in the inactive experiment spec (JSON export), 'ml verify-research' (offline PASS/FAIL/MISSING/BLOCKED report), 'ml diagnostics' (source-positive candidate coverage, evidence availability, generator invariance, scalability) and the review-context archive recovery pass. Tests include an independent reference for candidates/2 and an end-to-end synthetic review workflow. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 37 ++ src/cryptoguard/ml/diagnostics.py | 302 +++++++++++++++++ src/cryptoguard/ml/evidence.py | 29 +- src/cryptoguard/ml/experiment_spec.py | 40 +++ src/cryptoguard/ml/hard_negative_archive.py | 35 ++ src/cryptoguard/ml/power.py | 42 +++ src/cryptoguard/ml/review_app/app.js | 6 +- src/cryptoguard/ml/review_server.py | 12 +- src/cryptoguard/ml/verify_research.py | 175 ++++++++++ tests/unit/test_ml_evidence_completion.py | 355 ++++++++++++++++++++ tests/unit/test_ml_validation_readiness.py | 1 - 11 files changed, 1028 insertions(+), 6 deletions(-) create mode 100644 src/cryptoguard/ml/diagnostics.py create mode 100644 src/cryptoguard/ml/verify_research.py create mode 100644 tests/unit/test_ml_evidence_completion.py diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index ca17f5b..eaf2a21 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -93,6 +93,15 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ) fr.add_argument("--out", type=Path, default=ML_DIR / "poisoning" / "review_sample") _add_review_parser(ml) + es = ml.add_parser("experiment-spec", help="write the pre-registered experiment spec (JSON)") + es.add_argument("--out", type=Path, default=Path("docs/ml/experiment-spec.json")) + vr = ml.add_parser("verify-research", help="offline reproducibility check of research inputs") + vr.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + vr.add_argument("--out", type=Path, default=ML_DIR / "verify-research.json") + vr.add_argument("--skip-archive-hash", action="store_true", help="size check only (fast)") + dg = ml.add_parser("diagnostics", help="label-free offline diagnostics (aggregate output)") + dg.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + dg.add_argument("--out", type=Path, default=ML_DIR / "diagnostics.json") iv = ml.add_parser("inventory", help="hash and describe every local research data file") iv.add_argument("--root", type=Path, default=Path(".")) iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") @@ -155,6 +164,34 @@ def run(args: argparse.Namespace) -> int: return _freeze_review_sample(args) if args.ml_command == "review": return _review(args) + if args.ml_command == "experiment-spec": + from cryptoguard.ml.experiment_spec import spec_json + + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(spec_json(), encoding="utf-8", newline="\n") + print(f"Wrote {args.out} (inactive until reviewed labels exist).") + return 0 + if args.ml_command == "verify-research": + import json + + from cryptoguard.ml.verify_research import verify + + report = verify(args.data_dir, ML_DIR, hash_archive=not args.skip_archive_hash) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8") + for c in report["checks"]: + print(f"{c['status']:8} {c['check']}: {c['detail']}") + print(f"Wrote {args.out}.") + return 0 if not any(c["status"] == "FAIL" for c in report["checks"]) else 1 + if args.ml_command == "diagnostics": + import json + + from cryptoguard.ml.diagnostics import run_diagnostics + + report = run_diagnostics(args.data_dir, ML_DIR / "poisoning") + args.out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8") + print(json.dumps({k: v for k, v in report.items() if k != "notes"}, indent=1)[:4000]) + return 0 if args.ml_command == "inventory": import json diff --git a/src/cryptoguard/ml/diagnostics.py b/src/cryptoguard/ml/diagnostics.py new file mode 100644 index 0000000..7cf914c --- /dev/null +++ b/src/cryptoguard/ml/diagnostics.py @@ -0,0 +1,302 @@ +"""Label-free offline diagnostics (``cryptoguard ml diagnostics``, Phase 11.7). Aggregate +output only. Nothing here is fraud-detection accuracy. + +1. **Source-positive candidate coverage.** For the payoff-linked source positives (the 60 + reserved review items excluded), rebuild a 7-day history before each planting from the + archive rows of the victim, then check whether ``candidates/2`` emits the planting. + - *strict*: no signer is known (the archive records none); + - *optimistic*: the victim's own non-poisoning outgoing rows count as signed. This uses + the source's flags only to model the signer, as a sensitivity bound. + - The history is source-selected, so this measures what the generator can see in such + data, not recall on real wallets. +2. **Evidence availability**: per-cohort coverage of the registered evidence packets. +3. **Generator invariance** on the 13 recorded windows: reordering, letter case, duplicates + and future activity. +4. **Scalability** on synthetic histories. +""" + +from __future__ import annotations + +import json +import sqlite3 +import time +import tracemalloc +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from cryptoguard.ml import candidates as cand + +DIAG_VERSION = "diagnostics/1" +WINDOW = 50_400 # about 7 days of blocks + + +def _fixture(victim: str, rows: list[tuple[Any, ...]], block: int, optimistic: bool) -> Any: + from cryptoguard.ml.tsuchiya_archive import POISONING + from cryptoguard.replay.models import RecordedTransfer, ReplayFixture + + transfers = [] + for line, b, tx, token, s, r, value, flags in rows: + signer = None + if optimistic and s == victim and not flags & POISONING: + signer = victim # the victim's own payment, assumed signed by it + v = 1 if value is None or value != value else max(0, round(value)) + transfers.append( + RecordedTransfer( + token=token, + sender=s, + recipient=r, + value=str(v), + block_number=b, + block_hash="0x" + "0" * 64, + transaction_hash=tx, + transaction_index=0, + log_index=line % 1_000_000, + tx_sender=signer, + ) + ) + return ReplayFixture( + case_id="diagnostic", + chain_id=1, + wallet=victim, + from_block=block - WINDOW, + to_block=block, + recorded_at=datetime(2026, 1, 1, tzinfo=UTC), + recorded_with="tsuchiya-archive rows (source-selected)", + rpc_requests=0, + transfer_scan_complete=False, + sender_lookups_skipped=len(transfers), + method=[], + wallet_code_hex={}, + block_timestamps={}, + transfers=transfers, + wallet_transactions=[], + ) + + +def source_positive_coverage(poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml.review_sample import read_sheet + + reserved = { + r["victim_event_id"] + for r in read_sheet(poisoning_dir / "review_sample" / "reviewer_sheet.jsonl") + } + packets = [ + p + for p in map( + json.loads, + (poisoning_dir / "review_packets_payoff_linked.jsonl") + .read_text(encoding="utf-8") + .splitlines(), + ) + if p["victim_event_id"] not in reserved + ] + con = sqlite3.connect( + f"file:{(poisoning_dir / 'archive_subset.sqlite').as_posix()}?mode=ro", uri=True + ) + q = ( + "select line, block, tx, token, sender, receiver, value, flags from transfers " + "where (sender = ? or receiver = ?) and block between ? and ? order by block, line" + ) + out: dict[str, Counter[str]] = {"strict": Counter(), "optimistic": Counter()} + by_subtype: dict[str, Counter[str]] = {"strict": Counter(), "optimistic": Counter()} + total: Counter[str] = Counter() + for p in packets: + v, b = p["victim"], p["observation_block"] + rows = con.execute(q, (v, v, b - WINDOW, b)).fetchall() + total[p["subtype"]] += 1 + for mode in ("strict", "optimistic"): + hits = [ + c + for c in cand.generate(_fixture(v, rows, b, mode == "optimistic")) + if c.event.planting_tx == p["planting_tx"] and c.event.lookalike == p["lookalike"] + ] + if hits: + by_subtype[mode][p["subtype"]] += 1 + for m in hits[0].methods: + out[mode][m] += 1 + con.close() + n = sum(total.values()) + return { + "population": "payoff-linked source positives minus the 60 reserved review items", + "attempts": n, + "by_subtype_total": dict(total), + **{ + mode: { + "emitted": sum(by_subtype[mode].values()), + "share": round(sum(by_subtype[mode].values()) / n, 4) if n else None, + "by_subtype": {s: f"{by_subtype[mode][s]}/{total[s]}" for s in sorted(total)}, + "methods_of_first_hit": dict(out[mode]), + } + for mode in ("strict", "optimistic") + }, + } + + +def evidence_availability(poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml.evidence import PACKETS + + out: dict[str, Any] = {} + for name, work in ( + ("review-sample/1", "review"), + ("hard-negative-candidates/1", "hard_negative/review"), + ): + path = poisoning_dir / work / "evidence" / PACKETS + if not path.exists(): + out[name] = "packets not built" + continue + ps = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + hist = sorted(p["wallet_history"]["rows_before_cutoff"] for p in ps) + out[name] = { + "items": len(ps), + "candidate_transfer_found": sum(bool(p["candidate_event"]) for p in ps), + "signer_known": sum(p["transaction_semantics"]["signer"] is not None for p in ps), + "token_on_reviewed_list": sum( + all(t["on_reviewed_token_list"] for t in p["token_provenance"]) + for p in ps + if p["token_provenance"] + ), + "wallet_history_rows_median": hist[len(hist) // 2] if hist else None, + "no_wallet_history": sum(h == 0 for h in hist), + "earlier_rows_with_address": sum( + p["address_relationship"]["earlier_rows_between_wallet_and_address"] > 0 for p in ps + ), + "graph_context_available": sum(p["graph_context"] is not None for p in ps), + "same_block_order_unknown": sum( + p["wallet_history"].get("same_block_rows_order_unknown", 0) > 0 for p in ps + ), + "statuses": dict(Counter(s for p in ps for s in p["coverage"]["statuses"])), + } + return out + + +def generator_invariance() -> dict[str, Any]: + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + + fixtures = [c.fixture for c in load_cases() if c.fixture] + [ + b.fixture for b in load_background() if b.fixture + ] + + def key(fx: Any) -> list[tuple[str, tuple[str, ...], Any]]: + return [(c.event.victim_event_id, c.methods, c.best_match) for c in cand.generate(fx)] + + checks: Counter[str] = Counter() + for fx in fixtures: + base = key(fx) + rev = fx.model_copy(update={"transfers": list(reversed(fx.transfers))}) + upper = fx.model_copy( + update={ + "wallet": fx.wallet.upper().replace("0X", "0x"), + "transfers": [ + t.model_copy( + update={ + "sender": t.sender.upper().replace("0X", "0x"), + "recipient": t.recipient.upper().replace("0X", "0x"), + } + ) + for t in fx.transfers + ], + } + ) + later = fx.model_copy( + update={ + "transfers": [ + *fx.transfers, + *[ + t.model_copy( + update={ + "block_number": fx.to_block + 1, + "transaction_hash": t.transaction_hash[:-4] + "ffff", + } + ) + for t in fx.transfers + ], + ] + } + ) + checks["reorder_identical"] += key(rev) == base + checks["letter_case_identical"] += key(upper) == base + checks["future_activity_keeps_past"] += key(later)[: len(base)] == base + return {"fixtures": len(fixtures), **dict(checks)} + + +def scalability() -> list[dict[str, Any]]: + import random + + from cryptoguard.replay.models import RecordedTransfer, ReplayFixture + + rng = random.Random(1) # noqa: S311 - synthetic workload, not security + wallet = "0x" + "11" * 20 + parties = ["0x" + f"{rng.getrandbits(160):040x}" for _ in range(400)] + out = [] + for n in (1_000, 10_000, 30_000): + ts = [] + for i in range(n): + out_tx = i % 3 == 0 + party = rng.choice(parties) + ts.append( + RecordedTransfer( + token="0xdac17f958d2ee523a2206206994597c13d831ec7", # noqa: S106 - USDT + sender=wallet if out_tx else party, + recipient=party if out_tx else wallet, + value=str(rng.choice([0, 5, 10**9])), + block_number=100 + i, + block_hash="0x" + "0" * 64, + transaction_hash="0x" + f"{i:064x}", + transaction_index=0, + log_index=0, + tx_sender=wallet if out_tx else None, + ) + ) + fx = ReplayFixture( + case_id="scale", + chain_id=1, + wallet=wallet, + from_block=100, + to_block=100 + n, + recorded_at=datetime(2026, 1, 1, tzinfo=UTC), + recorded_with="synthetic", + rpc_requests=0, + transfer_scan_complete=True, + sender_lookups_skipped=0, + method=[], + wallet_code_hex={}, + block_timestamps={}, + transfers=ts, + wallet_transactions=[], + ) + tracemalloc.start() + t0 = time.perf_counter() + c = cand.generate(fx) + dt = time.perf_counter() - t0 + peak = tracemalloc.get_traced_memory()[1] + tracemalloc.stop() + out.append( + { + "transfers": n, + "candidates": len(c), + "seconds": round(dt, 3), + "peak_mib": round(peak / 2**20, 1), + } + ) + return out + + +def run_diagnostics(data_dir: Path, poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml.cross_dataset import git_state + + t0 = time.perf_counter() + return { + "version": DIAG_VERSION, + "candidate_version": cand.CANDIDATE_VERSION, + "git": git_state(), + "source_positive_coverage": source_positive_coverage(poisoning_dir), + "evidence_availability": evidence_availability(poisoning_dir), + "generator_invariance": generator_invariance(), + "scalability": scalability(), + "runtime_seconds": round(time.perf_counter() - t0, 1), + "rpc_requests": 0, + "notes": "aggregate only; the source-positive histories are source-selected rows", + } diff --git a/src/cryptoguard/ml/evidence.py b/src/cryptoguard/ml/evidence.py index ee29c07..ab3b187 100644 --- a/src/cryptoguard/ml/evidence.py +++ b/src/cryptoguard/ml/evidence.py @@ -34,7 +34,7 @@ from cryptoguard.ml.payments import TRUSTED_TOKENS -EVIDENCE_VERSION = "evidence-packets/1" +EVIDENCE_VERSION = "evidence-packets/2" # /2: same-block ambiguity, relationship reading MAX_HISTORY = 50 PACKETS = "evidence_packets.jsonl" Status = Literal[ @@ -47,6 +47,7 @@ "unknown_token_legitimacy", "unsupported_contract_execution", "insufficient_evidence", + "same_block_order_unknown", ] ARCHIVE_COLUMNS = "line, block, tx, token, sender, receiver, value" # never flags or intended @@ -177,6 +178,16 @@ def packet( and _before(r, cutoff, position) ] prior_pair = [r for r in history if addr in (r.sender, r.receiver)] + # Same-block rows whose order relative to the candidate is unknown: neither shown as + # history nor silently dropped. + ambiguous = [ + r + for r in rows + if wallet in (r.sender, r.receiver) + and r.block == cutoff + and r.tx != tx + and (position is None or r.order is None) + ] signers = {r.signer for r in candidate} if candidate and None in signers: statuses.append("unknown_signer") @@ -191,6 +202,8 @@ def packet( statuses.append("complete_for_declared_scope") if source is None: statuses.append("insufficient_evidence") + if ambiguous: + statuses.append("same_block_order_unknown") def view(r: Row) -> dict[str, Any]: return { @@ -217,6 +230,7 @@ def view(r: Row) -> dict[str, Any]: ], "address_relationship": { "earlier_rows_between_wallet_and_address": len(prior_pair), + "interpretation": _relationship(len(prior_pair), source), "note": "find the earlier counterparty yourself in the wallet history below; no " "similarity is computed here", }, @@ -235,6 +249,7 @@ def view(r: Row) -> dict[str, Any]: ], "wallet_history": { "rows_before_cutoff": len(history), + "same_block_rows_order_unknown": len(ambiguous), "shown": [view(r) for r in history[-max_history:]], "window": list(window) if window else None, }, @@ -256,6 +271,18 @@ def view(r: Row) -> dict[str, Any]: } +def _relationship(n: int, source: str | None) -> str: + """What a count of earlier wallet-address rows means under this coverage. Missing + history is never read as 'unfamiliar'.""" + if source is None: + return "no wallet history is available locally: familiarity is unknown" + if source == "recorded_window": + scope = "in the complete recorded window (history before the window is not recorded)" + else: + scope = "among the rows a research dataset kept (ordinary activity is missing)" + return f"{n} earlier row(s) {scope}" if n else f"none {scope}; this is not proof of novelty" + + def _explain(source: str | None) -> str: if source == "recorded_window": return ( diff --git a/src/cryptoguard/ml/experiment_spec.py b/src/cryptoguard/ml/experiment_spec.py index a9bbd78..9b326ef 100644 --- a/src/cryptoguard/ml/experiment_spec.py +++ b/src/cryptoguard/ml/experiment_spec.py @@ -74,6 +74,12 @@ ), } FEATURE_GROUPS["combined"] = tuple(c for g in list(FEATURE_GROUPS.values()) for c in g) +# Value, token and transaction shape separated the source frames almost perfectly (Phase +# 11.5: value AUC 1.0, shape 0.98-0.99). This ablation drops them. +SOURCE_PROXIES = FEATURE_GROUPS["transaction_only"] +FEATURE_GROUPS["combined_without_source_proxies"] = tuple( + c for c in FEATURE_GROUPS["combined"] if c not in SOURCE_PROXIES +) SPEC: dict[str, Any] = { "version": SPEC_VERSION, @@ -114,9 +120,43 @@ "feature_groups": FEATURE_GROUPS, "resource_budget": "CPU only, < 2 GB RAM, < 2 minutes per fit (larger needs approval)", "no_gnn": "graph context enters as tabular features; no GNN without a new hypothesis", + "fairness": [ + "every method (rules, heuristics, models) scores the same eligible events", + "every method sees only information available at the same cutoff", + "every method is judged against the same label policy and the same split", + "the production rule is replayed on the same recorded histories, never with more " + "context than the models", + ], + "label_provenance": { + "positive": "label-policy/1 reviewed_attack (two independent humans, confirmed)", + "negative": "label-policy/1 reviewed_legitimate (two independent humans, confirmed, " + "positive evidence of a legitimate interpretation)", + "unknown": "excluded from the strict benchmark and counted", + }, + "candidate_population": "defined by candidates/2 before any model exists; never by a " + "model score", + "test_set": "untouched until the model, features, threshold rule and metrics are frozen", + "label_count_stages": { + "smoke_test": "any labels; software correctness only, never a reported metric", + "feature_exploration": ">= 30 per class from >= 5 campaign groups (activation gate)", + "hyperparameter_selection": "a validation split disjoint by campaign and later in " + "time; >= 30 per class in validation itself", + "performance_estimate": "an untouched test split; see ml/power.bound_table for what " + "its negatives can bound", + "low_fpr_claim": "FPR <= 1% needs about 300+ effectively independent negatives with " + "0 false positives (one-sided 95%)", + "generalization": "several time periods and many campaigns; not reachable with the " + "current cohorts", + }, } +def spec_json() -> str: + import json + + return json.dumps(SPEC, indent=1, sort_keys=True) + "\n" + + def forbidden_columns(columns: tuple[str, ...]) -> list[str]: return [c for c in columns if any(w in c.lower() for w in FORBIDDEN_COLUMN_WORDS)] diff --git a/src/cryptoguard/ml/hard_negative_archive.py b/src/cryptoguard/ml/hard_negative_archive.py index bee037e..0088e78 100644 --- a/src/cryptoguard/ml/hard_negative_archive.py +++ b/src/cryptoguard/ml/hard_negative_archive.py @@ -142,3 +142,38 @@ def context_scan(data_dir: Path, out_dir: Path, *, progress: Any = None) -> dict source_sha256=source["sha256"], progress=progress, ) + + +REVIEW_CONTEXT_DB = "review_context.sqlite" + + +def review_context_scan(data_dir: Path, sheets: list[Path], out_dir: Path) -> dict[str, Any]: + """Phase 11.7 recovery pass: every archive row touching any wallet, address under + review or planting transaction of the frozen reviewer sheets. The rows are still only + what the source kept (lookalike-related), never a complete wallet history.""" + from cryptoguard.ml.review_sample import read_sheet + + rows = [r for s in sheets for r in read_sheet(s)] + manifest = build_targets( + { + "review_wallets": {r["wallet"] for r in rows}, + "review_addresses": {r["address_under_review"] for r in rows}, + "review_txs": {r["transaction"] for r in rows}, + } + ) + out_dir.mkdir(parents=True, exist_ok=True) + targets_path = out_dir / "review_context_targets.json" + atomic_write(targets_path, json.dumps(manifest).encode()) + archive = data_dir / "tsuchiya2025" / ARCHIVE + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + work = out_dir / "spill" + summary = scan( + archive, + load_targets(targets_path), + out_dir / REVIEW_CONTEXT_DB, + work_dir=work, + source_sha256=source["sha256"], + ) + if work.exists() and not any(work.iterdir()): + work.rmdir() + return summary diff --git a/src/cryptoguard/ml/power.py b/src/cryptoguard/ml/power.py index 6ec13b4..e1aff5b 100644 --- a/src/cryptoguard/ml/power.py +++ b/src/cryptoguard/ml/power.py @@ -53,3 +53,45 @@ def plan_table(targets: tuple[float, ...] = (0.10, 0.05, 0.01), **{f"negatives_deff_{d}": (math.ceil(n * d) if n else None) for d in deffs}, }) # fmt: skip return rows + + +def _binom_cdf(k: int, n: int, p: float) -> float: + return sum(math.comb(n, i) * p**i * (1 - p) ** (n - i) for i in range(k + 1)) + + +def clopper_pearson_upper(k: int, n: float, alpha: float = 0.05) -> float: + """Exact one-sided (1 - alpha) upper bound for k events in n trials. A non-integer n + (an effective sample size) is rounded down, which is conservative.""" + m = math.floor(n) + if m <= 0 or k > m: + return 1.0 + if k == m: + return 1.0 + lo, hi = k / m, 1.0 + for _ in range(100): # bisection on P(X <= k | p) = alpha + mid = (lo + hi) / 2 + if _binom_cdf(k, m, mid) > alpha: + lo = mid + else: + hi = mid + return hi + + +def bound_table(sizes: tuple[int, ...] = (30, 35, 50, 100, 300, 1000), + deffs: tuple[float, ...] = (1.0, 2.0)) -> list[dict[str, Any]]: # fmt: skip + """What n reviewed legitimate events can show about FPR: the upper bound when 0 or 1 + of them is flagged. One-sided 95% exact (Clopper-Pearson) and two-sided 95% Wilson; + clustering divides n by the design effect.""" + rows = [] + for n in sizes: + for d in deffs: + n_eff = n / d + rows.append({ + "negatives": n, + "design_effect": d, + "effective_n": round(n_eff, 1), + "upper_0_flagged_cp_one_sided": round(clopper_pearson_upper(0, n_eff), 4), + "upper_1_flagged_cp_one_sided": round(clopper_pearson_upper(1, n_eff), 4), + "upper_0_flagged_wilson_two_sided": round((wilson(0.0, n_eff) or (0, 1))[1], 4), + }) # fmt: skip + return rows diff --git a/src/cryptoguard/ml/review_app/app.js b/src/cryptoguard/ml/review_app/app.js index 3aebf22..58be8c6 100644 --- a/src/cryptoguard/ml/review_app/app.js +++ b/src/cryptoguard/ml/review_app/app.js @@ -48,6 +48,7 @@ const STATUS_TEXT = { unknown_token_legitimacy: ["warn", "Token not on the reviewed list (unknown, not necessarily fake)"], unsupported_contract_execution: ["warn", "Contract execution not interpretable offline"], insufficient_evidence: ["warn", "No local evidence"], + same_block_order_unknown: ["warn", "Other transfers in the same block; their order is unknown"], }; const FACTS = [ ["wallet", "Wallet"], @@ -262,10 +263,11 @@ function renderEvidence(box, ev) { ev.token_provenance.map((t) => [t.token, t.on_reviewed_token_list ? "yes" : "unknown"]))); box.append(el("h4", "4. Address relationship")); const rel = ev.address_relationship; - box.append(el("p", `${rel.earlier_rows_between_wallet_and_address} earlier row(s) between the wallet and this address. ${rel.note}.`)); + box.append(el("p", `Between the wallet and this address: ${rel.interpretation || rel.earlier_rows_between_wallet_and_address + " earlier row(s)"}. ${rel.note}.`)); const hist = ev.wallet_history; const d = el("details"); - d.append(el("summary", `5. Wallet history before the cutoff: ${hist.rows_before_cutoff} row(s), showing the last ${hist.shown.length}`)); + const same = hist.same_block_rows_order_unknown ? `; ${hist.same_block_rows_order_unknown} more in the same block, order unknown (not shown)` : ""; + d.append(el("summary", `5. Wallet history before the cutoff: ${hist.rows_before_cutoff} row(s), showing the last ${hist.shown.length}${same}`)); if (hist.shown.length) d.append(table(heads, hist.shown.map(row))); box.append(d); if (ev.graph_context) { diff --git a/src/cryptoguard/ml/review_server.py b/src/cryptoguard/ml/review_server.py index 1fcc3e0..b48fc6c 100644 --- a/src/cryptoguard/ml/review_server.py +++ b/src/cryptoguard/ml/review_server.py @@ -185,7 +185,12 @@ def _json(self, status: int, obj: Any) -> None: def _host_ok(self) -> bool: port = port_ref[0] - return self.headers.get("Host") in (f"127.0.0.1:{port}", f"localhost:{port}") + allowed = (f"127.0.0.1:{port}", f"localhost:{port}") + if self.headers.get("Host") not in allowed: + return False + # A browser names the page that sent a request; only this app's own page may. + origin = self.headers.get("Origin") + return origin is None or origin in {f"http://{a}" for a in allowed} def _authorized(self) -> bool: token = self.headers.get("X-Review-Token", "") @@ -214,7 +219,10 @@ def do_POST(self) -> None: return self._json(HTTPStatus.FORBIDDEN, {"error": "missing or bad token"}) if self.headers.get("Content-Type", "").split(";")[0] != "application/json": return self._json(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, {"error": "JSON only"}) - length = int(self.headers.get("Content-Length") or 0) + raw_length = self.headers.get("Content-Length") or "0" + if not raw_length.isdigit(): # also refuses negatives, which would read to EOF + return self._json(HTTPStatus.BAD_REQUEST, {"error": "bad Content-Length"}) + length = int(raw_length) if length > MAX_BODY: return self._json(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, {"error": "too large"}) try: diff --git a/src/cryptoguard/ml/verify_research.py b/src/cryptoguard/ml/verify_research.py new file mode 100644 index 0000000..9d0a1a7 --- /dev/null +++ b/src/cryptoguard/ml/verify_research.py @@ -0,0 +1,175 @@ +"""Offline reproducibility check of the poisoning research inputs (``cryptoguard ml +verify-research``, Phase 11.7). + +It fetches nothing and regenerates nothing. Every check is reported as: +- ``PASS``; +- ``FAIL``: a file is present but wrong; +- ``MISSING``: a file is absent; +- ``BLOCKED``: waiting on an external dependency, such as human reviews. +""" + +from __future__ import annotations + +import json +import sqlite3 +from collections.abc import Callable +from pathlib import Path +from typing import Any + +VERIFY_VERSION = "verify-research/1" + + +def _check(name: str, fn: Callable[[], tuple[str, str]]) -> dict[str, str]: + try: + status, detail = fn() + except FileNotFoundError as exc: + status, detail = "MISSING", str(exc) + except Exception as exc: # a check must report, never abort the whole verification + status, detail = "FAIL", f"{type(exc).__name__}: {exc}" + return {"check": name, "status": status, "detail": detail} + + +def verify(data_dir: Path, ml_dir: Path, *, hash_archive: bool = True) -> dict[str, Any]: + from cryptoguard.ml import review_sample as rs + from cryptoguard.ml.annotation import PROTOCOL + from cryptoguard.ml.candidates import CANDIDATE_VERSION, EVENT_FEATURE_VERSION + from cryptoguard.ml.cross_dataset import git_state + from cryptoguard.ml.evidence import EVIDENCE_VERSION, PACKETS + from cryptoguard.ml.experiment_spec import SPEC_VERSION + from cryptoguard.ml.fetch import TSUCHIYA_FILES, digests + from cryptoguard.ml.label_policy import POLICY_VERSION + from cryptoguard.ml.reconcile import RECONCILE_VERSION + from cryptoguard.ml.sources import SOURCES, sha256_file + from cryptoguard.ml.tsuchiya_archive import PARSER_VERSION + + poisoning = ml_dir / "poisoning" + checks: list[dict[str, str]] = [] + + for name, pinned in TSUCHIYA_FILES.items(): + path = data_dir / "tsuchiya2025" / name + + def tsuchiya(path: Path = path, pinned: Any = pinned) -> tuple[str, str]: + if not path.exists(): + raise FileNotFoundError(f"{path} (never downloaded automatically)") + if path.stat().st_size != pinned.size: + return "FAIL", f"size {path.stat().st_size} != pinned {pinned.size}" + if path.stat().st_size > 100 << 20 and not hash_archive: + return "PASS", "size matches (hash skipped on request)" + _, sha = digests(path) + ok = pinned.sha256 is None or sha == pinned.sha256 + return ("PASS" if ok else "FAIL"), f"sha256 {sha[:16]}" + + checks.append(_check(f"source {name}", tsuchiya)) + for source in SOURCES.values(): + for f in source.files: + path = data_dir / source.name / f.path + + def pinned_file(path: Path = path, f: Any = f) -> tuple[str, str]: + if not path.exists(): + raise FileNotFoundError(str(path)) + sha = sha256_file(path) + return ("PASS" if sha == f.sha256 else "FAIL"), f"sha256 {sha[:16]}" + + checks.append(_check(f"source {source.name}/{f.path}", pinned_file)) + + def subset_check(name: str) -> Callable[[], tuple[str, str]]: + def check() -> tuple[str, str]: + path = poisoning / name + if not path.exists(): + raise FileNotFoundError(str(path)) + con = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True) + try: + meta = dict(con.execute("SELECT key, value FROM meta").fetchall()) + finally: + con.close() + summary = json.loads(meta["summary"]) + pinned = TSUCHIYA_FILES["address_poisoning_ethereum.sql.gz"].sha256 + ok = ( + meta.get("complete") == "1" + and meta.get("parser_version") == PARSER_VERSION + and summary.get("source_sha256") == pinned + ) + return ("PASS" if ok else "FAIL"), f"{summary['stored_target_rows']:,} stored rows" + + return check + + for name in ( + "archive_subset.sqlite", + "hard_negative/context_subset.sqlite", + "review/review_context.sqlite", + ): + checks.append(_check(f"derived {name}", subset_check(name))) + + def extract() -> tuple[str, str]: + from cryptoguard.ml.hard_negative_archive import load_rows + + rows = load_rows(poisoning / "hard_negative") + return "PASS", f"{len(rows):,} uncategorized rows, hash matches its summary" + + checks.append(_check("derived uncategorized rows", extract)) + + for cohort, hashes in rs.COHORTS.items(): + sample = poisoning / ( + "review_sample" if cohort == rs.SAMPLE_VERSION else "hard_negative/cohort_v1" + ) + work = poisoning / ("review" if cohort == rs.SAMPLE_VERSION else "hard_negative/review") + + def frozen(sample: Path = sample, cohort: str = cohort) -> tuple[str, str]: + if not (sample / rs.MANIFEST).exists(): + raise FileNotFoundError(f"{sample} (frozen files are local, never committed)") + m = rs.verify_frozen(sample, cohort=cohort) + return "PASS", f"{len(m['selected'])} items, selection {m['selection_sha256'][:12]}" + + def packets(work: Path = work, hashes: dict[str, str] = hashes) -> tuple[str, str]: + path = work / "evidence" / PACKETS + if "evidence" not in hashes: + return "BLOCKED", "no evidence packets registered" + if not path.exists(): + raise FileNotFoundError(f"{path} (rebuild with `ml review build-evidence`)") + sha = sha256_file(path) + return ("PASS" if sha == hashes["evidence"] else "FAIL"), f"sha256 {sha[:16]}" + + def reviews(work: Path = work) -> tuple[str, str]: + subs = [ + p + for p in poisoning.rglob("submission.json") + if "review" in p.parts or "hard_negative" in p.parts + ] + return ("BLOCKED" if not subs else "PASS"), f"{len(subs)} finalized submission(s)" + + checks += [ + _check(f"frozen cohort {cohort}", frozen), + _check(f"evidence packets {cohort}", packets), + _check(f"human review {cohort}", reviews), + ] + checks.append( + { + "check": "experiment activation", + "status": "BLOCKED", + "detail": f"{SPEC_VERSION} inactive: no reviewed labels", + } + ) + return { + "version": VERIFY_VERSION, + "git": git_state(), + "versions": { + "parser": PARSER_VERSION, + "reconcile": RECONCILE_VERSION, + "candidates": CANDIDATE_VERSION, + "event_features": EVENT_FEATURE_VERSION, + "evidence": EVIDENCE_VERSION, + "protocol": PROTOCOL, + "label_policy": POLICY_VERSION, + "experiment_spec": SPEC_VERSION, + }, + "checks": checks, + "summary": { + s: sum(c["status"] == s for c in checks) for s in ("PASS", "FAIL", "MISSING", "BLOCKED") + }, + "limitations": [ + "hashes prove the files are unchanged, not that their contents are correct", + "derived files are checked against their own summaries; re-derivation needs the " + "archive passes (about 50 minutes each)", + ], + "rpc_requests": 0, + } diff --git a/tests/unit/test_ml_evidence_completion.py b/tests/unit/test_ml_evidence_completion.py new file mode 100644 index 0000000..52fc8c3 --- /dev/null +++ b/tests/unit/test_ml_evidence_completion.py @@ -0,0 +1,355 @@ +"""Phase 11.7: evidence completeness semantics, review-server hardening, an independent +reference for the candidate generator, exact FPR bounds, the experiment spec, research +verification and an end-to-end synthetic review workflow. + +Synthetic data only. The synthetic reviewers below are software fixtures, not people. +""" + +from __future__ import annotations + +import http.client +import json +import random +import threading +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import candidates as cand +from cryptoguard.ml import evidence as ev +from cryptoguard.ml import experiment_spec as spec +from cryptoguard.ml import power +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml import unblind as ub +from cryptoguard.ml.annotation import AnnotationError +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.ml.review_server import ReviewApp, serve +from cryptoguard.ml.submissions import agreement_report, check_submission +from tests.review_fixtures import ATTEMPT_FIELDS, INSUFFICIENT_FIELDS, fields, frozen +from tests.unit.test_ml_poisoning import FAKE, FRIEND, LOOKALIKE, USDT, WALLET, fixture, transfer +from tests.unit.test_ml_validation_readiness import ITEM, archive_db, arow, base_rows + +STRANGER = "0x" + "3c" * 20 + +# --- evidence completeness semantics ------------------------------------------------------ + + +def test_same_block_rows_of_unknown_order_are_counted_not_dropped(tmp_path: Path) -> None: + rows = [*base_rows(), (7, 1_000, "0xother", USDT, WALLET, STRANGER, 0, 1.0, 1.0, 1, None, 4, 4)] + (p,) = ev.build([ITEM], archive_dbs=[archive_db(tmp_path / "a.sqlite", rows)], fixtures=[]) + assert p["wallet_history"]["same_block_rows_order_unknown"] == 1 + assert "same_block_order_unknown" in p["coverage"]["statuses"] + assert all(r["transaction"] != "0xother" for r in p["wallet_history"]["shown"]) + + +def test_absence_is_read_differently_under_each_coverage(tmp_path: Path) -> None: + """'No earlier interaction' must not read as 'unfamiliar' when history is partial.""" + complete = ev.packet(ITEM, rows=[], source="recorded_window", window=(0, 2_000)) + partial = ev.packet(ITEM, rows=[], source="archive", window=None) + nothing = ev.packet(ITEM, rows=[], source=None, window=None) + texts = {p["address_relationship"]["interpretation"] for p in (complete, partial, nothing)} + assert len(texts) == 3 + assert "complete recorded window" in complete["address_relationship"]["interpretation"] + assert "ordinary activity is missing" in partial["address_relationship"]["interpretation"] + assert "unknown" in nothing["address_relationship"]["interpretation"] + assert "partial_history" in partial["coverage"]["statuses"] + assert "insufficient_evidence" in nothing["coverage"]["statuses"] + + +def test_duplicate_rows_across_sources_count_once(tmp_path: Path) -> None: + a = archive_db(tmp_path / "a.sqlite", base_rows()) + b = archive_db(tmp_path / "b.sqlite", base_rows()) + (one,) = ev.build([ITEM], archive_dbs=[a], fixtures=[]) + (two,) = ev.build([ITEM], archive_dbs=[a, b], fixtures=[]) + assert one == two + + +def test_future_graph_edges_never_change_a_packet(tmp_path: Path) -> None: + later = [arow(9, 1_200, "0xlate", LOOKALIKE, "0x" + "77" * 20, 0.0, flags=2)] + (a,) = ev.build( + [ITEM], archive_dbs=[archive_db(tmp_path / "a.sqlite", base_rows())], fixtures=[] + ) + (b,) = ev.build( + [ITEM], archive_dbs=[archive_db(tmp_path / "b.sqlite", [*base_rows(), *later])], fixtures=[] + ) + assert a["graph_context"] == b["graph_context"] + + +# --- review server hardening ------------------------------------------------------------------- + + +@pytest.fixture +def server(tmp_path: Path): + from cryptoguard.ml import training + + app = ReviewApp(training.make_package("A", tmp_path / "t")) + with app.store: + httpd, _ = serve(app) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + try: + yield app, httpd.server_address[1] + finally: + httpd.shutdown() + httpd.server_close() + + +def raw(port: int, method: str, path: str, headers: dict[str, str], body: bytes = b"") -> int: + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + conn.putrequest(method, path, skip_host=True, skip_accept_encoding=True) + for k, v in headers.items(): + conn.putheader(k, v) + conn.endheaders(body or None) + status = conn.getresponse().status + conn.close() + return status + + +def test_foreign_origin_and_bad_lengths_are_refused(server) -> None: + app, port = server + base = {"Host": f"127.0.0.1:{port}", "X-Review-Token": app.token} + assert raw(port, "GET", "/api/state", base) == 200 + assert raw(port, "GET", "/api/state", base | {"Origin": "https://evil.example"}) == 421 + assert raw(port, "GET", "/api/state", base | {"Origin": f"http://127.0.0.1:{port}"}) == 200 + post = base | {"Content-Type": "application/json"} + assert raw(port, "POST", "/api/save", post | {"Content-Length": "-1"}) == 400 + assert raw(port, "POST", "/api/save", post | {"Content-Length": "abc"}) == 400 + + +# --- candidate generator: an independent reference --------------------------------------------- + + +def _ref_affix(a: str, b: str) -> tuple[int, int]: + """Matched leading and trailing hex characters, written from the rule's definition.""" + x, y = a.lower()[2:], b.lower()[2:] + lead = next((i for i in range(min(len(x), len(y))) if x[i] != y[i]), min(len(x), len(y))) + trail = next( + (i for i in range(min(len(x), len(y))) if x[-1 - i] != y[-1 - i]), min(len(x), len(y)) + ) + return lead, trail + + +def _reference(fx: Any) -> list[tuple[str, frozenset[str]]]: + """candidates/2 from its documented rules only (no code shared with the generator).""" + w = fx.wallet.lower() + ts = sorted(fx.transfers, key=lambda t: (t.block_number, t.transaction_index, t.log_index)) + chosen_pos: list[tuple[tuple[int, int, int], str]] = [] + for t in fx.transfers: + if t.sender.lower() == w and t.tx_sender is not None and t.tx_sender.lower() == w: + chosen_pos.append( + ((t.block_number, t.transaction_index, t.log_index), t.recipient.lower()) + ) + for t in fx.wallet_transactions: + if t.to and int(t.value): + chosen_pos.append(((t.block_number, t.transaction_index, -1), t.to.lower())) + out = [] + for t in ts: + incoming, outgoing = t.recipient.lower() == w, t.sender.lower() == w + if not (incoming or outgoing): + continue + pos = (t.block_number, t.transaction_index, t.log_index) + party = (t.sender if incoming else t.recipient).lower() + matched = False + for p, k in chosen_pos: + if p < pos and k != party: + lead, trail = _ref_affix(party, k) + matched |= lead + trail >= 6 and trail >= 3 + value, token = int(t.value), t.token.lower() + signed = None if t.tx_sender is None else t.tx_sender.lower() == w + m = set() + if incoming and value == 0: + m.add("zero_value_in") + if outgoing and signed is False: + m.add("spoofed_out") + if incoming and matched: + m.add("lookalike_in") + if token not in TRUSTED_TOKENS: + m.add("untrusted_token_in") + if incoming and token in cand.STABLECOINS and 0 < value <= 10_000: + m.add("dust_in") + if m: + out.append((t.transaction_hash, frozenset(m))) + return out + + +def test_generator_matches_an_independent_reference() -> None: + rng = random.Random(11) + shared_suffix = ["0xd29" + rng.choice("0123456789abcdef") * 33 + "d7d5" for _ in range(6)] + parties = [FRIEND, LOOKALIKE, STRANGER, *shared_suffix, FRIEND.upper().replace("0X", "0x")] + for _ in range(40): + ts = [] + for i in range(20): + b = rng.randrange(100, 900) + if rng.random() < 0.4: + ts.append( + transfer( + b, + WALLET, + rng.choice(parties), + rng.choice([0, 7, 10**9]), + tx_sender=rng.choice([WALLET, None, STRANGER]), + idx=i, + ) + ) + else: + ts.append( + transfer( + b, + rng.choice(parties), + WALLET, + rng.choice([0, 7, 10**9]), + token=rng.choice([USDT, FAKE]), + idx=i, + ) + ) + fx = fixture(ts, []) + got = [(c.event.planting_tx, frozenset(c.methods)) for c in cand.generate(fx)] + assert got == _reference(fx) + + +def test_malformed_counterparties_never_crash_or_match() -> None: + fx = fixture( + [ + transfer(500, WALLET, FRIEND, 1, tx_sender=WALLET, idx=1), + transfer(900, "0xd296", WALLET, 5_000_000_000, idx=1), + ], + [], + ) + assert "lookalike_in" not in {m for c in cand.generate(fx) for m in c.methods} + + +# --- exact FPR bounds and the experiment spec --------------------------------------------------- + + +def test_exact_bounds_match_closed_forms() -> None: + for n in (30, 35, 50, 100, 300): + assert power.clopper_pearson_upper(0, n) == pytest.approx(1 - 0.05 ** (1 / n), abs=1e-6) + p = power.clopper_pearson_upper(1, n) # P(X <= 1) = 0.05 at the bound + assert (1 - p) ** n + n * p * (1 - p) ** (n - 1) == pytest.approx(0.05, abs=1e-6) + rows = {(r["negatives"], r["design_effect"]): r for r in power.bound_table()} + assert ( + rows[(100, 2.0)]["upper_0_flagged_cp_one_sided"] + == rows[(50, 1.0)]["upper_0_flagged_cp_one_sided"] + ) # clustering halves the information + + +def test_spec_has_a_source_proxy_free_ablation_and_exports() -> None: + clean = spec.FEATURE_GROUPS["combined_without_source_proxies"] + assert not set(clean) & set(spec.SOURCE_PROXIES) + assert set(clean) < set(spec.FEATURE_GROUPS["combined"]) + exported = json.loads(spec.spec_json()) + assert exported["status"] == "inactive" + assert "fairness" in exported + assert "low_fpr_claim" in exported["label_count_stages"] + + +def test_research_verification_reports_missing_inputs_without_fetching(tmp_path: Path) -> None: + from cryptoguard.ml.verify_research import verify + + report = verify(tmp_path / "data", tmp_path / "ml", hash_archive=False) + statuses = {c["check"]: c["status"] for c in report["checks"]} + assert statuses["source address_poisoning_ethereum.sql.gz"] == "MISSING" + assert report["summary"]["FAIL"] == 0 + assert report["rpc_requests"] == 0 + + +def test_a_corrupted_lease_database_is_not_reported_as_busy(tmp_path: Path) -> None: + from sqlalchemy.exc import DatabaseError + + from cryptoguard.database.history import HistoryRepository + from cryptoguard.database.leases import LeaseBusyError, LeaseStore + from cryptoguard.database.repository import create_db_engine + + path = tmp_path / "bad.db" + path.write_bytes(b"this is not a sqlite database" * 100) + store = LeaseStore(HistoryRepository(create_db_engine(f"sqlite:///{path.as_posix()}"))) + with pytest.raises(DatabaseError) as err: + store.acquire("k", 30) + assert not isinstance(err.value, LeaseBusyError) + + +# --- end-to-end synthetic review workflow -------------------------------------------------------- + + +def _http_save( + app: ReviewApp, port: int, item: dict[str, Any], base: dict[str, Any], revision: int = 0 +) -> int: + body = json.dumps( + { + "fields": fields(item["item"], item["victim_event_id"], base), + "expected_revision": revision, + } + ).encode() + headers = { + "Host": f"127.0.0.1:{port}", + "X-Review-Token": app.token, + "Content-Type": "application/json", + "Content-Length": str(len(body)), + } + return raw(port, "POST", "/api/save", headers, body) + + +def test_end_to_end_synthetic_workflow_with_failures(tmp_path: Path, monkeypatch) -> None: + _, sample, manifest = frozen(tmp_path, monkeypatch) + work = tmp_path / "work" + pkg_a = ub.make_package(sample, work, "A", tmp_path / "pa") + + def session(pkg: Path): + app = ReviewApp(pkg) + app.store.__enter__() + httpd, _ = serve(app) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return app, httpd + + def stop(app: ReviewApp, httpd: Any) -> None: + httpd.shutdown() + httpd.server_close() + app.store.__exit__() + + items = rs.read_sheet(sample / rs.SHEET) + app, httpd = session(pkg_a) + port = httpd.server_address[1] + assert _http_save(app, port, items[0], ATTEMPT_FIELDS) == 200 + old_token = app.token + stop(app, httpd) # the server restarts: a new session token, saved work kept + + (pkg_a / "annotations" / "annotations.log.jsonl.tmp").write_bytes(b"{half") # torn save + app, httpd = session(pkg_a) + port = httpd.server_address[1] + stale = {"Host": f"127.0.0.1:{port}", "X-Review-Token": old_token} + assert raw(port, "GET", "/api/state", stale) == 403 + assert len(app.state()["decisions"]) == 1 + for it in items[1:]: + assert _http_save(app, port, it, ATTEMPT_FIELDS) == 200 + app.finalize() + stop(app, httpd) + sub_a = pkg_a / "annotations" / "submission.json" + + assert check_submission(sub_a, sample, cohort=rs.SAMPLE_VERSION) == [] + with pytest.raises(KeyError): + check_submission(sub_a, sample, cohort="no-such-cohort/1") + with pytest.raises(ub.UnblindingRefused): + ub.unblind(sample, work, [sub_a]) # premature: one reviewer + + pkg_b = ub.make_package(sample, work, "B", tmp_path / "pb") + app, httpd = session(pkg_b) + port = httpd.server_address[1] + for i, it in enumerate(items): + assert _http_save(app, port, it, INSUFFICIENT_FIELDS if i < 5 else ATTEMPT_FIELDS) == 200 + app.finalize() + stop(app, httpd) + sub_b = pkg_b / "annotations" / "submission.json" + + corrupt = tmp_path / "corrupt.json" + corrupt.write_bytes(sub_b.read_bytes()[:-40]) + assert check_submission(corrupt, sample, cohort=rs.SAMPLE_VERSION) + with pytest.raises(AnnotationError): + agreement_report([sub_a, corrupt], sample, cohort=rs.SAMPLE_VERSION) + + agree = agreement_report([sub_a, sub_b], sample, cohort=rs.SAMPLE_VERSION) + assert agree["binary"]["disagreements"] == 5 + report = ub.unblind(sample, work, [sub_a, sub_b]) + assert report["items_reviewed_by_all"] == len(manifest["selected"]) + assert report["primary_all_reviewers_attempt"]["overall"]["positives"] == len(items) - 5 + log = (work / ub.ACCESS_LOG).read_text(encoding="utf-8").splitlines() + assert len(log) == 1 # exactly one opening of the key, by the successful unblind diff --git a/tests/unit/test_ml_validation_readiness.py b/tests/unit/test_ml_validation_readiness.py index fb70d4f..804a4d8 100644 --- a/tests/unit/test_ml_validation_readiness.py +++ b/tests/unit/test_ml_validation_readiness.py @@ -104,7 +104,6 @@ def test_future_rows_labels_and_payoffs_never_change_a_packet(tmp_path: Path) -> before = build(tmp_path, base_rows(), "a.sqlite") rows = [ *base_rows(), - arow(4, 1_000, "0xsameblock", WALLET, STRANGER), # same block, order unknown arow(5, 1_500, "0xpay", WALLET, LOOKALIKE, 5_000.0, flags=16), # later payoff arow(6, 2_000, "0xlater", LOOKALIKE, STRANGER, 0.0, flags=2), ] From 3ee994fc4c67589011ca9eb3226f14d3bbe0283f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 15:05:27 +0300 Subject: [PATCH 34/92] feat(ml): include the review-context recovery rows in evidence packets The Phase 11.7 recovery pass (every archive row touching a review wallet, address or planting tx; 24,142 rows, still source-selected) becomes an evidence input. Reviewer guide: technical-problem procedure and how to read the new coverage wording. Co-Authored-By: Claude Opus 5.5 --- docs/ml/reviewer-guide.md | 16 ++++++++++++++++ src/cryptoguard/ml/cli.py | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/ml/reviewer-guide.md b/docs/ml/reviewer-guide.md index bd20a42..290992a 100644 --- a/docs/ml/reviewer-guide.md +++ b/docs/ml/reviewer-guide.md @@ -129,6 +129,22 @@ The numbered buttons show which items are saved. "Insufficient evidence" instead. - **Save fails:** your input is kept as a draft in the browser. Fix the message shown, or restart the command, and save again. +- **"Session expired" or the page stops loading:** stop the command (Ctrl+C) and run it + again. Use the new address it prints, because the old one stops working. Saved + decisions are kept. +- **Anything else technical:** contact the maintainer, and describe the problem without + pasting item addresses into public channels. Never edit files in your folder by hand: + the files are hash-protected, and an edited file is rejected. + +## Reading the evidence panel's wording + +- **"none in the complete recorded window"**: the wallet really had no such transfer in + that window. Earlier history was not recorded. +- **"none among the rows a research dataset kept"**: this says nothing about ordinary + activity, which is missing. Check an explorer before concluding the address was new to + the wallet. +- **"Other transfers in the same block; their order is unknown"**: those transfers are + not shown, because they may have happened after the item. ## Finishing diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index eaf2a21..dc7a9ea 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -504,7 +504,8 @@ def _review(args: argparse.Namespace) -> int: from cryptoguard.ml.evidence import build_cohort dbs = [ML_DIR / "poisoning" / "archive_subset.sqlite", - HN_DIR / "context_subset.sqlite"] # fmt: skip + HN_DIR / "context_subset.sqlite", + REVIEW_WORK / "review_context.sqlite"] # fmt: skip m = build_cohort(args.sample, args.work / "evidence", archive_dbs=dbs, cohort=cohort) print(f"{m['items']} packets for {cohort}; sha256 {m['packets_sha256']} " f"(0 RPC requests).") # fmt: skip From e77189bcdc84fc292bc819c28daecf0c8dade65e Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 15:07:19 +0300 Subject: [PATCH 35/92] feat(ml): register amendment-3 evidence packets (evidence-packets/2) Built at 3ee994f on a clean tree, before any review or package: same frozen sheets, plus same-block ambiguity, coverage wording and the recovered archive rows (all 19 Cohort B archive items that had no local wallet history now have pre-cutoff rows, still source-selected). review-sample/1: 7f75f593...; hard-negative-candidates/1: fcb4765e... Leak checks: no payoff transaction, source label or post-cutoff row. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/review_sample.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cryptoguard/ml/review_sample.py b/src/cryptoguard/ml/review_sample.py index b144faa..c126352 100644 --- a/src/cryptoguard/ml/review_sample.py +++ b/src/cryptoguard/ml/review_sample.py @@ -328,13 +328,15 @@ class FrozenIntegrityError(ReviewSampleError): KEY: "f333386d20ce327df27c2747aef317e96e030c61650f3f20b60d06f038802ad9", MANIFEST: "05dc1b1679f9fdce7560ff5da1f9a869fd84c8617646410e56aa3cbce59e3868", } -# Protocol amendment 2: offline pre-cutoff evidence packets (evidence-packets/1), built at -# 240ba9b on a clean tree before any review. Separate files; the frozen sheets are untouched. +# Offline pre-cutoff evidence packets, separate files; the frozen sheets are untouched. +# Amendment 2 registered evidence-packets/1 (240ba9b: A 68f11afb..., B 1c7f32c6...). +# Amendment 3 (Phase 11.7, before any review or package) replaces them with +# evidence-packets/2 built at 3ee994f (clean tree) from the same sheets plus recovered rows. COHORTS[SAMPLE_VERSION]["evidence"] = ( - "68f11afba87266ee393dcf33a84c913c55fca9c01656f7a1b1d6dfc5122d46ae" + "7f75f5936c7b6e3f96eea7921e9bf2097f114ce65123f7a4db4c46a4c7295747" ) COHORTS["hard-negative-candidates/1"]["evidence"] = ( - "1c7f32c64c9c2beb0342baf8762d5381a5923f0c04389e83dd5da4919cdc01bf" + "fcb4765e4a2ef870c003bd1abc4ddf1bf40e69dc1c0747748dd4ce75e51ad567" ) From 3a2f94b6d8ac180d3a67e6686e509f8cea48c786 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 15:20:50 +0300 Subject: [PATCH 36/92] docs(ml): Phase 11.7 evidence completion report, amendment 3, experiment spec export Records the offline recovery (all 19 Cohort B archive items gain pre-cutoff rows), evidence coverage for all 95 items, the remaining signer/receipt/token gap and its exactly sized RPC proposal (not run), source-positive coverage of candidates/2 on signer-less data (0.4%), PTXPhish-Tsuchiya agreement, exact FPR bounds by sample size, review server fixes and gates A-L. State unchanged: REVIEW_READY, 0 human submissions. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 +++ ML.md | 3 + ML_ANNOTATION_AUDIT.md | 12 ++ ML_BENCHMARK_READINESS.md | 15 ++ ML_EVIDENCE_COMPLETION.md | 338 +++++++++++++++++++++++++++++++ ML_HARD_NEGATIVE_STUDY.md | 9 + ML_HUMAN_VALIDATION_READINESS.md | 10 + ML_RESEARCH_PLAN.md | 4 +- docs/ml/experiment-spec.json | 147 ++++++++++++++ docs/ml/review-protocol.md | 38 ++++ docs/ml/reviewer-handoff.md | 8 + 11 files changed, 608 insertions(+), 1 deletion(-) create mode 100644 ML_EVIDENCE_COMPLETION.md create mode 100644 docs/ml/experiment-spec.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc8b72..0f451fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,31 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Evidence completion and review hardening (Phase 11.7) +- An offline recovery pass over the local archive gives all 19 Cohort B archive items + that had no local wallet history some pre-cutoff rows (still source-selected). +- Evidence packets v2, registered as amendment 3 before any review: + - same-block rows of unknown order are counted, never dropped silently; + - coverage-specific wording, so missing history never reads as novelty. +- The review server refuses negative or non-numeric `Content-Length` and foreign browser + `Origin`s. +- Added `ml verify-research`: an offline PASS/FAIL/MISSING/BLOCKED report on sources, + derived files, frozen cohorts, evidence and reviews. +- Added `ml diagnostics`: + - source-positive candidate coverage, 0.4% strict, because the archive has no signer; + - evidence availability; + - generator invariance; + - scalability. +- Added `ml experiment-spec`: a JSON export with fairness, label provenance, + label-count stages and a source-proxy-free ablation. +- Added exact FPR bounds by sample size: 35 negatives cannot show FPR below about 8%. +- Cross-check: 207 of 214 PTXPhish poisoning transactions are Tsuchiya payoffs, and the + attack methods agree on 81.5% of those linked to an attempt. +- Tests: an independent reference implementation of `candidates/2`, an end-to-end + synthetic review workflow with failure injection, and a corrupt lease database. +- Docs: ML_EVIDENCE_COMPLETION.md, amendment 3, and reviewer-guide wording and problem + procedure. + ### Human validation readiness (Phase 11.6) - Both frozen cohorts re-verified byte for byte, and the history of Cohort B's superseded first draw audited. No reviewer, package or submission exists: state REVIEW_READY. diff --git a/ML.md b/ML.md index 132d69e..5a55468 100644 --- a/ML.md +++ b/ML.md @@ -63,6 +63,9 @@ method and decision log. - `ml/label_policy.py`, `ml/experiment_spec.py` (inactive) and `ml/power.py`. See [ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md). + - Phase 11.7: `ml/diagnostics.py` (label-free diagnostics) and `ml/verify_research.py` + (offline reproducibility report: `cryptoguard ml verify-research`). + [ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md) - **Further reading:** [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md) covers the pilot reconstruction and the data-loss fix. [ML_RESEARCH_PLAN.md](ML_RESEARCH_PLAN.md) has the issue register, the collection design and the next experiment. diff --git a/ML_ANNOTATION_AUDIT.md b/ML_ANNOTATION_AUDIT.md index 18659f8..dd88586 100644 --- a/ML_ANNOTATION_AUDIT.md +++ b/ML_ANNOTATION_AUDIT.md @@ -345,3 +345,15 @@ No P0 finding: every hash, uniqueness, separation, allocation and reserve-order - **Calibration.** A synthetic training cohort precedes real review. - **Sensitivity analyses** are pre-specified in protocol B4. - **Status:** [ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md). + +## 22. Amendment 3 (Phase 11.7) + +- **New packets.** The evidence packets are now `evidence-packets/2`: same-block rows of + unknown order are counted, and the coverage wording is explicit. Recovered archive rows + give every Cohort B archive item pre-cutoff history. The hashes are registered before + any review. +- **Server fixes.** The review server refuses malformed `Content-Length` and foreign + `Origin`s. +- **Workflow test.** A full synthetic review workflow, with failure injection, is tested + end to end. +- **Details:** [ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md). diff --git a/ML_BENCHMARK_READINESS.md b/ML_BENCHMARK_READINESS.md index 5211803..20212be 100644 --- a/ML_BENCHMARK_READINESS.md +++ b/ML_BENCHMARK_READINESS.md @@ -163,3 +163,18 @@ as gates A-K. The pre-registered experiment (`ml/experiment_spec.py`) stays inactive until at least 30 reviewed labels per class exist, from at least 5 campaign groups each. + +## 10. Phase 11.7 + +[ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md) evaluates gates A-L. + +- **Pass:** A, C, K, L. +- **Pass with limitations:** B, D, G, H. +- **Blocked by human review:** E, F, J. +- **Fail:** I. + +Two new findings: +- **Rule replay on archive items** needs signer data no local source has. `candidates/2` + re-emits only 0.4% of source positives on signer-less data. +- **Sample size:** 35 reviewed negatives cannot bound FPR below about 8%. A 1% claim needs + about 300 effectively independent negatives. diff --git a/ML_EVIDENCE_COMPLETION.md b/ML_EVIDENCE_COMPLETION.md new file mode 100644 index 0000000..b4b36e6 --- /dev/null +++ b/ML_EVIDENCE_COMPLETION.md @@ -0,0 +1,338 @@ +# Evidence completion and review readiness (Phase 11.7) + +**State: still REVIEW_READY: HUMAN ANNOTATION PENDING.** + +| Item | Status | +|---|---| +| Finalized human submissions | 0 | +| Human-reviewed items | 0 of 95 (190 decisions pending) | +| Reviewers recruited | none | +| RPC requests / downloads | 0 / 0 | +| Model trained | none | + +## 1. Executive summary + +- **Evidence recovered offline.** One extra streaming pass over the local archive gave + all 19 Cohort B archive items that had *no* local wallet history some pre-cutoff rows. + Cohort B's median rose from 0 to 18 rows. + - The rows are still only what the source kept, never complete history. +- **Evidence semantics fixed.** The packets now: + - count same-block rows of unknown order instead of dropping them silently; + - say what "no earlier interaction" means under complete, source-selected or absent + coverage. + + These changes are registered as amendment 3, before any review or package. +- **The remaining evidence gap needs authorization.** Signers are unknown for 85 of 95 + items, receipts for all 95, and token legitimacy for 28 tokens. Local data cannot close + this; about 292 RPC requests could (§19). +- **Independent corroboration.** PTXPhish (expert-reviewed, NDSS 2025) holds 214 + address-poisoning transactions. 207 of them are Tsuchiya payoffs. Where both sources + name an attack method (173), they agree 141 times (81.5%). For 11 Cohort A items, the + victim's later payment is a PTXPhish transaction, and the methods agree 11 of 11. + - This corroborates *losses* and attack methods at the source level. It is not review + of the plantings. +- **Negative finding.** On archive-style data, which has no signer, `candidates/2` + re-emits only 6 of 1,409 source positives (0.4%), or 51 (3.6%) with an optimistic signer + assumption. Its main planting rule needs the transaction signer. +- **Hardening.** + - The review server now refuses negative or malformed `Content-Length` (a negative + value made it read until the client closed) and foreign browser `Origin`s. + - New tests: an independent reference implementation for the generator, and a full + synthetic review workflow with failure injection. + - `ml verify-research` reports reproducibility status. + +## 2. Research state + +**Track A** (PTXPhish classifier) is unchanged and separate. + +**Track B** (wallet-centric poisoning): +- the production rule detector stays the baseline; +- the pre-registered ML comparison (`docs/ml/experiment-spec.json`) is inactive; +- no labels exist. + +## 3. Frozen cohort integrity + +Both cohorts verify byte for byte (`ml review verify`, `ml verify-research`): + +| | Cohort A (60 items) | Cohort B (35 items) | +|---|---|---| +| Selection | `e368beb4…` | `ae9df36a…` | +| Sheet | `a0ec4b6e…` | `121c112d…` | +| Key | `407b412f…` | `f333386d…` | +| Manifest | `c38ae31d…` | `05dc1b16…` | + +- The design audit still passes. +- The only change is amendment 3: new evidence-packet files, registered by hash. The + frozen sheets, keys and manifests are untouched. + +## 4. Evidence availability (all 95 items) + +**Matrix.** The item-level matrix is local (`data/ml/poisoning/review/ +evidence_coverage_matrix.jsonl`, git-ignored). Aggregates: + +| Field | Cohort A (60) | Cohort B (35) | +|---|---|---| +| Candidate transfer available | 60 | 35 | +| Signer known | 0 | 10 (recorded-wallet items) | +| Receipt recorded | 0 | 0 (a recorded Transfer log implies success) | +| Token on the reviewed list | 33 | 29 | +| Wallet rows before cutoff (median) | 22 | 18 (was 0) | +| Items with no local wallet rows | 0 | 1 (a recorded wallet with an empty window) | +| Earlier rows between wallet and address | 26 | 3 | +| Graph context available | 60 (archive) | 24 (archive) | +| Same-block rows of unknown order | 4 items | 1 item | + +## 5. Cohort B historical coverage + +**Before:** 19 of the 24 archive items had no local wallet row before the cutoff. + +**After the recovery pass:** +- 0 of 24 archive items lack rows; +- 24 items gained rows; +- the 11 recorded-wallet items are complete for their window, but nothing before it. + +## 6. Offline recovery attempts + +| Source searched | Review wallets found | Usable? | +|---|---|---| +| Tsuchiya archive, new targeted pass (wallets, addresses, txs of all 95 items) | all | **yes**: 24,142 rows, 1,369 s, peak 256 MiB | +| Existing archive subsets | Cohort A only | already used | +| Recorded replay windows | 7 Cohort B wallets | already used | +| Pilot recordings | 0 | no | +| Poison-Hunter sample | 0 | no | +| PTXPhish chain records | 11 Cohort A wallets | **no**: all 11 are the victims' *later* payments (20 to 930,525 blocks after the cutoff). They are outcomes, so they are excluded from evidence | + +- **What no local source has:** transaction signers, receipts or token metadata for + archive-derived items, and complete ordinary history for any archive wallet. + +## 7. Point-in-time guarantees + +- **The cutoff** is the candidate's block, and the evidence position is just before the + candidate's transaction. + - Rows strictly earlier are shown. + - Same-block rows are shown only when the recorded transaction order proves they came + first. + - Same-block rows of unknown order are *counted* and flagged, never shown or dropped + silently. +- **What the packets never read:** flags, intended addresses, payoffs or labels. +- **Tests:** metamorphic tests cover future rows, later payoffs, relabelling, future graph + edges, duplicates across sources and reordering. +- **Checks on the real packets:** no payoff transaction and no source label appear. All + 10 history rows dated in the cutoff block are recorded-window rows of proven earlier + order. + +## 8. Reviewer evidence quality + +**Can a reviewer recognise impersonation without being told the answer?** + +- **Cohort A: yes, partially.** In all 60 packets the imitated counterparty is visible as + an earlier counterparty. Reviewers must find it themselves; no similarity is computed. + But the archive keeps only look-alike-related rows, which can make attacks look more + obvious than a full history would (disclosed). +- **Cohort B: now yes, for every archive item.** The recorded-wallet items show their full + window. +- **Wording.** The evidence panel's wording and the reviewer guide now explain each + coverage case, including that a missing interaction under partial coverage is not + novelty. + +## 9. Review application fixes + +**Defects fixed:** +- **P1:** a negative `Content-Length` made a handler read until the client closed. + Non-numeric values crashed the handler. Both now get 400. +- **P2:** a request carrying a foreign `Origin` header was accepted. It is now refused; + the existing token header already blocked cross-site requests. + +**Checked and found adequate:** +- a 24-byte session token sent only in a header; +- the token lives in the URL fragment, which browsers never send to the server or as a + Referer, and is removed from the address bar; +- 12-hour expiry, a Host check, strict CSP, a static whitelist (no file paths from + requests) and a 64 KiB body cap; +- no request logging; +- answer keys never loaded by the server; +- stores and finalization separate per reviewer. + +**End-to-end synthetic workflow** (test). Package, then HTTP saves, then a server restart +(the old token is refused and saved work kept), a torn save recovered, finalization, +submission check, a corrupt export refused, premature unblinding refused, agreement, and +unblinding with exactly one logged key access. The synthetic reviewers are software +fixtures. + +## 10. Statistical validation + +Agreement and estimators were already tested against hand-computed values (Phase 11.4, +11.6). New this phase is the sufficiency table (`ml/power.bound_table`): the upper bound on +FPR when 0 or 1 of *n* reviewed legitimate events is flagged. + +| n | Design effect | Upper bound, 0 flagged (one-sided 95% exact) | Upper bound, 1 flagged | Upper bound, 0 flagged (two-sided 95% Wilson) | +|---|---|---|---|---| +| 30 | 1 | 9.5% | 14.9% | 11.4% | +| 35 | 1 | 8.2% | 12.9% | 9.9% | +| 50 | 1 | 5.8% | 9.1% | 7.1% | +| 100 | 1 | 2.95% | 4.7% | 3.7% | +| 100 | 2 | 5.8% | 9.1% | 7.1% | +| 300 | 1 | 0.99% | 1.6% | 1.3% | +| 1,000 | 1 | 0.30% | 0.47% | 0.38% | + +**Reading the table.** +- 35 negatives, even all correct, cannot show an FPR below about 8%. +- A 1% claim needs about 300 effectively independent negatives with no error. +- These describe the sampled population only. Neither cohort's class mix is prevalence, + and the two are never pooled. + +## 11. Benchmark design + +`docs/ml/experiment-spec.json` (generated from `ml/experiment_spec.py`, inactive) now also +fixes: +- **fairness:** same events, cutoff, labels and split for rules and models; +- **label provenance:** for positives, negatives and unknowns; +- **candidate population:** defined before any model; +- **an untouched test set;** +- **six label-count stages:** smoke test, exploration, tuning, estimation, low-FPR claim, + generalization; +- **an ablation without source proxies:** no value, token or shape features, because they + separated the source frames almost perfectly. + +## 12. Valid offline diagnostics (`ml diagnostics`, aggregate) + +**A. Source-positive candidate coverage.** +- **Population:** 1,409 payoff-linked source positives (60 reserved excluded): 745 fake + token, 614 spoofed `transferFrom`, 50 dust. +- **Method:** a 7-day history of source-selected archive rows before each planting. + +| Mode | Emitted | Fake token | Spoofed transferFrom | Dust | +|---|---|---|---|---| +| strict (no signer known) | **6 (0.4%)** | 0/745 | 2/614 | 4/50 | +| optimistic (victim's own non-poisoning sends signed) | 51 (3.6%) | 0/745 | 2/614 | 49/50 | + +- **Why so low.** Fake-token and spoofed plantings appear as transfers *from* the victim + (98% in the archive). The rule for them (`spoofed_out`) needs the planting transaction's + real signer, which the archive does not record. With known signers, dust plantings are + found by `lookalike_in` (49/50). +- **What this is.** A structural limitation measured on source-selected data, not the + generator's recall on real wallets. It is the clearest evidence that signer data is the + bottleneck. + +**B. Evidence availability:** §4. + +**C. Generator invariance** on all 13 recorded windows: reordered input, upper-case +addresses and added future activity leave the candidates identical (13/13 each). + +**D. Scalability** (synthetic, with memory tracing on, which slows it): + +| Transfers | Time | Peak memory | +|---|---|---| +| 1,000 | 0.09 s | 1.0 MiB | +| 10,000 | 0.90 s | 9.9 MiB | +| 30,000 | 2.95 s | 28.4 MiB | + +Without tracing, 10,000 transfers take 0.13 s, as before. + +**E. Source agreement (PTXPhish vs Tsuchiya).** +- 207 of 214 PTXPhish poisoning transactions (96.7%) are Tsuchiya payoffs. +- Attack-method agreement on the 173 linked to an attempt: 141 (81.5%). Most disagreements + are PTXPhish "zero-value" cases whose latest attempt before payment was a fake token (19), + consistent with competing plantings. +- **Caveat:** the two datasets may share upstream signals (for example explorer phishing + tags), so this is corroboration, not independence proof. + +**F. Rule-failure taxonomy.** The demonstrated failure (A) is missing signer data. No +other failure class is claimed without labels. + +## 13. Candidate-generator evaluation + +- **Independent reference.** A new test re-implements `candidates/2` from its documented + rules: its own affix comparison and choice set, with no shared code. It matches on 40 + random fixtures. These include shared suffixes, checksum-case addresses, unknown and + third-party signers, and untrusted tokens. +- **Malformed addresses** neither crash nor match. +- **Suffix bucketing is exact:** the rule requires at least 3 shared trailing characters. + +## 14. Code quality + +| ID | Pri | Finding | Status | +|---|---|---|---| +| 41 | P1 | Negative or non-numeric `Content-Length` in the review server | Fixed; test | +| 42 | P2 | Foreign `Origin` accepted | Fixed; test | +| 43 | P1 | Evidence silently dropped same-block rows of unknown order | Fixed (`evidence-packets/2`); test | +| 44 | P1 | "0 earlier rows" read the same under complete and partial coverage | Fixed: coverage-specific wording; test | +| 45 | P2 | `verify-research` would report absent frozen files as FAIL | Reported as MISSING; test | +| 46 | P2 | Corrupted lease database: confirmed not mapped to `LeaseBusyError` | Test added; no change needed | + +**Reviewed, not changed.** +- Two `_canonical` JSON helpers (review sample vs annotation) differ by design. Each is + the frozen hash basis of its artifact; unifying them would change committed hashes. +- No other duplicated logic was found to cause an inconsistency. + +## 15. Security findings + +- **Review server:** §9. +- **Data:** all archive-derived files, packets, matrices, packages and diagnostics stay + local. Only code, specs and aggregates are committed. +- **No secrets** in logs (the server logs nothing). +- **Parsing:** archive parsing never executes SQL. The SQLite queries take parameters, + and their only f-string is a fixed column list. + +## 16. Testing and CI + +The PR description records the counts from this phase's full run. New tests: +- `tests/unit/test_ml_evidence_completion.py`: same-block ambiguity, coverage wording, + duplicates, future graph edges, Origin and length refusal, the independent generator + reference, malformed addresses, exact bounds, spec export, offline verification, a + corrupt lease database, and the end-to-end workflow. + +## 17. Resource usage + +| Step | Runtime | Peak | +|---|---|---| +| Recovery pass (35 M rows) | 1,369 s | 256 MiB | +| Evidence rebuild (95 items) | about 20 s | under 400 MiB | +| Diagnostics | 263 s | (not traced) | +| Verification incl. 2.3 GB hash | about 30 s | small | +| Disk | +11 MB (`review_context.sqlite`) | | + +0 RPC requests. + +## 18. Remaining human dependencies + +1. Two independent human reviewers for both cohorts: 190 decisions, plus training. +2. Without them, gates E, F, I and J cannot move. + +## 19. Remaining data dependencies + +**Proposed, not executed.** Separate approval is needed for a provider with historical +(archive) state. The request: +- `eth_getTransactionByHash` for the 85 items with unknown signers; +- `eth_getTransactionReceipt` for all 95 planting transactions (status and log emitter); +- `eth_getCode` and `name`/`symbol`/`decimals` at the cutoff block for 28 unreviewed + tokens. + +**About 292 requests; cap 365 with retries.** It would close the signer, receipt and token +gaps for every review item. Complete ordinary wallet history is a far larger collection +(ML_HUMAN_VALIDATION_READINESS.md §15). + +## 20. Highest-value next research action + +**Recruit the two independent reviewers** and start the review with the current packets. +It needs no new data and no authorization. Everything else waits on their decisions. + +**If you prefer to close the signer gap first,** the request in §19 is small and exactly +sized. Deciding on it is yours. + +## Decision gates + +| Gate | Status | +|---|---| +| A Frozen sample integrity | **PASS** | +| B Evidence quality | PASS WITH LIMITATIONS (history for 94/95; signers unknown for 85, receipts for 95) | +| C Historical correctness | **PASS** (metamorphic tests; real-packet leak checks) | +| D Reviewer independence | PASS WITH LIMITATIONS (procedural on shared computers; no humans yet) | +| E Positive labels | BLOCKED BY HUMAN REVIEW | +| F Negative labels | BLOCKED BY HUMAN REVIEW | +| G Source bias | PASS WITH LIMITATIONS (measured and documented; selection bias remains) | +| H Leakage-safe splits | PASS WITH LIMITATIONS (guards tested; no real labelled split) | +| I Statistical adequacy | **FAIL** (0 labels; 35 negatives cannot bound FPR below about 8%) | +| J ML comparison readiness | BLOCKED BY HUMAN REVIEW (spec inactive; signer data also missing for rule replay on archive items) | +| K Production isolation | **PASS** | +| L Engineering quality | **PASS** (defects 41-46 handled; tests and CI listed in the PR) | diff --git a/ML_HARD_NEGATIVE_STUDY.md b/ML_HARD_NEGATIVE_STUDY.md index 6c900d2..78ff486 100644 --- a/ML_HARD_NEGATIVE_STUDY.md +++ b/ML_HARD_NEGATIVE_STUDY.md @@ -452,3 +452,12 @@ RPC. - **Generator speed.** `candidates/2` buckets chosen counterparties by their last 3 characters (an exact shortcut, since the rule requires them). 10,000 transfers take 0.13 s instead of 13 s, and the output is unchanged. + +## 27. Phase 11.7 follow-up + +- **Recovered history.** The 19 Cohort B archive items without local wallet history now + have pre-cutoff rows, from one more offline pass over the archive. +- **Generator on signer-less data.** On archive-style data, `candidates/2` re-emits only 6 + of 1,409 source positives. The rule for the dominant planting shape needs signer data + the archive lacks. +- **Details:** [ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md) §12. diff --git a/ML_HUMAN_VALIDATION_READINESS.md b/ML_HUMAN_VALIDATION_READINESS.md index f2e3b95..f5ebc91 100644 --- a/ML_HUMAN_VALIDATION_READINESS.md +++ b/ML_HUMAN_VALIDATION_READINESS.md @@ -327,3 +327,13 @@ measured review time, which replaces the 5-minute assumption. | I Statistical adequacy | **FAIL** (0 labels; 35 candidates bound FPR at about 10% at best) | | J ML readiness | BLOCKED BY MISSING HUMAN EVIDENCE (spec inactive) | | K Production isolation | **PASS** (research modules load neither database nor API; findings unchanged) | + +## Phase 11.7 update + +[ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md) supersedes the evidence numbers in +§4 and the gate statuses above. Changes: +- all 24 Cohort B archive items now have pre-cutoff wallet rows (19 recovered offline); +- the packets are now `evidence-packets/2` (amendment 3); +- the gates are re-evaluated as A-L. + +The state is unchanged: REVIEW_READY: HUMAN ANNOTATION PENDING. diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index fd8e0a5..37a1802 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -12,7 +12,9 @@ pool of 8,877 unlabeled hard-negative candidates and a second frozen cohort of 3 ([ML_HARD_NEGATIVE_STUDY.md](ML_HARD_NEGATIVE_STUDY.md)). Phase 11.6 made both cohorts review-ready (evidence packets, protocol amendment 2, training cohort, handoff): status REVIEW_READY: HUMAN ANNOTATION PENDING -([ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md)). Data model and labels: +([ML_HUMAN_VALIDATION_READINESS.md](ML_HUMAN_VALIDATION_READINESS.md)); Phase 11.7 +completed the offline evidence and hardened the workflow +([ML_EVIDENCE_COMPLETION.md](ML_EVIDENCE_COMPLETION.md)). Data model and labels: [ML_POISONING_DATASET.md](ML_POISONING_DATASET.md). Pilot: [ML_PILOT_AUDIT.md](ML_PILOT_AUDIT.md). Generated numbers: [ML_POISONING_TABLES.md](ML_POISONING_TABLES.md). diff --git a/docs/ml/experiment-spec.json b/docs/ml/experiment-spec.json new file mode 100644 index 0000000..8eee593 --- /dev/null +++ b/docs/ml/experiment-spec.json @@ -0,0 +1,147 @@ +{ + "baselines": [ + "detectors.poisoning (production rule)", + "similarity heuristic (candidates.similar)", + "transaction-shape heuristic (subtype)", + "wallet-history heuristic (no prior payment to the recipient)", + "logistic regression", + "LightGBM" + ], + "calibration": "reliability curve and Brier score only with >= 100 reviewed items per class", + "candidate_population": "defined by candidates/2 before any model exists; never by a model score", + "cutoff": "after the candidate's transaction executes, before anything later in its block", + "eligibility": "candidates/2 outputs with complete or partial recorded history; known-positive overlaps never serve as negatives", + "fairness": [ + "every method (rules, heuristics, models) scores the same eligible events", + "every method sees only information available at the same cutoff", + "every method is judged against the same label policy and the same split", + "the production rule is replayed on the same recorded histories, never with more context than the models" + ], + "feature_groups": { + "combined": [ + "prefix_to_imitated", + "suffix_to_imitated", + "plausible_impersonated", + "recipient_lookalike_of_known", + "recipient_max_affix_to_known", + "value_is_zero", + "token_trusted", + "subtype_dust", + "subtype_fake_token", + "subtype_other", + "subtype_spoofed_transfer_from", + "subtype_zero_value", + "prior_payments_to_recipient", + "prior_interactions_with_recipient", + "distinct_prior_recipients", + "recent_new_recipient_share", + "unsolicited_events_with_recipient", + "history_available", + "history_partial", + "observed_blocks", + "blocks_since_first_interaction", + "blocks_since_last_interaction", + "blocks_since_imitated_chosen", + "recent_unsolicited_in", + "lookalike_victims_before", + "signer_victims_before", + "lookalike_plantings_observed" + ], + "combined_without_source_proxies": [ + "prefix_to_imitated", + "suffix_to_imitated", + "plausible_impersonated", + "recipient_lookalike_of_known", + "recipient_max_affix_to_known", + "prior_payments_to_recipient", + "prior_interactions_with_recipient", + "distinct_prior_recipients", + "recent_new_recipient_share", + "unsolicited_events_with_recipient", + "history_available", + "history_partial", + "observed_blocks", + "blocks_since_first_interaction", + "blocks_since_last_interaction", + "blocks_since_imitated_chosen", + "recent_unsolicited_in", + "lookalike_victims_before", + "signer_victims_before", + "lookalike_plantings_observed" + ], + "graph_context_only": [ + "lookalike_victims_before", + "signer_victims_before", + "lookalike_plantings_observed" + ], + "similarity_only": [ + "prefix_to_imitated", + "suffix_to_imitated", + "plausible_impersonated", + "recipient_lookalike_of_known", + "recipient_max_affix_to_known" + ], + "temporal_only": [ + "blocks_since_first_interaction", + "blocks_since_last_interaction", + "blocks_since_imitated_chosen", + "recent_unsolicited_in" + ], + "transaction_only": [ + "value_is_zero", + "token_trusted", + "subtype_dust", + "subtype_fake_token", + "subtype_other", + "subtype_spoofed_transfer_from", + "subtype_zero_value" + ], + "wallet_history_only": [ + "prior_payments_to_recipient", + "prior_interactions_with_recipient", + "distinct_prior_recipients", + "recent_new_recipient_share", + "unsolicited_events_with_recipient", + "history_available", + "history_partial", + "observed_blocks" + ] + }, + "label_count_stages": { + "feature_exploration": ">= 30 per class from >= 5 campaign groups (activation gate)", + "generalization": "several time periods and many campaigns; not reachable with the current cohorts", + "hyperparameter_selection": "a validation split disjoint by campaign and later in time; >= 30 per class in validation itself", + "low_fpr_claim": "FPR <= 1% needs about 300+ effectively independent negatives with 0 false positives (one-sided 95%)", + "performance_estimate": "an untouched test split; see ml/power.bound_table for what its negatives can bound", + "smoke_test": "any labels; software correctness only, never a reported metric" + }, + "label_provenance": { + "negative": "label-policy/1 reviewed_legitimate (two independent humans, confirmed, positive evidence of a legitimate interpretation)", + "positive": "label-policy/1 reviewed_attack (two independent humans, confirmed)", + "unknown": "excluded from the strict benchmark and counted" + }, + "no_gnn": "graph context enters as tabular features; no GNN without a new hypothesis", + "populations": { + "test": "a later, untouched set; the frozen cohorts count only if never used in development (benchmark.Holdout)", + "train": "reviewed items outside both frozen review cohorts", + "validation": "grouped-temporal split of the training population" + }, + "prediction_unit": "victim-event: one candidate transfer to or from one wallet", + "primary_metric": "average precision on test, reported with recall at FPR <= 5%", + "resource_budget": "CPU only, < 2 GB RAM, < 2 minutes per fit (larger needs approval)", + "secondary_metrics": [ + "precision", + "recall", + "FPR", + "ROC-AUC", + "precision at review capacity 50", + "candidate recall (separately)", + "latency" + ], + "split": "grouped-temporal/1 with typed-groups/1 entities (victim, lookalike, planting tx, signer, imitated, counterfeit token); public tokens and routers never link", + "status": "inactive", + "target": "label-policy/1 strict binary: reviewed_attack=1, reviewed_legitimate=0", + "test_set": "untouched until the model, features, threshold rule and metrics are frozen", + "threshold": "chosen on validation only: the highest recall with FPR <= 5%", + "version": "poisoning-attempt-supervised/1" +} diff --git a/docs/ml/review-protocol.md b/docs/ml/review-protocol.md index 4b6d46c..57879d1 100644 --- a/docs/ml/review-protocol.md +++ b/docs/ml/review-protocol.md @@ -284,3 +284,41 @@ Each reviewer first works through the synthetic training package packets and separate teaching notes, read afterwards. Training decisions stay in the training folder and can never be unblinded. The real items are never used for calibration. + +--- + +# Amendment 3 (Phase 11.7, before any review or package) + +**Status when written:** +- No reviewer had been recruited, no package issued, no decision made. +- No key was opened. The frozen sheets, keys and manifests are unchanged. + +## C1. Changes + +The evidence packets become `evidence-packets/2`: +1. **Same-block rows of unknown order** relative to the item are counted and flagged + (`same_block_order_unknown`). Before, they were dropped silently. They are still not + shown. +2. **The address relationship** carries a coverage-specific interpretation. "None" under + source-selected or absent coverage is stated not to mean novelty. +3. **Inputs** now include the Phase 11.7 recovery pass: every archive row touching a + review wallet, address or planting transaction. All 19 Cohort B archive items that had + no local wallet rows now have pre-cutoff rows. These rows are still source-selected. + +## C2. Registered hashes + +Built at commit `3ee994f` on a clean tree: + +| Cohort | Packets SHA-256 | +|---|---| +| `review-sample/1` | `7f75f5936c7b6e3f96eea7921e9bf2097f114ce65123f7a4db4c46a4c7295747` | +| `hard-negative-candidates/1` | `fcb4765e4a2ef870c003bd1abc4ddf1bf40e69dc1c0747748dd4ce75e51ad567` | + +They replace the amendment-2 hashes. Packages made earlier would be refused, but none +existed. + +## C3. Leak checks on the built packets + +- No payoff transaction and no source label term appear. +- Every history row is before the cutoff block, or a same-block row whose recorded order + proves it came earlier. diff --git a/docs/ml/reviewer-handoff.md b/docs/ml/reviewer-handoff.md index a4fdfe1..bd0eb39 100644 --- a/docs/ml/reviewer-handoff.md +++ b/docs/ml/reviewer-handoff.md @@ -84,3 +84,11 @@ training cases once a reviewer has done them. [--cohort …]`. It needs no key. 7. Only then: `cryptoguard ml review unblind …` per cohort. Report aggregates. Keep the per-item files local. + +## 7. Optional, needs your approval: closing the signer gap + +The packets lack signers for 85 items, receipts for all 95 and metadata for 28 tokens. +No local source has them. A request of about 292 calls (cap 365) to a provider with +historical state would close these gaps (ML_EVIDENCE_COMPLETION.md §19). It is not needed +to start the review, and nothing is collected without your explicit approval of a cap and +a provider. From 815284914aa089b15de3d553d5e90b7176b995bd Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 17:17:25 +0300 Subject: [PATCH 37/92] feat(ml): reviewer kit builder and send-ready invitation scripts/make_reviewer_kit.py builds one zip per reviewer pseudonym: the training folder, the two frozen cohorts under neutral names (set-1, set-2), the reviewer guide, a setup README and the review tool's committed code without reports, tests or research docs. It refuses to finish unless every sheet and evidence file has its registered hash, no key, manifest, database or submission is present, and the real folders contain no source or cohort words. A maintainer-only record maps folders to cohorts. The invitation now states the assumed 9 hours and no payment, the checklist uses the kit, and the handoff flags the CC BY-NC-ND sharing question for the maintainer to decide before sending. Co-Authored-By: Claude Opus 5.5 --- docs/ml/reviewer-guide.md | 10 +- docs/ml/reviewer-handoff.md | 42 +++++-- docs/ml/reviewer-kit-readme.md | 64 +++++++++++ scripts/make_reviewer_kit.py | 202 +++++++++++++++++++++++++++++++++ tests/test_reviewer_kit.py | 79 +++++++++++++ 5 files changed, 380 insertions(+), 17 deletions(-) create mode 100644 docs/ml/reviewer-kit-readme.md create mode 100644 scripts/make_reviewer_kit.py create mode 100644 tests/test_reviewer_kit.py diff --git a/docs/ml/reviewer-guide.md b/docs/ml/reviewer-guide.md index 290992a..462cc41 100644 --- a/docs/ml/reviewer-guide.md +++ b/docs/ml/reviewer-guide.md @@ -12,13 +12,13 @@ are never used as data, and the real items are never used for practice. ## Setup (once per folder) -1. Get your personal review folders from the maintainer. Each contains - `reviewer_sheet.jsonl`, `reviewer.json` and usually `evidence_packets.jsonl`, and - nothing else is needed. -2. From the CryptoGuard repository, with Python 3.12 and `uv`, run: +1. Get your personal kit from the maintainer. Its `README.md` explains the setup. Each + review folder contains `reviewer_sheet.jsonl`, `reviewer.json` and usually + `evidence_packets.jsonl`, and nothing else is needed. +2. From the kit's `cryptoguard` folder, with `uv` installed, run: ```bash - uv run cryptoguard ml review serve --package + uv run --no-dev cryptoguard ml review serve --package ``` 3. Your browser opens the review page. If it does not, open the exact address the command diff --git a/docs/ml/reviewer-handoff.md b/docs/ml/reviewer-handoff.md index bd0eb39..fdec9a2 100644 --- a/docs/ml/reviewer-handoff.md +++ b/docs/ml/reviewer-handoff.md @@ -1,9 +1,10 @@ # Reviewer handoff (maintainer) Materials for recruiting two independent human reviewers. Nothing here has been sent. No -reviewer has been contacted, has agreed or exists yet. +reviewer has been contacted, has agreed or exists yet. Only the maintainer contacts +reviewers; no tool or AI assistant sends anything. -## 1. Invitation draft (edit before sending; promise nothing not yet decided) +## 1. Invitation (ready to send; adjust the greeting, promise nothing not yet decided) > **Subject: Independent review of Ethereum transactions (address-poisoning research)** > @@ -13,7 +14,7 @@ reviewer has been contacted, has agreed or exists yet. > local review page on your own computer and, if you wish, a public block explorer. > > What it involves: -> - installing a Python tool from a private repository; +> - installing `uv` and running a small local Python tool that I send you as a zip file; > - working independently, without discussing items with the other reviewer until both > of you have submitted; > - recording, for each item, a decision, your reasons and what you saw. @@ -21,7 +22,8 @@ reviewer has been contacted, has agreed or exists yet. > The data come from a licensed research dataset and must stay on your computer. They are > not to be shared or published. > -> My rough estimate is [N] hours. This is an assumption, not a measured time. +> My rough estimate is about 9 hours in total, which you can split over several sessions. +> This is an assumption, not a measured time. There is no payment. > > Would you be willing? @@ -47,6 +49,12 @@ training cases once a reviewer has done them. ## 4. Data handling +**Decide before sending.** The packets are derived from Tsuchiya et al. data under +CC BY-NC-ND 4.0, whose "NoDerivatives" term restricts sharing adapted material. Sending +it privately to two reviewers for non-commercial research may be acceptable, but that is +your judgement or the dataset authors' to make, not this tool's. Asking the authors is the +safe route. This is not legal advice. + - Packages contain addresses derived from CC BY-NC-ND 4.0 research data. Keep them on the reviewer's computer, use them only for this review, and delete them afterwards if asked. - Return only `annotations/submission.json`. @@ -70,15 +78,25 @@ training cases once a reviewer has done them. - `cryptoguard ml review build-evidence --cohort hard-negative-candidates/1` The printed hashes must equal the registered ones (`review_sample.COHORTS`). -3. For each reviewer R (pseudonyms `A`, `B`): - - `cryptoguard ml review training-package --reviewer R --out /training-R` - - `cryptoguard ml review package --reviewer R --out /sample-R` - - `cryptoguard ml review package --cohort hard-negative-candidates/1 --reviewer R --out - /candidates-R` -4. Send each reviewer only their own three folders, `docs/ml/reviewer-guide.md` and this - repository's setup instructions. +3. Build one kit per pseudonym (`A`, `B`) from a clean tree. A pseudonym is not tied to + a person until its kit is sent; give `A` to whoever agrees first. + + ```bash + uv run python scripts/make_reviewer_kit.py --reviewer A + ``` + + This writes `data/ml/poisoning/outbox/reviewer-A.zip` and a maintainer-only + `reviewer-A.record.json`. The kit holds three folders (`training`, `set-1` = + `review-sample/1`, `set-2` = `hard-negative-candidates/1`), the guide, a setup README + and the review tool's code without the reports, tests or research docs. The script + refuses to finish if any check fails (registered hashes, no key or manifest, no + source words in the real folders). The neutral folder names and the code-only copy keep + the cohort descriptions out of the reviewers' sight. +4. Send each reviewer only their own zip, privately (not a public link). Write the date + into `sent` in the record file. 5. When a submission arrives, run - `cryptoguard ml review check-submission [--cohort …]` and fix nothing by hand. A + `cryptoguard ml review check-submission [--cohort …]` and fix nothing by hand + (`set-1` needs no `--cohort`; `set-2` needs `--cohort hard-negative-candidates/1`). A problem goes back to the reviewer. 6. With both finalized: run `cryptoguard ml review agreement --submission A --submission B [--cohort …]`. It needs no key. diff --git a/docs/ml/reviewer-kit-readme.md b/docs/ml/reviewer-kit-readme.md new file mode 100644 index 0000000..94230b7 --- /dev/null +++ b/docs/ml/reviewer-kit-readme.md @@ -0,0 +1,64 @@ +# Your review kit + +This kit is personal to you. Please do not pass it on. + +## What is in it + +| Folder or file | What it is | +|---|---| +| `README.md` | this page | +| `reviewer-guide.md` | how to decide, what to record and what to do if something goes wrong | +| `cryptoguard/` | the local review tool | +| `training/` | 10 invented practice cases | +| `set-1/` | the first real set | +| `set-2/` | the second real set | + +## Setup (once) + +1. Install `uv`: . It fetches + Python 3.12 itself on first use, together with the tool's dependencies from PyPI. +2. Open a terminal in the `cryptoguard` folder of this kit. + +## Reviewing + +Do the folders in this order: `training`, then `set-1`, then `set-2`. For each folder, run +the command below from the `cryptoguard` folder (`training` shown): + +```bash +uv run --no-dev cryptoguard ml review serve --package ../training +``` + +The first run takes a minute or two while `uv` sets things up. + +The review page opens in your browser. Read `reviewer-guide.md` before the first real +item, and read `training/training_notes.md` only after trying the practice cases. + +Each folder has a **Finalize submission** button. After finalizing, the folder can no +longer be changed. + +## Working independently + +- Work alone. Please don't discuss items with the other reviewer until you have both + finalized. +- Use only this kit, the guide and, if you wish, a public block explorer. +- Please don't look up this project's other documents or code comments about how the + items were chosen. They could influence your judgement. +- If you see something by accident, carry on and record it in the item's questions. That + is not a problem. + +## Returning your work + +Send the maintainer these three files, and nothing else: +- `training/annotations/submission.json` +- `set-1/annotations/submission.json` +- `set-2/annotations/submission.json` + +Please don't send screenshots or item details. + +## Data + +The items come from research datasets whose licences forbid redistribution. Please: +- keep the kit on your own computer; +- use it only for this review; +- don't post item details anywhere; +- delete the kit afterwards if the maintainer asks. diff --git a/scripts/make_reviewer_kit.py b/scripts/make_reviewer_kit.py new file mode 100644 index 0000000..a78d6fe --- /dev/null +++ b/scripts/make_reviewer_kit.py @@ -0,0 +1,202 @@ +"""Build one reviewer's kit: three blinded folders, the guide and a reviewer-only copy of the tool. + +Usage: uv run python scripts/make_reviewer_kit.py --reviewer A [--out data/ml/poisoning/outbox] + +Writes /reviewer-/, /reviewer-.zip and a maintainer-only record +/reviewer-.record.json (folder -> cohort mapping, hashes), then checks the kit +(exit code 1 on any problem). Nothing is sent: the maintainer sends the zip. 0 RPC requests. + +Folder names are neutral (set-1, set-2) and the code copy leaves out the reports, tests and +research docs, which describe how the items were chosen. +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import shutil +import subprocess +import sys +import tarfile +import zipfile +from collections.abc import Mapping +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +FOLDERS = {"set-1": "review-sample/1", "set-2": "hard-negative-candidates/1"} +TOP_LEVEL = {"README.md", "reviewer-guide.md", "cryptoguard", "training", *FOLDERS} +CODE_PATHS = ("src", "pyproject.toml", "uv.lock", ".python-version", "LICENSE") +CODE_TOP_LEVEL = {*CODE_PATHS, "README.md"} +SET_FILES = {"reviewer_sheet.jsonl", "evidence_packets.jsonl", "reviewer.json", + "replacement_sheet.jsonl"} # fmt: skip +TRAINING_FILES = {"reviewer_sheet.jsonl", "evidence_packets.jsonl", "reviewer.json", + "training_notes.md"} # fmt: skip +INFO_KEYS = {"reviewer", "protocol", "selection_sha256", "sheet_sha256", "training"} +FORBIDDEN_NAMES = ("unblinding_key", "sample_manifest", ".sqlite", ".db", ".env", "submission.json") +DOC_PATHS = ("docs/ml/reviewer-guide.md", "docs/ml/reviewer-kit-readme.md") +# Words that would tell a reviewer where an item came from. Checked in the real folders only. +FORBIDDEN_WORDS = (b"tsuchiya", b"ptxphish", b"poison-hunter", b"payoff", b"hard-negative", + b"hard_negative", b"unblind", b"review-sample") # fmt: skip +CODE_README = ( + "# CryptoGuard review tool\n\nThe local review tool only. See ../README.md for how to use it.\n" +) + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def expected_hashes() -> dict[str, dict[str, str]]: + from cryptoguard.ml import review_sample as rs + from cryptoguard.ml import training + + out = {"training": {"sheet": training.sheet_sha256(), "evidence": training.packets_sha256()}} + for folder, cohort in FOLDERS.items(): + reg = rs.COHORTS[cohort] + out[folder] = {"sheet": reg["sheet"], "evidence": reg["evidence"]} + return out + + +def check(kit: Path, reviewer: str, expected: Mapping[str, Mapping[str, str]]) -> list[str]: + """Every problem that would make the kit unsafe or unusable; empty means it may be sent.""" + problems: list[str] = [] + top = {p.name for p in kit.iterdir()} + if top != TOP_LEVEL: + problems.append(f"top level is {sorted(top)}, expected {sorted(TOP_LEVEL)}") + for path in kit.rglob("*"): + rel = path.relative_to(kit).as_posix() + if any(bad in path.name.lower() for bad in FORBIDDEN_NAMES): + problems.append(f"forbidden file {rel}") + if path.is_dir() and path.name in {"annotations", "data", "tests", ".venv"}: + problems.append(f"forbidden folder {rel}") + code = kit / "cryptoguard" + if code.is_dir(): + extra = {p.name for p in code.iterdir()} - CODE_TOP_LEVEL + if extra: + problems.append(f"code copy has extra entries {sorted(extra)}") + reports = [p.name for p in code.rglob("*.md") if p.name.startswith("ML")] + if reports: + problems.append(f"code copy has research reports {reports}") + for folder, want in expected.items(): + d = kit / folder + if not d.is_dir(): + problems.append(f"{folder}: missing") + continue + allowed = TRAINING_FILES if folder == "training" else SET_FILES + names = {p.name for p in d.iterdir()} + if names - allowed: + problems.append(f"{folder}: unexpected files {sorted(names - allowed)}") + for kind, name in ( + ("sheet", "reviewer_sheet.jsonl"), + ("evidence", "evidence_packets.jsonl"), + ): + f = d / name + if not f.is_file() or sha256(f) != want[kind]: + problems.append(f"{folder}: {name} missing or not the registered bytes") + info_path = d / "reviewer.json" + info = json.loads(info_path.read_text(encoding="utf-8")) if info_path.is_file() else {} + if info.get("reviewer") != reviewer: + problems.append(f"{folder}: reviewer.json is not for reviewer {reviewer}") + if set(info) - INFO_KEYS: + problems.append( + f"{folder}: reviewer.json has extra keys {sorted(set(info) - INFO_KEYS)}" + ) + if folder != "training": + for f in (p for p in d.iterdir() if p.is_file()): + text = f.read_bytes().lower() + hits = [w.decode() for w in FORBIDDEN_WORDS if w in text] + if hits: + problems.append(f"{folder}/{f.name}: contains {hits}") + return problems + + +def zip_problems(kit: Path, archive: Path) -> list[str]: + with zipfile.ZipFile(archive) as z: + zipped = {n.split("/", 1)[1] for n in z.namelist() if "/" in n and not n.endswith("/")} + on_disk = {p.relative_to(kit).as_posix() for p in kit.rglob("*") if p.is_file()} + return [] if zipped == on_disk else ["zip contents differ from the kit folder"] + + +def git(*args: str) -> bytes: + return subprocess.run( # noqa: S603 (our own fixed commands) + ["git", *args], # noqa: S607 + cwd=ROOT, + capture_output=True, + check=True, + ).stdout + + +def head_commit() -> str: + """HEAD, refusing uncommitted changes in anything the kit copies.""" + dirty = git("status", "--porcelain", "--", *CODE_PATHS, *DOC_PATHS).decode() + if dirty.strip(): + raise SystemExit(f"uncommitted changes in the kit's code or docs:\n{dirty}") + return git("rev-parse", "HEAD").decode().strip() + + +def copy_code(dest: Path, commit: str) -> None: + """Extract the committed code (never the working tree).""" + tar = git("archive", "--format=tar", commit, "--", *CODE_PATHS) + with tarfile.open(fileobj=io.BytesIO(tar)) as t: + t.extractall(dest, filter="data") + (dest / "README.md").write_text(CODE_README, encoding="utf-8", newline="\n") + + +def build(reviewer: str, out: Path) -> Path: + from cryptoguard.ml import training + from cryptoguard.ml.cli import COHORT_DIRS, COHORT_WORK + from cryptoguard.ml.unblind import make_package + + kit = out / f"reviewer-{reviewer}" + if kit.exists(): + raise SystemExit(f"{kit} exists; a kit is built once per reviewer") + commit = head_commit() + kit.mkdir(parents=True) + training.make_package(reviewer, kit / "training") + for folder, cohort in FOLDERS.items(): + make_package( + COHORT_DIRS[cohort], COHORT_WORK[cohort], reviewer, kit / folder, cohort=cohort + ) + shutil.copyfile(ROOT / "docs/ml/reviewer-guide.md", kit / "reviewer-guide.md") + shutil.copyfile(ROOT / "docs/ml/reviewer-kit-readme.md", kit / "README.md") + copy_code(kit / "cryptoguard", commit) + + problems = check(kit, reviewer, expected_hashes()) + archive = out / f"reviewer-{reviewer}.zip" + if not problems: + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as z: + for p in sorted(kit.rglob("*")): + if p.is_file(): + z.write(p, f"{kit.name}/{p.relative_to(kit).as_posix()}") + problems = zip_problems(kit, archive) + if problems: + print("\n".join(f"PROBLEM: {p}" for p in problems), file=sys.stderr) + raise SystemExit(1) + record = { + "reviewer": reviewer, + "commit": commit, + "folders": {"training": "training/1", **FOLDERS}, + "zip_sha256": sha256(archive), + "hashes": expected_hashes(), + "sent": None, # the maintainer fills this in by hand when the kit is sent + } + (out / f"reviewer-{reviewer}.record.json").write_text( + json.dumps(record, indent=1) + "\n", encoding="utf-8" + ) + return archive + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--reviewer", required=True, help="pseudonym, e.g. A") + parser.add_argument("--out", type=Path, default=Path("data/ml/poisoning/outbox")) + args = parser.parse_args() + archive = build(args.reviewer, args.out) + print(f"Kit for reviewer {args.reviewer}: {archive} (sha256 {sha256(archive)}); checks passed.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_reviewer_kit.py b/tests/test_reviewer_kit.py new file mode 100644 index 0000000..8c2c95d --- /dev/null +++ b/tests/test_reviewer_kit.py @@ -0,0 +1,79 @@ +"""The reviewer-kit check refuses anything that would unblind a reviewer or leak data.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +from pathlib import Path +from types import ModuleType + +import pytest + +SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "make_reviewer_kit.py" + + +@pytest.fixture(scope="module") +def kit_mod() -> ModuleType: + spec = importlib.util.spec_from_file_location("make_reviewer_kit", SCRIPT) + assert spec + assert spec.loader + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _kit(root: Path) -> tuple[Path, dict[str, dict[str, str]]]: + kit = root / "reviewer-A" + expected: dict[str, dict[str, str]] = {} + for folder in ("training", "set-1", "set-2"): + d = kit / folder + d.mkdir(parents=True) + sheet, packets = f"sheet {folder}\n".encode(), f"packets {folder}\n".encode() + (d / "reviewer_sheet.jsonl").write_bytes(sheet) + (d / "evidence_packets.jsonl").write_bytes(packets) + (d / "reviewer.json").write_text(json.dumps({"reviewer": "A", "protocol": "p"})) + expected[folder] = {"sheet": hashlib.sha256(sheet).hexdigest(), + "evidence": hashlib.sha256(packets).hexdigest()} # fmt: skip + (kit / "training" / "training_notes.md").write_text("# notes; payoff is fine here\n") + code = kit / "cryptoguard" + (code / "src" / "cryptoguard").mkdir(parents=True) + (code / "src" / "cryptoguard" / "submissions.py").write_text("") + for name in ("pyproject.toml", "uv.lock", ".python-version", "LICENSE", "README.md"): + (code / name).write_text("") + (kit / "README.md").write_text("") + (kit / "reviewer-guide.md").write_text("") + return kit, expected + + +def test_clean_kit_passes(kit_mod: ModuleType, tmp_path: Path) -> None: + kit, expected = _kit(tmp_path) + assert kit_mod.check(kit, "A", expected) == [] + + +@pytest.mark.parametrize( + ("mutate", "needle"), + [ + (lambda k: (k / "set-1" / "unblinding_key.jsonl").write_text("{}"), "unblinding_key"), + (lambda k: (k / "set-2" / "sample_manifest.json").write_text("{}"), "sample_manifest"), + (lambda k: (k / "cryptoguard" / "ML_REPORT.md").write_text(""), "ML_REPORT.md"), + (lambda k: (k / "cryptoguard" / "tests").mkdir(), "tests"), + (lambda k: (k / "set-1" / "annotations").mkdir(), "annotations"), + (lambda k: (k / "set-2" / "reviewer_sheet.jsonl").write_text("x"), "registered bytes"), + (lambda k: (k / "set-1" / "reviewer.json").write_text('{"reviewer": "B"}'), "reviewer A"), + ( + lambda k: (k / "set-1" / "reviewer.json").write_text('{"reviewer": "A", "cohort": 1}'), + "extra keys", + ), + ( + lambda k: (k / "set-2" / "replacement_sheet.jsonl").write_text("Tsuchiya row"), + "tsuchiya", + ), + (lambda k: (k / "notes.txt").write_text(""), "top level"), + ], +) +def test_check_refuses(kit_mod: ModuleType, tmp_path: Path, mutate: object, needle: str) -> None: + kit, expected = _kit(tmp_path) + mutate(kit) # type: ignore[operator] + problems = kit_mod.check(kit, "A", expected) + assert any(needle in p for p in problems), problems From 20c3b6319d27cc66e5e4be9900614799d3e500ad Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 17:17:52 +0300 Subject: [PATCH 38/92] fix(ml): reviewer kit reads the sheet hash under its registry key Co-Authored-By: Claude Opus 5.5 --- scripts/make_reviewer_kit.py | 2 +- tests/test_reviewer_kit.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/scripts/make_reviewer_kit.py b/scripts/make_reviewer_kit.py index a78d6fe..0c34c1e 100644 --- a/scripts/make_reviewer_kit.py +++ b/scripts/make_reviewer_kit.py @@ -55,7 +55,7 @@ def expected_hashes() -> dict[str, dict[str, str]]: out = {"training": {"sheet": training.sheet_sha256(), "evidence": training.packets_sha256()}} for folder, cohort in FOLDERS.items(): reg = rs.COHORTS[cohort] - out[folder] = {"sheet": reg["sheet"], "evidence": reg["evidence"]} + out[folder] = {"sheet": reg[rs.SHEET], "evidence": reg["evidence"]} return out diff --git a/tests/test_reviewer_kit.py b/tests/test_reviewer_kit.py index 8c2c95d..f64060a 100644 --- a/tests/test_reviewer_kit.py +++ b/tests/test_reviewer_kit.py @@ -77,3 +77,18 @@ def test_check_refuses(kit_mod: ModuleType, tmp_path: Path, mutate: object, need mutate(kit) # type: ignore[operator] problems = kit_mod.check(kit, "A", expected) assert any(needle in p for p in problems), problems + + +def test_expected_hashes_are_the_registered_ones(kit_mod: ModuleType) -> None: + from cryptoguard.ml import review_sample as rs + from cryptoguard.ml import training + + want = kit_mod.expected_hashes() + assert want["training"] == { + "sheet": training.sheet_sha256(), + "evidence": training.packets_sha256(), + } + for folder, cohort in kit_mod.FOLDERS.items(): + reg = rs.COHORTS[cohort] + assert want[folder] == {"sheet": reg[rs.SHEET], "evidence": reg["evidence"]} + assert kit_mod.FOLDERS == {"set-1": rs.SAMPLE_VERSION, "set-2": "hard-negative-candidates/1"} From 999794a70d9197cac7a4a01e5029309d5f89dda5 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 18:48:24 +0300 Subject: [PATCH 39/92] docs(ml): pre-register the Phase 12.1 lookalike-prioritization protocol Frozen before any outcome-based metric: task, eligibility (1,068 episodes), feature definitions with typed missingness, baselines, the fixed hybrid, group-aware temporal split, four Holm-adjusted primary comparisons against the production similarity, decision rule, exploratory analyses and budgets. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.1.md | 215 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 docs/ml/protocol-12.1.md diff --git a/docs/ml/protocol-12.1.md b/docs/ml/protocol-12.1.md new file mode 100644 index 0000000..67a1488 --- /dev/null +++ b/docs/ml/protocol-12.1.md @@ -0,0 +1,215 @@ +# Phase 12.1 protocol: temporal and graph signals for lookalike prioritization + +**Version:** `protocol-12.1/1`. Frozen in git before any outcome-based number was computed. + +**Known before freezing:** +- the eligibility counts (§3) and the exclusions; +- the asymmetric coverage of the old subset (§4); +- the Phase 11.7 coverage results (§8.1); +- the published literature; +- the packets' text summaries of the *paid* lookalikes only. + +No ranking metric had been computed. Anything not listed as primary below is exploratory. + +## 1. Question + +Do wallet history, timing and cross-victim infrastructure order known poisoning candidates +by the risk that the victim copies them better than the address similarity that +CryptoGuard's detector ranks by? A reproducible "no" is an acceptable result. + +## 2. Tasks and what each can show + +| Task | Population | Shows | Cannot show | +|---|---|---|---| +| 1. Candidate generation | P1-cov: payoff-linked source positives | which planting shapes `candidates/2` can emit from source-selected archive history | recall on real wallets (the source and generator share heuristics) | +| 2/3. Prioritization by outcome (`lookalike-prioritization/1`) | P1-rank: victims with a confirmed payoff and k >= 2 planted lookalikes | which point-in-time signals rank the lookalike the victim later paid above its rivals | detection, precision, recall, FPR, theft prevention; behaviour on victims who never paid | +| Availability and cost | P2: the 13 recorded wallet windows | which features exist in a production-like recording, runtime | anything about labels | +| Mechanism | P3: the 4 incident fixtures | whether the paid lookalike is reachable by each signal | independent validation (they are development cases) | +| Correctness | P4: synthetic cases | cutoff, missingness, leakage, invariance | real-world performance | + +Results are reported per population and never pooled. + +## 3. Prediction unit and eligibility (P1-rank) + +The unit is one episode, `(chain 1, victim, first confirmed payoff block T, cutoff c)`, with +primary cutoff `c = T - 1`. + +**Victims:** archive payoff victims, minus: +- the wallets of both frozen cohorts (91 wallets); +- the 4 incident victims. + +**Candidates:** the distinct non-victim parties of the source's poisoning-flagged rows +(zero-value, tiny or counterfeit) between the victim and another address, at a block <= c. +- Same-block rows are counted, never used. +- **Outcome:** the receiver of the victim's first confirmed payoff (source-confirmed). + +**An episode is eligible when:** +- exactly one lookalike was paid in block T; +- that lookalike planted at or before c; +- k >= 2. + +**Counts at freezing:** +- 1,068 eligible episodes; +- excluded: + - 60 protected review wallets (no incident victim is a payoff victim); + - 96 with no confirmed payoff row; + - 1 with several lookalikes paid in the payoff block; + - 277 with a single candidate. +- Across all victims, 4 poisoning rows fall in a payoff block. + +**Protected cohorts:** +- not one of the 95 frozen events, or any other event of their wallets, enters any + computation; +- review keys and manifests are never read. + +Cohort A's 1,335 reserves are archive events of other victims. They are used here only in +aggregate, and no item is inspected. + +## 4. Data and coverage + +**Victim rows: `archive_subset.sqlite`.** It holds every archive row touching a payoff +victim: all of the source's poisoning, intended and payoff rows, but no ordinary activity. +"No earlier payment to address X" is therefore `not_observed`, not zero. + +**Cross-victim rows: `research/graph_context.sqlite`.** One new offline archive pass +stores every row touching any of the 13,418 candidate lookalikes or 26,816 planting +transactions. + +The old subset covered only the 1,551 *paid* lookalikes. Any cross-victim count read from +it would have been complete for the outcome and partial for its rivals: a leak by +selection. The new pass covers both alike. + +**Not available anywhere locally:** +- transaction signers, so H3's shared-signer edges are untestable here; +- receipts; +- contract code. + +## 5. Features at cutoff c + +Each feature uses only rows with block <= c. + +- **Missing values** are `not_observed` (`None`), never 0. `0` means observed and none. +- **R_c:** the receivers of the victim's own non-poisoning outgoing rows. +- **Reference of l:** the r in R_c that passes the production detector's `is_lookalike` + (default `PoisoningConfig`) with the largest prefix+suffix, ties to the most recent use. + +| Id | Family | Definition | +|---|---|---| +| B0 | production similarity | prefix+suffix of l vs its reference; 0 if R_c is non-empty but nothing passes; `None` if R_c is empty | +| B1 | source similarity | max prefix+suffix of l vs the source-claimed `intended` of its plantings; `None` if absent | +| B2 | transaction semantics | type of l's latest planting: tiny (real token) 3 > counterfeit 2 > zero-value 1 | +| B3 | recipient history (H1) | number of the victim's outgoing rows to l's reference; 0 if no reference; `None` if R_c is empty | +| T0 | temporal (H2) | recency: `-(c - block of l's latest planting)` | +| T1 | temporal | distinct planting transactions by l to the victim | +| T2 | temporal | exposure: `sum over l's planting txs of exp(-(c - block) / 7200)` (7,200 blocks is about a day) | +| T3 | temporal x history | 1 if l's latest planting is later than the victim's latest payment to l's reference, else 0; `None` without a reference | +| T4 | temporal | burst: l's plantings to the victim in `(c - 7200, c]` | +| G1 | graph (H3) | distinct other victims l planted to | +| G2 | graph | distinct other victims with a confirmed payoff to l (source-labelled) | +| G3 | graph | largest number of distinct victims in one of l's planting transactions to this victim | +| NC | negative control | distinct study victims planted in the same token contract as l's latest planting | + +**Abstention.** A method abstains on an episode when any candidate's value is `None`. It +then ties all candidates, so it scores exactly at random. Abstentions are reported per +method. Missing evidence is never ranked as risk or as safety. + +## 6. Methods + +- **Single-feature rankings:** B0–B3, T0–T4 and G1–G3, higher is riskier. Ties are kept. +- **Random:** all candidates tied. +- **H_fixed (B6, H5):** the mean of within-episode normalized average ranks (0 lowest, 1 + highest) of B1, B3, T2 and G1, one per hypothesis family. Components that abstain are + left out. If every component abstains, all candidates tie. +- **Learned (exploratory only):** a conditional logit fitted as an L2 logistic regression + (C = 1, no intercept) on paid-minus-rival feature differences. + - Data: development episodes only. + - Features: B0–B3, T0–T4, G1–G3; `None` becomes 0 plus an indicator. + - Standardized on the development set; seed 0. + - Evaluated once on the test split. + +No method has a tuned parameter. The constants 7,200 and the B2 order are fixed here. + +## 7. Metrics, split and inference + +**Metrics:** +- Top-1 (primary): `1/m` if the paid lookalike is among the m candidates tied for the top + score, else 0. +- MRR (secondary): the expected reciprocal rank under random tie-breaking. +- Random reference: `1/k` and `H_k/k`. + +**Groups:** a union-find over episodes sharing a candidate lookalike or a planting +transaction. If the largest group exceeds 20% of episodes, episodes are linked only by +shared candidate lookalikes. Both group counts are reported. + +**Split:** +- Groups are ordered by their earliest payoff block. The latest go to *test* until it holds + at least 40% of episodes; the rest are *development*. +- Confirmatory tests use test only. +- Development is used only to fit the learned model. + +**Primary comparisons:** paired top-1 differences on the test split, against B0, Holm at +0.05 over four tests. + +| Test | Hypothesis | Comparison | +|---|---|---| +| P-H1 | recipient history | B3 − B0 | +| P-H2 | temporal | T0 − B0 | +| P-H3 | graph | G1 − B0 | +| P-H5 | hybrid | H_fixed − B0 | + +**Inference:** +- p-values: a group-level sign-flip permutation (10,000 draws, seed 20261102). +- Intervals: a 95% group bootstrap (2,000 draws, same seed). + +**Decision.** A signal is *supported* when all three hold: +- Holm p < 0.05; +- the interval excludes 0; +- the difference is at least 0.05. + +It is *null* when the interval lies within ±0.05, and *inconclusive* otherwise. + +## 8. Exploratory analyses (no confirmatory claims) + +1. **Coverage (Task 1):** `candidates/2` in strict and optimistic signer modes. Lookbacks + of 7 days (as in Phase 11.7), 30 days and all archive history. Emitted share per subtype, + and the rule that blocked each miss. +2. **Every method against random and B0**, on development, test and all episodes; MRR. +3. **Strata:** year (2022 / 2023 / 2024+), the paid lookalike's subtype, and k (2, 3–5, 6+). +4. **Robustness:** + - cutoff lag `c = T - 1, T - 300, T - 7200`; + - victim-history lookback limited to 7 days, 30 days or all; + - 50% of the victim's outgoing rows dropped (seed 0); + - graph rows limited to the last 30 days, or 50% dropped (seed 0). + - Reported: top-1, the share of episodes whose top-1 set changes, abstention. +5. **Leakage checks:** rows after c are added, and every feature must be unchanged. + - Within-episode shuffle of G1 across candidates (expected: random). + - Global shuffle of graph rows between lookalikes (expected: no signal if G1 carries + lookalike-specific information). +6. **Negative control NC.** Public tokens (USDT, USDC, DAI) are expected to make it + uninformative. +7. **Ablations of H_fixed:** each component removed in turn, and the missingness + indicators removed from the learned model. +8. **Source-shift:** feature distributions by year and subtype, and paid versus rival. +9. **Errors:** H_fixed misses on test, by category. Aggregate only. +10. **P2 availability and runtime; P3 mechanism.** + +## 9. Budgets + +- **Archive pass:** one, offline, about 25 minutes, under 512 MiB. +- **Each experiment:** under 2 minutes and under 1 GB RAM, CPU only. +- **No new RPC requests and no downloads.** +- **Outputs:** aggregate JSON under `data/ml/research/` (git-ignored, derived from + CC BY-NC-ND data). The report holds aggregates only. + +## 10. Known limitations, fixed in advance + +- **The population is conditioned on a payoff.** It says nothing about victims who never + paid, or about attempts in general. +- **Source-defined candidates and outcome.** The source flags the candidates and confirms + the payoff with its own heuristics, which may use information after c. The candidate + set may therefore depend on the outcome. Features never read flags beyond selecting + plantings, except G2, which reads the source's payoff flag on earlier rows. +- **Archive history is source-selected.** B0, B3 and T3 see only the payments the source + kept. +- **Multiplicity.** Many methods and strata are reported. Only the four primary tests are + confirmatory. From 12f09a1daf9640d1e49c03db7f768199ee00bb84 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 2 Nov 2026 21:31:41 +0300 Subject: [PATCH 40/92] feat(ml): Phase 12.1 lookalike-prioritization study, pre-outcome fixes Implements the pre-registered protocol (docs/ml/protocol-12.1.md, 999794a): episodes, point-in-time features with typed missingness, a typed cross-victim graph, grouped paired inference with Holm, and the `ml lookalike-study` command (aggregate output only, 0 RPC requests). Recorded before any outcome was computed (docs/ml/protocol-12.1-deviations.md): - F1: rows of the 91 frozen review wallets never become graph edges. - F2: the archive scanner builds its indexes after the load (same schema); maintaining them during inserts journalled gigabytes on a shared disk. - D1: entity/campaign overlap with the 95 frozen items is measured; the primary tests are repeated without it as a sensitivity analysis, and the exploratory learned model is not fitted on overlapping episodes. - D2: paid vs rival historical coverage is audited, not assumed. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.1-deviations.md | 83 +++ src/cryptoguard/ml/cli.py | 22 + src/cryptoguard/ml/diagnostics.py | 6 +- src/cryptoguard/ml/lookalike_ranking.py | 668 ++++++++++++++++++++++++ src/cryptoguard/ml/lookalike_study.py | 660 +++++++++++++++++++++++ src/cryptoguard/ml/tsuchiya_archive.py | 13 +- tests/test_ml_lookalike_ranking.py | 518 ++++++++++++++++++ tests/unit/test_ml_tsuchiya_archive.py | 5 + 8 files changed, 1970 insertions(+), 5 deletions(-) create mode 100644 docs/ml/protocol-12.1-deviations.md create mode 100644 src/cryptoguard/ml/lookalike_ranking.py create mode 100644 src/cryptoguard/ml/lookalike_study.py create mode 100644 tests/test_ml_lookalike_ranking.py diff --git a/docs/ml/protocol-12.1-deviations.md b/docs/ml/protocol-12.1-deviations.md new file mode 100644 index 0000000..7d85d85 --- /dev/null +++ b/docs/ml/protocol-12.1-deviations.md @@ -0,0 +1,83 @@ +# Phase 12.1 protocol: deviations and implementation fixes + +The protocol is frozen at commit `999794a` (`docs/ml/protocol-12.1.md`) and is not edited. +This file records every change made after freezing. All entries below were written +**before the study was run**: no outcome, metric or feature value of the real episodes had +been computed when they were committed. The primary hypotheses, metrics, split, groups, +tests and decision rule are unchanged. + +## F1. Protected wallets entered the cross-victim graph (defect, fixed) + +Protocol section 3 says that no event of the frozen cohorts' wallets enters any +computation. The study removed those wallets as *episodes*, but the graph index (G1, G2, +G3) still counted their archive rows: a protected wallet could be a "prior victim" of a +candidate lookalike. + +**Fix:** `GraphIndex(exclude=...)`. Rows where either party is a protected wallet never +become an edge. The study passes the 91 protected wallets to every graph it builds: +- the primary graph; +- the `graph_drop_50` robustness graph; +- the cut graphs of the leakage control. + +A test covers planted, paid and same-tx edges. + +## F2. Archive pass rewrote its indexes on every batch (defect, fixed) + +The first graph-context pass ran for about two hours and had covered 32% of the archive +when its process ended with the session. About 420k target rows had been stored by then. +The cause was the three secondary indexes, maintained during random-key inserts: +- every 20k-row commit journalled most index pages; +- the scan had written about 5 GB for a 200 MB file, on a shared, saturated disk. + +**Fix:** the scanner now creates the indexes once, after the load. The finished schema is +identical, and a test checks that the indexes exist. + +The partial file was not used: the archive is not block-ordered (88,845 order inversions +in the stored prefix), so it was not a clean time prefix. The pass was re-run from the +start with the same target manifest. + +## D1. Entity and campaign overlap with the frozen items (added analysis) + +The protocol excludes the frozen cohorts' *wallets*. A study episode can still share an +attacker entity with a frozen item. + +An episode **overlaps** if any of the following holds: +- one of its candidates, or a planting counterparty, is a frozen item's wallet or address + under review; +- one of its planting transactions is a frozen item's transaction; +- it shares a protocol linkage group with an episode that overlaps directly. + +All of these are read from the blinded reviewer sheets only. + +**Added:** +- the count of overlapping episodes per split; +- the four primary tests repeated without overlapping test episodes, as a **sensitivity** + analysis (Holm over the same four); +- the exploratory learned model is fitted on development episodes **without** overlapping + ones, so no fitted parameter is shaped by an entity under human review. + +The confirmatory result remains the pre-registered test on all eligible test episodes. If +the two disagree on any decision, the report says so and does not choose between them. + +## D2. Coverage-symmetry audit (added check) + +Protocol section 4 states that the new pass covers paid and rival lookalikes alike. This +is now verified, not assumed. For paid and rival candidates separately, the audit +reports: +- the share targeted by the manifest; +- the share of their planting rows present in the graph database; +- the share of their planting transactions targeted; +- the median number of archive rows observed at the cutoff; +- the share the old subset would have covered. + +It also checks that the graph database was built from this exact manifest (by hash). If +the audit fails, every G feature result is reported as invalid. + +## Unchanged + +- Eligibility and the 1,068 episodes. +- The features B0–B3, T0–T4, G1–G3 and NC, and their missingness rules. +- The methods, including H_fixed's components. +- The metrics, the linkage groups, the temporal split, the bootstrap and permutation + settings, the seed, Holm over P-H1, P-H2, P-H3 and P-H5, and the decision margin. +- The frozen cohorts' files, hashes and packages: read only, never modified. diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index dc7a9ea..9ffe6da 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -102,6 +102,14 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None dg = ml.add_parser("diagnostics", help="label-free offline diagnostics (aggregate output)") dg.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) dg.add_argument("--out", type=Path, default=ML_DIR / "diagnostics.json") + ls = ml.add_parser( + "lookalike-study", help="Phase 12.1 lookalike prioritization study (aggregate output)" + ) + ls.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + ls.add_argument("--out", type=Path, default=ML_DIR / "research" / "lookalike-study.json") + ls.add_argument( + "--graph-scan", action="store_true", help="first run the graph-context archive pass" + ) iv = ml.add_parser("inventory", help="hash and describe every local research data file") iv.add_argument("--root", type=Path, default=Path(".")) iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") @@ -192,6 +200,20 @@ def run(args: argparse.Namespace) -> int: args.out.write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8") print(json.dumps({k: v for k, v in report.items() if k != "notes"}, indent=1)[:4000]) return 0 + if args.ml_command == "lookalike-study": + import json + + from cryptoguard.ml import lookalike_ranking, lookalike_study + + poisoning = ML_DIR / "poisoning" + if args.graph_scan: + lookalike_ranking.graph_context_scan(args.data_dir, poisoning) + report = lookalike_study.run(poisoning) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=1, default=str) + "\n", encoding="utf-8") + print(json.dumps(report["primary"], indent=1)) + print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") + return 0 if args.ml_command == "inventory": import json diff --git a/src/cryptoguard/ml/diagnostics.py b/src/cryptoguard/ml/diagnostics.py index 7cf914c..57e8ef1 100644 --- a/src/cryptoguard/ml/diagnostics.py +++ b/src/cryptoguard/ml/diagnostics.py @@ -32,7 +32,9 @@ WINDOW = 50_400 # about 7 days of blocks -def _fixture(victim: str, rows: list[tuple[Any, ...]], block: int, optimistic: bool) -> Any: +def _fixture( + victim: str, rows: list[tuple[Any, ...]], block: int, optimistic: bool, window: int = WINDOW +) -> Any: from cryptoguard.ml.tsuchiya_archive import POISONING from cryptoguard.replay.models import RecordedTransfer, ReplayFixture @@ -60,7 +62,7 @@ def _fixture(victim: str, rows: list[tuple[Any, ...]], block: int, optimistic: b case_id="diagnostic", chain_id=1, wallet=victim, - from_block=block - WINDOW, + from_block=block - window, to_block=block, recorded_at=datetime(2026, 1, 1, tzinfo=UTC), recorded_with="tsuchiya-archive rows (source-selected)", diff --git a/src/cryptoguard/ml/lookalike_ranking.py b/src/cryptoguard/ml/lookalike_ranking.py new file mode 100644 index 0000000..d2f226e --- /dev/null +++ b/src/cryptoguard/ml/lookalike_ranking.py @@ -0,0 +1,668 @@ +"""Within-victim lookalike prioritization at a cutoff before the payoff (Phase 12.1). + +Research task ``lookalike-prioritization/1`` (pre-registered in docs/ml/protocol-12.1.md): +a victim that later made a source-confirmed payoff had k >= 2 distinct lookalikes plant +transfers to it beforehand. At a cutoff before the payoff, rank those candidates with +point-in-time features; the observed outcome is which one the victim paid. This measures +which signals order *known candidates* by the risk that the victim copies them. It is not +detection: every candidate is a source-flagged planting, the population is conditioned on a +payoff happening, and nothing here estimates precision, recall or FPR. + +Data (all local, 0 RPC requests): + +- ``archive_subset.sqlite``: every archive row touching a payoff victim. For a study victim + this holds all of the source's poisoning, intended and payoff rows, but not its ordinary + activity, so "no earlier payment observed" is ``None`` (not observed), never zero. +- ``research/graph_context.sqlite`` (``graph_context_scan``): every archive row touching any + candidate lookalike or planting transaction. Rivals and paid lookalikes are then covered + alike; the older subset covered only paid lookalikes, which would leak the outcome into + any cross-victim feature. + +Protected: the wallets of both frozen review cohorts and the incident victims are excluded +before anything is computed, rows touching a protected wallet never become a graph edge, and +the review keys and manifests are never read. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import sqlite3 +from bisect import bisect_right +from collections import Counter, defaultdict +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +TASK = "lookalike-prioritization/1" +PROTOCOL = "protocol-12.1/1" +FEATURE_VERSION = "lookalike-features/1" +GRAPH_DB = "graph_context.sqlite" +RESEARCH_DIR = "research" +DAY = 7_200 # blocks, about one day; fixed by the protocol +FEATURES = ("B0", "B1", "B2", "B3", "T0", "T1", "T2", "T3", "T4", "G1", "G2", "G3", "NC") +_ROWS = ( + "select line, block, tx, token, sender, receiver, sender_is_victim, value_usd, flags, " + "intended from transfers" +) + +Value = float | None # None: not observed. 0 means observed and none. + + +@dataclass(frozen=True, slots=True) +class Row: + line: int + block: int + tx: str + token: str + sender: str + receiver: str + sender_is_victim: bool | None + value_usd: float | None + flags: int + intended: str | None + + +@dataclass(frozen=True, slots=True) +class Episode: + """One victim's first confirmed payoff and the source-flagged plantings before it. + + ``plantings`` and ``victim_out`` hold only rows strictly before ``payoff_block``; rows in + the payoff block itself have no known order relative to it and are counted in + ``same_block_rows`` instead.""" + + victim: str + payoff_block: int + paid: str + plantings: tuple[Row, ...] # poisoning rows between the victim and a lookalike + victim_out: tuple[Row, ...] # the victim's own non-poisoning outgoing rows + same_block_rows: int + + @property + def candidates(self) -> tuple[str, ...]: + return tuple(sorted({lookalike_of(r, self.victim) for r in self.plantings})) + + +def lookalike_of(row: Row, victim: str) -> str: + """The non-victim party of a planting (incoming transfers and spoofed transfer-froms).""" + return row.receiver if row.sender == victim else row.sender + + +def _row(t: Sequence[Any]) -> Row: + siv = None if t[6] is None else bool(t[6]) + usd = None if t[7] is None or t[7] != t[7] else float(t[7]) + return Row(t[0], t[1], t[2], t[3], t[4], t[5], siv, usd, t[8], t[9]) + + +def protected_wallets(poisoning_dir: Path) -> frozenset[str]: + """Wallets of both frozen review cohorts, read from the blinded sheets only.""" + from cryptoguard.ml.review_sample import read_sheet + + sheets = ( + poisoning_dir / "review_sample" / "reviewer_sheet.jsonl", + poisoning_dir / "hard_negative" / "cohort_v1" / "reviewer_sheet.jsonl", + ) + return frozenset(r["wallet"].lower() for s in sheets for r in read_sheet(s)) + + +def protected_entities(poisoning_dir: Path) -> tuple[frozenset[str], frozenset[str]]: + """Addresses (wallets and addresses under review) and transactions of the 95 frozen + items, from the blinded sheets only.""" + from cryptoguard.ml.review_sample import read_sheet + + sheets = ( + poisoning_dir / "review_sample" / "reviewer_sheet.jsonl", + poisoning_dir / "hard_negative" / "cohort_v1" / "reviewer_sheet.jsonl", + ) + addresses: set[str] = set() + txs: set[str] = set() + for s in sheets: + for r in read_sheet(s): + addresses |= {r["wallet"].lower(), r["address_under_review"].lower()} + txs.add(r["transaction"].lower()) + return frozenset(addresses), frozenset(txs) + + +def protected_overlap( + episodes: Sequence[Episode], addresses: frozenset[str], txs: frozenset[str] +) -> list[bool]: + """Per episode: does it share an entity with a frozen item (a candidate or planting + counterparty that is a protected address, or a planting tx that is a protected tx), or + sit in the same protocol linkage group as an episode that does (campaign overlap).""" + direct = [ + bool(set(e.candidates) & addresses) + or any(r.tx in txs or {r.sender, r.receiver} & addresses for r in e.plantings) + for e in episodes + ] + grp, _ = protocol_groups(episodes) + tainted = {g for g, d in zip(grp, direct, strict=True) if d} + return [g in tainted for g in grp] + + +def episode_from_rows(victim: str, rows: Iterable[Row]) -> Episode | str: + """The episode for one victim, or the reason it is ineligible.""" + from cryptoguard.ml.tsuchiya_archive import PAYOFF, POISONING + + ordered = sorted(set(rows), key=lambda r: (r.block, r.line)) + payoffs = [r for r in ordered if r.flags & PAYOFF and r.sender == victim] + if not payoffs: + return "no_confirmed_payoff_row" + t = payoffs[0].block + paid = {r.receiver for r in payoffs if r.block == t} + if len(paid) != 1: + return "several_lookalikes_paid_in_payoff_block" + plantings, out, same_block = [], [], 0 + for r in ordered: + if r.block > t: + break + if r.flags & POISONING and victim in (r.sender, r.receiver): + if lookalike_of(r, victim) == victim: + continue + if r.block == t: + same_block += 1 + else: + plantings.append(r) + elif r.sender == victim and not r.flags & PAYOFF and r.block < t: + out.append(r) + ep = Episode(victim, t, paid.pop(), tuple(plantings), tuple(out), same_block) + if ep.paid not in ep.candidates: + return "paid_lookalike_planted_no_earlier_transfer" + if len(ep.candidates) < 2: + return "single_candidate" + return ep + + +def load_episodes(poisoning_dir: Path) -> tuple[list[Episode], dict[str, int]]: + """Eligible episodes (sorted by victim) and the count of every exclusion reason.""" + targets = json.loads((poisoning_dir / "archive_targets.json").read_text(encoding="utf-8")) + groups = targets["groups"] + excluded: Counter[str] = Counter() + protected = protected_wallets(poisoning_dir) + incident = set(groups["incident_victims"]) + victims = [] + for v in sorted(groups["payoff_victims"]): + if v in protected: + excluded["protected_review_wallet"] += 1 + elif v in incident: + excluded["incident_victim"] += 1 + else: + victims.append(v) + con = _connect(poisoning_dir / "archive_subset.sqlite") + episodes = [] + try: + for v in victims: + rows = map(_row, con.execute(_ROWS + " where sender = ? or receiver = ?", (v, v))) + ep = episode_from_rows(v, rows) + if isinstance(ep, str): + excluded[ep] += 1 + else: + episodes.append(ep) + finally: + con.close() + return episodes, dict(sorted(excluded.items())) + + +def _connect(path: Path) -> sqlite3.Connection: + if not path.exists(): + raise FileNotFoundError(path) + return sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True) + + +# --- the symmetric graph-context pass ---------------------------------------------------- + + +def graph_context_scan(data_dir: Path, poisoning_dir: Path) -> dict[str, Any]: + """One archive pass storing every row touching any candidate lookalike or planting + transaction of the study episodes (rivals included). About 25 minutes, bounded memory.""" + from cryptoguard.ml.annotation import atomic_write + from cryptoguard.ml.fetch import TSUCHIYA_FILES, verify_local + from cryptoguard.ml.hard_negative_archive import ARCHIVE + from cryptoguard.ml.tsuchiya_archive import build_targets, load_targets, scan + + episodes, _ = load_episodes(poisoning_dir) + manifest = build_targets( + { + "candidate_lookalikes": {c for e in episodes for c in e.candidates}, + "planting_txs": {r.tx for e in episodes for r in e.plantings}, + } + ) + out_dir = poisoning_dir / RESEARCH_DIR + out_dir.mkdir(parents=True, exist_ok=True) + targets_path = out_dir / "graph_context_targets.json" + atomic_write(targets_path, json.dumps(manifest).encode()) + archive = data_dir / "tsuchiya2025" / ARCHIVE + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + work = out_dir / "spill" + summary = scan( + archive, + load_targets(targets_path), + out_dir / GRAPH_DB, + work_dir=work, + source_sha256=source["sha256"], + ) + if work.exists() and not any(work.iterdir()): + work.rmdir() + return summary + + +def victim_of(row: Row) -> str | None: + """The victim side of an archive row, from the source's ``is_sender_victim``.""" + if row.sender_is_victim is None: + return None + return row.sender if row.sender_is_victim else row.receiver + + +Edge = tuple[int, int, str] # (block, line, victim) + + +class GraphIndex: + """Typed, time-stamped cross-victim edges of lookalikes, built lazily per address. + + - ``planted``: lookalike -> victim, a poisoning row (zero-value, tiny or counterfeit); + - ``paid_by``: victim -> lookalike, a confirmed payoff row (source-labelled); + - ``in_tx``: planting tx -> victim, for batch size. + + Only the source's ``is_sender_victim`` decides the victim side; rows without it are + skipped. Token contracts are never a node, so shared public tokens link nothing. Every + query takes a cutoff and sees only edges at or before it. Rows touching an ``exclude``d + address (the frozen review wallets) never become an edge.""" + + def __init__( + self, + fetch_lookalike: Callable[[str], Iterable[Row]], + fetch_tx: Callable[[str], Iterable[Row]], + *, + keep: Callable[[Row], bool] | None = None, + exclude: frozenset[str] = frozenset(), + ) -> None: + self._fetch_l, self._fetch_tx, self._keep = fetch_lookalike, fetch_tx, keep + self._exclude = exclude + self._l: dict[str, tuple[list[Edge], list[Edge]]] = {} + self._tx: dict[str, list[Edge]] = {} + + def _skip(self, r: Row) -> bool: + if r.sender in self._exclude or r.receiver in self._exclude: + return True + return self._keep is not None and not self._keep(r) + + def _edges(self, lookalike: str) -> tuple[list[Edge], list[Edge]]: + if lookalike not in self._l: + from cryptoguard.ml.tsuchiya_archive import PAYOFF, POISONING + + planted, paid = set(), set() + for r in self._fetch_l(lookalike): + v = victim_of(r) + if v is None or v == lookalike or self._skip(r): + continue + if r.flags & POISONING and lookalike_of(r, v) == lookalike: + planted.add((r.block, r.line, v)) + elif r.flags & PAYOFF and r.sender == v and r.receiver == lookalike: + paid.add((r.block, r.line, v)) + self._l[lookalike] = (sorted(planted), sorted(paid)) + return self._l[lookalike] + + def _tx_edges(self, tx: str) -> list[Edge]: + if tx not in self._tx: + from cryptoguard.ml.tsuchiya_archive import POISONING + + edges = set() + for r in self._fetch_tx(tx): + v = victim_of(r) + if v is not None and r.flags & POISONING and not self._skip(r): + edges.add((r.block, r.line, v)) + self._tx[tx] = sorted(edges) + return self._tx[tx] + + @staticmethod + def _victims(edges: list[Edge], cutoff: int, since: int | None) -> set[str]: + hi = bisect_right(edges, (cutoff, math.inf, "")) + return {v for b, _, v in edges[:hi] if since is None or b > since} + + def prior_victims(self, lookalike: str, cutoff: int, since: int | None = None) -> set[str]: + return self._victims(self._edges(lookalike)[0], cutoff, since) + + def prior_payers(self, lookalike: str, cutoff: int, since: int | None = None) -> set[str]: + return self._victims(self._edges(lookalike)[1], cutoff, since) + + def tx_victims(self, tx: str, cutoff: int) -> set[str]: + return self._victims(self._tx_edges(tx), cutoff, None) + + +def sqlite_graph( + path: Path, + keep: Callable[[Row], bool] | None = None, + exclude: frozenset[str] = frozenset(), +) -> GraphIndex: + con = _connect(path) + by_l = _ROWS + " where sender = ? or receiver = ?" + + def fetch_l(a: str) -> list[Row]: + return [_row(t) for t in con.execute(by_l, (a, a))] + + def fetch_tx(tx: str) -> list[Row]: + return [_row(t) for t in con.execute(_ROWS + " where tx = ?", (tx,))] + + return GraphIndex(fetch_l, fetch_tx, keep=keep, exclude=exclude) + + +def memory_graph(rows: Iterable[Row], exclude: frozenset[str] = frozenset()) -> GraphIndex: + """A graph over rows held in memory (tests and small studies).""" + by_addr: defaultdict[str, list[Row]] = defaultdict(list) + by_tx: defaultdict[str, list[Row]] = defaultdict(list) + for r in rows: + by_addr[r.sender].append(r) + if r.receiver != r.sender: + by_addr[r.receiver].append(r) + by_tx[r.tx].append(r) + return GraphIndex(lambda a: by_addr.get(a, []), lambda t: by_tx.get(t, []), exclude=exclude) + + +# --- features ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class View: + """How an episode is observed: the cutoff lag and the robustness transformations.""" + + lag: int = 1 # cutoff c = payoff_block - lag + victim_lookback: int | None = None # victim rows only in (c - lookback, c] + victim_drop: float = 0.0 # share of the victim's outgoing rows removed + seed: int = 0 + + def cutoff(self, ep: Episode) -> int: + return ep.payoff_block - self.lag + + def keeps_victim_row(self, r: Row, c: int) -> bool: + if self.victim_lookback is not None and r.block <= c - self.victim_lookback: + return False + return not _dropped(r.line, self.victim_drop, self.seed) + + +def _dropped(line: int, fraction: float, seed: int) -> bool: + if fraction <= 0: + return False + h = hashlib.sha256(f"{seed}:{line}".encode()).digest() + return int.from_bytes(h[:8], "big") / 2**64 < fraction + + +def graph_keep(drop: float, seed: int = 0) -> Callable[[Row], bool]: + """Row filter for graph robustness: drop a share of rows (seeded).""" + return lambda r: not _dropped(r.line, drop, seed) + + +@dataclass +class TokenIndex: + """Study victims planted per token contract, for the negative control NC.""" + + by_token: dict[str, list[tuple[int, str]]] = field(default_factory=dict) + + @classmethod + def build(cls, episodes: Iterable[Episode]) -> TokenIndex: + acc: defaultdict[str, set[tuple[int, str]]] = defaultdict(set) + for e in episodes: + for r in e.plantings: + acc[r.token].add((r.block, e.victim)) + return cls({t: sorted(v) for t, v in acc.items()}) + + def victims(self, token: str, cutoff: int, exclude: str) -> int: + rows = self.by_token.get(token, []) + hi = bisect_right(rows, (cutoff, "￿")) + return len({v for _, v in rows[:hi] if v != exclude}) + + +def candidate_features( + ep: Episode, + view: View, + graph: GraphIndex | None, + tokens: TokenIndex | None, + *, + graph_lookback: int | None = None, +) -> dict[str, dict[str, Value]] | None: + """Features of every candidate at the view's cutoff, or None when the episode is not + evaluable there (the paid lookalike has not planted yet, or fewer than 2 candidates).""" + from cryptoguard.detectors.poisoning import PoisoningConfig, affix_match, is_lookalike + from cryptoguard.ml.tsuchiya_archive import COUNTERFEIT, TINY, ZERO + + c = view.cutoff(ep) + plantings = [r for r in ep.plantings if r.block <= c] + by_l: defaultdict[str, list[Row]] = defaultdict(list) + for r in plantings: + by_l[lookalike_of(r, ep.victim)].append(r) + if ep.paid not in by_l or len(by_l) < 2: + return None + out = [r for r in ep.victim_out if r.block <= c and view.keeps_victim_row(r, c)] + uses: defaultdict[str, list[int]] = defaultdict(list) + for r in out: + uses[r.receiver].append(r.block) + cfg = PoisoningConfig() + since = None if graph_lookback is None else c - graph_lookback + result: dict[str, dict[str, Value]] = {} + for lk, rows in sorted(by_l.items()): + tx_block: dict[str, int] = {} + for r in rows: + tx_block[r.tx] = min(tx_block.get(r.tx, r.block), r.block) + last = max(rows, key=lambda r: (r.block, r.line)) + f: dict[str, Value] = {} + # B0 / B3 / T3: the production similarity against the victim's own recipients. + if not uses: + f["B0"] = f["B3"] = f["T3"] = None + else: + best: tuple[int, int, str] | None = None + for ref, blocks in uses.items(): + m = is_lookalike(lk, ref, cfg) + if m is not None: + key = (m[0] + m[1], max(blocks), ref) + best = key if best is None or key > best else best + if best is None: + f["B0"], f["B3"], f["T3"] = 0.0, 0.0, None + else: + f["B0"] = float(best[0]) + f["B3"] = float(len(uses[best[2]])) + f["T3"] = 1.0 if last.block > best[1] else 0.0 + intended = [r.intended for r in rows if r.intended and r.intended != lk] + f["B1"] = float(max(sum(affix_match(lk, i)) for i in intended)) if intended else None + if last.flags & COUNTERFEIT: + f["B2"] = 2.0 + elif last.flags & TINY: + f["B2"] = 3.0 + elif last.flags & ZERO: + f["B2"] = 1.0 + else: + f["B2"] = None + f["T0"] = -float(c - last.block) + f["T1"] = float(len(tx_block)) + f["T2"] = sum(math.exp(-(c - b) / DAY) for b in tx_block.values()) + f["T4"] = float(sum(1 for b in tx_block.values() if b > c - DAY)) + if graph is None: + f["G1"] = f["G2"] = f["G3"] = None + else: + f["G1"] = float(len(graph.prior_victims(lk, c, since) - {ep.victim})) + f["G2"] = float(len(graph.prior_payers(lk, c, since) - {ep.victim})) + sizes = [len(graph.tx_victims(tx, c)) for tx in tx_block] + f["G3"] = float(max(sizes)) if sizes and max(sizes) > 0 else None + f["NC"] = None if tokens is None else float(tokens.victims(last.token, c, ep.victim)) + result[lk] = f + return result + + +# --- methods and metrics ----------------------------------------------------------------- + +Scores = dict[str, float] + + +def single(feature: str) -> Callable[[Mapping[str, Mapping[str, Value]]], Scores | None]: + def score(feats: Mapping[str, Mapping[str, Value]]) -> Scores | None: + vals = {lk: f[feature] for lk, f in feats.items()} + if any(v is None for v in vals.values()): + return None # abstain: missing evidence is never ranked as risk or safety + return {lk: float(v) for lk, v in vals.items() if v is not None} + + score.__name__ = feature + return score + + +def normalized_ranks(values: Mapping[str, float]) -> dict[str, float]: + """Average ranks scaled to [0, 1]; 1 is the highest value. All equal -> all 0.5.""" + order = sorted(values, key=lambda k: values[k]) + k = len(order) + ranks: dict[str, float] = {} + i = 0 + while i < k: + j = i + while j + 1 < k and values[order[j + 1]] == values[order[i]]: + j += 1 + avg = (i + j) / 2 + for n in range(i, j + 1): + ranks[order[n]] = avg / (k - 1) if k > 1 else 0.5 + i = j + 1 + return ranks + + +def hybrid( + components: Sequence[str], +) -> Callable[[Mapping[str, Mapping[str, Value]]], Scores | None]: + """H_fixed: mean normalized rank of the components that do not abstain.""" + + def score(feats: Mapping[str, Mapping[str, Value]]) -> Scores | None: + parts = [s for s in (single(c)(feats) for c in components) if s is not None] + if not parts: + return None + ranked = [normalized_ranks(p) for p in parts] + return {lk: sum(r[lk] for r in ranked) / len(ranked) for lk in feats} + + score.__name__ = "H(" + ",".join(components) + ")" + return score + + +HYBRID = ("B1", "B3", "T2", "G1") + + +def top1(scores: Scores | None, paid: str, k: int) -> float: + """1/m if the paid candidate is among the m tied at the top; abstention = random.""" + if scores is None: + return 1.0 / k + top = max(scores.values()) + m = sum(1 for v in scores.values() if v == top) + return 1.0 / m if scores[paid] == top else 0.0 + + +def mrr(scores: Scores | None, paid: str, k: int) -> float: + """Expected reciprocal rank of the paid candidate under random tie-breaking.""" + if scores is None: + return sum(1 / j for j in range(1, k + 1)) / k + p = scores[paid] + better = sum(1 for v in scores.values() if v > p) + tied = sum(1 for v in scores.values() if v == p) + return sum(1 / (better + j) for j in range(1, tied + 1)) / tied + + +# --- groups, split and inference --------------------------------------------------------- + + +def groups(episodes: Sequence[Episode], *, by_tx: bool = True) -> list[int]: + """Union-find over episodes sharing a candidate lookalike (and a planting tx).""" + parent = list(range(len(episodes))) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + seen: dict[str, int] = {} + for i, e in enumerate(episodes): + keys = [f"l:{c}" for c in e.candidates] + if by_tx: + keys += [f"t:{r.tx}" for r in e.plantings] + for key in keys: + if key in seen: + a, b = find(i), find(seen[key]) + if a != b: + parent[max(a, b)] = min(a, b) + else: + seen[key] = i + roots = [find(i) for i in range(len(episodes))] + names = {r: n for n, r in enumerate(sorted(set(roots)))} + return [names[r] for r in roots] + + +def protocol_groups(episodes: Sequence[Episode]) -> tuple[list[int], str]: + g = groups(episodes, by_tx=True) + largest = max(Counter(g).values()) + if largest > 0.2 * len(episodes): + return groups(episodes, by_tx=False), "candidate_lookalike" + return g, "candidate_lookalike_and_planting_tx" + + +def temporal_split( + episodes: Sequence[Episode], grp: Sequence[int], test_share: float = 0.4 +) -> list[str]: + """Groups ordered by their earliest payoff; the latest go to test until it holds at + least ``test_share`` of episodes.""" + start: dict[int, int] = {} + size: Counter[int] = Counter(grp) + for e, g in zip(episodes, grp, strict=True): + start[g] = min(start.get(g, e.payoff_block), e.payoff_block) + test: set[int] = set() + n = 0 + for g in sorted(start, key=lambda g: (start[g], g), reverse=True): + if n >= test_share * len(episodes): + break + test.add(g) + n += size[g] + return ["test" if g in test else "dev" for g in grp] + + +def paired( + d: Sequence[float], + grp: Sequence[int], + *, + seed: int = 20261102, + n_boot: int = 2_000, + n_perm: int = 10_000, +) -> dict[str, Any]: + """Mean paired difference, group-bootstrap 95% interval and group sign-flip p-value.""" + import numpy as np + + d_arr = np.asarray(d, dtype=float) + g_arr = np.asarray(grp) + ids, inv = np.unique(g_arr, return_inverse=True) + sums = np.bincount(inv, weights=d_arr) + counts = np.bincount(inv) + rng = np.random.default_rng(seed) + n_g = len(ids) + pick = rng.integers(0, n_g, size=(n_boot, n_g)) + boot = sums[pick].sum(axis=1) / counts[pick].sum(axis=1) + obs = sums.sum() / counts.sum() + signs = rng.choice((-1.0, 1.0), size=(n_perm, n_g)) + null = np.abs(signs @ sums) / counts.sum() + p = (1 + int((null >= abs(obs) - 1e-12).sum())) / (n_perm + 1) + lo, hi = np.percentile(boot, [2.5, 97.5]) + return { + "mean": float(obs), + "ci95": [float(lo), float(hi)], + "p": p, + "episodes": len(d_arr), + "groups": n_g, + } + + +def holm(ps: Mapping[str, float]) -> dict[str, float]: + order = sorted(ps, key=lambda k: ps[k]) + adj: dict[str, float] = {} + running = 0.0 + for i, k in enumerate(order): + running = max(running, min(1.0, (len(order) - i) * ps[k])) + adj[k] = running + return adj + + +def decision(diff: Mapping[str, Any], p_holm: float, margin: float = 0.05) -> str: + lo, hi = diff["ci95"] + if p_holm < 0.05 and (lo > 0 or hi < 0) and abs(diff["mean"]) >= margin: + return "supported" if diff["mean"] > 0 else "reversed" + if -margin < lo and hi < margin: + return "null" + return "inconclusive" diff --git a/src/cryptoguard/ml/lookalike_study.py b/src/cryptoguard/ml/lookalike_study.py new file mode 100644 index 0000000..dcf0688 --- /dev/null +++ b/src/cryptoguard/ml/lookalike_study.py @@ -0,0 +1,660 @@ +"""Phase 12.1 experiments (``cryptoguard ml lookalike-study``), as pre-registered in +docs/ml/protocol-12.1.md. Aggregate output only; 0 RPC requests. + +Only the four primary comparisons are confirmatory. Everything else in the output is +exploratory and labelled so. +""" + +from __future__ import annotations + +import json +import random +import statistics +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import Any + +from cryptoguard.ml import lookalike_ranking as lr + +STUDY_VERSION = "lookalike-study/1" +SEED = 20261102 +PUBLIC_TOKENS = frozenset( + { + "0xdac17f958d2ee523a2206206994597c13d831ec7", # USDT + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", # USDC + "0x6b175474e89094c44da98b954eedeac495271d0f", # DAI + } +) +PRIMARY = {"P-H1": "B3", "P-H2": "T0", "P-H3": "G1", "P-H5": "H"} +KEY_METHODS = ("random", "B0", "B1", "B3", "T0", "T2", "G1", "H") +Feats = dict[str, dict[str, lr.Value]] +Method = Callable[[Mapping[str, Mapping[str, lr.Value]]], "lr.Scores | None"] + + +def methods() -> dict[str, Method]: + out: dict[str, Method] = {"random": lambda f: None} + for name in lr.FEATURES: + out[name] = lr.single(name) + out["H"] = lr.hybrid(lr.HYBRID) + return out + + +def _score( + feats: Sequence[Feats | None], eps: Sequence[lr.Episode], ms: Mapping[str, Method] +) -> dict[str, dict[str, list[Any]]]: + """Per method: top-1, MRR, abstention and the top set for every evaluable episode.""" + res: dict[str, dict[str, list[Any]]] = {m: defaultdict(list) for m in ms} + for f, e in zip(feats, eps, strict=True): + if f is None: + continue + k = len(f) + for name, m in ms.items(): + s = m(f) + r = res[name] + r["top1"].append(lr.top1(s, e.paid, k)) + r["mrr"].append(lr.mrr(s, e.paid, k)) + r["abstain"].append(s is None) + r["top"].append( + frozenset(f) + if s is None + else frozenset(c for c, v in s.items() if v == max(s.values())) + ) + return res + + +def _summary(r: Mapping[str, list[Any]]) -> dict[str, Any]: + n = len(r["top1"]) + return { + "episodes": n, + "top1": round(statistics.fmean(r["top1"]), 4) if n else None, + "mrr": round(statistics.fmean(r["mrr"]), 4) if n else None, + "abstain_share": round(sum(r["abstain"]) / n, 4) if n else None, + } + + +def _subset(r: Mapping[str, list[Any]], idx: Sequence[int]) -> dict[str, list[Any]]: + return {k: [v[i] for i in idx] for k, v in r.items()} + + +def subtype(ep: lr.Episode) -> str: + from cryptoguard.ml.tsuchiya_archive import COUNTERFEIT, TINY, ZERO + + rows = [r for r in ep.plantings if lr.lookalike_of(r, ep.victim) == ep.paid] + last = max(rows, key=lambda r: (r.block, r.line)) + if last.sender == ep.victim: + return "spoofed_transfer_from" + if last.flags & COUNTERFEIT: + return "fake_token" + if last.flags & TINY: + return "tiny" + return "zero_value" if last.flags & ZERO else "other" + + +def _year(block: int) -> str: + from cryptoguard.ml.review_sample import YEAR_STARTS + + y = next((y for y, start in YEAR_STARTS if block >= start), 2022) + return "2024+" if y >= 2024 else str(y) + + +def _kbin(k: int) -> str: + return "2" if k == 2 else "3-5" if k <= 5 else "6+" + + +# --- the exploratory learned model -------------------------------------------------------- + +_LOG = ("B3", "T1", "T4", "G1", "G2", "G3") +_LEARNED = ("B0", "B1", "B2", "B3", "T0", "T1", "T2", "T3", "T4", "G1", "G2", "G3") + + +def _vec(f: Mapping[str, lr.Value], indicators: bool) -> list[float]: + import math + + out: list[float] = [] + for name in _LEARNED: + v = f[name] + x = 0.0 if v is None else float(v) + if v is not None and name in _LOG: + x = math.log1p(x) + if v is not None and name == "T0": + x = -math.log1p(-x) + out.append(x) + if indicators: + out.append(1.0 if v is None else 0.0) + return out + + +def learned( + feats: Sequence[Feats | None], + eps: Sequence[lr.Episode], + split: Sequence[str], + *, + indicators: bool = True, +) -> tuple[Method, dict[str, Any]]: + """Conditional logit as L2 logistic regression on paid-minus-rival differences, fitted + on development episodes only (exploratory).""" + import numpy as np + from sklearn.linear_model import LogisticRegression + + dev = [(f, e) for f, e, s in zip(feats, eps, split, strict=True) if s == "dev" and f] + raw = np.array([_vec(v, indicators) for f, _ in dev for v in f.values()]) + mu, sd = raw.mean(axis=0), raw.std(axis=0) + sd[sd == 0] = 1.0 + xs, ys = [], [] + for f, e in dev: + z = {c: (np.array(_vec(v, indicators)) - mu) / sd for c, v in f.items()} + for c in f: + if c != e.paid: + xs += [z[e.paid] - z[c], z[c] - z[e.paid]] + ys += [1, 0] + model = LogisticRegression(C=1.0, fit_intercept=False, max_iter=2_000, random_state=0) + model.fit(np.array(xs), np.array(ys)) + w = model.coef_[0] + + def score(f: Mapping[str, Mapping[str, lr.Value]]) -> lr.Scores: + return {c: float(((np.array(_vec(v, indicators)) - mu) / sd) @ w) for c, v in f.items()} + + names = [n for name in _LEARNED for n in ((name, name + "_missing") if indicators else (name,))] + info = { + "dev_episodes": len(dev), + "pairs": len(ys), + "weights": {n: round(float(x), 4) for n, x in zip(names, w, strict=True)}, + } + return score, info + + +# --- Task 1: candidate coverage ------------------------------------------------------------- + + +def coverage(poisoning_dir: Path, protected: frozenset[str]) -> dict[str, Any]: + """``candidates/2`` on archive history before each payoff-linked planting (exploratory).""" + import sqlite3 + + from cryptoguard.ml import candidates as cand + from cryptoguard.ml.diagnostics import _fixture + + packets = [ + p + for p in map( + json.loads, + (poisoning_dir / "review_packets_payoff_linked.jsonl") + .read_text(encoding="utf-8") + .splitlines(), + ) + if p["victim"] not in protected + ] + con = sqlite3.connect( + f"file:{(poisoning_dir / 'archive_subset.sqlite').as_posix()}?mode=ro", uri=True + ) + q = ( + "select line, block, tx, token, sender, receiver, value, flags from transfers " + "where (sender = ? or receiver = ?) and block between ? and ? order by block, line" + ) + out: dict[str, Any] = { + "population": "payoff-linked source positives minus protected wallets", + "attempts": len(packets), + } + for label, window in (("7d", 50_400), ("30d", 216_000), ("all", 10**9)): + for mode in ("strict", "optimistic"): + hit: Counter[str] = Counter() + total: Counter[str] = Counter() + reasons: Counter[str] = Counter() + for p in packets: + v, b = p["victim"], p["observation_block"] + rows = con.execute(q, (v, v, max(0, b - window), b)).fetchall() + total[p["subtype"]] += 1 + fx = _fixture(v, rows, b, mode == "optimistic", window=min(window, b)) + emitted = any( + c.event.planting_tx == p["planting_tx"] and c.event.lookalike == p["lookalike"] + for c in cand.generate(fx) + ) + if emitted: + hit[p["subtype"]] += 1 + continue + planting = [ + r for r in rows if r[2] == p["planting_tx"] and p["lookalike"] in (r[4], r[5]) + ] + if not planting: + reasons["planting_row_absent"] += 1 + elif planting[0][4] == v: + reasons["outgoing_needs_signer"] += 1 + else: + chosen = ( + {r[5] for r in rows if r[4] == v and r[1] < b} + if mode == "optimistic" + else set() + ) + if not chosen: + reasons["incoming_no_signed_payment_in_window"] += 1 + elif not any(cand.similar(p["lookalike"], c) for c in chosen): + reasons["incoming_below_generator_similarity"] += 1 + else: + reasons["other"] += 1 + n = sum(total.values()) + out[f"{label}_{mode}"] = { + "emitted": sum(hit.values()), + "share": round(sum(hit.values()) / n, 4) if n else None, + "by_subtype": {s: f"{hit[s]}/{total[s]}" for s in sorted(total)}, + "miss_reasons": dict(reasons), + } + con.close() + return out + + +# --- P2 and P3 ------------------------------------------------------------------------------ + + +def availability() -> dict[str, Any]: + """Which ranking features a production-like recording can compute (P2, P3).""" + from cryptoguard.ml import candidates as cand + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + + out: dict[str, Any] = {} + for label, fixtures in ( + ("P2_background", [b.fixture for b in load_background() if b.fixture]), + ("P3_incidents", [c.fixture for c in load_cases() if c.fixture]), + ): + n = with_ref = multi = 0 + per_wallet: list[int] = [] + t0 = time.perf_counter() + for fx in fixtures: + cs = cand.generate(fx) + n += len(cs) + with_ref += sum(1 for c in cs if c.best_match is not None) + looks = {c.event.lookalike for c in cs} + per_wallet.append(len(looks)) + multi += len(looks) >= 2 + out[label] = { + "windows": len(fixtures), + "candidates": n, + "candidates_with_reference": with_ref, + "windows_with_2plus_lookalikes": multi, + "distinct_lookalikes_per_window": per_wallet, + "seconds": round(time.perf_counter() - t0, 3), + "features_computable": { + "B0_B3_T3": "yes, from the wallet's own signed history", + "B1": "no: needs the source's intended address", + "B2": "partly: counterfeit needs token reputation", + "T0_T1_T2_T4": "yes", + "G1_G2_G3": "no: needs a cross-wallet index at the cutoff", + }, + } + return out + + +def _before(c: int) -> Callable[[lr.Row], bool]: + return lambda r: r.block <= c + + +def coverage_symmetry( + episodes: Sequence[lr.Episode], poisoning_dir: Path, gpath: Path +) -> dict[str, Any]: + """Do paid and rival lookalikes get the same historical observation? The graph pass + must have targeted every candidate and planting tx, and must hold every planting row + the victim-side subset holds, for paid and rivals alike. The older subset's targeting + is reported to show the asymmetry this pass removes.""" + import sqlite3 + + from cryptoguard.ml.tsuchiya_archive import load_targets + + manifest = load_targets(poisoning_dir / lr.RESEARCH_DIR / "graph_context_targets.json") + old = json.loads((poisoning_dir / "archive_targets.json").read_text(encoding="utf-8")) + old_lookalikes = set(old["groups"].get("payoff_lookalikes", ())) + con = sqlite3.connect(f"file:{gpath.as_posix()}?mode=ro", uri=True) + try: + meta = dict(con.execute("SELECT key, value FROM meta").fetchall()) + scanned = json.loads(meta["summary"])["target_manifest_sha256"] + acc: dict[str, Counter[str]] = {"paid": Counter(), "rival": Counter()} + rows_seen: dict[str, list[int]] = {"paid": [], "rival": []} + for e in episodes: + c = e.payoff_block - 1 + by_l: defaultdict[str, list[lr.Row]] = defaultdict(list) + for r in e.plantings: + by_l[lr.lookalike_of(r, e.victim)].append(r) + for lk, rows in by_l.items(): + side = "paid" if lk == e.paid else "rival" + a = acc[side] + a["candidates"] += 1 + a["targeted_address"] += lk in manifest.addresses + a["targeted_in_old_subset"] += lk in old_lookalikes + a["planting_rows"] += len(rows) + a["planting_txs_targeted"] += sum(r.tx in manifest.txs for r in rows) + a["planting_rows_in_graph_db"] += sum( + con.execute("SELECT 1 FROM transfers WHERE line = ?", (r.line,)).fetchone() + is not None + for r in rows + ) + n = con.execute( + "SELECT count(*) FROM transfers WHERE (sender = ? OR receiver = ?) " + "AND block <= ?", + (lk, lk, c), + ).fetchone()[0] + rows_seen[side].append(n) + finally: + con.close() + out: dict[str, Any] = {"scan_used_this_manifest": scanned == manifest.sha256} + for side, a in acc.items(): + n = a["candidates"] + out[side] = { + "candidates": n, + "targeted_share": round(a["targeted_address"] / n, 4) if n else None, + "old_subset_targeted_share": round(a["targeted_in_old_subset"] / n, 4) if n else None, + "planting_rows_in_graph_db_share": ( + round(a["planting_rows_in_graph_db"] / a["planting_rows"], 4) + if a["planting_rows"] + else None + ), + "planting_txs_targeted_share": ( + round(a["planting_txs_targeted"] / a["planting_rows"], 4) + if a["planting_rows"] + else None + ), + "archive_rows_at_cutoff_median": ( + statistics.median(rows_seen[side]) if rows_seen[side] else None + ), + } + out["symmetric"] = bool( + out["scan_used_this_manifest"] + and all(out[s]["targeted_share"] == 1.0 for s in acc) + and all(out[s]["planting_rows_in_graph_db_share"] == 1.0 for s in acc) + ) + return out + + +# --- the study ------------------------------------------------------------------------------ + + +def run(poisoning_dir: Path) -> dict[str, Any]: + t_start = time.perf_counter() + episodes, exclusions = lr.load_episodes(poisoning_dir) + gpath = poisoning_dir / lr.RESEARCH_DIR / lr.GRAPH_DB + # Rows touching a frozen review wallet never enter the graph (protocol section 3). + blind = lr.protected_wallets(poisoning_dir) + graph = lr.sqlite_graph(gpath, exclude=blind) + tokens = lr.TokenIndex.build(episodes) + grp, linkage = lr.protocol_groups(episodes) + split = lr.temporal_split(episodes, grp) + ms = methods() + t0 = time.perf_counter() + feats = [lr.candidate_features(e, lr.View(), graph, tokens) for e in episodes] + feature_seconds = time.perf_counter() - t0 + # Eligibility guarantees every episode is evaluable at the primary cutoff, so result + # lists and episode indices align. + if any(f is None for f in feats): + raise RuntimeError("an eligible episode is not evaluable at the primary cutoff") + res = _score(feats, episodes, ms) + test_idx = [i for i, s in enumerate(split) if s == "test"] + dev_idx = [i for i, s in enumerate(split) if s == "dev"] + report: dict[str, Any] = { + "task": lr.TASK, + "protocol": lr.PROTOCOL, + "study_version": STUDY_VERSION, + "feature_version": lr.FEATURE_VERSION, + "episodes": len(episodes), + "exclusions": exclusions, + "groups": { + "linkage": linkage, + "count": len(set(grp)), + "largest": max(Counter(grp).values()), + "by_tx_count": len(set(lr.groups(episodes, by_tx=True))), + }, + "split": { + s: { + "episodes": sum(1 for x in split if x == s), + "groups": len({g for g, x in zip(grp, split, strict=True) if x == s}), + } + for s in ("dev", "test") + }, + "k": { + "mean": round(statistics.fmean(len(f) for f in feats if f), 2), + "median": statistics.median(len(f) for f in feats if f), + }, + } + + report["coverage_symmetry"] = coverage_symmetry(episodes, poisoning_dir, gpath) + overlap = lr.protected_overlap(episodes, *lr.protected_entities(poisoning_dir)) + report["protected_overlap"] = { + "episodes_linked": sum(overlap), + "test_episodes_linked": sum(overlap[i] for i in test_idx), + "dev_episodes_linked": sum(overlap[i] for i in dev_idx), + } + + # Primary (confirmatory): paired top-1 differences against B0 on the test split. + g_test = [grp[i] for i in test_idx] + prim: dict[str, Any] = {} + for test, m in PRIMARY.items(): + d = [res[m]["top1"][i] - res["B0"]["top1"][i] for i in test_idx] + prim[test] = {"method": m, "baseline": "B0", **lr.paired(d, g_test, seed=SEED)} + adj = lr.holm({k: v["p"] for k, v in prim.items()}) + for k, v in prim.items(): + v["p_holm"] = adj[k] + v["decision"] = lr.decision(v, adj[k]) + report["primary"] = prim + + # Sensitivity (deviation D1): the same tests without episodes that share an entity or a + # linkage group with a frozen review item. + clean = [i for i in test_idx if not overlap[i]] + sens: dict[str, Any] = {} + for test, m in PRIMARY.items(): + d = [res[m]["top1"][i] - res["B0"]["top1"][i] for i in clean] + sens[test] = lr.paired(d, [grp[i] for i in clean], seed=SEED) + adj_s = lr.holm({k: v["p"] for k, v in sens.items()}) + for k, v in sens.items(): + v["p_holm"] = adj_s[k] + v["decision"] = lr.decision(v, adj_s[k]) + report["primary_without_protected_overlap"] = sens + + # Exploratory: every method by split, and against random on all episodes. + report["methods"] = { + m: { + s: _summary(_subset(res[m], idx)) + for s, idx in ( + ("dev", dev_idx), + ("test", test_idx), + ("all", list(range(len(episodes)))), + ) + } + for m in ms + } + report["vs_random_all"] = { + m: lr.paired( + [a - b for a, b in zip(res[m]["top1"], res["random"]["top1"], strict=True)], + grp, + seed=SEED, + n_perm=2_000, + ) + for m in KEY_METHODS + if m != "random" + } + report["vs_B0_all"] = { + m: lr.paired( + [a - b for a, b in zip(res[m]["top1"], res["B0"]["top1"], strict=True)], + grp, + seed=SEED, + n_perm=2_000, + ) + for m in ("B1", "B2", "T1", "T2", "T3", "T4", "G2", "G3", "NC") + } + + # Exploratory: strata. + strata: dict[str, dict[str, Any]] = {} + keys: tuple[tuple[str, Callable[[lr.Episode, Feats], str]], ...] = ( + ("year", lambda e, f: _year(e.payoff_block)), + ("paid_subtype", lambda e, f: subtype(e)), + ("k", lambda e, f: _kbin(len(f))), + ) + for name, key in keys: + buckets: defaultdict[str, list[int]] = defaultdict(list) + for i, (e, f) in enumerate(zip(episodes, feats, strict=True)): + if f is not None: + buckets[key(e, f)].append(i) + strata[name] = { + b: {m: _summary(_subset(res[m], idx))["top1"] for m in KEY_METHODS} + | {"episodes": len(idx)} + for b, idx in sorted(buckets.items()) + } + report["strata"] = strata + + # Exploratory: hybrid ablations and the learned model (test split). + abl: dict[str, Any] = {"H": _summary(_subset(res["H"], test_idx))["top1"]} + for drop in lr.HYBRID: + rest = tuple(c for c in lr.HYBRID if c != drop) + r = _score( + [feats[i] for i in test_idx], [episodes[i] for i in test_idx], {"h": lr.hybrid(rest)} + )["h"] + abl[f"H_without_{drop}"] = _summary(r)["top1"] + report["ablations_test"] = abl + learned_out: dict[str, Any] = {} + for ind in (True, False): + # Deviation D1: development episodes linked to a frozen item are not fitted on. + fit_split = ["overlap" if o else s for s, o in zip(split, overlap, strict=True)] + score, info = learned(feats, episodes, fit_split, indicators=ind) + r = _score([feats[i] for i in test_idx], [episodes[i] for i in test_idx], {"m": score})["m"] + d = [a - res["B0"]["top1"][i] for a, i in zip(r["top1"], test_idx, strict=True)] + learned_out["with_indicators" if ind else "without_indicators"] = { + **info, + "test": _summary(r), + "vs_B0_test": lr.paired(d, g_test, seed=SEED, n_perm=2_000), + } + report["learned_exploratory"] = learned_out + + # Exploratory: robustness. Changes are measured on the episodes evaluable in both. + base_top = {m: res[m]["top"] for m in KEY_METHODS} + rob: dict[str, Any] = {} + variants: list[tuple[str, lr.View, Any, int | None]] = [ + ("lag_300", lr.View(lag=300), graph, None), + ("lag_7200", lr.View(lag=7_200), graph, None), + ("victim_lookback_7d", lr.View(victim_lookback=50_400), graph, None), + ("victim_lookback_30d", lr.View(victim_lookback=216_000), graph, None), + ("victim_drop_50", lr.View(victim_drop=0.5, seed=0), graph, None), + ("graph_lookback_30d", lr.View(), graph, 216_000), + ( + "graph_drop_50", + lr.View(), + lr.sqlite_graph(gpath, keep=lr.graph_keep(0.5, 0), exclude=blind), + None, + ), + ] + evaluable = [i for i, f in enumerate(feats) if f is not None] + for name, view, g, glb in variants: + vf = [lr.candidate_features(e, view, g, tokens, graph_lookback=glb) for e in episodes] + vr = _score(vf, episodes, {m: ms[m] for m in KEY_METHODS}) + keep = [i for i in evaluable if vf[i] is not None] + pos = {i: n for n, i in enumerate(i for i in range(len(episodes)) if vf[i] is not None)} + entry: dict[str, Any] = {"evaluable": len(keep)} + for m in KEY_METHODS: + same_set = [i for i in keep if set(vf[i] or {}) == set(feats[i] or {})] + changed = sum(1 for i in same_set if vr[m]["top"][pos[i]] != base_top[m][i]) + entry[m] = { + **_summary(vr[m]), + "top_set_changed_share": round(changed / len(same_set), 4) if same_set else None, + } + rob[name] = entry + report["robustness"] = rob + + # Exploratory: leakage and randomization controls. + rng = random.Random(SEED) # noqa: S311 - seeded research sampling, not security + sample = rng.sample(range(len(episodes)), min(100, len(episodes))) + mismatches = 0 + for i in sample: + c = episodes[i].payoff_block - 1 + g_cut = lr.sqlite_graph(gpath, keep=_before(c), exclude=blind) + if lr.candidate_features(episodes[i], lr.View(), g_cut, tokens) != feats[i]: + mismatches += 1 + shuffled_within, shuffled_global = [], [] + pool = [v["G1"] for fs in feats if fs for v in fs.values()] + rng.shuffle(pool) + it = iter(pool) + for f, e in zip(feats, episodes, strict=True): + if f is None: + continue + vals = [v["G1"] for v in f.values()] + rng.shuffle(vals) + within: Feats = {c: {"G1": v} for c, v in zip(f, vals, strict=True)} + glob: Feats = {c: {"G1": next(it)} for c in f} + shuffled_within.append(lr.top1(lr.single("G1")(within), e.paid, len(f))) + shuffled_global.append(lr.top1(lr.single("G1")(glob), e.paid, len(f))) + public = sum(1 for e in episodes for r in e.plantings if r.token in PUBLIC_TOKENS) + report["controls"] = { + "future_rows_cut_graph_mismatches": f"{mismatches}/{len(sample)}", + "G1_within_episode_shuffle_top1": round(statistics.fmean(shuffled_within), 4), + "G1_global_shuffle_top1": round(statistics.fmean(shuffled_global), 4), + "random_top1": report["methods"]["random"]["all"]["top1"], + "NC_top1": report["methods"]["NC"]["all"]["top1"], + "plantings_in_public_tokens_share": round( + public / sum(len(e.plantings) for e in episodes), 4 + ), + } + + # Exploratory: source shift (paid vs rival, by year) and availability. + shift: dict[str, Any] = {} + for name in ("B0", "B1", "B3", "T0", "T1", "G1", "G2", "G3", "NC"): + paid_v: list[float] = [ + x + for f, e in zip(feats, episodes, strict=True) + if f + for x in (f[e.paid][name],) + if x is not None + ] + rival_v: list[float] = [ + x + for f, e in zip(feats, episodes, strict=True) + if f + for c, v in f.items() + if c != e.paid + for x in (v[name],) + if x is not None + ] + avail: dict[str, float | None] = {} + for y in ("2022", "2023", "2024+"): + seen = [ + f[e.paid][name] is not None + for f, e in zip(feats, episodes, strict=True) + if f and _year(e.payoff_block) == y + ] + avail[y] = round(sum(seen) / len(seen), 3) if seen else None + shift[name] = { + "paid_median": statistics.median(paid_v) if paid_v else None, + "rival_median": statistics.median(rival_v) if rival_v else None, + "available_share_by_year": avail, + } + report["source_shift"] = shift + + # Exploratory: errors of H on test. + errors: Counter[str] = Counter() + for i in test_idx: + f, e = feats[i], episodes[i] + if f is None or res["H"]["top1"][i] == 1.0: + continue + errors["miss_or_tie"] += 1 + if res["H"]["top1"][i] > 0: + errors["paid_tied_at_top"] += 1 + for m, label in ( + ("T0", "paid_not_most_recent"), + ("B1", "paid_not_most_similar"), + ("G1", "paid_not_most_reused"), + ("B3", "paid_reference_not_most_used"), + ): + if e.paid not in res[m]["top"][i]: + errors[label] += 1 + if f[e.paid]["B0"] is None: + errors["no_victim_payment_history_observed"] += 1 + if res["B1"]["abstain"][i]: + errors["source_intended_missing"] += 1 + report["errors_test_H"] = dict(errors) + + report["coverage_task1"] = coverage(poisoning_dir, lr.protected_wallets(poisoning_dir)) + report["availability"] = availability() + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + peak = peak_rss_bytes() + report["resources"] = { + "feature_seconds_primary": round(feature_seconds, 2), + "total_seconds": round(time.perf_counter() - t_start, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + "rpc_requests": 0, + } + return report diff --git a/src/cryptoguard/ml/tsuchiya_archive.py b/src/cryptoguard/ml/tsuchiya_archive.py index 4bdba93..0b36b52 100644 --- a/src/cryptoguard/ml/tsuchiya_archive.py +++ b/src/cryptoguard/ml/tsuchiya_archive.py @@ -669,7 +669,7 @@ def scan( for leftover in (tmp, *(tmp.with_name(tmp.name + s) for s in ("-journal", "-wal", "-shm"))): leftover.unlink(missing_ok=True) db = sqlite3.connect(tmp) - db.executescript(_DDL) + db.executescript(_DDL_TABLES) db.executemany( "INSERT INTO meta(key, value) VALUES (?, ?)", [("schema_version", str(SCHEMA_VERSION)), ("parser_version", PARSER_VERSION)], @@ -747,7 +747,8 @@ def scan( if progress is not None and reader.stats.data_rows % progress_every == 0: progress(reader.stats) stored += _insert(db, pending) - distinct = {name: c.count() for name, c in counters.items()} + db.executescript(_DDL_INDEXES) + distinct ={name: c.count() for name, c in counters.items()} # Spill files only grow until cleanup, so the total written after the final flush # in ``count`` is the peak temporary disk use. peak_spill = sum(c.bytes_written for c in counters.values()) @@ -813,7 +814,7 @@ def scan( return summary -_DDL = """ +_DDL_TABLES = """ PRAGMA journal_mode = DELETE; CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE transfers ( @@ -831,10 +832,16 @@ def scan( first_digits INTEGER, last_digits INTEGER ); +""" +# Built once after the load: maintaining three random-key indexes during the insert +# rewrites most index pages on every batch commit (gigabytes of journal for a +# million-row subset on a contended disk). The finished schema is the same. +_DDL_INDEXES = """ CREATE INDEX transfers_sender ON transfers(sender); CREATE INDEX transfers_receiver ON transfers(receiver); CREATE INDEX transfers_tx ON transfers(tx); """ +_DDL = _DDL_TABLES + _DDL_INDEXES def _insert(db: sqlite3.Connection, rows: list[tuple[Any, ...]]) -> int: diff --git a/tests/test_ml_lookalike_ranking.py b/tests/test_ml_lookalike_ranking.py new file mode 100644 index 0000000..3526c4f --- /dev/null +++ b/tests/test_ml_lookalike_ranking.py @@ -0,0 +1,518 @@ +"""Lookalike prioritization (Phase 12.1): eligibility, point-in-time features, typed graph +edges, missingness, metrics and inference. Synthetic rows only.""" + +from __future__ import annotations + +import itertools +import statistics +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from cryptoguard.ml import lookalike_ranking as lr +from cryptoguard.ml.tsuchiya_archive import COUNTERFEIT, INTENDED, PAYOFF, TINY, ZERO + +V = "0x" + "a" * 40 # victim +R = "0x1234" + "0" * 32 + "abcd" # the recipient the victim pays +L1 = "0x1234" + "f" * 32 + "abcd" # imitates R (4 + 4) +L2 = "0x12" + "e" * 36 + "cd" # weak (2 + 2): fails the detector's thresholds +L3 = "0x1234" + "e" * 31 + "babcd" # imitates R (4 + 5) +OTHER = "0x" + "b" * 40 # another victim +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +FAKE = "0x" + "c" * 40 + +_line = itertools.count(1) + + +def row( + block: int, + sender: str, + receiver: str, + flags: int, + *, + tx: str | None = None, + token: str = USDT, + siv: bool | None = None, + intended: str | None = None, +) -> lr.Row: + n = next(_line) + return lr.Row( + n, block, tx or f"0x{n:064x}", token, sender, receiver, siv, None, flags, intended + ) + + +def base_rows() -> list[lr.Row]: + return [ + row(100, V, R, INTENDED, siv=True), + row(200, V, R, INTENDED, siv=True), + row(210, L1, V, ZERO, siv=False, intended=R), + row(220, L2, V, TINY, siv=False, intended=R), + row(230, L1, V, ZERO, siv=False, intended=R), + row(300, V, L1, PAYOFF, siv=True), + ] + + +def episode(rows: list[lr.Row] | None = None) -> lr.Episode: + ep = lr.episode_from_rows(V, rows if rows is not None else base_rows()) + assert isinstance(ep, lr.Episode), ep + return ep + + +# --- eligibility ------------------------------------------------------------------------- + + +def test_episode_uses_first_payoff_and_excludes_same_block() -> None: + rows = [*base_rows(), row(300, L3, V, ZERO, siv=False), row(500, V, L2, PAYOFF, siv=True)] + ep = episode(rows) + assert (ep.payoff_block, ep.paid) == (300, L1) + assert ep.candidates == (L1, L2) # L3 planted in the payoff block: order unknown + assert ep.same_block_rows == 1 + assert {r.receiver for r in ep.victim_out} == {R} + + +@pytest.mark.parametrize( + ("rows", "reason"), + [ + ([row(210, L1, V, ZERO, siv=False)], "no_confirmed_payoff_row"), + ([row(210, L1, V, ZERO, siv=False), row(300, V, L1, PAYOFF, siv=True)], "single_candidate"), + ( + [row(210, L2, V, ZERO, siv=False), row(300, V, L1, PAYOFF, siv=True)], + "paid_lookalike_planted_no_earlier_transfer", + ), + ( + [ + row(210, L1, V, ZERO), + row(220, L2, V, ZERO), + row(300, V, L1, PAYOFF), + row(300, V, L2, PAYOFF), + ], + "several_lookalikes_paid_in_payoff_block", + ), + ], +) +def test_ineligible_reasons(rows: list[lr.Row], reason: str) -> None: + assert lr.episode_from_rows(V, rows) == reason + + +def test_spoofed_transfer_from_counts_as_planting() -> None: + rows = [ + row(100, V, R, INTENDED), + row(210, V, L1, ZERO), + row(220, L2, V, ZERO), + row(300, V, L1, PAYOFF), + ] + assert episode(rows).candidates == (L1, L2) + + +# --- features ------------------------------------------------------------------------------ + + +def test_feature_values_and_missingness() -> None: + f = lr.candidate_features(episode(), lr.View(), None, None) + assert f is not None + assert f[L1]["B0"] == 8.0 + assert f[L2]["B0"] == 0.0 # observed, no reference: zero + assert f[L1]["B3"] == 2.0 + assert f[L2]["B3"] == 0.0 + assert f[L1]["T3"] == 1.0 + assert f[L2]["T3"] is None # no reference: not observed + assert f[L1]["B1"] == 8.0 + assert f[L2]["B1"] == 4.0 + assert f[L1]["B2"] == 1.0 + assert f[L2]["B2"] == 3.0 + assert f[L1]["T0"] == -(299 - 230) + assert f[L1]["T1"] == 2.0 + assert f[L1]["G1"] is None + assert f[L1]["NC"] is None # no graph, no token index + + +def test_missing_history_is_not_zero_and_methods_abstain() -> None: + rows = [r for r in base_rows() if not r.flags & INTENDED] + f = lr.candidate_features(episode(rows), lr.View(), None, None) + assert f is not None + assert all(v["B0"] is None and v["B3"] is None for v in f.values()) + assert lr.single("B0")(f) is None + assert lr.top1(lr.single("B0")(f), L1, 2) == 0.5 # abstention scores exactly at random + + +def test_future_rows_do_not_change_features() -> None: + ep = episode() + graph = lr.memory_graph([row(150, L1, OTHER, ZERO, siv=False)]) + before = lr.candidate_features(ep, lr.View(), graph, lr.TokenIndex.build([ep])) + future = [ + row(400, L2, V, ZERO, siv=False), + row(301, V, R, INTENDED, siv=True), + row(350, L1, OTHER, ZERO, siv=False), + row(360, OTHER, L1, PAYOFF, siv=True), + ] + ep2 = episode([*base_rows(), *future]) + graph2 = lr.memory_graph([row(150, L1, OTHER, ZERO, siv=False), *future]) + after = lr.candidate_features(ep2, lr.View(), graph2, lr.TokenIndex.build([ep2])) + assert before == after + + +def test_lag_moves_cutoff_and_can_make_episode_unevaluable() -> None: + ep = episode() + assert lr.candidate_features(ep, lr.View(lag=85), None, None) is None # c=215: only L1 + f = lr.candidate_features(ep, lr.View(lag=75), None, None) # c=225 + assert f is not None + assert f[L1]["T1"] == 1.0 + + +def test_victim_drop_is_seeded_and_deterministic() -> None: + ep = episode() + a = lr.candidate_features(ep, lr.View(victim_drop=0.5, seed=3), None, None) + b = lr.candidate_features(ep, lr.View(victim_drop=0.5, seed=3), None, None) + assert a == b + full = lr.candidate_features(ep, lr.View(victim_drop=1.0), None, None) + assert full is not None + assert full[L1]["B0"] is None + + +# --- typed graph ----------------------------------------------------------------------- + + +def test_graph_counts_reuse_payoffs_and_batches_before_cutoff_only() -> None: + tx = "0x" + "9" * 64 + rows = [ + row(150, L1, OTHER, ZERO, siv=False), + row(150, L1, OTHER, ZERO, siv=False), # duplicate edge, other line + row(160, OTHER, L1, PAYOFF, siv=True), + row(210, L1, V, ZERO, tx=tx, siv=False), + row(210, L3, "0x" + "d" * 40, ZERO, tx=tx, siv=False), + row(900, L1, "0x" + "e" * 40, ZERO, siv=False), # after the cutoff + row(155, L1, "0x" + "f" * 40, ZERO, siv=None), # victim side unknown: skipped + ] + g = lr.memory_graph(rows) + assert g.prior_victims(L1, 299) == {OTHER, V} + assert g.prior_payers(L1, 299) == {OTHER} + assert g.tx_victims(tx, 299) == {V, "0x" + "d" * 40} + assert g.prior_victims(L1, 149) == set() + eprows = [ + *base_rows()[:2], + row(210, L1, V, ZERO, tx=tx, siv=False), + row(220, L2, V, TINY, siv=False), + row(300, V, L1, PAYOFF, siv=True), + ] + f = lr.candidate_features(episode(eprows), lr.View(), g, None) + assert f is not None + assert f[L1]["G1"] == 1.0 + assert f[L1]["G2"] == 1.0 + assert f[L1]["G3"] == 2.0 + assert f[L2]["G1"] == 0.0 + assert f[L2]["G3"] is None + + +def test_shared_public_token_links_nothing() -> None: + rows = [ + row(150, L1, OTHER, TINY, siv=False, token=USDT), + row(150, L2, "0x" + "d" * 40, TINY, siv=False, token=USDT), + ] + g = lr.memory_graph(rows) + assert g.prior_victims(L2, 299) == {"0x" + "d" * 40} # USDT is not a node + assert g.prior_victims(L1, 299) == {OTHER} + + +def test_self_loops_and_cycles_are_safe() -> None: + rows = [ + row(10, L1, L1, ZERO, siv=True), + row(11, L1, L3, ZERO, siv=False), + row(12, L3, L1, ZERO, siv=False), + ] + g = lr.memory_graph(rows) + assert g.prior_victims(L1, 100) == {L3} + assert g.prior_victims(L3, 100) == {L1} + assert g.prior_victims("0x" + "7" * 40, 100) == set() # isolated node + + +def test_protected_wallet_rows_never_become_graph_edges() -> None: + tx = "0x" + "9" * 64 + rows = [ + row(150, L1, OTHER, ZERO, tx=tx, siv=False), + row(150, L1, "0x" + "d" * 40, ZERO, tx=tx, siv=False), + row(160, OTHER, L1, PAYOFF, siv=True), + ] + g = lr.memory_graph(rows, exclude=frozenset({OTHER})) + assert g.prior_victims(L1, 299) == {"0x" + "d" * 40} + assert g.prior_payers(L1, 299) == set() + assert g.tx_victims(tx, 299) == {"0x" + "d" * 40} + + +def test_protected_overlap_is_direct_or_through_a_linkage_group() -> None: + e1 = episode() # candidates L1, L2 + e2 = episode( + [ + row(100, V, R, INTENDED, siv=True), + row(210, L1, V, ZERO, siv=False, intended=R), # shares L1 with e1 + row(220, L3, V, ZERO, siv=False, intended=R), + row(300, V, L1, PAYOFF, siv=True), + ] + ) + e3 = episode( + [ + row(100, V, R, INTENDED, siv=True), + row(210, "0x" + "5" * 40, V, ZERO, siv=False), + row(220, "0x" + "6" * 40, V, ZERO, siv=False), + row(300, V, "0x" + "5" * 40, PAYOFF, siv=True), + ] + ) + assert lr.protected_overlap([e1, e2, e3], frozenset({L2}), frozenset()) == [ + True, + True, # campaign overlap: linked to e1 through L1 + False, + ] + tx = e3.plantings[0].tx + assert lr.protected_overlap([e1, e2, e3], frozenset(), frozenset({tx})) == [ + False, + False, + True, + ] + + +def test_token_index_negative_control() -> None: + e1 = episode() + e2 = replace(e1, victim=OTHER) + tokens = lr.TokenIndex.build([e1, e2]) + assert tokens.victims(USDT, 299, exclude=V) == 1 + assert tokens.victims(FAKE, 299, exclude=V) == 0 + + +# --- methods and metrics --------------------------------------------------------------- + + +def _brute_mrr(scores: dict[str, float], paid: str) -> float: + vals = [] + for perm in itertools.permutations(scores): + order = sorted(perm, key=lambda c: -scores[c]) # stable: ties in random order + vals.append(1 / (order.index(paid) + 1)) + return statistics.fmean(vals) + + +@pytest.mark.parametrize( + "scores", + [ + {"a": 1.0, "b": 1.0, "c": 0.0}, + {"a": 0.0, "b": 2.0, "c": 2.0, "d": 2.0}, + {"a": 3.0, "b": 2.0, "c": 1.0}, + ], +) +def test_mrr_equals_brute_force_tie_average(scores: dict[str, float]) -> None: + for paid in scores: + assert lr.mrr(scores, paid, len(scores)) == pytest.approx(_brute_mrr(scores, paid)) + + +def test_top1_ties_and_random() -> None: + assert lr.top1({"a": 1, "b": 1, "c": 0}, "a", 3) == 0.5 + assert lr.top1({"a": 1, "b": 1, "c": 0}, "c", 3) == 0.0 + assert lr.top1(None, "a", 4) == 0.25 + assert lr.mrr(None, "a", 3) == pytest.approx((1 + 1 / 2 + 1 / 3) / 3) + + +def test_normalized_ranks_and_hybrid_skip_abstaining_components() -> None: + assert lr.normalized_ranks({"a": 1, "b": 1, "c": 5}) == {"a": 0.25, "b": 0.25, "c": 1.0} + feats: dict[str, dict[str, lr.Value]] = {"x": {"A": 1.0, "B": None}, "y": {"A": 2.0, "B": 0.0}} + assert lr.hybrid(("A", "B"))(feats) == {"x": 0.0, "y": 1.0} + assert lr.hybrid(("B",))(feats) is None + + +# --- groups, split and inference ------------------------------------------------------- + + +def _eps(n: int) -> list[lr.Episode]: + out = [] + for i in range(n): + v = f"0x{i + 1:040x}" + a, b = f"0x{1000 + i:040x}", f"0x{2000 + i // 2:040x}" # b shared by pairs + rows = [ + row(10 * i + 1, a, v, ZERO), + row(10 * i + 2, b, v, ZERO), + row(10 * i + 5, v, a, PAYOFF), + ] + ep = lr.episode_from_rows(v, rows) + assert isinstance(ep, lr.Episode) + out.append(ep) + return out + + +def test_groups_link_shared_lookalikes_and_split_keeps_groups_whole() -> None: + eps = _eps(10) + g = lr.groups(eps) + assert len(set(g)) == 5 + assert all(g[2 * i] == g[2 * i + 1] for i in range(5)) + split = lr.temporal_split(eps, g, test_share=0.4) + assert split.count("test") == 4 + assert split[-1] == "test" + assert split[0] == "dev" + for grp in set(g): + assert len({s for s, x in zip(split, g, strict=True) if x == grp}) == 1 + + +def test_paired_is_deterministic_and_null_for_zero_differences() -> None: + d, g = [0.0] * 20, list(range(20)) + out = lr.paired(d, g, n_perm=500, n_boot=200) + assert out["mean"] == 0.0 + assert out["p"] == 1.0 + assert out["groups"] == 20 + d2 = [1.0] * 30 + a = lr.paired(d2, list(range(30)), n_perm=999, n_boot=200) + assert a == lr.paired(d2, list(range(30)), n_perm=999, n_boot=200) + assert a["p"] < 0.01 + assert a["ci95"] == [1.0, 1.0] + + +def test_paired_counts_groups_not_episodes() -> None: + out = lr.paired([1.0, 1.0, 1.0, -1.0], [0, 0, 0, 1], n_perm=500, n_boot=200) + assert out["groups"] == 2 + assert out["episodes"] == 4 + assert out["p"] > 0.2 # two clusters cannot be significant + + +def test_holm_and_decision() -> None: + adj = lr.holm({"a": 0.01, "b": 0.02, "c": 0.04}) + assert adj == pytest.approx({"a": 0.03, "b": 0.04, "c": 0.04}) + assert lr.decision({"mean": 0.1, "ci95": [0.05, 0.15]}, 0.01) == "supported" + assert lr.decision({"mean": -0.1, "ci95": [-0.15, -0.05]}, 0.01) == "reversed" + assert lr.decision({"mean": 0.01, "ci95": [-0.02, 0.03]}, 0.5) == "null" + assert lr.decision({"mean": 0.03, "ci95": [-0.02, 0.09]}, 0.2) == "inconclusive" + + +def test_counterfeit_flag_wins_over_tiny_in_semantics() -> None: + rows = [ + row(100, V, R, INTENDED), + row(210, L1, V, TINY | COUNTERFEIT, token=FAKE), + row(220, L2, V, TINY), + row(300, V, L1, PAYOFF), + ] + f = lr.candidate_features(episode(rows), lr.View(), None, None) + assert f is not None + assert f[L1]["B2"] == 2.0 + assert f[L2]["B2"] == 3.0 + + +# --- end-to-end smoke run on a synthetic data directory ------------------------------- + + +def _synthetic_dir(tmp: Path, n: int = 30) -> Path: + import json + import sqlite3 + + from cryptoguard.ml.tsuchiya_archive import _DDL, build_targets + + d = tmp / "poisoning" + (d / lr.RESEARCH_DIR).mkdir(parents=True) + rows: list[tuple[Any, ...]] = [] + victims, packets = [], [] + lookalikes: set[str] = set() + planting_txs: set[str] = set() + line = 0 + + def add( + block: int, + tx: str, + sender: str, + receiver: str, + siv: bool, + flags: int, + intended: str | None, + value: float = 0.0, + ) -> None: + nonlocal line + line += 1 + rows.append( + ( + line, + block, + tx, + USDT, + sender, + receiver, + int(siv), + value, + 0.0, + flags, + intended, + None, + None, + ) + ) + + for i in range(n): + v = f"0x{i + 1:040x}" + ref = f"0x{0xABC000 + i:06x}" + "0" * 30 + f"{i:04x}" + good = ref[:8] + "f" * 30 + ref[-4:] + rival = ref[:5] + "e" * 33 + ref[-4:] + b = 1_000_000 + 10_000 * i + victims.append(v) + add(b, f"0x{line:064x}", v, ref, True, INTENDED, None, 5e9) + # the paid lookalike plants later in half the episodes, earlier in the rest + late, early = (good, rival) if i % 2 else (rival, good) + lookalikes |= {good, rival} + planting_txs |= {f"0x{line:064x}", f"0x{line + 1:064x}"} + add(b + 100, f"0x{line:064x}", early, v, False, ZERO, ref) + add(b + 200, f"0x{line:064x}", late, v, False, TINY, ref, 1000.0) + add(b + 300, f"0x{line:064x}", v, good, True, PAYOFF, None, 4e9) + packets.append( + { + "victim": v, + "observation_block": b + 200, + "planting_tx": f"0x{line - 2:064x}", + "lookalike": late, + "subtype": "dust", + } + ) + manifest = build_targets({"candidate_lookalikes": lookalikes, "planting_txs": planting_txs}) + (d / lr.RESEARCH_DIR / "graph_context_targets.json").write_text(json.dumps(manifest)) + summary = json.dumps({"target_manifest_sha256": manifest["sha256"]}) + for name in ("archive_subset.sqlite", f"{lr.RESEARCH_DIR}/{lr.GRAPH_DB}"): + con = sqlite3.connect(d / name) + con.executescript(_DDL) + con.executemany("insert into transfers values (?,?,?,?,?,?,?,?,?,?,?,?,?)", rows) + con.execute("insert into meta values ('summary', ?)", (summary,)) + con.commit() + con.close() + groups = {"payoff_victims": victims, "incident_victims": [], "payoff_lookalikes": []} + (d / "archive_targets.json").write_text(json.dumps({"version": 1, "groups": groups})) + (d / "review_packets_payoff_linked.jsonl").write_text( + "".join(json.dumps(p) + "\n" for p in packets) + ) + return d + + +def test_study_runs_end_to_end_on_synthetic_data( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from cryptoguard.ml import lookalike_study as ls + + d = _synthetic_dir(tmp_path) + protected = "0x" + f"{1:040x}" + monkeypatch.setattr(lr, "protected_wallets", lambda _d: frozenset({protected})) + # Episode i = 3 (victim 4): its paid lookalike is a frozen item's address under review. + v3 = 3 + ref3 = f"0x{0xABC000 + v3:06x}" + "0" * 30 + f"{v3:04x}" + under_review = ref3[:8] + "f" * 30 + ref3[-4:] + monkeypatch.setattr( + lr, "protected_entities", lambda _d: (frozenset({protected, under_review}), frozenset()) + ) + report = ls.run(d) + assert report["coverage_symmetry"]["symmetric"] is True + assert report["coverage_symmetry"]["paid"]["candidates"] == 29 + assert report["coverage_symmetry"]["rival"]["old_subset_targeted_share"] == 0.0 + assert report["protected_overlap"]["episodes_linked"] == 1 + assert set(report["primary_without_protected_overlap"]) == set(ls.PRIMARY) + assert report["episodes"] == 29 + assert report["exclusions"] == {"protected_review_wallet": 1} + assert report["controls"]["future_rows_cut_graph_mismatches"].startswith("0/") + assert set(report["primary"]) == set(ls.PRIMARY) + for v in report["primary"].values(): + assert v["decision"] in {"supported", "reversed", "null", "inconclusive"} + assert 0 < v["p_holm"] <= 1 + assert report["split"]["test"]["episodes"] >= 0.4 * 29 + # The paid lookalike is always the most similar one: B1 must find it every time. + assert report["methods"]["B1"]["all"]["top1"] == 1.0 + # Recency is right in exactly the episodes where the paid one planted last: odd i in + # 1..29 (victim 0 is protected), 15 of 29. + assert report["methods"]["T0"]["all"]["top1"] == pytest.approx(15 / 29, abs=1e-4) + assert report["methods"]["random"]["all"]["top1"] == 0.5 + assert report["resources"]["rpc_requests"] == 0 diff --git a/tests/unit/test_ml_tsuchiya_archive.py b/tests/unit/test_ml_tsuchiya_archive.py index e71b57b..d13ae3e 100644 --- a/tests/unit/test_ml_tsuchiya_archive.py +++ b/tests/unit/test_ml_tsuchiya_archive.py @@ -376,6 +376,11 @@ def test_scan_reproduces_counts_and_stores_only_targets(tmp_path: Path) -> None: assert [r.tx for r in rows] == [h(1), h(2), h(3), h(4), h(1)] assert summary["target_manifest_sha256"] == s["target_manifest_sha256"] assert not (tmp_path / "w" / "victims").exists() # spill files cleaned up + # The lookup indexes are built after the load, but they must exist in the result. + con = sqlite3.connect(out) + indexes = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='index'")} + con.close() + assert {"transfers_sender", "transfers_receiver", "transfers_tx"} <= indexes def test_rule_coverage_is_measured_per_subtype(tmp_path: Path) -> None: From b552c2dfbed3f3b327b2db0513b6333d498e742a Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 00:43:59 +0300 Subject: [PATCH 41/92] fix(ml): format the scanner; add the post-hoc recency-gap diagnostic - tsuchiya_archive: restore formatting broken in 12f09a1 (CI Format step). - lookalike_study: recency_gap_diagnostic, labelled post-hoc (deviation D4): paid vs rival planting-to-cutoff gaps and T0 among long-gap episodes, to test whether recency is built into the source's payoff matching. No primary result depends on it. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/lookalike_study.py | 47 ++++++++++++++++++++++++++ src/cryptoguard/ml/tsuchiya_archive.py | 2 +- tests/test_ml_lookalike_ranking.py | 3 ++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/cryptoguard/ml/lookalike_study.py b/src/cryptoguard/ml/lookalike_study.py index dcf0688..f2825a8 100644 --- a/src/cryptoguard/ml/lookalike_study.py +++ b/src/cryptoguard/ml/lookalike_study.py @@ -364,6 +364,52 @@ def coverage_symmetry( return out +def recency_gap_diagnostic(episodes: Sequence[lr.Episode]) -> dict[str, Any]: + """Post-hoc (not pre-registered): is T0's advantage built into the source's payoff + matching? A matching window would cap the paid lookalike's planting-to-cutoff gap, and + recency would lose its edge among the episodes with long paid gaps.""" + paid: list[float] = [] + rival: list[float] = [] + long_t0: list[float] = [] + long_random: list[float] = [] + for e in episodes: + f = lr.candidate_features(e, lr.View(), None, None) + if f is None: + continue + gap = -float(f[e.paid]["T0"] or 0.0) + paid.append(gap) + rival += [-float(v["T0"] or 0.0) for c, v in f.items() if c != e.paid] + if gap > 30 * lr.DAY: + long_t0.append(lr.top1(lr.single("T0")(f), e.paid, len(f))) + long_random.append(1 / len(f)) + + def quantiles(xs: list[float]) -> dict[str, float]: + xs = sorted(xs) + return {f"p{q}": xs[min(len(xs) - 1, q * len(xs) // 100)] for q in (50, 90, 99)} | { + "max": xs[-1] + } + + return { + "label": "post-hoc diagnostic, not pre-registered", + "paid_gap_blocks": quantiles(paid) if paid else None, + "rival_gap_blocks": quantiles(rival) if rival else None, + "share_gap_over_days": { + str(d): { + "paid": round(sum(g > d * lr.DAY for g in paid) / len(paid), 4) if paid else None, + "rival": round(sum(g > d * lr.DAY for g in rival) / len(rival), 4) + if rival + else None, + } + for d in (1, 7, 30, 90, 365) + }, + "paid_gap_over_30d": { + "episodes": len(long_t0), + "T0_top1": round(statistics.fmean(long_t0), 4) if long_t0 else None, + "random_top1": round(statistics.fmean(long_random), 4) if long_random else None, + }, + } + + # --- the study ------------------------------------------------------------------------------ @@ -646,6 +692,7 @@ def run(poisoning_dir: Path) -> dict[str, Any]: errors["source_intended_missing"] += 1 report["errors_test_H"] = dict(errors) + report["recency_gap_posthoc"] = recency_gap_diagnostic(episodes) report["coverage_task1"] = coverage(poisoning_dir, lr.protected_wallets(poisoning_dir)) report["availability"] = availability() from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes diff --git a/src/cryptoguard/ml/tsuchiya_archive.py b/src/cryptoguard/ml/tsuchiya_archive.py index 0b36b52..65d68d0 100644 --- a/src/cryptoguard/ml/tsuchiya_archive.py +++ b/src/cryptoguard/ml/tsuchiya_archive.py @@ -748,7 +748,7 @@ def scan( progress(reader.stats) stored += _insert(db, pending) db.executescript(_DDL_INDEXES) - distinct ={name: c.count() for name, c in counters.items()} + distinct = {name: c.count() for name, c in counters.items()} # Spill files only grow until cleanup, so the total written after the final flush # in ``count`` is the peak temporary disk use. peak_spill = sum(c.bytes_written for c in counters.values()) diff --git a/tests/test_ml_lookalike_ranking.py b/tests/test_ml_lookalike_ranking.py index 3526c4f..3ae5185 100644 --- a/tests/test_ml_lookalike_ranking.py +++ b/tests/test_ml_lookalike_ranking.py @@ -516,3 +516,6 @@ def test_study_runs_end_to_end_on_synthetic_data( assert report["methods"]["T0"]["all"]["top1"] == pytest.approx(15 / 29, abs=1e-4) assert report["methods"]["random"]["all"]["top1"] == 0.5 assert report["resources"]["rpc_requests"] == 0 + gap = report["recency_gap_posthoc"] + assert gap["paid_gap_blocks"]["max"] == 199.0 # (b + 299) - (b + 100), by design + assert gap["paid_gap_over_30d"]["episodes"] == 0 From 3153dcfb197c723daf67d86033ade57d8037e4e5 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 00:44:00 +0300 Subject: [PATCH 42/92] docs(ml): Phase 12.1 temporal and graph research report ML_TEMPORAL_GRAPH_RESEARCH.md reports the pre-registered lookalike-prioritization study (aggregates only, 0 RPC requests). Test split, 428 episodes, top-1 vs the production similarity score B0 (0.300): recency T0 0.618 (supported), hybrid 0.462 (supported via its temporal part), recipient history B3 0.247 (reversed), graph G1 0.206 (reversed; equal to random). Retrospective, payoff-conditioned ranking only: no precision, FPR, recall or detection claim. Deviations D3 (runtime budget overrun) and D4 (post-hoc diagnostic) recorded; ML.md, ML_RESEARCH_PLAN.md and CHANGELOG.md updated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++ ML.md | 12 + ML_RESEARCH_PLAN.md | 21 ++ ML_TEMPORAL_GRAPH_RESEARCH.md | 476 ++++++++++++++++++++++++++++ docs/ml/protocol-12.1-deviations.md | 29 ++ 5 files changed, 557 insertions(+) create mode 100644 ML_TEMPORAL_GRAPH_RESEARCH.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f451fd..c4fc970 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,25 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Temporal and graph lookalike prioritization (Phase 12.1) +- Pre-registered study `lookalike-prioritization/1`, run with + `cryptoguard ml lookalike-study` (aggregate output, 0 RPC requests). It ranks the + lookalikes that planted to a victim before a source-confirmed payoff, using + point-in-time features with typed missingness and a typed cross-victim graph. +- A symmetric offline archive pass covers paid and rival lookalikes alike. The earlier + subset covered 0.2% of rivals, which would have leaked the outcome into graph features. + The coverage audit passes. +- Results on test, against the production similarity score (top-1 0.300): + - recency, 0.618: supported; + - graph reuse, 0.206: equal to random; + - recipient-history counts, 0.247: below the production score. +- These are retrospective ranking results, not detection metrics. Report: + ML_TEMPORAL_GRAPH_RESEARCH.md. +- Fixed: + - rows of frozen review wallets entered the graph index; + - the archive scanner maintained indexes during inserts. It now builds them after the + load, and the schema is unchanged. + ### Evidence completion and review hardening (Phase 11.7) - An offline recovery pass over the local archive gives all 19 Cohort B archive items that had no local wallet history some pre-cutoff rows (still source-selected). diff --git a/ML.md b/ML.md index 5a55468..6e8a858 100644 --- a/ML.md +++ b/ML.md @@ -260,6 +260,18 @@ and is kept in the run ledger. full-data run), so the test split is a previously examined development benchmark. Timeline: ML_GENERALIZATION_AUDIT.md §4. +## Phase 12.1: lookalike prioritization (research only) + +The study ranked the source-flagged lookalikes that planted to a victim before its first +confirmed payoff. On test: +- recency of the latest planting puts the paid lookalike first 62% of the time; +- the production similarity score does so 30% of the time, and random 20%; +- cross-victim graph features do not beat random. + +This is a retrospective, payoff-conditioned result. Nothing is integrated: the +production detector and its warnings are unchanged. Details are in +[ML_TEMPORAL_GRAPH_RESEARCH.md](ML_TEMPORAL_GRAPH_RESEARCH.md). + ## Limitations - One labelled source, with a benign class of prominent accounts; precision on real traffic diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 37a1802..c6d5bf8 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -182,3 +182,24 @@ Issues 13–20 are in that document's §24. The plan as approved: - **Still missing afterwards:** verified negatives (gate B). They need a reviewed sample of legitimate lookalike-shaped interactions, which no public source provides. That remains the real blocker for supervised learning on this task. + +## 8. Done (Phase 12.1): temporal and graph signals for lookalike prioritization + +The study was pre-registered in `docs/ml/protocol-12.1.md` (`999794a`) and run offline, +with 0 RPC requests. Results are in +[ML_TEMPORAL_GRAPH_RESEARCH.md](ML_TEMPORAL_GRAPH_RESEARCH.md). + +The task was retrospective: rank the lookalikes that had planted to a victim who later +paid one of them. The test split had 428 episodes. Top-1 against the production +similarity score (B0, 0.300): + +| Signal | Top-1 | Decision | +|---|---|---| +| T0 recency | 0.618 | supported | +| H_fixed hybrid | 0.462 | supported, through its temporal part only | +| B3 recipient history | 0.247 | reversed | +| G1 graph reuse | 0.206 | reversed; equal to random | + +- **Not a detection result:** no precision, FPR or recall was measured. +- **Next:** pre-register recency-first warning ordering on a population not used here. + diff --git a/ML_TEMPORAL_GRAPH_RESEARCH.md b/ML_TEMPORAL_GRAPH_RESEARCH.md new file mode 100644 index 0000000..4fdca1b --- /dev/null +++ b/ML_TEMPORAL_GRAPH_RESEARCH.md @@ -0,0 +1,476 @@ +# Temporal and graph signals for address-poisoning prioritization (Phase 12.1) + +This study is retrospective. Its population is conditioned on a payoff, and its candidates +and outcomes come from the source's flags. It measures which signals put the paid +lookalike first among lookalikes the source had already flagged. It is **not** a detection +benchmark. It estimates no precision, false-positive rate, recall, real-world AP or +theft-prevention effect, and every number below is an aggregate. + +| Item | Value | +|---|---| +| Protocol (frozen) | [`docs/ml/protocol-12.1.md`](docs/ml/protocol-12.1.md), commit `999794a` | +| Deviations and fixes | [`docs/ml/protocol-12.1-deviations.md`](docs/ml/protocol-12.1-deviations.md); F1, F2, D1 and D2 were committed before any outcome (`12f09a1`) | +| Code | `ml/lookalike_ranking.py`, `ml/lookalike_study.py`; command `cryptoguard ml lookalike-study` | +| Output (git-ignored) | `data/ml/research/lookalike-study.json`, `data/ml/research/recency-gap-posthoc.json` | +| RPC requests | 0. No downloads. Nothing paid. | +| Production detector | unchanged; nothing here is wired into it | + +## 1. Summary + +The task: rank the k ≥ 2 lookalikes that had planted transfers to a victim, at the block +before the victim's first confirmed payoff. The outcome is which one was paid. Results on +the test split (428 episodes, 427 groups) follow. **B0 is the unchanged production +similarity score.** + +| Method | Top-1 | MRR | +|---|---|---| +| random | 0.199 | 0.403 | +| **B0** production similarity | 0.300 | 0.501 | +| B3 recipient history | 0.247 | 0.458 | +| **T0 recency** | **0.618** | **0.764** | +| G1 graph reuse | 0.206 | 0.407 | +| H_fixed (B1, B3, T2, G1) | 0.462 | 0.631 | + +| Primary test (Holm over 4) | Top-1 difference vs B0, 95% CI | Holm p | Decision | +|---|---|---|---| +| P-H1 recipient history, B3 − B0 | −0.053 [−0.096, −0.014] | 0.007 | reversed | +| P-H2 temporal, T0 − B0 | **+0.318 [0.262, 0.372]** | 0.0004 | **supported** | +| P-H3 graph, G1 − B0 | −0.094 [−0.132, −0.057] | 0.0004 | reversed | +| P-H5 hybrid, H − B0 | +0.162 [0.123, 0.203] | 0.0004 | supported | + +Holm p = 0.0004 is the resolution floor of 10,000 permutations times 4 tests. + +- **Positive:** recency of the lookalike's latest planting is a strong ordering signal. It + holds a day before the payoff, in every year and every k bin, and among episodes whose + paid lookalike last planted more than 30 days earlier. +- **Negative:** + - The cross-victim graph (G1, G2, G3) does not beat random. + - Recipient-history counts (B3) do worse than the production score. + - The source's intended-address similarity (B1) adds nothing over B0. + - The hybrid is supported only because it contains a temporal component, and it is + worse than recency alone. +- **Caveat:** the candidates and the outcome are source-defined. The recency effect is a + property of payoffs that the source confirmed, not yet of wallets in general. + +## 2. Question and scope + +The central question asks whether three things improve detection or prioritization over +the existing poisoning rules: +- temporal wallet context; +- historical recipient relationships; +- graph-based attacker infrastructure. + +**This phase answers prioritization only, for one retrospective task.** +- **Task 2:** within-victim ranking (`lookalike-prioritization/1`), the confirmatory task. +- **Task 1:** candidate-generation coverage. Exploratory, carried over from Phase 11.7. +- **Outcome research:** the payoff-conditioned framing itself. + +No detection task is evaluable here. The background rows are unlabeled, and unknown is +not benign. + +## 3. Retrospective ranking versus prospective detection + +| | This study (retrospective) | Prospective detection (not measured) | +|---|---|---| +| Population | victims who later paid a flagged lookalike | every wallet, most never poisoned or never paying | +| Candidates | source-flagged plantings only | everything a wallet receives | +| Outcome | which flagged lookalike was paid | whether a transfer is an attack, and whether a warning prevents loss | +| Metrics | top-1, MRR within an episode | precision, FPR, recall, prevented loss | +| Supports | "among flagged lookalikes, rank recent ones first" | none of the prospective claims | + +T0 needs only the wallet's own history, so it is computable prospectively (§21). Whether +recency-first ordering prevents a single loss is untested. + +## 4. Pre-registration and deviations + +- **Frozen before analysis:** the protocol at `999794a`. Its hypotheses, metrics, split, + groups, tests and decision rule were not changed. +- **Recorded before any outcome was computed** (`12f09a1`, pushed before the study ran): + - **F1, defect:** rows of the 91 frozen wallets entered the graph index. Fixed with + `GraphIndex(exclude=...)`. + - **F2, defect:** the archive scanner maintained its three indexes during inserts. The + first pass wrote about 5 GB of journal, reached 32% in about two hours and ended with + the session. The indexes are now built after the load, with the same schema. The + partial output was discarded (§23). + - **D1:** entity and campaign overlap with the 95 frozen items. Sensitivity tests were + added, and the learned model is not fitted on overlapping episodes. + - **D2:** a coverage-symmetry audit. +- **Added after the results:** + - **D3:** the runtime budget was overrun (§23). It does not affect any value. + - **D4:** the post-hoc recency-gap diagnostic (§20). It is labelled post-hoc, and no + primary result depends on it. + +## 5. Data and sources + +All data is local and derived from Tsuchiya et al. (USENIX Security 2025), *Ethereum +address poisoning* archive. The archive is CC BY-NC-ND 4.0, so it is kept local and only +aggregates are committed. + +- **`archive_subset.sqlite`:** every archive row touching a payoff victim. It holds the + source's poisoning, intended and payoff rows, but no ordinary activity. +- **`research/graph_context.sqlite`** (new): one offline pass over all 34,905,969 archive + rows. It stored 1,306,648 rows touching any of the 13,418 candidate lookalikes or 26,816 + planting transactions. It was built from a hashed target manifest, and the audit checks + that hash. +- **Not available locally:** signers, receipts and contract code. Shared-signer edges (H3) + are untestable. + +## 6. Populations + +Each population is reported separately and never pooled. + +| Id | Population | Use here | +|---|---|---| +| P1-cov | payoff-linked attempts (1,409, protected wallets removed) | Task 1 coverage (§21) | +| P1-rank | eligible episodes (1,068) | confirmatory ranking | +| P2 | background windows (unlabeled) | availability only: 9 windows, 2 with k ≥ 2 | +| P3 | incident windows | availability only: 4 windows, all with k ≥ 2 | +| P4 | frozen review cohorts (95 items) | **excluded** from every computation | + +## 7. Eligibility and exclusions + +From the archive's payoff victims, the study keeps **1,068 eligible episodes**. Excluded: + +| Reason | Victims | +|---|---| +| protected review wallet | 60 | +| no confirmed payoff row | 96 | +| several lookalikes paid in the payoff block | 1 | +| single candidate (k = 1) | 277 | + +These counts equal the protocol's figures at freezing. k has mean 12.6 and median 5. + +## 8. Protected cohorts and overlap + +- The 91 wallets of both frozen cohorts are excluded as episodes. Their rows never become + graph edges (F1, tested). +- Review keys and manifests were never read. Overlap uses the blinded sheets only. +- **Overlap (D1):** 1 episode, in the test split, shares an entity or a linkage group with a + frozen item. + - Without it (427 test episodes), all four primary decisions are unchanged. The + differences are −0.054, +0.318, −0.095 and +0.162. + - The learned model was fitted on 640 development episodes. None of them overlaps. +- Frozen cohort files, hashes, packets and selection procedures were not modified. + +## 9. Coverage symmetry: the outcome leak, audited + +The earlier subset targeted payoff lookalikes only. Any cross-victim count read from it +would have been complete for the paid candidate and nearly empty for its rivals. + +| | Paid (1,068) | Rival (12,367) | +|---|---|---| +| Targeted by the new manifest | 100% | 100% | +| Planting rows present in the graph database | 100% | 100% | +| Planting transactions targeted | 100% | 100% | +| Covered by the old subset | 100% | **0.2%** | +| Median archive rows at the cutoff | 2 | 1 | + +- The scan used this exact manifest (hash match), so the audit's verdict is + **symmetric**. +- The remaining difference in rows observed is a difference in activity, not in coverage. + +## 10. Features and missingness + +All features use only rows at or before the cutoff c = T − 1. +- **B0:** the production detector's prefix+suffix against the victim's own recipients. +- **B1:** source intended-address similarity. +- **B2:** transaction semantics. +- **B3:** payments to the reference. +- **T0:** recency. +- **T1:** distinct planting transactions. +- **T2:** decayed exposure. +- **T3:** planting later than the last real payment. +- **T4:** one-day burst. +- **G1 / G2:** other victims and other payers. +- **G3:** batch size. +- **NC:** token-level negative control. + +**Missingness:** +- `None` means not observed, and `0` means observed and none. +- A method abstains, scoring exactly at random, when any candidate is `None`. +- At the primary cutoff, only T3 abstains (1.4%). Missingness indicators therefore change + nothing in the learned model (§17). +- Under the 7-day victim lookback, B0 and B3 abstain on 29% of episodes. + +## 11. Methods + +- Single-feature rankings, with ties kept. +- Random. +- **H_fixed:** the mean normalized rank of B1, B3, T2 and G1, one per hypothesis family, + with fixed weights. +- **Learned (exploratory):** a conditional logit, L2 with C = 1, fitted on development + pairs. + +No method has a tuned parameter. + +## 12. Metrics, groups, split, inference + +- **Metrics:** top-1 is tie-averaged, and MRR is the expectation under random + tie-breaking. +- **Groups:** + - Linking by shared transactions gave 600 groups with an oversized largest group, so + the protocol's fallback applied: linkage by shared candidate lookalikes. + - That gives 1,059 groups; the largest has 6 episodes. +- **Temporal split by group:** + - development: 640 episodes, 632 groups; + - test: 428 episodes, 427 groups. +- **Inference:** + - paired group bootstrap, 95% CI, 2,000 draws; + - group sign-flip permutation, 10,000 draws, seed 20261102; + - Holm over the four primary tests; + - margin 0.05. + +## 13. Primary results + +These are the four tests in §1, run once on the test split. + +- **"Reversed" is the protocol's term for significantly worse than B0.** It does not mean + the signal points the wrong way: + - **B3 vs random:** +0.038 [0.026, 0.051] on all episodes. B3 is weakly informative, + but less so than B0. + - **G1 vs random:** +0.005 [−0.007, 0.018], p = 0.39. There is no evidence that G1 + carries information. +- **The production score B0 is only modestly better than random:** +0.076 [0.055, 0.096] + on all episodes. + +## 14. Exploratory: every method against B0 + +These are paired top-1 differences on all 1,068 episodes, with no multiplicity control. + +| Method | vs B0 | 95% CI | +|---|---|---| +| T2 decayed exposure | +0.373 | [0.340, 0.406] | +| T4 one-day burst | +0.096 | [0.068, 0.124] | +| T3 planted after last real payment | +0.046 | [0.023, 0.069] | +| T1 planting count | +0.037 | [0.006, 0.066] | +| B1 source similarity | −0.002 | [−0.004, 0.000] | +| B2 semantics | −0.013 | [−0.038, 0.012] | +| G2 other payers | −0.075 | [−0.096, −0.055] | +| G3 batch size | −0.092 | [−0.122, −0.061] | +| NC negative control | −0.109 | [−0.135, −0.086] | + +Development and test agree on which side of B0 each method falls, except B2 and T3, which +flip: +- T0 scores 0.730 on development and 0.618 on test; +- B0 scores 0.305 and 0.300. + +## 15. Temporal analysis + +Recency (T0) and decayed exposure (T2), which is dominated by the latest planting, are +the only strong signals. + +- **Paid versus rival gap** (from the cutoff to the lookalike's latest planting): + - paid: median 19,709 blocks, about 2.7 days; + - rival: median 472,545 blocks, about 66 days. +- **Robustness:** with the cutoff a day earlier (T − 7,200, 745 evaluable episodes), T0 + scores 0.649 against B0's 0.310 and random's 0.220. +- **Burst and count** (T4, T1) add little beyond recency. + +**Mechanism.** 96% of paid lookalikes (1,025 of 1,068) last planted a spoofed transfer +that shows the victim as sender, so it appears in the victim's own outgoing history. The +pattern fits a victim copying the newest matching entry from that history. This is an +interpretation, not a tested causal claim. + +## 16. Graph analysis and controls + +| Check | Result | Expected | +|---|---|---| +| G1 top-1 | 0.233 (all) | — | +| G1 within-episode shuffle | 0.223 | random (0.228) ✓ | +| G1 global shuffle | 0.227 | random ✓ | +| Rows after the cutoff added, features compared | 0/100 mismatches | 0 ✓ | +| Graph lookback 30 days | G1 0.244 | — | +| Graph rows 50% dropped | G1 0.235 | — | +| NC (token negative control) | **0.194 < random 0.228** | random ✗ | + +- **G features:** the paid and rival medians are both 0 for G1 and G2. The cross-victim + reuse of a lookalike does not distinguish the one that gets paid. G2 and G3 are slightly + *below* random. +- **The negative control is not null.** It is anti-informative: + - paid lookalikes' latest plantings are in tokens planted to fewer study victims + (median 127 against 359); + - 55% of all plantings are in USDT, USDC or DAI. + - So token choice correlates with the outcome, and that confounds any token-level + signal. + - The bias runs against NC, so it does not inflate any positive claim here. It shows + that paid and rival lookalikes differ in campaign structure as well as timing. + +## 17. Hybrid, ablations and learned model + +| Test split | Top-1 | +|---|---| +| H_fixed | 0.462 | +| H without T2 | 0.322 | +| H without B1 | 0.469 | +| H without B3 | 0.475 | +| H without G1 | 0.477 | +| T0 alone | 0.618 | +| Learned, with or without indicators | 0.591 | + +- **H_fixed is carried by T2.** Removing any non-temporal component *improves* it, so the + supported P-H5 is a temporal result diluted by the other families. +- **Learned model** (exploratory; 640 development episodes, 10,878 pairs): + - largest standardized weights: T0 2.00, T3 1.00, B3 0.63, B2 0.34; G1 −0.02; + - against B0 on test: +0.291 [0.245, 0.339]; + - it does not beat T0 alone, so no learned model is justified. +- Removing the missingness indicators changes nothing (§10). + +## 18. Strata + +Top-1 on all episodes. + +| Stratum | n | random | B0 | T0 | H | +|---|---|---|---|---|---| +| 2022 | 62 | 0.404 | 0.441 | 0.718 | 0.629 | +| 2023 | 891 | 0.221 | 0.298 | 0.684 | 0.483 | +| 2024+ | 115 | 0.186 | 0.266 | 0.678 | 0.457 | +| k = 2 | 205 | 0.500 | 0.512 | 0.781 | 0.676 | +| k = 3–5 | 339 | 0.274 | 0.370 | 0.757 | 0.591 | +| k ≥ 6 | 524 | 0.091 | 0.178 | 0.601 | 0.350 | +| spoofed transfer | 1,025 | 0.230 | 0.305 | 0.687 | 0.494 | +| tiny transfer | 40 | 0.167 | 0.265 | 0.625 | 0.350 | + +- The fake-token (n = 1) and zero-value (n = 2) paid subtypes are too small to read. +- 2022 and the tiny subtype are small strata. + +## 19. Robustness + +Each variant is computed on the episodes evaluable under it. The last column is the share +of episodes whose T0 top set changed. + +| Variant | Evaluable | B0 | T0 | H | T0 top set changed | +|---|---|---|---|---|---| +| primary (T − 1) | 1,068 | 0.303 | 0.685 | 0.489 | — | +| cutoff T − 300 | 922 | 0.304 | 0.667 | 0.504 | 3.2% | +| cutoff T − 7,200 | 745 | 0.310 | 0.649 | 0.521 | 5.7% | +| victim history 7 days | 1,068 | 0.361 | 0.685 | 0.524 | 0% | +| victim history 30 days | 1,068 | 0.346 | 0.685 | 0.517 | 0% | +| victim rows 50% dropped | 1,068 | 0.310 | 0.685 | 0.483 | 0% | +| graph 30 days | 1,068 | 0.303 | 0.685 | 0.491 | 0% | +| graph 50% dropped | 1,068 | 0.303 | 0.685 | 0.489 | 0% | + +**Restricting the victim's history to the last 7 or 30 days *raises* B0.** This is more +evidence that recency is what matters. It is exploratory and not a tuned improvement. + +## 20. Source shift and the recency check + +- **Feature availability:** every feature is 100% available in every year, except T3 + (§10). +- **Shifts by year:** k grows in later years, so random top-1 falls from 0.40 (2022) to + 0.19 (2024+). T0 stays at 0.68–0.72. +- **Post-hoc diagnostic (D4, not pre-registered).** If the source matched payoffs only + within a time window, recency would be built into the label. + - **No narrow window:** paid gaps reach 1.70M blocks, about 236 days. 11.1% of paid gaps + exceed 30 days. + - **Recency keeps its edge on long gaps:** among the 119 episodes whose paid gap exceeds + 30 days, T0 scores 0.487 against random's 0.205. + - **A soft cap cannot be excluded:** no paid gap exceeds 365 days, while 1.9% of rival + gaps do. + +## 21. Task 1 coverage, and prospective availability + +**Candidate generation** (`candidates/2`) on the 1,409 payoff-linked attempts: + +| Window | Strict signer | Optimistic signer | +|---|---|---| +| 7 days | 6 (0.43%) | 51 (3.6%) | +| 30 days | 6 (0.43%) | 54 (3.8%) | +| all history | 6 (0.43%) | 54 (3.8%) | + +- 1,355 misses are spoofed outgoing transfers that need the signer, which the archive + lacks. Longer windows do not help. +- Dust is emitted on 50 of 50 under the optimistic mode. + +**Computable prospectively, from a wallet's own signed history:** B0, B3, T0–T4. +- B1 is not: it needs the source's intended address. +- G1–G3 are not: they need a cross-wallet index at the cutoff. + +**Where the ranking task arises:** +- P2: 2 of 9 background windows have k ≥ 2. +- P3: all 4 incident windows do (k = 3, 9, 5, 18). + +## 22. Error analysis + +On test, H_fixed misses or ties in 244 of 428 episodes, 29 of them tied at the top. +Categories overlap: + +| The paid lookalike was not… | Misses | +|---|---| +| the most similar (B1) | 177 | +| the most reused (G1) | 131 | +| the most recent (T0) | 119 | +| tied to the most-used reference (B3) | 116 | + +On all episodes, H's top-1 falls from 0.68 at k = 2 to 0.35 at k ≥ 6 (§18). No item was +inspected; the numbers are aggregates only. + +## 23. Resources and cost + +| Step | Wall | Peak RSS | Notes | +|---|---|---|---| +| First archive pass (failed) | ~2 h | ~210 MiB | 32% done, ended with the session; partial file not used (F2) | +| Archive pass (fixed scanner) | 58 min (scan 45 min) | 344 MiB | 34.9M rows; 1.02 GB peak spill, cleaned; 596 MB output | +| Study | 2 h 16 min | 744 MiB | primary features 1 h 47 min, almost all graph lookups | +| Post-hoc diagnostic | < 1 min | — | no graph | + +- **The protocol's budget of 2 minutes per experiment was overrun (D3).** The cause is SQLite + lookups for 13,435 candidates on one HDD shared with other projects' jobs, at 0% idle. +- The memory limits held: under 512 MiB for the pass, under 1 GB for the study. +- **G features are the most expensive and add nothing.** +- CPU only. 0 RPC requests. + +## 24. Limitations + +1. **The population is conditioned on a payoff.** Nothing here concerns victims who never + paid, or attempts in general. +2. **The candidates and outcome are source-defined.** + - The source's heuristics may use information after c. + - Recency could partly reflect how the source matched payoffs (§20). +3. **The history is source-selected.** B0, B3 and T3 see only the payments the source + kept. That may handicap B0 relative to a wallet with full history. +4. **The data is dominated by one mechanism.** 96% of paid lookalikes used spoofed + transfers, so the results speak mostly to that subtype. +5. **One source.** There is no independent dataset of ranking outcomes, so external + validity is untested. +6. **The negative control failed to be null** (§16). Campaign structure differs between + paid and rival lookalikes in ways not modelled here. +7. **Multiplicity.** Only the four primary tests are confirmatory. +8. **No human labels exist.** The 95 frozen items are unreviewed. + +## 25. Conclusions, blockers and next experiment + +**Positive (confirmatory, retrospective).** Among source-flagged lookalikes that planted +to a victim who later paid one, recency picks the paid lookalike first 62% of the time on +test. That is twice the production similarity score (30%) and three times random (20%). +The result holds a day before the payoff, across years and k, and on long-gap episodes. +P-H5 is also supported, but only through its temporal component. + +**Negative (confirmatory).** +- Cross-victim graph reuse (P-H3) gives no ranking signal. +- Recipient-history counts (P-H1) do worse than the production score. +- In exploratory comparisons, intended-address similarity, transaction semantics, batch + size and prior payers add nothing. +- A learned combination does not beat recency alone. + +**Source-selection limitations.** These are the limitations in §24, items 1–6. They bound +every claim to "payoffs confirmed by this source". + +**Not claimed.** +- No precision, FPR, recall, AP, detection improvement or prevented loss. +- No change to the production detector, and no deterministic warning suppressed. + +**Blockers.** +- Human review of the 95 frozen items: waiting on two reviewers; no labels anywhere. +- No signer data: spoofed transfers stay outside `candidates/2`'s strict coverage. +- No prospective population with outcomes. +- G features would need a cross-wallet index that production does not have. They are not + worth building, on this evidence. + +**Next experiment** (to pre-register; not started): +- **What:** test recency-first ordering of lookalike warnings, B0-passing candidates + ordered by T0, as a fixed rule. +- **Where:** a population not used here, such as a later archive release or independently + reviewed incidents. +- **Measure:** the share of losses in which the paid lookalike was the top warning, not + detection accuracy. +- **Constraint:** no RPC beyond a newly approved budget. diff --git a/docs/ml/protocol-12.1-deviations.md b/docs/ml/protocol-12.1-deviations.md index 7d85d85..782552a 100644 --- a/docs/ml/protocol-12.1-deviations.md +++ b/docs/ml/protocol-12.1-deviations.md @@ -73,6 +73,35 @@ reports: It also checks that the graph database was built from this exact manifest (by hash). If the audit fails, every G feature result is reported as invalid. +## Added after the study was run + +These entries were written after the results existed. Neither changes a pre-registered +value. + +### D3. Runtime budget overrun + +Section 9 set a budget of about 25 minutes for the archive pass and under 2 minutes for +each experiment. + +| Step | Wall | Peak RSS | +|---|---|---| +| Archive pass | 58 min, of which the scan took 45 min | 344 MiB | +| Study | 2 h 16 min | 744 MiB | + +Almost all of the study's time went to the primary feature extraction, which took +1 h 47 min. Its cost was SQLite graph lookups for 13,435 candidates, on one HDD shared +with other projects' jobs and running at 0% idle. The memory limits held. Results do not +depend on runtime. + +### D4. Post-hoc recency-gap diagnostic + +`recency_gap_diagnostic` asks whether T0's advantage is built into the source's payoff +matching. It reports: +- the paid and rival planting-to-cutoff gap quantiles; +- T0 among episodes whose paid gap exceeds 30 days. + +It is labelled post-hoc in the output and in the report. No decision depends on it. + ## Unchanged - Eligibility and the 1,068 episodes. From 03f1c1d53c58066f4bd6487e465f82e0d60e372b Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 10:53:37 +0300 Subject: [PATCH 43/92] docs(ml): pre-register the Phase 12.2 recency-validation protocol Frozen before any 12.2 outcome is computed. Primary test H1: does recency still beat the production similarity score once every rival faces the source's own payoff-confirmation rule ("poisoning between the intended and the payoff transfer")? Secondary H2: recency ordering of production warnings on an archive-observation replay. H3: the 4 recorded incidents, descriptive. All archive analyses are classified as retrospective sensitivity analysis of previously examined data, not independent validation. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.2.md | 244 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 docs/ml/protocol-12.2.md diff --git a/docs/ml/protocol-12.2.md b/docs/ml/protocol-12.2.md new file mode 100644 index 0000000..418c836 --- /dev/null +++ b/docs/ml/protocol-12.2.md @@ -0,0 +1,244 @@ +# Phase 12.2 protocol: is the recency result a source-selection artifact? + +- **Task:** `recency-validation/1`. +- **Operational scorer:** `poisoning-warning-rank/1`. +- **Written and committed before** any analysis below was computed. Phase 12.1 outputs + (`data/ml/research/phase12.1/`, SHA-256 `94734a71…` for `lookalike-study.json`) are + preserved and not recomputed in place. + +## 0. What is already known, and what that rules out + +Phase 12.1 examined the outcomes of **every** eligible archive episode: 1,068 episodes in +total, 640 in development and 428 in test. Any further analysis of these episodes is +therefore **retrospective internal sensitivity analysis**, never independent validation. A +new split or seed does not change that. + +The source's documentation (`data/external/tsuchiya2025/guidance.ipynb`) describes how +payoffs were confirmed. For each candidate payoff, the authors checked whether "the +poisoning transfer exists between the intended and the payoff transfer". This rule +constrains the time of the paid lookalike's planting, and only the paid lookalike's: rivals +were never subjected to it. It alone could produce a recency advantage. Testing that is +the main purpose of this phase. + +## 1. Populations and their classification + +| Id | Population | Candidate set | Classification | +|---|---|---|---| +| R | the 1,068 Phase 12.1 episodes (protocol 12.1 eligibility, protected wallets excluded) | source plantings at or before c | previously examined development data | +| R-SR | R, each candidate set restricted by the symmetric confirmation rule (§3) | source plantings that satisfy SR | retrospective internal sensitivity analysis | +| O-arch | R, with the production detector run on the archive rows at or before c | production poisoning warnings | retrospective operational replay on a source-selected stream | +| X-inc | the 4 recorded incident fixtures (`replay/cases`) | production warnings from complete recorded wallet streams | external source, operational replay; n = 4, descriptive | +| P2 | recorded background windows | production warnings | operational diagnostics only; no outcome labels | +| P4 | the 95 frozen review items | — | excluded from everything | + +**Ruled out as validation data:** +- the BSC payoff file: not available locally, and downloading it is not authorized; +- Poison-Hunter: 89 of its 105 in-definition rows are the same archive attempts, and it + has no record of which lookalike was paid; +- PTXPhish: phishing transactions, with no candidate rivals; +- the archive's 13,683 unconfirmed payoff rows: their labels are uncertain by the source's + own account, and using them would take two more full archive passes. They are listed as + a future opportunity (§10). + +## 2. Frozen scorers + +**T0** is Phase 12.1 recency, `lookalike-features/1`, unchanged: +- definition: `-(c - b)`, where b is the block of the candidate's latest source planting + to the victim at a block <= c; +- plantings are the source's zero-value, tiny and counterfeit rows between the victim and + the candidate, in either direction; +- rows in the payoff block are excluded; +- the unit is blocks; same-block order is not used; +- ties are scored tie-averaged (`1/m`). + +**B0** is the unchanged production similarity: prefix+suffix of the candidate against its +reference among the victim's own outgoing rows (Phase 12.1 §5). + +**OP0, the operational baseline.** Production warnings are ordered by: +1. severity tier (critical_evidence > elevated_risk > review_recommended > informational + > unknown); +2. then prefix+suffix, descending. + +Remaining ties are tied. + +**OP1, `poisoning-warning-rank/1`.** The same severity tier first, then the recency of the +warning's latest *planting* signal at or before the cutoff: +- planting signals are `zero_value_transfer`, `spoofed_outgoing_transfer` and + `unsolicited_incoming_transfer`; +- the wallet's own sends never count; +- remaining ties are tied in the metric. The displayed order breaks them by prefix+suffix + descending, then by address. + +A warning without a planting signal has no recency basis. It is placed after the warnings +of its tier that have one, in OP0 order, and marked `no_recency_basis`. No warning is ever +removed or re-tiered. + +No parameter of T0, B0, OP0 or OP1 is tuned in this phase. + +## 3. The symmetric confirmation rule (SR) + +For candidate l of episode e at cutoff c: +- `A(l)`: the non-null source `intended` addresses of l's plantings at or before c, other + than l. +- `I`: the victim's source-flagged *intended* rows at or before c. + +**SR_any(l)** (primary) is True when some planting p of l, with intended address a, has an +intended row i to a with `i.block < p.block`. Same-block pairs do not count, because their +order is unknown. SR_any is `None` when `A(l)` is empty, and False otherwise. + +**SR_latest(l)** (sensitivity) is True when the latest planting of l is later than the +victim's latest intended row to any a in `A(l)`. + +**Manipulation check** (reported first): the share of paid and of rival candidates with +SR_any True. If the paid share is far below 1, this reading of the source's rule does not +reproduce it, and H1 is reported as weakened. + +**R-SR episodes:** candidates with SR_any True. An episode is eligible when the paid +candidate is among them and at least 2 remain. SR `None` candidates are excluded, and +their inclusion is a sensitivity analysis. + +## 4. Hypotheses and decision rules + +| Test | Population | Comparison | Null | +|---|---|---|---| +| **H1** (primary) | R-SR, all eligible episodes | top-1(T0) − top-1(B0) | recency has no advantage once rivals face the same confirmation rule | +| **H2** (secondary) | O-arch: episodes where the paid lookalike is among at least 2 production warnings | top-1(OP1) − top-1(OP0) | recency does not improve the ordering of production warnings | +| H3 (descriptive) | X-inc | the paid recipient's rank under OP0 and OP1 | none tested | + +**Inference** (H1, H2): +- paired top-1 differences, clustered on the Phase 12.1 linkage groups (shared candidate + lookalikes), computed once on all of R; +- p-values from a group sign-flip permutation, 10,000 draws; +- intervals from a group bootstrap, 2,000 draws; +- seed 20261103; +- Holm over H1 and H2. + +**Decision for each test:** +- **survives:** Holm p < 0.05, the CI excludes 0, and the difference is at least 0.05; +- **explained / null:** the CI lies within ±0.05, or the difference is at most 0 with the + CI excluding positive values above 0.05; +- **inconclusive:** otherwise. + +For H1, the attenuation `(Δ_R − Δ_R-SR) / Δ_R` is also reported, where `Δ_R` is +recomputed on the same episodes. + +**Phase classification:** + +| Outcome | Classification | +|---|---| +| H1 survives | source-conditional retrospective effect | +| H1 explained | selection-artifact result | +| otherwise | inconclusive | + +With only 4 external cases, the phase cannot be classified as independently supported. + +## 5. Exploratory analyses (no confirmatory claims) + +E1. **C1, within-episode permutation of T0 values** (200 seeded repeats). Expected: random. + +E2. **C6, reversed time order (oldest first).** Expected: below random if recency carries +information. + +E3. **C3, timing perturbation.** Planting blocks are jittered uniformly by ±1 day and +±7 days (seeded). Reported: T0 top-1. + +E4. **Timestamp coarsening** to 1-day and 7-day buckets, which creates ties. + +E5. **C4, token strata.** +- The token class of the paid candidate's latest planting: a public stablecoin (USDT, + USDC, DAI) or other. +- Candidate sets restricted to candidates whose latest planting is in a public stablecoin. + +E6. **C5, k bins** with group counts. + +E7. **Symmetric maximum lookback** of 30, 90 and 180 days. Candidates whose latest +planting is older than the window are dropped, applied to all candidates alike. + +E8. **Without immediate copies:** episodes are dropped when the paid gap is under 300 +blocks, about an hour. This stratifies on an outcome attribute and is labelled so. + +E9. **Strata:** +- year; +- paid subtype; +- victim activity tertile, by the number of victim outgoing rows at or before c; +- the age of the most recent candidate (under 1 hour, 1 hour to 1 day, 1 to 7 days, over + 7 days), which uses no outcome; +- the largest group's share. + +E10. **Negative-control investigation:** +- NC within token class; +- the within-episode Spearman correlation of NC with T0; +- NC on episodes whose candidates' latest plantings all share one token class. + +E11. **History perturbations:** +- drop each candidate's latest planting (a missed observation); +- inject exact duplicate rows; +- shuffle line order within blocks. + +E12. **Errors:** a 2×2 of T0 against B0 success (top-1 = 1), with aggregate categories. + +E13. **Operational coverage (O-arch):** +- the share of source candidates the production detector warns on at c, paid against + rival; +- the share of episodes eligible for H2. + +E14. **P2 diagnostics:** +- warnings and windows with at least 2 warnings; +- the share of windows whose order changes between OP0 and OP1; +- that the warning set is identical under both orders; +- runtime; +- invariance when rows after the cutoff are added. + +## 6. Missing data + +`None` means not observed, never 0. +- T0 is always observed in R. +- B0 abstains as in Phase 12.1. +- SR `None` excludes a candidate from R-SR. +- OP1 without a basis is handled as in §2. + +Abstentions are reported per analysis. + +## 7. Protected entities + +- The 91 frozen wallets are excluded as episodes, and their rows never become graph + edges. +- The overlap set (wallets, addresses under review, transactions, linkage groups) is read + from the blinded sheets only. Overlap counts are reported, and H1 and H2 are repeated + without overlapping episodes. +- Frozen cohort files are not modified, and their hashes are re-verified at the end. + +## 8. Engineering gate: exactness before speed + +Phase 12.1 spent 1 h 47 min in lazy per-address SQLite graph lookups. +- **Before any 12.2 result is produced:** a single-pass preloaded graph index must + reproduce the saved Phase 12.1 report exactly. Every key except `resources` must be equal + as JSON. +- **If it differs:** the optimization is not used, and the difference is investigated. +- **Profiling** (query plan, rows per lookup, time per lookup, I/O) is measured on a sample + before the change. + +## 9. Budgets + +| Run | Wall time | Memory | +|---|---|---| +| Full 12.2 study | under 15 min | under 1 GB RSS | +| Graph preload | under 5 min | — | + +0 RPC requests and no downloads. Outputs are aggregates under `data/ml/research/` +(git-ignored). + +## 10. Limitations fixed in advance + +1. R is previously examined. Nothing here is independent validation. +2. SR is our reading of a rule the source describes in one sentence, and the + manipulation check bounds how well it reproduces it. +3. O-arch runs the production detector on a source-selected stream with no signers and + unknown same-block order. Its warnings are not what a live wallet would have shown. +4. X-inc has 4 cases. Its results are descriptive and were not used to choose T0. The + candidate generator and detector were, however, developed with these fixtures in view. +5. **Future validation data:** + - the 13,683 unconfirmed archive payoffs: label-uncertain, and they need about 2 hours + of offline passes; + - the BSC payoff file: needs download approval; + - newly recorded incidents: need an approved RPC budget. From 623b36d441dbc0827cdb851d4b16d05a86035d2f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 11:11:55 +0300 Subject: [PATCH 44/92] perf(ml): single-pass graph preload, exact; Phase 12.2 analysis code Profiling (300 seeded lookups each) showed correct index use but one random page read per matched row on a shared HDD: 96 ms per lookalike lookup and 512 ms per planting-tx lookup, against 13 s to scan all 1,306,648 rows. - lookalike_ranking: preload_graph builds every typed edge in one sequential pass, with the lazy index's per-row rules factored into shared functions; edge-level keep filters reproduce graph_keep and the cutoff filter. - lookalike_study: preloaded by default (--lazy-graph keeps the reference); coverage_symmetry uses one pass instead of two lookups per candidate. Exactness gate on the real data: the full Phase 12.1 report is reproduced key for key (result hash 1dbc763f...), 8,157 s -> 179 s, 744 -> 485 MiB. - warning_rank (poisoning-warning-rank/1, research only, not wired in): orders production warnings by severity tier, then the latest planting signal at or before the cutoff; never removes or re-tiers a warning. - recency_validation: the pre-registered Phase 12.2 analyses (protocol 03f1c1d), committed before they are run. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 23 +- src/cryptoguard/ml/lookalike_ranking.py | 131 ++++- src/cryptoguard/ml/lookalike_study.py | 120 +++- src/cryptoguard/ml/recency_validation.py | 695 +++++++++++++++++++++++ src/cryptoguard/ml/warning_rank.py | 135 +++++ tests/test_ml_lookalike_ranking.py | 85 +++ tests/test_ml_recency_validation.py | 213 +++++++ 7 files changed, 1350 insertions(+), 52 deletions(-) create mode 100644 src/cryptoguard/ml/recency_validation.py create mode 100644 src/cryptoguard/ml/warning_rank.py create mode 100644 tests/test_ml_recency_validation.py diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 9ffe6da..399b95e 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -110,6 +110,15 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ls.add_argument( "--graph-scan", action="store_true", help="first run the graph-context archive pass" ) + ls.add_argument( + "--lazy-graph", action="store_true", help="Phase 12.1 per-address lookups (reference)" + ) + rv = ml.add_parser( + "recency-validation", help="Phase 12.2 recency validation (aggregate output)" + ) + rv.add_argument( + "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "recency-validation.json" + ) iv = ml.add_parser("inventory", help="hash and describe every local research data file") iv.add_argument("--root", type=Path, default=Path(".")) iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") @@ -208,12 +217,24 @@ def run(args: argparse.Namespace) -> int: poisoning = ML_DIR / "poisoning" if args.graph_scan: lookalike_ranking.graph_context_scan(args.data_dir, poisoning) - report = lookalike_study.run(poisoning) + report = lookalike_study.run(poisoning, lazy_graph=args.lazy_graph) args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(json.dumps(report, indent=1, default=str) + "\n", encoding="utf-8") print(json.dumps(report["primary"], indent=1)) print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") return 0 + if args.ml_command == "recency-validation": + import json + + from cryptoguard.ml import recency_validation + + report = recency_validation.run(ML_DIR / "poisoning") + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=1, default=str) + "\n", encoding="utf-8") + for key in ("manipulation_check", "H1_symmetric_confirmation", "H2_production_warnings"): + print(key, json.dumps(report[key], indent=1)) + print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") + return 0 if args.ml_command == "inventory": import json diff --git a/src/cryptoguard/ml/lookalike_ranking.py b/src/cryptoguard/ml/lookalike_ranking.py index d2f226e..434f486 100644 --- a/src/cryptoguard/ml/lookalike_ranking.py +++ b/src/cryptoguard/ml/lookalike_ranking.py @@ -31,7 +31,7 @@ import sqlite3 from bisect import bisect_right from collections import Counter, defaultdict -from collections.abc import Callable, Iterable, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -255,6 +255,31 @@ def victim_of(row: Row) -> str | None: Edge = tuple[int, int, str] # (block, line, victim) +EdgeKeep = Callable[[int, int], bool] # (block, line) -> keep + + +def _lookalike_edge(r: Row, lookalike: str, exclude: frozenset[str]) -> tuple[bool, Edge] | None: + """``(is_payoff, edge)`` when row ``r`` is a typed edge of ``lookalike``. Shared by the + lazy and the preloaded index, so both build exactly the same edges.""" + from cryptoguard.ml.tsuchiya_archive import PAYOFF, POISONING + + v = victim_of(r) + if v is None or v == lookalike or r.sender in exclude or r.receiver in exclude: + return None + if r.flags & POISONING and lookalike_of(r, v) == lookalike: + return False, (r.block, r.line, v) + if r.flags & PAYOFF and r.sender == v and r.receiver == lookalike: + return True, (r.block, r.line, v) + return None + + +def _tx_edge(r: Row, exclude: frozenset[str]) -> Edge | None: + from cryptoguard.ml.tsuchiya_archive import POISONING + + v = victim_of(r) + if v is None or not r.flags & POISONING or r.sender in exclude or r.receiver in exclude: + return None + return (r.block, r.line, v) class GraphIndex: @@ -282,36 +307,28 @@ def __init__( self._l: dict[str, tuple[list[Edge], list[Edge]]] = {} self._tx: dict[str, list[Edge]] = {} - def _skip(self, r: Row) -> bool: - if r.sender in self._exclude or r.receiver in self._exclude: - return True - return self._keep is not None and not self._keep(r) - def _edges(self, lookalike: str) -> tuple[list[Edge], list[Edge]]: if lookalike not in self._l: - from cryptoguard.ml.tsuchiya_archive import PAYOFF, POISONING - - planted, paid = set(), set() + planted: set[Edge] = set() + paid: set[Edge] = set() for r in self._fetch_l(lookalike): - v = victim_of(r) - if v is None or v == lookalike or self._skip(r): + if self._keep is not None and not self._keep(r): continue - if r.flags & POISONING and lookalike_of(r, v) == lookalike: - planted.add((r.block, r.line, v)) - elif r.flags & PAYOFF and r.sender == v and r.receiver == lookalike: - paid.add((r.block, r.line, v)) + e = _lookalike_edge(r, lookalike, self._exclude) + if e is not None: + (paid if e[0] else planted).add(e[1]) self._l[lookalike] = (sorted(planted), sorted(paid)) return self._l[lookalike] def _tx_edges(self, tx: str) -> list[Edge]: if tx not in self._tx: - from cryptoguard.ml.tsuchiya_archive import POISONING - - edges = set() + edges: set[Edge] = set() for r in self._fetch_tx(tx): - v = victim_of(r) - if v is not None and r.flags & POISONING and not self._skip(r): - edges.add((r.block, r.line, v)) + if self._keep is not None and not self._keep(r): + continue + e = _tx_edge(r, self._exclude) + if e is not None: + edges.add(e) self._tx[tx] = sorted(edges) return self._tx[tx] @@ -347,6 +364,73 @@ def fetch_tx(tx: str) -> list[Row]: return GraphIndex(fetch_l, fetch_tx, keep=keep, exclude=exclude) +@dataclass(frozen=True) +class PreloadedEdges: + """Every typed edge of a fixed set of lookalikes and planting txs, built in one + sequential pass. A lazy index does one random-access lookup per address instead: on the + research database that was 96 ms per lookalike and 512 ms per tx on a shared HDD, against + 13 s for a sequential scan of all 1.3M rows.""" + + planted: dict[str, list[Edge]] + paid: dict[str, list[Edge]] + tx: dict[str, list[Edge]] + + def index(self, keep: EdgeKeep | None = None) -> GraphIndex: + """A ``GraphIndex`` over these edges; ``keep`` filters on (block, line). Asking for an + address or tx outside the preloaded sets raises, rather than silently seeing none.""" + + def pick(edges: list[Edge]) -> list[Edge]: + return edges if keep is None else [e for e in edges if keep(e[0], e[1])] + + g = GraphIndex(_unloaded, _unloaded) + g._l = {a: (pick(self.planted[a]), pick(self.paid[a])) for a in self.planted} + g._tx = {t: pick(e) for t, e in self.tx.items()} + return g + + +def _unloaded(key: str) -> list[Row]: + raise KeyError(f"{key} is not in the preloaded graph") + + +def preload_graph( + rows: Iterable[Row], + lookalikes: Iterable[str], + txs: Iterable[str], + exclude: frozenset[str] = frozenset(), +) -> PreloadedEdges: + """One pass over ``rows``, with the lazy index's per-row edge rules.""" + looks, tx_set = frozenset(lookalikes), frozenset(txs) + planted: dict[str, set[Edge]] = {a: set() for a in looks} + paid: dict[str, set[Edge]] = {a: set() for a in looks} + in_tx: dict[str, set[Edge]] = {t: set() for t in tx_set} + names: dict[str, str] = {} # one string object per victim + for r in rows: + for lk in {r.sender, r.receiver} & looks: + e = _lookalike_edge(r, lk, exclude) + if e is not None: + b, line, v = e[1] + (paid if e[0] else planted)[lk].add((b, line, names.setdefault(v, v))) + if r.tx in tx_set: + te = _tx_edge(r, exclude) + if te is not None: + in_tx[r.tx].add((te[0], te[1], names.setdefault(te[2], te[2]))) + return PreloadedEdges( + {a: sorted(v) for a, v in planted.items()}, + {a: sorted(v) for a, v in paid.items()}, + {t: sorted(v) for t, v in in_tx.items()}, + ) + + +def sqlite_rows(path: Path) -> Iterator[Row]: + """Every row of a research database, in storage order (sequential I/O).""" + con = _connect(path) + try: + for t in con.execute(_ROWS + " order by line"): + yield _row(t) + finally: + con.close() + + def memory_graph(rows: Iterable[Row], exclude: frozenset[str] = frozenset()) -> GraphIndex: """A graph over rows held in memory (tests and small studies).""" by_addr: defaultdict[str, list[Row]] = defaultdict(list) @@ -392,6 +476,11 @@ def graph_keep(drop: float, seed: int = 0) -> Callable[[Row], bool]: return lambda r: not _dropped(r.line, drop, seed) +def graph_keep_edge(drop: float, seed: int = 0) -> EdgeKeep: + """``graph_keep`` for a preloaded index: the same rows survive.""" + return lambda _block, line: not _dropped(line, drop, seed) + + @dataclass class TokenIndex: """Study victims planted per token contract, for the negative control NC.""" diff --git a/src/cryptoguard/ml/lookalike_study.py b/src/cryptoguard/ml/lookalike_study.py index f2825a8..ffd969f 100644 --- a/src/cryptoguard/ml/lookalike_study.py +++ b/src/cryptoguard/ml/lookalike_study.py @@ -297,44 +297,46 @@ def coverage_symmetry( the victim-side subset holds, for paid and rivals alike. The older subset's targeting is reported to show the asymmetry this pass removes.""" import sqlite3 + from bisect import bisect_right from cryptoguard.ml.tsuchiya_archive import load_targets manifest = load_targets(poisoning_dir / lr.RESEARCH_DIR / "graph_context_targets.json") old = json.loads((poisoning_dir / "archive_targets.json").read_text(encoding="utf-8")) old_lookalikes = set(old["groups"].get("payoff_lookalikes", ())) + # One sequential pass instead of two random lookups per candidate (same counts). + looks = {c for e in episodes for c in e.candidates} + lines: set[int] = set() + blocks: defaultdict[str, list[int]] = defaultdict(list) + for r in lr.sqlite_rows(gpath): + lines.add(r.line) + for a in {r.sender, r.receiver} & looks: + blocks[a].append(r.block) + for v in blocks.values(): + v.sort() con = sqlite3.connect(f"file:{gpath.as_posix()}?mode=ro", uri=True) try: meta = dict(con.execute("SELECT key, value FROM meta").fetchall()) scanned = json.loads(meta["summary"])["target_manifest_sha256"] - acc: dict[str, Counter[str]] = {"paid": Counter(), "rival": Counter()} - rows_seen: dict[str, list[int]] = {"paid": [], "rival": []} - for e in episodes: - c = e.payoff_block - 1 - by_l: defaultdict[str, list[lr.Row]] = defaultdict(list) - for r in e.plantings: - by_l[lr.lookalike_of(r, e.victim)].append(r) - for lk, rows in by_l.items(): - side = "paid" if lk == e.paid else "rival" - a = acc[side] - a["candidates"] += 1 - a["targeted_address"] += lk in manifest.addresses - a["targeted_in_old_subset"] += lk in old_lookalikes - a["planting_rows"] += len(rows) - a["planting_txs_targeted"] += sum(r.tx in manifest.txs for r in rows) - a["planting_rows_in_graph_db"] += sum( - con.execute("SELECT 1 FROM transfers WHERE line = ?", (r.line,)).fetchone() - is not None - for r in rows - ) - n = con.execute( - "SELECT count(*) FROM transfers WHERE (sender = ? OR receiver = ?) " - "AND block <= ?", - (lk, lk, c), - ).fetchone()[0] - rows_seen[side].append(n) finally: con.close() + acc: dict[str, Counter[str]] = {"paid": Counter(), "rival": Counter()} + rows_seen: dict[str, list[int]] = {"paid": [], "rival": []} + for e in episodes: + c = e.payoff_block - 1 + by_l: defaultdict[str, list[lr.Row]] = defaultdict(list) + for r in e.plantings: + by_l[lr.lookalike_of(r, e.victim)].append(r) + for lk, rows in by_l.items(): + side = "paid" if lk == e.paid else "rival" + a = acc[side] + a["candidates"] += 1 + a["targeted_address"] += lk in manifest.addresses + a["targeted_in_old_subset"] += lk in old_lookalikes + a["planting_rows"] += len(rows) + a["planting_txs_targeted"] += sum(r.tx in manifest.txs for r in rows) + a["planting_rows_in_graph_db"] += sum(r.line in lines for r in rows) + rows_seen[side].append(bisect_right(blocks.get(lk, []), c)) out: dict[str, Any] = {"scan_used_this_manifest": scanned == manifest.sha256} for side, a in acc.items(): n = a["candidates"] @@ -413,13 +415,69 @@ def quantiles(xs: list[float]) -> dict[str, float]: # --- the study ------------------------------------------------------------------------------ -def run(poisoning_dir: Path) -> dict[str, Any]: +def comparable(report: Mapping[str, Any]) -> Any: + """A report without its timing fields, for exact old-vs-new comparisons.""" + + def strip(x: Any) -> Any: + if isinstance(x, Mapping): + return {k: strip(v) for k, v in x.items() if k != "seconds"} + if isinstance(x, list): + return [strip(v) for v in x] + return x + + return strip({k: v for k, v in report.items() if k != "resources"}) + + +class Graphs: + """The study's graph indexes: preloaded in one sequential pass (default), or the + Phase 12.1 lazy per-address SQLite lookups (``lazy=True``, kept as the reference).""" + + def __init__( + self, + gpath: Path, + episodes: Sequence[lr.Episode], + blind: frozenset[str], + *, + lazy: bool = False, + ) -> None: + self.gpath, self.blind, self.lazy = gpath, blind, lazy + t = time.perf_counter() + self.edges = ( + None + if lazy + else lr.preload_graph( + lr.sqlite_rows(gpath), + {c for e in episodes for c in e.candidates}, + {r.tx for e in episodes for r in e.plantings}, + blind, + ) + ) + self.preload_seconds = round(time.perf_counter() - t, 2) + + def full(self) -> lr.GraphIndex: + if self.edges is None: + return lr.sqlite_graph(self.gpath, exclude=self.blind) + return self.edges.index() + + def dropped(self, share: float, seed: int) -> lr.GraphIndex: + if self.edges is None: + return lr.sqlite_graph(self.gpath, keep=lr.graph_keep(share, seed), exclude=self.blind) + return self.edges.index(lr.graph_keep_edge(share, seed)) + + def before(self, c: int) -> lr.GraphIndex: + if self.edges is None: + return lr.sqlite_graph(self.gpath, keep=_before(c), exclude=self.blind) + return self.edges.index(lambda block, _line: block <= c) + + +def run(poisoning_dir: Path, *, lazy_graph: bool = False) -> dict[str, Any]: t_start = time.perf_counter() episodes, exclusions = lr.load_episodes(poisoning_dir) gpath = poisoning_dir / lr.RESEARCH_DIR / lr.GRAPH_DB # Rows touching a frozen review wallet never enter the graph (protocol section 3). blind = lr.protected_wallets(poisoning_dir) - graph = lr.sqlite_graph(gpath, exclude=blind) + graphs = Graphs(gpath, episodes, blind, lazy=lazy_graph) + graph = graphs.full() tokens = lr.TokenIndex.build(episodes) grp, linkage = lr.protocol_groups(episodes) split = lr.temporal_split(episodes, grp) @@ -580,7 +638,7 @@ def run(poisoning_dir: Path) -> dict[str, Any]: ( "graph_drop_50", lr.View(), - lr.sqlite_graph(gpath, keep=lr.graph_keep(0.5, 0), exclude=blind), + graphs.dropped(0.5, 0), None, ), ] @@ -607,7 +665,7 @@ def run(poisoning_dir: Path) -> dict[str, Any]: mismatches = 0 for i in sample: c = episodes[i].payoff_block - 1 - g_cut = lr.sqlite_graph(gpath, keep=_before(c), exclude=blind) + g_cut = graphs.before(c) if lr.candidate_features(episodes[i], lr.View(), g_cut, tokens) != feats[i]: mismatches += 1 shuffled_within, shuffled_global = [], [] @@ -699,6 +757,8 @@ def run(poisoning_dir: Path) -> dict[str, Any]: peak = peak_rss_bytes() report["resources"] = { + "graph_mode": "lazy" if lazy_graph else "preloaded", + "graph_preload_seconds": graphs.preload_seconds, "feature_seconds_primary": round(feature_seconds, 2), "total_seconds": round(time.perf_counter() - t_start, 1), "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), diff --git a/src/cryptoguard/ml/recency_validation.py b/src/cryptoguard/ml/recency_validation.py new file mode 100644 index 0000000..d106607 --- /dev/null +++ b/src/cryptoguard/ml/recency_validation.py @@ -0,0 +1,695 @@ +"""Phase 12.2 (``cryptoguard ml recency-validation``), as pre-registered in +docs/ml/protocol-12.2.md. Aggregate output only; 0 RPC requests. + +Every archive analysis here re-examines the Phase 12.1 episodes. It is retrospective +sensitivity analysis, never independent validation. H1 and H2 are the confirmatory tests, +H3 is descriptive, and everything else is exploratory and labelled so. +""" + +from __future__ import annotations + +import math +import random +import statistics +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any + +from cryptoguard.ml import lookalike_ranking as lr + +STUDY_VERSION = "recency-validation/1" +PROTOCOL = "protocol-12.2/1" +SEED = 20261103 +DAY = lr.DAY +PUBLIC_TOKENS = frozenset( + { + "0xdac17f958d2ee523a2206206994597c13d831ec7", # USDT + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", # USDC + "0x6b175474e89094c44da98b954eedeac495271d0f", # DAI + } +) +Feats = Mapping[str, Mapping[str, lr.Value]] +Scores = dict[str, float] + + +# --- the symmetric confirmation rule (protocol section 3) --------------------------------- + + +def _intended_rows(ep: lr.Episode, c: int) -> dict[str, list[int]]: + """Blocks of the victim's source-flagged intended rows at or before ``c``, by receiver.""" + from cryptoguard.ml.tsuchiya_archive import INTENDED + + out: defaultdict[str, list[int]] = defaultdict(list) + for r in ep.victim_out: + if r.flags & INTENDED and r.block <= c: + out[r.receiver].append(r.block) + return out + + +def confirmation_rule(ep: lr.Episode, c: int) -> dict[str, tuple[bool | None, bool | None]]: + """Per candidate at ``c``: ``(SR_any, SR_latest)``, both ``None`` when no planting of it + names an intended address. SR_any: some planting with intended address ``a`` comes + strictly after an intended row to ``a``. SR_latest: its latest planting comes after + the victim's latest intended row to any of its intended addresses.""" + intended = _intended_rows(ep, c) + by_l: defaultdict[str, list[lr.Row]] = defaultdict(list) + for r in ep.plantings: + if r.block <= c: + by_l[lr.lookalike_of(r, ep.victim)].append(r) + out: dict[str, tuple[bool | None, bool | None]] = {} + for lk, rows in by_l.items(): + named = [r for r in rows if r.intended and r.intended != lk] + if not named: + out[lk] = (None, None) + continue + sr_any = any(any(b < r.block for b in intended.get(r.intended or "", [])) for r in named) + latest = max(r.block for r in rows) + last_intended = max( + (max(intended[a]) for a in {r.intended for r in named} if a and a in intended), + default=None, + ) + out[lk] = (sr_any, last_intended is not None and latest > last_intended) + return out + + +# --- scoring helpers ---------------------------------------------------------------------- + + +def _top1(scores: Mapping[str, float] | None, paid: str, cands: Iterable[str]) -> float: + keys = list(cands) + if scores is None: + return 1.0 / len(keys) + return lr.top1({k: scores[k] for k in keys}, paid, len(keys)) + + +def _single(f: Feats, name: str, keep: Iterable[str] | None = None) -> Scores | None: + keys = list(f) if keep is None else list(keep) + vals = {k: f[k][name] for k in keys} + if any(v is None for v in vals.values()): + return None + return {k: float(v) for k, v in vals.items() if v is not None} + + +def _mean(xs: Sequence[float]) -> float | None: + return round(statistics.fmean(xs), 4) if xs else None + + +def _cmp( + t0: Sequence[float], b0: Sequence[float], grp: Sequence[int], *, n_perm: int = 10_000 +) -> dict[str, Any]: + d = [a - b for a, b in zip(t0, b0, strict=True)] + if not d: + return {"episodes": 0} + out = lr.paired(d, grp, seed=SEED, n_perm=n_perm) + out["T0_top1"] = _mean(t0) + out["B0_top1"] = _mean(b0) + return out + + +# --- archive-observation replay of the production detector (H2, E13) --------------------- + + +def production_cases(ep: lr.Episode, c: int) -> list[Any]: + """Run the unchanged production detector on the victim's archive rows at or before ``c``. + + The archive has no signers, no raw values and no in-block order, so: + - signers are unknown (``None``); + - the value is 0 for zero-value rows and 1 otherwise; + - the archive line stands in for the log index.""" + from cryptoguard.blockchain.erc20 import TransferEvent + from cryptoguard.core.address import to_checksum_address + from cryptoguard.detectors.poisoning import detect_poisoning + from cryptoguard.ml.tsuchiya_archive import ZERO + + rows = sorted( + {r for r in (*ep.plantings, *ep.victim_out) if r.block <= c}, + key=lambda r: (r.block, r.line), + ) + events = [ + TransferEvent( + token=to_checksum_address(r.token), + sender=to_checksum_address(r.sender), + recipient=to_checksum_address(r.receiver), + value=0 if r.flags & ZERO else 1, + block_number=r.block, + block_hash="", + transaction_hash=r.tx, + transaction_index=0, + log_index=r.line, + tx_sender=None, + ) + for r in rows + ] + return detect_poisoning(ep.victim, events, chain_id=1, wallet_is_plain_eoa=None) + + +def _op_top1(cases: Sequence[Any], paid: str, c: int) -> tuple[float, float]: + from cryptoguard.ml.warning_rank import baseline_score, recency_score + + k = len(cases) + # Exact integers: a float would lose the block resolution of the packed key. + s0: dict[str, float] = {x.suspect.lower(): _pack(baseline_score(x)) for x in cases} + s1: dict[str, float] = {x.suspect.lower(): _pack(recency_score(x, c)) for x in cases} + return lr.top1(s0, paid, k), lr.top1(s1, paid, k) + + +def _pack(t: tuple[int, ...]) -> int: + """Lexicographic tuple as one integer (each field < 10**10).""" + out = 0 + for x in t: + out = out * 10**10 + int(x) + return out + + +# --- recorded incidents (H3) and background windows (E14) --------------------------------- + + +def incidents() -> list[dict[str, Any]]: + from cryptoguard.detectors.poisoning import PoisoningConfig + from cryptoguard.ml.warning_rank import rank_warnings + from cryptoguard.replay.engine import Visibility, detector_outputs + from cryptoguard.replay.models import load_cases + + out = [] + for case in load_cases(): + if case.fixture is None: + continue + m = case.manifest + c = m.harm.block_number - 1 + cases, _ = detector_outputs( + case.fixture, c, Visibility.ERC20_PLUS_WALLET_TRANSACTIONS, PoisoningConfig() + ) + paid = m.harm.recipient.lower() + entry: dict[str, Any] = {"case": m.case_id, "warnings": len(cases)} + warned = [x for x in cases if x.suspect.lower() == paid] + entry["paid_warned"] = bool(warned) + if warned and len(cases) >= 2: + t0, t1 = _op_top1(cases, paid, c) + entry |= {"OP0_top1": round(t0, 4), "OP1_top1": round(t1, 4), "random": 1 / len(cases)} + ranked = rank_warnings(cases, c) + entry["OP1_display_rank"] = next(r.rank for r in ranked if r.suspect.lower() == paid) + entry["paid_basis"] = next(r.basis for r in ranked if r.suspect.lower() == paid) + out.append(entry) + return out + + +def background() -> dict[str, Any]: + from cryptoguard.detectors.poisoning import PoisoningConfig + from cryptoguard.ml.warning_rank import baseline_score, rank_warnings + from cryptoguard.replay.background import load_background + from cryptoguard.replay.engine import Visibility, detector_outputs + + t = time.perf_counter() + windows = multi = changed = preserved = no_basis = n = 0 + for b in load_background(): + if b.fixture is None: + continue + windows += 1 + c = b.fixture.to_block + cases, _ = detector_outputs( + b.fixture, c, Visibility.ERC20_PLUS_WALLET_TRANSACTIONS, PoisoningConfig() + ) + n += len(cases) + ranked = rank_warnings(cases, c) + preserved += sorted(r.suspect for r in ranked) == sorted(x.suspect for x in cases) + no_basis += sum(r.basis == "no_recency_basis" for r in ranked) + if len(cases) >= 2: + multi += 1 + base = sorted(cases, key=lambda x: (baseline_score(x), x.suspect.lower()), reverse=True) + changed += [x.suspect for x in base] != [r.suspect for r in ranked] + return { + "windows": windows, + "warnings": n, + "windows_with_2plus_warnings": multi, + "windows_order_changed": changed, + "windows_warning_set_preserved": preserved, + "warnings_without_recency_basis": no_basis, + "seconds": round(time.perf_counter() - t, 3), + } + + +# --- the study ------------------------------------------------------------------------------ + + +def _strata( + keys: Sequence[str], + grp: Sequence[int], + t0: Sequence[float], + b0: Sequence[float], + rnd: Sequence[float], +) -> dict[str, Any]: + by: defaultdict[str, list[int]] = defaultdict(list) + for i, k in enumerate(keys): + by[k].append(i) + return { + k: { + "episodes": len(ix), + "groups": len({grp[i] for i in ix}), + "T0": _mean([t0[i] for i in ix]), + "B0": _mean([b0[i] for i in ix]), + "random": _mean([rnd[i] for i in ix]), + } + for k, ix in sorted(by.items()) + } + + +def _restricted( + eps: Sequence[lr.Episode], + feats: Sequence[Feats], + grp: Sequence[int], + keep: Callable[[int, str], bool], +) -> dict[str, Any]: + """T0 vs B0 on candidate sets restricted by ``keep(episode index, candidate)``; an + episode counts when the paid candidate survives and k >= 2.""" + t0, b0, rnd, g = [], [], [], [] + dropped_paid = small = 0 + for i, (e, f) in enumerate(zip(eps, feats, strict=True)): + ks = [c for c in f if keep(i, c)] + if e.paid not in ks: + dropped_paid += 1 + continue + if len(ks) < 2: + small += 1 + continue + t0.append(_top1(_single(f, "T0", ks), e.paid, ks)) + b0.append(_top1(_single(f, "B0", ks), e.paid, ks)) + rnd.append(1 / len(ks)) + g.append(grp[i]) + out = _cmp(t0, b0, g, n_perm=2_000) + out |= {"random_top1": _mean(rnd), "paid_removed": dropped_paid, "fewer_than_2": small} + return out + + +def run(poisoning_dir: Path) -> dict[str, Any]: + t_start = time.perf_counter() + episodes, exclusions = lr.load_episodes(poisoning_dir) + tokens = lr.TokenIndex.build(episodes) + grp, linkage = lr.protocol_groups(episodes) + feats: list[Feats] = [] + for e in episodes: + fe = lr.candidate_features(e, lr.View(), None, tokens) + if fe is None: + raise RuntimeError("an eligible episode is not evaluable at the primary cutoff") + feats.append(fe) + n = len(episodes) + cut = [e.payoff_block - 1 for e in episodes] + t0 = [_top1(_single(f, "T0"), e.paid, f) for f, e in zip(feats, episodes, strict=True)] + b0 = [_top1(_single(f, "B0"), e.paid, f) for f, e in zip(feats, episodes, strict=True)] + rnd = [1 / len(f) for f in feats] + report: dict[str, Any] = { + "task": STUDY_VERSION, + "protocol": PROTOCOL, + "classification": "retrospective internal sensitivity analysis (previously examined)", + "episodes": n, + "distinct_victims": len({e.victim for e in episodes}), + "exclusions": exclusions, + "groups": { + "linkage": linkage, + "count": len(set(grp)), + "largest": max(Counter(grp).values()), + }, + "k": { + "mean": round(statistics.fmean(len(f) for f in feats), 2), + "median": statistics.median(len(f) for f in feats), + "bins": dict(Counter(_kbin(len(f)) for f in feats)), + }, + "R_all": _cmp(t0, b0, grp, n_perm=2_000) | {"random_top1": _mean(rnd)}, + } + + # Protected overlap (protocol section 7). + overlap = lr.protected_overlap(episodes, *lr.protected_entities(poisoning_dir)) + report["protected_overlap"] = {"episodes_linked": sum(overlap)} + + # H1: the symmetric confirmation rule. + sr = [confirmation_rule(e, cc) for e, cc in zip(episodes, cut, strict=True)] + manip: dict[str, Counter[str]] = {"paid": Counter(), "rival": Counter()} + for e, rule in zip(episodes, sr, strict=True): + for lk, (any_, lt) in rule.items(): + side = manip["paid" if lk == e.paid else "rival"] + side["candidates"] += 1 + side["any_true"] += any_ is True + side["any_none"] += any_ is None + side["latest_true"] += lt is True + report["manipulation_check"] = { + side: { + "candidates": m["candidates"], + "SR_any_true_share": round(m["any_true"] / m["candidates"], 4), + "SR_none_share": round(m["any_none"] / m["candidates"], 4), + "SR_latest_true_share": round(m["latest_true"] / m["candidates"], 4), + } + for side, m in manip.items() + } + h1_idx = [ + i + for i, (e, s) in enumerate(zip(episodes, sr, strict=True)) + if s[e.paid][0] is True and sum(1 for v in s.values() if v[0] is True) >= 2 + ] + + def sr_keep(i: int, c: str) -> bool: + return sr[i][c][0] is True + + h1_t0, h1_b0, h1_rnd, h1_full_t0, h1_full_b0 = [], [], [], [], [] + for i in h1_idx: + e, f = episodes[i], feats[i] + ks = [c for c in f if sr_keep(i, c)] + h1_t0.append(_top1(_single(f, "T0", ks), e.paid, ks)) + h1_b0.append(_top1(_single(f, "B0", ks), e.paid, ks)) + h1_rnd.append(1 / len(ks)) + h1_full_t0.append(t0[i]) + h1_full_b0.append(b0[i]) + h1g = [grp[i] for i in h1_idx] + h1 = _cmp(h1_t0, h1_b0, h1g) | {"random_top1": _mean(h1_rnd)} + full = _cmp(h1_full_t0, h1_full_b0, h1g, n_perm=2_000) + h1["delta_same_episodes_full_sets"] = round(full["mean"], 4) if h1_idx else None + h1["attenuation"] = ( + round((full["mean"] - h1["mean"]) / full["mean"], 4) if h1_idx and full["mean"] else None + ) + h1["excluded"] = { + "paid_SR_not_true": sum( + 1 for e, s in zip(episodes, sr, strict=True) if s[e.paid][0] is not True + ), + "fewer_than_2_SR_candidates": sum( + 1 + for e, s in zip(episodes, sr, strict=True) + if s[e.paid][0] is True and sum(1 for v in s.values() if v[0] is True) < 2 + ), + } + + # H2: production warnings, archive observation. + t = time.perf_counter() + h2_op0, h2_op1, h2_g, h2_idx = [], [], [], [] + warned: dict[str, Counter[str]] = {"paid": Counter(), "rival": Counter()} + for i, e in enumerate(episodes): + cases = production_cases(e, cut[i]) + sus = {x.suspect.lower() for x in cases} + for c in feats[i]: + w = warned["paid" if c == e.paid else "rival"] + w["candidates"] += 1 + w["warned"] += c in sus + if e.paid in sus and len(cases) >= 2: + op0, op1 = _op_top1(cases, e.paid, cut[i]) + h2_op0.append(op0) + h2_op1.append(op1) + h2_g.append(grp[i]) + h2_idx.append(i) + h2 = _cmp(h2_op1, h2_op0, h2_g) + h2 = { + **{k: v for k, v in h2.items() if k not in ("T0_top1", "B0_top1")}, + "OP1_top1": h2.get("T0_top1"), + "OP0_top1": h2.get("B0_top1"), + } + report["production_replay_seconds"] = round(time.perf_counter() - t, 1) + report["E13_operational_coverage"] = { + side: { + "candidates": w["candidates"], + "warned_share": round(w["warned"] / w["candidates"], 4), + } + for side, w in warned.items() + } | {"H2_eligible_episodes": len(h2_idx)} + + adj = lr.holm({"H1": h1["p"], "H2": h2["p"]}) if h1_idx and h2_idx else {} + for name, res in (("H1", h1), ("H2", h2)): + if name in adj: + res["p_holm"] = adj[name] + res["decision"] = _decision(res, adj[name]) + report["H1_symmetric_confirmation"] = h1 + report["H2_production_warnings"] = h2 + + # Sensitivity: H1 and H2 without protected overlap; H1 with SR_latest and with SR None. + clean = [i for i in range(n) if not overlap[i]] + report["H1_without_overlap"] = _restricted( + [episodes[i] for i in clean], + [feats[i] for i in clean], + [grp[i] for i in clean], + lambda j, c: sr[clean[j]][c][0] is True, + ) + report["H1_SR_latest"] = _restricted(episodes, feats, grp, lambda i, c: sr[i][c][1] is True) + report["H1_SR_none_included"] = _restricted( + episodes, feats, grp, lambda i, c: sr[i][c][0] is not False + ) + report["H3_incidents"] = incidents() + + # E1 within-episode permutation of T0; E2 reversed time. + rng = random.Random(SEED) # noqa: S311 - seeded research sampling, not security + perm: list[float] = [] + for f, e in zip(feats, episodes, strict=True): + t0_vals = [f[c]["T0"] for c in f] + acc = 0.0 + for _ in range(200): + rng.shuffle(t0_vals) + shuffled = {c: float(v or 0.0) for c, v in zip(f, t0_vals, strict=True)} + acc += lr.top1(shuffled, e.paid, len(f)) + perm.append(acc / 200) + rev = [ + _top1({c: -float(f[c]["T0"] or 0.0) for c in f}, e.paid, f) + for f, e in zip(feats, episodes, strict=True) + ] + report["E1_within_episode_permutation_top1"] = _mean(perm) + report["E2_oldest_first_top1"] = _mean(rev) + report["random_top1"] = _mean(rnd) + + # E3 timing jitter; E4 coarsening. + def gaps(e: lr.Episode, c: int, shift: Callable[[lr.Row], int]) -> dict[str, float]: + g: dict[str, int] = {} + for r in e.plantings: + if r.block <= c: + lk = lr.lookalike_of(r, e.victim) + b = min(c, r.block + shift(r)) + g[lk] = min(g.get(lk, 1 << 62), c - b) + return {k: float(v) for k, v in g.items()} + + jit: dict[str, float | None] = {} + for days in (1, 7): + j = days * DAY + vals: list[float] = [] + for e, cc in zip(episodes, cut, strict=True): + r2 = random.Random(f"{SEED}:{e.victim}:{days}") # noqa: S311 - seeded research + shifts: dict[int, int] = {} + + def shift( + r: lr.Row, s: dict[int, int] = shifts, rr: random.Random = r2, j: int = j + ) -> int: + return s.setdefault(r.line, rr.randint(-j, j)) + + gp = gaps(e, cc, shift) + vals.append(_top1({k: -v for k, v in gp.items()}, e.paid, gp)) + jit[f"jitter_{days}d"] = _mean(vals) + for days in (1, 7): + vals = [] + for e, cc in zip(episodes, cut, strict=True): + gp = gaps(e, cc, lambda _r: 0) + vals.append( + _top1({k: -math.floor(v / (days * DAY)) for k, v in gp.items()}, e.paid, gp) + ) + jit[f"coarsened_{days}d"] = _mean(vals) + report["E3_E4_timing"] = jit + + # E5 token class; E6 k bins; E9 strata. + def last_token(e: lr.Episode, lk: str, c: int) -> str: + rows = [r for r in e.plantings if r.block <= c and lr.lookalike_of(r, e.victim) == lk] + return max(rows, key=lambda r: (r.block, r.line)).token + + paid_cls = [ + "public_stablecoin" if last_token(e, e.paid, cc) in PUBLIC_TOKENS else "other" + for e, cc in zip(episodes, cut, strict=True) + ] + report["E5_paid_token_class"] = _strata(paid_cls, grp, t0, b0, rnd) + report["E5_public_token_candidates_only"] = _restricted( + episodes, feats, grp, lambda i, c: last_token(episodes[i], c, cut[i]) in PUBLIC_TOKENS + ) + report["E6_k"] = _strata([_kbin(len(f)) for f in feats], grp, t0, b0, rnd) + + # E7 symmetric maximum lookback; E8 no immediate copies. + def within(days: int) -> Callable[[int, str], bool]: + return lambda i, c: -(feats[i][c]["T0"] or 0) <= days * DAY + + report["E7_symmetric_lookback"] = { + f"{w}d": _restricted(episodes, feats, grp, within(w)) for w in (30, 90, 180) + } + non_imm = [i for i in range(n) if -(feats[i][episodes[i].paid]["T0"] or 0) >= 300] + report["E8_paid_gap_at_least_300_blocks"] = _cmp( + [t0[i] for i in non_imm], [b0[i] for i in non_imm], [grp[i] for i in non_imm], n_perm=2_000 + ) | { + "random_top1": _mean([rnd[i] for i in non_imm]), + "label": "stratified on an outcome attribute", + } + + from cryptoguard.ml.lookalike_study import _year, subtype + + activity = [ + sum(1 for r in e.victim_out if r.block <= cc) for e, cc in zip(episodes, cut, strict=True) + ] + q1, q2 = statistics.quantiles(activity, n=3) + newest = [min(-(v["T0"] or 0) for v in f.values()) for f in feats] + largest_share = max(Counter(grp).values()) / n + report["E9_strata"] = { + "year": _strata([_year(e.payoff_block) for e in episodes], grp, t0, b0, rnd), + "paid_subtype": _strata([subtype(e) for e in episodes], grp, t0, b0, rnd), + "victim_activity_tertile": _strata( + ["low" if a <= q1 else "mid" if a <= q2 else "high" for a in activity], grp, t0, b0, rnd + ), + "newest_candidate_age": _strata([_agebin(x) for x in newest], grp, t0, b0, rnd), + "largest_group_share": round(largest_share, 4), + } + + # E10 negative control. + nc = [_top1(_single(f, "NC"), e.paid, f) for f, e in zip(feats, episodes, strict=True)] + rho = [] + for f in feats: + if len(f) >= 3: + r_ = _spearman([f[c]["NC"] or 0.0 for c in f], [f[c]["T0"] or 0.0 for c in f]) + if r_ is not None: + rho.append(r_) + same_cls = [ + i + for i, (e, f) in enumerate(zip(episodes, feats, strict=True)) + if len({last_token(e, c, cut[i]) in PUBLIC_TOKENS for c in f}) == 1 + ] + report["E10_negative_control"] = { + "NC_top1": _mean(nc), + "random_top1": _mean(rnd), + "by_paid_token_class": { + k: { + "episodes": len(ix), + "NC": _mean([nc[i] for i in ix]), + "random": _mean([rnd[i] for i in ix]), + } + for k in ("public_stablecoin", "other") + for ix in ([i for i in range(n) if paid_cls[i] == k],) + }, + "within_episode_spearman_NC_T0": { + "episodes": len(rho), + "mean": _mean(rho), + "median": round(statistics.median(rho), 4) if rho else None, + }, + "candidates_share_token_class": { + "episodes": len(same_cls), + "NC": _mean([nc[i] for i in same_cls]), + "random": _mean([rnd[i] for i in same_cls]), + }, + } + + # E11 history perturbations. + def t0_on(eps: Sequence[lr.Episode]) -> tuple[float | None, int]: + vals = [] + for e in eps: + f = lr.candidate_features(e, lr.View(), None, None) + if f is not None: + vals.append(_top1(_single(f, "T0"), e.paid, f)) + return _mean(vals), len(vals) + + def drop_latest(e: lr.Episode) -> lr.Episode: + latest: dict[str, lr.Row] = {} + for r in e.plantings: + lk = lr.lookalike_of(r, e.victim) + if lk not in latest or (r.block, r.line) > (latest[lk].block, latest[lk].line): + latest[lk] = r + gone = set(latest.values()) + return replace(e, plantings=tuple(r for r in e.plantings if r not in gone)) + + def duplicate(e: lr.Episode) -> lr.Episode: + return replace( + e, plantings=e.plantings + tuple(replace(r, line=r.line + 10**9) for r in e.plantings) + ) + + def reorder(e: lr.Episode) -> lr.Episode: + rr = random.Random(f"{SEED}:{e.victim}:reorder") # noqa: S311 - seeded research + by_b: defaultdict[int, list[lr.Row]] = defaultdict(list) + for r in e.plantings: + by_b[r.block].append(r) + out = [] + for _b, rows in by_b.items(): + lines = [r.line for r in rows] + rr.shuffle(lines) + out += [replace(r, line=ln) for r, ln in zip(rows, lines, strict=True)] + return replace(e, plantings=tuple(out)) + + base_t0 = _mean(t0) + e11: dict[str, Any] = {"primary_T0_top1": base_t0} + for name, fn in ( + ("drop_latest_planting", drop_latest), + ("duplicate_rows", duplicate), + ("reorder_within_block", reorder), + ): + v, k = t0_on([fn(e) for e in episodes]) + e11[name] = {"T0_top1": v, "evaluable": k} + report["E11_history_perturbations"] = e11 + + # E12 errors (top-1 == 1 means the paid candidate alone at the top). + cells: Counter[str] = Counter() + cats: dict[str, Counter[str]] = defaultdict(Counter) + for i, (e, f) in enumerate(zip(episodes, feats, strict=True)): + cell = f"T0_{'hit' if t0[i] == 1.0 else 'miss'}__B0_{'hit' if b0[i] == 1.0 else 'miss'}" + cells[cell] += 1 + cat = cats[cell] + gap = -(f[e.paid]["T0"] or 0) + cat["paid_gap_over_30d"] += gap > 30 * DAY + cat["two_plus_candidates_within_1d"] += ( + sum(1 for v in f.values() if -(v["T0"] or 0) <= DAY) >= 2 + ) + cat["paid_planted_more_than_once"] += (f[e.paid]["T1"] or 0) >= 2 + cat["k_6_plus"] += len(f) >= 6 + cat["B0_tied_at_top"] += 0 < b0[i] < 1 + report["E12_errors"] = {k: {"episodes": v, **cats[k]} for k, v in sorted(cells.items())} + + report["E14_background"] = background() + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + peak = peak_rss_bytes() + report["resources"] = { + "total_seconds": round(time.perf_counter() - t_start, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + "rpc_requests": 0, + "graph_used": False, + } + return report + + +def _decision(diff: Mapping[str, Any], p_holm: float, margin: float = 0.05) -> str: + """Protocol 12.2 section 4.""" + lo, hi = diff["ci95"] + if p_holm < 0.05 and lo > 0 and diff["mean"] >= margin: + return "survives" + if (-margin < lo and hi < margin) or (diff["mean"] <= 0 and hi < margin): + return "explained_or_null" + return "inconclusive" + + +def _kbin(k: int) -> str: + return "2" if k == 2 else "3-5" if k <= 5 else "6+" + + +def _agebin(gap: float) -> str: + if gap < 300: + return "a_under_1h" + if gap < DAY: + return "b_1h_to_1d" + if gap < 7 * DAY: + return "c_1d_to_7d" + return "d_over_7d" + + +def _spearman(x: Sequence[float], y: Sequence[float]) -> float | None: + def ranks(v: Sequence[float]) -> list[float]: + order = sorted(range(len(v)), key=lambda i: v[i]) + r = [0.0] * len(v) + i = 0 + while i < len(order): + j = i + while j + 1 < len(order) and v[order[j + 1]] == v[order[i]]: + j += 1 + for m in range(i, j + 1): + r[order[m]] = (i + j) / 2 + i = j + 1 + return r + + rx, ry = ranks(x), ranks(y) + mx, my = statistics.fmean(rx), statistics.fmean(ry) + sx = math.sqrt(sum((a - mx) ** 2 for a in rx)) + sy = math.sqrt(sum((b - my) ** 2 for b in ry)) + if sx == 0 or sy == 0: + return None + return sum((a - mx) * (b - my) for a, b in zip(rx, ry, strict=True)) / (sx * sy) diff --git a/src/cryptoguard/ml/warning_rank.py b/src/cryptoguard/ml/warning_rank.py new file mode 100644 index 0000000..651eab4 --- /dev/null +++ b/src/cryptoguard/ml/warning_rank.py @@ -0,0 +1,135 @@ +"""Experimental recency ordering of production poisoning warnings (``poisoning-warning-rank/1``). + +Research only (protocol ``docs/ml/protocol-12.2.md``). It takes the cases the production +detector already produced and returns a display order for an experimental view. It never: +- adds, removes, merges or re-tiers a warning; +- changes a case object; +- emits a probability. + +Ordering: +1. Severity tier, as production assigns it. +2. Within a tier, the recency of the warning's latest *planting* signal at or before the + cutoff: a zero-value transfer, a spoofed outgoing transfer or an unsolicited incoming + transfer. The wallet's own sends never count. +3. Ties break by prefix+suffix descending, then by address. That is deterministic for + display only; the research metric keeps them tied. + +A warning with no planting signal at or before the cutoff has no recency basis. It is placed +after its tier's warnings that have one, in baseline order, and is marked +``no_recency_basis``. + +Phase 12.1 found that recency put the paid lookalike first among *source-flagged* candidates +in a payoff-conditioned archive. That is a retrospective ranking result, not a fraud +probability and not a validated warning policy. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Literal + +from cryptoguard.detectors.poisoning import PoisoningCase +from cryptoguard.risk.rules import Severity + +RANK_VERSION = "poisoning-warning-rank/1" +TASK = "poisoning-warning-rank/1" +PLANTING_SIGNALS = frozenset( + {"zero_value_transfer", "spoofed_outgoing_transfer", "unsolicited_incoming_transfer"} +) +TIER = { + Severity.CRITICAL_EVIDENCE: 4, + Severity.ELEVATED_RISK: 3, + Severity.REVIEW_RECOMMENDED: 2, + Severity.INFORMATIONAL: 1, + Severity.UNKNOWN: 0, +} + +Basis = Literal["latest_planting_signal", "no_recency_basis"] + + +@dataclass(frozen=True) +class RankedWarning: + rank: int # 1-based display position in the experimental view + suspect: str + rule_id: str + severity: str + similarity: int # prefix + suffix, as production computed it + basis: Basis + basis_block: int | None + basis_transaction: str | None + blocks_before_cutoff: int | None + cutoff_block: int + algorithm: str + explanation: str + + +def planting_basis(case: PoisoningCase, cutoff: int) -> tuple[int, str | None] | None: + """The block (and transaction) of the case's latest planting signal at or before + ``cutoff``; ``None`` when it has none.""" + best: tuple[int, str | None] | None = None + for s in case.signals: + if s.code not in PLANTING_SIGNALS or s.block_number is None or s.block_number > cutoff: + continue + if best is None or s.block_number > best[0]: + best = (s.block_number, s.transaction_hash) + return best + + +def baseline_score(case: PoisoningCase) -> tuple[int, int]: + """OP0: severity tier, then prefix+suffix.""" + return TIER.get(case.severity, 0), case.prefix_match + case.suffix_match + + +def recency_score(case: PoisoningCase, cutoff: int) -> tuple[int, int, int]: + """OP1: severity tier, then (has a basis, basis block); without a basis, prefix+suffix + keeps the baseline order behind the warnings that have one.""" + tier, similarity = baseline_score(case) + basis = planting_basis(case, cutoff) + return (tier, 1, basis[0]) if basis is not None else (tier, 0, similarity) + + +def rank_warnings(cases: Sequence[PoisoningCase], cutoff: int) -> list[RankedWarning]: + """Every case, in the experimental order. The output always holds the same warnings as + the input.""" + keyed = sorted( + cases, + key=lambda c: ( + recency_score(c, cutoff), + c.prefix_match + c.suffix_match, + # Address ascending as the final tie-break: negate via sort on a reversed key. + tuple(-ord(ch) for ch in c.suspect.lower()), + ), + reverse=True, + ) + out: list[RankedWarning] = [] + for i, c in enumerate(keyed, start=1): + basis = planting_basis(c, cutoff) + if basis is None: + explanation = ( + "No planting signal at or before the cutoff: kept in baseline order within " + "its severity tier." + ) + else: + explanation = ( + f"Within severity {c.severity.value}, ordered by its latest planting signal at " + f"block {basis[0]} ({cutoff - basis[0]} blocks before cutoff {cutoff}), " + f"against {len(cases) - 1} other warning(s). Ordering only: not a probability." + ) + out.append( + RankedWarning( + rank=i, + suspect=c.suspect, + rule_id=c.rule_id, + severity=c.severity.value, + similarity=c.prefix_match + c.suffix_match, + basis="no_recency_basis" if basis is None else "latest_planting_signal", + basis_block=None if basis is None else basis[0], + basis_transaction=None if basis is None else basis[1], + blocks_before_cutoff=None if basis is None else cutoff - basis[0], + cutoff_block=cutoff, + algorithm=RANK_VERSION, + explanation=explanation, + ) + ) + return out diff --git a/tests/test_ml_lookalike_ranking.py b/tests/test_ml_lookalike_ranking.py index 3ae5185..47fb1a0 100644 --- a/tests/test_ml_lookalike_ranking.py +++ b/tests/test_ml_lookalike_ranking.py @@ -271,6 +271,58 @@ def test_protected_overlap_is_direct_or_through_a_linkage_group() -> None: ] +def test_preloaded_graph_equals_the_lazy_index_on_random_rows() -> None: + import random + + rng = random.Random(7) + addrs = [f"0x{i:040x}" for i in range(1, 13)] + txs = [f"0x{i:064x}" for i in range(1, 9)] + flags = (ZERO, TINY, COUNTERFEIT, PAYOFF, INTENDED, ZERO | PAYOFF) + rows = [ + row( + rng.randrange(100, 400), + rng.choice(addrs), + rng.choice(addrs), + rng.choice(flags), + tx=rng.choice(txs), + siv=rng.choice((True, False, None)), + ) + for _ in range(600) + ] + rows += rows[:20] # exact duplicates + exclude = frozenset(addrs[:2]) + edges = lr.preload_graph(rows, addrs, txs, exclude) + for keep_row, keep_edge in ( + (None, None), + (lr.graph_keep(0.5, 3), lr.graph_keep_edge(0.5, 3)), + (lambda r: r.block <= 250, lambda b, _l: b <= 250), + ): + by_addr: dict[str, list[lr.Row]] = {} + by_tx: dict[str, list[lr.Row]] = {} + for r in rows: + for a in {r.sender, r.receiver}: + by_addr.setdefault(a, []).append(r) + by_tx.setdefault(r.tx, []).append(r) + lazy = lr.GraphIndex( + lambda a, m=by_addr: m.get(a, []), + lambda t, m=by_tx: m.get(t, []), + keep=keep_row, + exclude=exclude, + ) + pre = edges.index(keep_edge) + for cutoff in (150, 300, 399): + for since in (None, 200): + for a in addrs: + assert pre.prior_victims(a, cutoff, since) == lazy.prior_victims( + a, cutoff, since + ) + assert pre.prior_payers(a, cutoff, since) == lazy.prior_payers(a, cutoff, since) + for tx in txs: + assert pre.tx_victims(tx, cutoff) == lazy.tx_victims(tx, cutoff) + with pytest.raises(KeyError): + edges.index().prior_victims("0x" + "9" * 40, 300) + + def test_token_index_negative_control() -> None: e1 = episode() e2 = replace(e1, victim=OTHER) @@ -516,6 +568,39 @@ def test_study_runs_end_to_end_on_synthetic_data( assert report["methods"]["T0"]["all"]["top1"] == pytest.approx(15 / 29, abs=1e-4) assert report["methods"]["random"]["all"]["top1"] == 0.5 assert report["resources"]["rpc_requests"] == 0 + assert report["resources"]["graph_mode"] == "preloaded" + # Exactness: the Phase 12.1 lazy lookups give the same report. + lazy = ls.run(d, lazy_graph=True) + assert ls.comparable(lazy) == ls.comparable(report) gap = report["recency_gap_posthoc"] assert gap["paid_gap_blocks"]["max"] == 199.0 # (b + 299) - (b + 100), by design assert gap["paid_gap_over_30d"]["episodes"] == 0 + + +def test_recency_validation_runs_end_to_end_on_synthetic_data( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from cryptoguard.ml import recency_validation as rv + + d = _synthetic_dir(tmp_path) + protected = "0x" + f"{1:040x}" + monkeypatch.setattr(lr, "protected_wallets", lambda _d: frozenset({protected})) + monkeypatch.setattr(lr, "protected_entities", lambda _d: (frozenset({protected}), frozenset())) + report = rv.run(d) + assert report["episodes"] == 29 + # Both lookalikes plant after the victim's intended transfer, so the symmetric rule keeps + # every candidate and H1 sees exactly the full sets. + assert report["manipulation_check"]["paid"]["SR_any_true_share"] == 1.0 + h1 = report["H1_symmetric_confirmation"] + assert h1["episodes"] == 29 + assert h1["T0_top1"] == report["R_all"]["T0_top1"] + assert h1["attenuation"] == 0.0 + assert h1["decision"] in {"survives", "explained_or_null", "inconclusive"} + # Exact duplicates and same-block reordering cannot move recency. + e11 = report["E11_history_perturbations"] + assert e11["duplicate_rows"]["T0_top1"] == e11["primary_T0_top1"] + assert e11["reorder_within_block"]["T0_top1"] == e11["primary_T0_top1"] + assert report["E1_within_episode_permutation_top1"] == pytest.approx(0.5, abs=0.05) + bg = report["E14_background"] + assert bg["windows_warning_set_preserved"] == bg["windows"] + assert report["resources"]["rpc_requests"] == 0 diff --git a/tests/test_ml_recency_validation.py b/tests/test_ml_recency_validation.py new file mode 100644 index 0000000..f2d38cb --- /dev/null +++ b/tests/test_ml_recency_validation.py @@ -0,0 +1,213 @@ +"""Phase 12.2: the symmetric confirmation rule, the experimental warning ranking and its +safety invariants, and the decision rules. Synthetic rows and packaged fixtures only.""" + +from __future__ import annotations + +import itertools + +import pytest + +from cryptoguard.detectors.poisoning import PoisoningCase, PoisoningSignal +from cryptoguard.ml import lookalike_ranking as lr +from cryptoguard.ml import recency_validation as rv +from cryptoguard.ml import warning_rank as wr +from cryptoguard.ml.tsuchiya_archive import INTENDED, PAYOFF, TINY, ZERO +from cryptoguard.risk.rules import Confidence, Severity + +V = "0x" + "a" * 40 +R = "0x1234" + "0" * 32 + "abcd" +L1 = "0x1234" + "f" * 32 + "abcd" +L2 = "0x1234" + "e" * 32 + "abcd" +L3 = "0x1234" + "d" * 32 + "abcd" +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +_line = itertools.count(1) + + +def row(block: int, sender: str, receiver: str, flags: int, intended: str | None = None) -> lr.Row: + n = next(_line) + siv = sender == V + return lr.Row(n, block, f"0x{n:064x}", USDT, sender, receiver, siv, None, flags, intended) + + +def episode(rows: list[lr.Row]) -> lr.Episode: + ep = lr.episode_from_rows(V, rows) + assert isinstance(ep, lr.Episode), ep + return ep + + +# --- the symmetric confirmation rule ----------------------------------------------------- + + +def test_confirmation_rule_needs_a_planting_strictly_after_an_intended_transfer() -> None: + ep = episode( + [ + row(100, V, R, INTENDED), + row(150, L1, V, ZERO, intended=R), # after the intended row: confirmable + row(90, L2, V, TINY, intended=R), # before it: not confirmable + row(100, L3, V, ZERO, intended=R), # same block: order unknown, not counted + row(160, "0x" + "5" * 40, V, ZERO), # no intended address: not evaluable + row(300, V, L1, PAYOFF), + ] + ) + sr = rv.confirmation_rule(ep, 299) + assert sr[L1] == (True, True) + assert sr[L2] == (False, False) + assert sr[L3] == (False, False) + assert sr["0x" + "5" * 40] == (None, None) + + +def test_confirmation_rule_latest_variant_uses_the_latest_intended_row() -> None: + ep = episode( + [ + row(100, V, R, INTENDED), + row(150, L1, V, ZERO, intended=R), + row(200, V, R, INTENDED), # a later intended row: L1's planting is now older + row(210, L2, V, ZERO, intended=R), + row(300, V, L2, PAYOFF), + ] + ) + sr = rv.confirmation_rule(ep, 299) + assert sr[L1] == (True, False) + assert sr[L2] == (True, True) + # Rows after the cutoff never count. + assert rv.confirmation_rule(ep, 199)[L1] == (True, True) + + +# --- the experimental warning ranking ---------------------------------------------------- + + +def case( + suspect: str, + severity: Severity, + signals: list[tuple[str, int | None]], + prefix: int = 4, + suffix: int = 4, +) -> PoisoningCase: + return PoisoningCase( + suspect=suspect, + reference=R, + reference_confirmed=True, + reference_first_used_block=1, + prefix_match=prefix, + suffix_match=suffix, + displayed_as="x", + random_match_odds="1", + signals=[ + PoisoningSignal(code=c, description="", transaction_hash=None, block_number=b) + for c, b in signals + ], + rule_id="poisoning", + severity=severity, + confidence=Confidence.MEDIUM, + explanation="", + recommended_action="", + first_seen_block=1, + ) + + +def test_ranking_keeps_every_warning_and_never_lowers_a_severity_tier() -> None: + old_critical = case(L1, Severity.CRITICAL_EVIDENCE, [("zero_value_transfer", 10)]) + recent_review = case(L2, Severity.REVIEW_RECOMMENDED, [("zero_value_transfer", 99)]) + no_basis = case(L3, Severity.CRITICAL_EVIDENCE, [("sent_to_lookalike", 50)]) + cases = [recent_review, no_basis, old_critical] + before = [c.model_dump() for c in cases] + ranked = wr.rank_warnings(cases, cutoff=100) + assert sorted(r.suspect for r in ranked) == sorted(c.suspect for c in cases) + assert [r.suspect for r in ranked] == [L1, L3, L2] # tier first; no basis after basis + assert ranked[1].basis == "no_recency_basis" + assert ranked[0].blocks_before_cutoff == 90 + assert "not a probability" in ranked[0].explanation + assert [c.model_dump() for c in cases] == before # inputs untouched + + +def test_own_sends_and_signals_after_the_cutoff_are_not_a_basis() -> None: + c = case(L1, Severity.ELEVATED_RISK, [("sent_to_lookalike", 90), ("zero_value_transfer", 120)]) + assert wr.planting_basis(c, 100) is None + c2 = case( + L1, + Severity.ELEVATED_RISK, + [("unsolicited_incoming_transfer", 40), ("spoofed_outgoing_transfer", 70)], + ) + assert wr.planting_basis(c2, 100) == (70, None) + assert ( + wr.planting_basis(case(L1, Severity.ELEVATED_RISK, [("zero_value_transfer", None)]), 100) + is None + ) + + +def test_ties_break_deterministically_by_similarity_then_address() -> None: + a = case(L2, Severity.ELEVATED_RISK, [("zero_value_transfer", 50)], prefix=4, suffix=4) + b = case(L1, Severity.ELEVATED_RISK, [("zero_value_transfer", 50)], prefix=4, suffix=4) + c = case(L3, Severity.ELEVATED_RISK, [("zero_value_transfer", 50)], prefix=5, suffix=5) + for order in itertools.permutations([a, b, c]): + assert [r.suspect for r in wr.rank_warnings(list(order), 100)] == [L3, L2, L1] + + +def test_research_metric_keeps_ties_and_resolves_single_blocks() -> None: + a = case(L1, Severity.ELEVATED_RISK, [("zero_value_transfer", 20_000_000)]) + b = case(L2, Severity.ELEVATED_RISK, [("zero_value_transfer", 20_000_001)]) + op0, op1 = rv._op_top1([a, b], L2.lower(), 20_000_005) + assert op0 == 0.5 # same tier and similarity: tied + assert op1 == 1.0 # one block more recent: exact, no float rounding + + +def test_ranking_of_recorded_incident_ignores_rows_after_the_cutoff() -> None: + from cryptoguard.detectors.poisoning import PoisoningConfig + from cryptoguard.replay.engine import Visibility, detector_outputs + from cryptoguard.replay.models import load_cases + + fx = next(c for c in load_cases() if c.fixture is not None) + assert fx.fixture is not None + cut = fx.manifest.harm.block_number - 1 + full = fx.fixture + trimmed = full.model_copy( + update={"transfers": [t for t in full.transfers if t.block_number <= cut]} + ) + vis, cfg = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS, PoisoningConfig() + a = wr.rank_warnings(detector_outputs(full, cut, vis, cfg)[0], cut) + b = wr.rank_warnings(detector_outputs(trimmed, cut, vis, cfg)[0], cut) + assert a == b + assert len(a) >= 2 + + +# --- production replay on archive rows, decisions, helpers ------------------------------- + + +def test_production_detector_runs_on_archive_rows_before_the_cutoff_only() -> None: + ep = episode( + [ + row(100, V, R, INTENDED), + row(150, L1, V, ZERO, intended=R), + row(160, L3, V, ZERO, intended=R), + row(300, V, L1, PAYOFF), + ] + ) + suspects = {c.suspect.lower() for c in rv.production_cases(ep, 299)} + assert {L1, L3} <= suspects + early = {c.suspect.lower() for c in rv.production_cases(ep, 155)} + assert L1 in early + assert L3 not in early # planted at 160, after this cutoff + + +@pytest.mark.parametrize( + ("mean", "ci", "p", "expected"), + [ + (0.2, (0.1, 0.3), 0.001, "survives"), + (0.01, (-0.03, 0.04), 0.5, "explained_or_null"), + (-0.1, (-0.2, 0.02), 0.01, "explained_or_null"), + (0.04, (0.01, 0.07), 0.01, "inconclusive"), + (0.2, (0.1, 0.3), 0.2, "inconclusive"), + ], +) +def test_phase_12_2_decision_rule( + mean: float, ci: tuple[float, float], p: float, expected: str +) -> None: + assert rv._decision({"mean": mean, "ci95": list(ci)}, p) == expected + + +def test_spearman_and_bins() -> None: + assert rv._spearman([1, 2, 3], [3, 2, 1]) == pytest.approx(-1.0) + assert rv._spearman([1, 1, 1], [1, 2, 3]) is None + assert rv._agebin(299) == "a_under_1h" + assert rv._agebin(7 * lr.DAY) == "d_over_7d" + assert rv._kbin(2) == "2" From ff9f2e33e713f458f957c1938d70648aff79249b Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 11:21:45 +0300 Subject: [PATCH 45/92] fix(ml): mypy in coverage_symmetry's single pass The loop variable shadowed the Counter used later in the same function (introduced in 623b36d; values were unaffected). Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/lookalike_study.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cryptoguard/ml/lookalike_study.py b/src/cryptoguard/ml/lookalike_study.py index ffd969f..bae264e 100644 --- a/src/cryptoguard/ml/lookalike_study.py +++ b/src/cryptoguard/ml/lookalike_study.py @@ -310,8 +310,8 @@ def coverage_symmetry( blocks: defaultdict[str, list[int]] = defaultdict(list) for r in lr.sqlite_rows(gpath): lines.add(r.line) - for a in {r.sender, r.receiver} & looks: - blocks[a].append(r.block) + for addr in {r.sender, r.receiver} & looks: + blocks[addr].append(r.block) for v in blocks.values(): v.sort() con = sqlite3.connect(f"file:{gpath.as_posix()}?mode=ro", uri=True) From c0e10123fa79214829a8377272dffe39ebbf8a06 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 11:21:47 +0300 Subject: [PATCH 46/92] docs(ml): Phase 12.2 recency validation report ML_RECENCY_VALIDATION.md reports the pre-registered study (protocol 03f1c1d; aggregates only, 0 RPC requests). H1: recency survives the source's payoff confirmation rule applied to every rival (top-1 0.682 vs 0.300, attenuation 0.2%). H2: within severity tiers, recency orders the production detector's own warnings better than similarity (0.502 vs 0.267). 3 of 3 rankable recorded incidents rank the stolen-funds recipient first (descriptive). All archive evidence re-examines Phase 12.1 episodes: source-conditional retrospective effect; the independence gate is blocked by data. Deviation D1 (H2 not repeated without the 1 overlap episode) recorded. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 + ML.md | 12 + ML_RECENCY_VALIDATION.md | 514 ++++++++++++++++++++++++++++ ML_RESEARCH_PLAN.md | 28 ++ docs/ml/protocol-12.2-deviations.md | 21 ++ 5 files changed, 594 insertions(+) create mode 100644 ML_RECENCY_VALIDATION.md create mode 100644 docs/ml/protocol-12.2-deviations.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c4fc970..61c3172 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,25 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Recency validation and experimental warning ordering (Phase 12.2) +- **Pre-registered study** `recency-validation/1`, run with + `cryptoguard ml recency-validation`. It produces aggregate output and makes 0 RPC + requests. +- **H1:** recency survives when every rival faces the source's own payoff-confirmation rule. + Top-1 is 0.682 against 0.300, and the rule attenuates the effect by 0.2%. +- **H2:** on the production detector's own warnings, ordering by severity then recency beats + ordering by severity then similarity: 0.502 against 0.267. +- **Status:** retrospective sensitivity analysis of previously examined data. No independent + validation was possible. Report: ML_RECENCY_VALIDATION.md. +- **Experimental ranker** `ml/warning_rank.py` (`poisoning-warning-rank/1`): + - orders warnings by severity tier, then by the latest planting signal; + - never removes or re-tiers a warning; + - is not wired into any production path. +- **Performance:** the graph is preloaded in one sequential pass, which reproduces Phase 12.1 + exactly (same result hash). + - The Phase 12.1 study drops from 8,157 s to 179 s, and from 744 to 485 MiB. + - The lazy per-address SQLite lookups are kept as `--lazy-graph`. + ### Temporal and graph lookalike prioritization (Phase 12.1) - Pre-registered study `lookalike-prioritization/1`, run with `cryptoguard ml lookalike-study` (aggregate output, 0 RPC requests). It ranks the diff --git a/ML.md b/ML.md index 6e8a858..a5592c5 100644 --- a/ML.md +++ b/ML.md @@ -272,6 +272,18 @@ This is a retrospective, payoff-conditioned result. Nothing is integrated: the production detector and its warnings are unchanged. Details are in [ML_TEMPORAL_GRAPH_RESEARCH.md](ML_TEMPORAL_GRAPH_RESEARCH.md). +## Phase 12.2: recency validation (research only) + +Recency was tested two ways. Both results come from previously examined archive episodes, +so they are not independent validation. +- **Selection artifact (H1):** recency survives the source's payoff-confirmation rule + applied to rivals too. Top-1 is 0.682 against similarity's 0.300. +- **Production warnings (H2):** within severity tiers, recency orders the production + detector's own warnings better than similarity does: 0.502 against 0.267. +- **Experimental ranker:** `ml/warning_rank.py` is experimental, not wired in, and never + removes or re-tiers a warning. +- **Details:** [ML_RECENCY_VALIDATION.md](ML_RECENCY_VALIDATION.md). + ## Limitations - One labelled source, with a benign class of prominent accounts; precision on real traffic diff --git a/ML_RECENCY_VALIDATION.md b/ML_RECENCY_VALIDATION.md new file mode 100644 index 0000000..df0f617 --- /dev/null +++ b/ML_RECENCY_VALIDATION.md @@ -0,0 +1,514 @@ +# Recency validation and operational warning ranking (Phase 12.2) + +| Item | Value | +|---|---| +| Protocol (frozen before any 12.2 outcome) | [`docs/ml/protocol-12.2.md`](docs/ml/protocol-12.2.md), commit `03f1c1d` | +| Analysis code (committed before it ran) | `623b36d`: `ml/recency_validation.py`, `ml/warning_rank.py`, `cryptoguard ml recency-validation` | +| Outputs (git-ignored, aggregates) | `data/ml/research/phase12.2/`: `recency-validation.json`, `exactness.json`, `lookalike-study-preloaded.json` | +| Phase 12.1 outputs | preserved unchanged in `data/ml/research/phase12.1/` | +| RPC requests / downloads | 0 / none | +| Production detector | unchanged; nothing is wired into it | + +**Scope.** This phase re-examines the archive episodes whose outcomes Phase 12.1 already +saw. Every archive result below is therefore a **retrospective internal sensitivity +analysis, not independent validation**. "Top-1" means the paid lookalike ranked first among +the candidates of a retrospective episode. It is not detection accuracy, precision, recall, +an FPR or a prevented loss. + +## 1. Executive summary + +**Result: a source-conditional retrospective effect, which fails the independence gate.** + +Q1 asked whether recency is an artifact of how the source confirmed payoffs. The source says +it confirmed a payoff by checking that a "poisoning transfer exists between the intended and +the payoff transfer". Applying that rule to rivals as well removes almost nothing (H1): + +| H1 | Recency (T0) | Production similarity (B0) | Difference [95% CI] | +|---|---|---|---| +| Rule as written (primary) | 0.682 | 0.300 | +0.382 [0.347, 0.417] | +| Stricter reading: latest planting after the latest intended transfer | 0.671 | 0.332 | +0.339 [0.300, 0.379] | + +- Primary: 1,059 episodes, Holm p = 0.0002, decision *survives*. +- Under the rule as written, the restriction attenuates the effect by 0.2%. 99.4% of rivals + also satisfy the rule, so it is not selective and cannot explain recency. +- The stricter reading is selective (95.9% of paid lookalikes, 61.1% of rivals), yet recency + still survives on its 910 episodes. + +Q2 asked whether the candidates were available at the cutoff. All candidates and features +are taken at or before the cutoff. +- When the unchanged production detector runs on the archive rows at the cutoff, it warns + on 99.2% of paid and 99.2% of rival lookalikes. +- So the candidate sets are, to that extent, what CryptoGuard itself would raise from this + stream. + +Q3 asked about generalization. There is **no untouched outcome dataset**. +- The only external data are the 4 recorded incidents, and 3 of them have at least 2 + warnings. +- In all 3, recency ordering puts the stolen-funds recipient first. Production order does + so in 1 of 3. +- This is descriptive, n = 3. + +Q4 asked about operational use. Ordering production warnings by severity tier, then +recency, puts the paid lookalike first more often than ordering by severity, then +similarity (H2): + +| H2 (1,057 episodes) | Top-1 | +|---|---| +| OP1: severity, then recency | 0.502 | +| OP0: severity, then similarity | 0.267 | +| Difference [95% CI] | +0.235 [0.208, 0.263], Holm p = 0.0002 | + +The ranker never removes or re-tiers a warning. It stays experimental and off by default. + +**Engineering.** The Phase 12.1 study now reproduces exactly (same result hash) in 179 s +instead of 8,157 s, and at 485 MiB instead of 744 MiB. The whole Phase 12.2 study runs in +38 s. + +## 2. Phase 12.1 baseline, verified + +The saved report, SHA-256 `94734a71…`, is reproduced exactly (§17–18). + +| Test split, 428 episodes | Top-1 | +|---|---| +| random | 0.199 | +| B0 | 0.300 | +| T0 | 0.618 | + +- T0 − B0 = +0.318 [0.262, 0.372]. +- On all 1,068 episodes, T0 scores 0.685 and B0 scores 0.303. + +## 3. Phase 12.2 pre-registration + +`03f1c1d` fixed every element before any analysis ran: +- the populations R, R-SR, O-arch, X-inc and P2, with their classifications; +- the frozen scorers T0, B0, OP0 and OP1; +- the symmetric confirmation rule (SR_any primary, SR_latest sensitivity) and a + manipulation check; +- H1 and H2 with Holm, and H3 as descriptive; +- the exploratory list E1–E14; +- the decision rules, the exactness gate and the budgets. + +The analysis code was committed (`623b36d`) before it ran. + +**Deviation.** H2 was not repeated without the 1 protected-overlap episode, although +§7 says it should be. One episode can move H2's mean by at most 1/1,057 ≈ 0.001. + +## 4. Dataset independence audit + +| Source | Unit and label mechanism | Outcomes examined before? | Overlap with Phase 12.1 | Classification | +|---|---|---|---|---| +| Tsuchiya archive, confirmed payoffs (1,634 rows; 1,068 eligible episodes) | source heuristics plus manual Etherscan confirmation | **yes, all** (12.1 development and test) | the same episodes | previously examined development data | +| Tsuchiya unconfirmed payoffs (13,683 rows) | the same heuristics, without confirmation | no | the same collection and rules; 143 rows touch study victims | not used: label-uncertain, needs about 2 h of offline passes (§25) | +| Tsuchiya BSC payoffs | the same method, another chain | no | none | **not local**; a download needs approval | +| Poison-Hunter | flagged poisoning transfers and addresses | partly (Phase 11.3) | 89 of 105 in-definition rows are archive attempts | not usable: no paid-versus-rival outcome | +| PTXPhish | phishing transactions | yes (Phase 11) | none | not usable: no rival candidates | +| Recorded incidents (4) | public post-incident reports; complete recorded wallet streams with signers | the ranking outcome was not examined before; the detector was developed with these fixtures in view | none (incident victims are not archive payoff victims) | **external source with limitations**, n = 4 (3 rankable) | +| Recorded background windows (9) | none | — | none | operational diagnostics only | +| Frozen review cohorts (95) | awaiting human review | — | — | **excluded** | + +**Independence gate: no genuinely independent outcome population exists locally.** + +## 5. Frozen recency definition + +`lookalike-features/1` T0 was verified in code (`candidate_features`) and is unchanged. + +| Question | Answer | +|---|---| +| Definition | `-(c - b)`, where b is the block of the candidate's latest source planting (zero-value, tiny or counterfeit; either direction) to the victim at or before c | +| Unit | blocks, not wall-clock time | +| Same-block order | not used | +| Ties | tie-averaged (`1/m`); random-order ties, not deterministic | +| Missing planting time | impossible in the archive: every row has a block | +| Repeated plantings | only the latest counts | +| Cutoff | inclusive, c = T − 1; rows in the payoff block are counted but never used | +| Deduplication | exact duplicate rows cannot change T0 (E11) | +| Future rows | excluded by construction, and tested (§6) | + +No defect was found, so no new version was made. + +## 6. Observation cutoff + +- **Archive analyses:** c = T − 1. +- **Robustness (Phase 12.1):** T − 300 and T − 7,200. +- **Operational replays:** `detector_outputs(fixture, cutoff)`, which reads only records at + or before the cutoff. +- **Tests** check that the following leave the candidate sets, the confirmation rule and the + rankings unchanged: + - rows after the cutoff; + - a later intended transfer; + - trimming a recorded incident's future transfers. + +## 7. Operational candidate availability + +The candidate lifecycle (brief §9) on O-arch: + +1. **Archive observation:** the source-selected rows at or before c. This means no ordinary + activity, no signers, and values known only as zero or nonzero. +2. **Generated by CryptoGuard:** the unchanged `detect_poisoning`, run on those rows: + - paid: 99.16% warned; + - rival: 99.23% warned. + - The paid and rival shares agree to within 0.1 percentage point, so warning generation + is not outcome-asymmetric. +3. **Eligible for H2:** 1,057 episodes in which the paid lookalike is among at least 2 + warnings. +4. **Never used to build candidate sets:** the payoff, or the source's "paid" label. + +The cutoff stream is **reconstructed and source-selected**, not a genuine recorded wallet +stream. Only the 4 incidents and 9 background windows are genuine recordings. + +## 8. Symmetric evidence verification + +From Phase 12.1, reproduced exactly here: +- paid and rival lookalikes were 100% targeted by the same manifest; +- 100% of their planting rows are present; +- the scan hash matches. + +For this phase: +- the same cutoff, filters and deduplication apply to both; +- features never read the outcome; +- SR uses only rows at or before c, and is computed identically for paid and rival. + +**Residual asymmetry.** +- SR_latest is satisfied by 95.9% of paid lookalikes and 61.1% of rivals. That is + outcome-associated, and expected if the latest planting is what gets copied. +- Restricting every candidate to SR_latest-true leaves the effect (§1). + +## 9. Negative-control investigation + +These are the pre-registered controls (E1, E2, E10). + +| Control | Null | What is fixed | Expected | Observed | +|---|---|---|---|---| +| E1, within-episode permutation of T0 (200 repeats) | T0 values carry no candidate information | candidate counts, value multiset | random (0.2275) | 0.2273 ✓ | +| E2, oldest first | — | everything | below random if recency is real | 0.057 | +| NC overall | token co-usage is uninformative | — | random | 0.194 < 0.228 | +| NC, paid's token public stablecoin (551) | — | — | random (0.249) | 0.313 | +| NC, paid's token other (517) | — | — | random (0.204) | 0.067 | +| NC, all candidates share a token class (501) | — | token class | random (0.306) | 0.289 | +| Within-episode Spearman of NC and T0 (623 episodes, k ≥ 3) | — | — | — | median −0.44 | + +**Interpretation.** NC's below-random score is largely explained by two things, but not +proven: +- it mixes token classes, and its sign flips between them; +- it is strongly anti-correlated with recency. Lookalikes whose latest planting used a token + shared by many study victims are older. + +Within a single token class it is close to random (−0.017). + +What remains open: why "other" tokens give NC its strongly anti-informative value. One +candidate explanation is a campaign-specific counterfeit contract. That is a hypothesis. + +## 10. Temporal matching bias + +| What the source documents | | +|---|---| +| The rule | a confirmed payoff needs a poisoning transfer between the intended transfer and the payoff (`guidance.ipynb`) | +| Not documented | a maximum lookback; nearest-event assignment; rounding; ordering inference | + +- **Manipulation check:** 100% of paid lookalikes satisfy SR_any, so our reading reproduces + the rule. 99.4% of rivals satisfy it too, so as written it barely selects. +- **Stricter reading:** recency survives SR_latest (§1). +- **Symmetric maximum lookbacks** (E7; a candidate is dropped when its latest planting is + older than the window): + +| Window | Episodes | T0 | B0 | random | +|---|---|---|---|---| +| 30 days | 827 | 0.667 | 0.332 | 0.307 | +| 90 days | 987 | 0.675 | 0.316 | 0.264 | +| 180 days | 1,050 | 0.683 | 0.306 | 0.239 | + +- **Without immediate copies** (E8; paid gap ≥ 300 blocks; stratified on an outcome + attribute): 877 episodes, T0 0.660, B0 0.306. +- **Phase 12.1 post-hoc check, verified:** + - paid gaps reach 1.70M blocks, about 236 days; + - 11.1% exceed 30 days; + - on those, T0 scores 0.487 against random's 0.205. + +**Unresolved.** Payoff candidates may have been flagged with an outcome-dependent temporal +rule that the source does not document, upstream of confirmation. These data cannot test +that (§21). + +## 11. Confounder analyses + +E5 and E9. Every comparison below is on all episodes, with n and groups reported. +- **Victim activity**, by the victim's outgoing rows at or before c: + +| Tertile | n | T0 | B0 | random | +|---|---|---|---|---| +| low | 364 | 0.717 | 0.384 | 0.351 | +| mid | 364 | 0.692 | 0.302 | 0.206 | +| high | 340 | 0.643 | 0.218 | 0.118 | + +- **The newest candidate's age**, which uses no outcome: T0 stays between 0.673 and 0.697 in + every bin (under 1 hour, 1 hour to 1 day, 1 to 7 days, over 7 days). Recency is therefore + not only "the attacker who planted minutes before". +- **Token class:** + - paid's latest planting in a public stablecoin (551): T0 0.708 against B0 0.313; + - other (517): T0 0.661 against B0 0.293; + - candidate sets restricted to public-stablecoin plantings (522): T0 0.763 against + B0 0.351. +- **Campaign concentration:** the largest linkage group holds 6 episodes (0.56%). No single + campaign dominates. + +## 12. Subgroup robustness + +| Stratum | n (groups) | T0 | B0 | random | +|---|---|---|---|---| +| 2022 | 62 (62) | 0.718 | 0.441 | 0.404 | +| 2023 | 891 (886) | 0.684 | 0.298 | 0.221 | +| 2024+ | 115 (113) | 0.678 | 0.266 | 0.186 | +| k = 2 | 205 (205) | 0.781 | 0.512 | 0.500 | +| k = 3–5 | 339 (339) | 0.757 | 0.370 | 0.274 | +| k ≥ 6 | 524 (516) | 0.601 | 0.178 | 0.091 | +| spoofed transfer | 1,025 (1,016) | 0.687 | 0.305 | 0.230 | +| tiny | 40 (40) | 0.625 | 0.265 | 0.167 | + +- The fake-token (n = 1) and zero-value (n = 2) subtypes are too small to read. +- **96% of episodes are spoofed transfers.** The result is essentially about that mechanism. + +## 13. History truncation and perturbations + +| Perturbation | Evaluable | T0 top-1 | +|---|---|---| +| none | 1,068 | 0.685 | +| planting blocks jittered ±1 day | 1,068 | 0.605 | +| jittered ±7 days | 1,068 | 0.555 | +| blocks coarsened to 1-day buckets (ties) | 1,068 | 0.590 | +| coarsened to 7 days | 1,068 | 0.516 | +| each candidate's latest planting dropped (a missed observation) | 420 | 0.720 | +| exact duplicate rows injected | 1,068 | 0.685 (unchanged) | +| line order shuffled within blocks | 1,068 | 0.685 (unchanged) | + +Phase 12.1's variants reproduce exactly: +- cutoff T − 7,200 (745 episodes): T0 0.649; +- victim lookback of 7 days: B0 rises to 0.361. + +**Reading the perturbations:** +- Recency degrades gracefully with timestamp noise, and stays well above B0 even at + 7-day precision. +- Dropping the latest planting leaves only episodes where every candidate had at least two + plantings, which is a different population. That 0.720 is not comparable to 0.685. + +## 14. Source-domain limitations + +- **One source:** Ethereum, mostly 2023, and 96% spoofed-transfer mechanisms. +- **Candidate sets are source-flagged plantings.** +- **History is source-kept rows only.** B0 sees only the intended transfers the source + recorded. +- **No BSC data, and no unconfirmed payoffs.** + +## 15. Operational warning ranking + +`ml/warning_rank.py`, `poisoning-warning-rank/1`, is research only and not imported by any +production path. + +- **Input:** production `PoisoningCase`s at a cutoff. +- **Output per warning:** + - rank; + - severity, unchanged; + - similarity; + - basis (`latest_planting_signal` or `no_recency_basis`); + - basis block and transaction; + - blocks before the cutoff; + - cutoff; + - algorithm version; + - explanation. For example: "Within severity elevated_risk, ordered by its latest planting + signal at block … (… blocks before cutoff …), against 3 other warning(s). Ordering only: + not a probability." +- **Order:** + 1. severity tier; + 2. latest planting signal (zero-value, spoofed outgoing, unsolicited incoming; the + wallet's own sends never count); + 3. similarity; + 4. address. +- **Without a basis:** a warning keeps its baseline order behind its tier's warnings that + have a basis. +- **Tested:** + - the warning set is always preserved; + - a lower tier never outranks a higher one; + - inputs are not mutated; + - ties are deterministic under every permutation; + - rows after the cutoff are ignored on a real incident; + - single-block resolution is exact. + +**Results:** + +| Population | Warnings / episodes | Rankable (≥ 2 warnings) | Result | +|---|---|---|---| +| O-arch (H2) | 1,057 eligible episodes | 1,057 | OP1 0.502 vs OP0 0.267, +0.235 [0.208, 0.263] | +| X-inc (H3) | 4 incidents | 3 | paid recipient ranked 1st by OP1 in 3 of 3 (OP0: 1 of 3; random: 1/3, 1/7, 1/4); the 4th incident has 1 warning | +| P2 background | 9 windows, 5 warnings | 2 | order changed in 1 window; warning set preserved in 9 of 9; 0 warnings without a basis; 8 ms | + +**OP1 is weaker than T0.** OP1 scores 0.502 against T0's 0.685 on its population because +severity tiers come first. The safety constraint therefore costs ranking power on this +retrospective task. That cost is accepted by design. + +## 16. Statistical uncertainty + +- **Clustering:** paired top-1 differences are clustered on 1,059 shared-lookalike linkage + groups. Every episode is a distinct victim (1,068). +- **Intervals:** group bootstrap, 2,000 draws. +- **p-values:** group sign-flip permutation, with 10,000 draws for H1 and H2 and 2,000 for + exploratory analyses. +- **Multiplicity:** Holm over H1 and H2. +- **Effect sizes:** H1 +0.38 and H2 +0.24 on top-1, against a random baseline of about 0.23. +- **What the intervals cover:** sampling variation over victims in *this* source population + only. They say nothing about other populations. + +## 17. Performance optimization + +**Profile** (300 seeded lookups each): +- query plans were correct: index searches, including a multi-index OR; +- per lookalike lookup: 96 ms mean, 271 ms p95, median 2 rows; +- per planting-transaction lookup: 512 ms mean, 1.87 s p95, median 20.5 rows; +- a sequential scan of all 1,306,648 rows took 13 s; +- the 596 MB file has 145,416 pages with a 2 MB cache. +- **The cost is one random page read per matched row on a shared HDD.** + +**Fix:** `preload_graph`, a single ordered pass that builds every typed edge with the lazy +index's own per-row rules (factored into shared functions). Edge-level keep filters +reproduce the 50% drop and the cutoff filters. `coverage_symmetry` now uses one pass +instead of two lookups per candidate. + +| Phase 12.1 study | Lazy (12.1) | Preloaded | +|---|---|---| +| Total wall time | 8,157 s | **179 s** | +| Graph build plus primary features | 6,429 s | 11 s + 9 s | +| Peak RSS | 744 MiB | 485 MiB | +| Disk read | not measured | 1,317 MiB, 340k operations | +| Result hash (all non-timing keys) | `1dbc763f7058f8c4` | `1dbc763f7058f8c4` | + +- Both runs took place on the same machine, with other projects' jobs present in both. +- The whole Phase 12.2 study took 38 s at 311 MiB peak, including 13 s for the production + replay. + +## 18. Exact-output equivalence + +- **Tests:** + - on random synthetic rows (duplicates, unknown victim side, exclusions; 3 keep filters; + 6 cutoff/since combinations), the preloaded and lazy indexes return identical + prior-victim, prior-payer and transaction-victim sets; + - an out-of-set query raises; + - the synthetic end-to-end study gives an identical report in both modes. +- **Real data:** `exactness.json` records that every key of the saved Phase 12.1 report, + apart from timing fields, is identical. The post-hoc recency-gap diagnostic is identical + too. + +## 19. Positive findings + +1. Recency is not explained by the source's documented confirmation rule, applied + symmetrically (H1, attenuation 0.2%). It also survives the stricter, selective reading. +2. Recency survives: + - symmetric 30-, 90- and 180-day lookbacks; + - removal of immediate copies; + - every year, k bin, victim-activity tertile, newest-candidate-age bin and token class; + - ±7-day timestamp noise. +3. Recency ordering of the production detector's own warnings, within severity tiers, + improves on similarity ordering on the archive replay (H2). It ranks the paid recipient + first in 3 of 3 rankable recorded incidents (descriptive). +4. The research pipeline is about 45× faster, with exactly reproduced results. + +## 20. Negative findings + +1. **No independent validation is possible with local data.** All archive evidence comes + from previously examined episodes. +2. The external check has only 3 rankable incidents, too few for inference. +3. The severity-first operational ordering loses about a quarter of the retrospective + advantage (0.502 against 0.685). +4. The ranking is almost entirely about spoofed-transfer poisoning. The tiny-transfer + stratum has 40 episodes, and the others have fewer than 3. +5. The negative control is not cleanly null. Its anomaly is explained only in part. + +## 21. Unresolved methodological issues + +- **How payoff candidates were first flagged.** The source flagged unconfirmed payoff + candidates before confirming them, and that step is undocumented. If it favoured + lookalikes that planted recently, recency would be partly built in at a stage these data + cannot see. +- **NC in "other" tokens** (§9). +- **Mechanism.** "The victim copies the newest matching history entry" is consistent with + the data but untested. No interface or behavioural data exist. +- **O-arch fidelity.** Signers are unknown, values are only zero or nonzero, and in-block + order is arbitrary. Production warnings on a live wallet could differ. + +## 22. Production safety + +- Since `3153dcf`, there are no changes under `detectors/`, `services/` or `risk/`. +- `warning_rank` is not imported by the API, services or CLI scoring paths. +- There is no new dependency and no model artifact. A rule-based scorer needs neither. +- No warning is suppressed, re-tiered or modified; tests enforce this. +- The frozen cohorts pass `ml verify-research`: 60 + 35 items, with selection and + evidence hashes unchanged. + +## 23. Reproducibility + +```bash +uv run --offline cryptoguard ml lookalike-study --out data/ml/research/phase12.2/lookalike-study-preloaded.json +``` + +```bash +uv run --offline cryptoguard ml recency-validation +``` + +- The inputs are the hash-verified local archive and the derived databases. Their hashes + are checked by `ml verify-research`. +- The seeds are fixed: 20261102 for Phase 12.1 and 20261103 for Phase 12.2. + +## 24. Data and licensing constraints + +- **Tsuchiya et al. data (CC BY-NC-ND 4.0):** stays local. Only aggregates are committed. +- **Poison-Hunter and PTXPhish:** have no licence, so nothing derived from them is + committed. +- **Not committed:** row-level records, frozen review material and answer keys. + +## 25. Recommended next experiment + +Pre-register and run recency on the archive's **13,683 unconfirmed payoff rows**: +- Their victims are disjoint from the study, apart from 143 rows. +- They were never examined. +- They were *not* subjected to the confirmation step. + +**What it tests.** If recency also orders lookalikes there, the confirmation step is ruled +out as its cause, and with it the documented selection mechanism. If recency is much +weaker there, the confirmation step is implicated. + +**Limitations:** +- the labels are uncertain by the source's own account, so results must be reported per + confirmation status; +- it is the same collection, so it still is not independent of the source's flagging + rules. + +**Cost:** +- two offline archive passes, about 2 hours on this disk, under 512 MiB; +- 0 RPC requests, no download; +- then the preloaded study, about 5 minutes. + +A genuinely independent test needs **newly recorded incidents**. That requires an approved +RPC budget, or the BSC payoff file, which requires download approval. + +## Research output table + +| Analysis | Population | Episodes (groups) | Cutoff | Candidate set | Baseline | New | Difference [95% CI] | Status | Main bias limitation | Runtime | +|---|---|---|---|---|---|---|---|---|---|---| +| Phase 12.1 primary | R test | 428 (427) | T − 1 | source plantings | B0 0.300 | T0 0.618 | +0.318 [0.262, 0.372] | source-conditional retrospective result | outcome seen; source-defined | 179 s (rerun) | +| H1 | R-SR (SR_any) | 1,059 (1,050) | T − 1 | source plantings satisfying SR | B0 0.300 | T0 0.682 | +0.382 [0.347, 0.417] | exploratory sensitivity analysis (pre-registered) | re-examined data; SR barely selective | 38 s (all of 12.2) | +| H1, SR_latest | R-SR | 910 (901) | T − 1 | stricter SR | B0 0.332 | T0 0.671 | +0.339 [0.300, 0.379] | exploratory sensitivity analysis | re-examined data | — | +| H2 | O-arch | 1,057 (1,049) | T − 1 | production warnings | OP0 0.267 | OP1 0.502 | +0.235 [0.208, 0.263] | operational replay diagnostic | source-selected stream, no signers | 13 s | +| H3 | X-inc | 3 rankable | harm − 1 | production warnings, recorded streams | OP0: 1/3 first | OP1: 3/3 first | — | external source, descriptive (n = 3) | tiny n; detector developed on these fixtures | < 1 s | +| E14 | P2 | 9 windows | window end | production warnings | — | — | warning set preserved 9/9 | operational diagnostic | no labels | 8 ms | +| Independent validation | — | — | — | — | — | — | — | **unsupported due to missing data** | — | — | + +## Decision gates + +| Gate | Status | Evidence | +|---|---|---| +| A. Source independence | **BLOCKED BY DATA** | no untouched outcome population (§4); 3 rankable incidents only | +| B. Temporal correctness | PASS WITH LIMITATIONS | everything at or before the cutoff, tested; archive candidate sets are source-defined | +| C. Selection-bias control | PASS WITH LIMITATIONS | symmetric extraction, warning generation and confirmation rule; the source's upstream flagging is unobservable | +| D. Negative-control validity | PASS WITH LIMITATIONS | E1 at random, E2 far below; NC anomaly mostly explained by token-class mixing and its correlation with recency | +| E. Recency robustness | PASS | every pre-registered sensitivity analysis keeps T0 at least 0.17 above B0 | +| F. Statistical adequacy | PASS WITH LIMITATIONS | grouped paired inference with Holm; but re-examined data, one source | +| G. Operational relevance | PASS WITH LIMITATIONS | operates on production warnings; archive replay is approximate; incidents n = 3 | +| H. Engineering efficiency | PASS | 179 s (from 8,157 s), 485 MiB; Phase 12.2 in 38 s | +| I. Production isolation | PASS | no production change; ranker isolated, tested non-suppressing | +| J. Reproducibility | PASS WITH LIMITATIONS | regenerable from hash-verified local inputs; the data cannot be redistributed | diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index c6d5bf8..15c3427 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -203,3 +203,31 @@ similarity score (B0, 0.300): - **Not a detection result:** no precision, FPR or recall was measured. - **Next:** pre-register recency-first warning ordering on a population not used here. +## 9. Done (Phase 12.2): is recency a source-selection artifact? + +The study was pre-registered in `docs/ml/protocol-12.2.md` (`03f1c1d`) and run offline, +with 0 RPC requests. Results are in [ML_RECENCY_VALIDATION.md](ML_RECENCY_VALIDATION.md). + +**Results.** + +| Test | Population | Ordering | Top-1 | Comparator | Difference | +|---|---|---|---|---|---| +| H1 | 1,059 episodes, the source's confirmation rule applied to rivals too | recency | 0.682 | similarity 0.300 | +0.382, attenuation 0.2% | +| H2 | the unchanged production detector's warnings | severity, then recency | 0.502 | severity, then similarity: 0.267 | +0.235 | + +- **Incidents:** in all 3 recorded incidents with at least 2 warnings, recency ordering puts + the stolen-funds recipient first. +- **Classification:** a source-conditional retrospective effect. The independence gate is + **blocked by data**: every archive episode was examined in Phase 12.1. + +**Engineering.** A single-pass graph preload reproduces Phase 12.1 exactly. It runs in +179 s instead of 8,157 s. + +**Next.** Pre-register recency on the 13,683 unconfirmed archive payoffs: +- they were never examined; +- they were not confirmed; +- it needs two offline passes, about 2 hours, and no RPC. + +A genuinely independent test needs newly recorded incidents, which need an approved RPC +budget. + diff --git a/docs/ml/protocol-12.2-deviations.md b/docs/ml/protocol-12.2-deviations.md new file mode 100644 index 0000000..584dc2a --- /dev/null +++ b/docs/ml/protocol-12.2-deviations.md @@ -0,0 +1,21 @@ +# Phase 12.2 protocol: deviations + +The protocol is frozen at `03f1c1d` and is not edited. The analysis code was committed at +`623b36d` before it ran. + +## D1. H2 not repeated without protected overlap (omission) + +**Section 7 asks** for H1 and H2 to be repeated without the episodes that overlap a frozen +item. + +**What happened:** only H1 was repeated. Its decision is unchanged: 1,058 episodes, ++0.382. + +**The H2 gap is negligible:** exactly 1 episode overlaps, and one episode can move H2's +mean top-1 difference by at most 1/1,057 ≈ 0.001. + +## No other deviations + +- **Unchanged:** the populations, scorers, rules, tests, seeds and decision rules. +- **Exploratory permutation counts:** sensitivity analyses use 2,000 sign-flip draws, as + allowed for exploratory output. H1 and H2 use 10,000, as pre-registered. From 8590366210b8ddcbdcd09ce638d35697728a7f73 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 11:29:59 +0300 Subject: [PATCH 47/92] docs(ml): pre-register recency on the source's unconfirmed payoffs Frozen before either archive pass runs. U-H1: does recency still beat the production similarity score on the 13,683 unconfirmed payoffs, which never went through the source's confirmation step? U-H2: the contrast with the Phase 12.2 effect, with fixed thresholds for "confirmation implicated" and "not implicated". Same-source, label-uncertain data: not independent validation. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.2-unconfirmed.md | 126 +++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 docs/ml/protocol-12.2-unconfirmed.md diff --git a/docs/ml/protocol-12.2-unconfirmed.md b/docs/ml/protocol-12.2-unconfirmed.md new file mode 100644 index 0000000..4f8fd0a --- /dev/null +++ b/docs/ml/protocol-12.2-unconfirmed.md @@ -0,0 +1,126 @@ +# Phase 12.2 follow-up protocol: recency on the source's unconfirmed payoffs + +- **Task:** `recency-unconfirmed/1`. +- **Frozen:** committed before either archive pass runs, so no row, count or outcome of this + population had been seen. The only facts known beforehand come from the Phase 11.3 scan + summary: + - the archive holds 13,683 rows flagged `payoff_transfer_unconfirmed`; + - 143 of them touch Phase 12.1 victims. + +Phase 12.2 (`docs/ml/protocol-12.2.md`) is unchanged. + +## 1. Question + +**Is the Phase 12.1 recency effect produced by the source's confirmation step?** The source +confirmed a payoff only after checking on Etherscan that "the poisoning transfer exists +between the intended and the payoff transfer". Its unconfirmed payoffs never went through +that check. If recency is strong there too, the confirmation step is not its cause. If it is +much weaker, the step is implicated. + +**Classification:** same-source, never-examined, **label-uncertain** data. It is not +independent validation: the collection and the upstream flagging rules are shared. + +## 2. Data (two offline passes; 0 RPC requests, no download) + +**Pass 1** extracts every archive row with the `payoff_transfer_unconfirmed` flag to +`data/ml/poisoning/unconfirmed/rows.jsonl`. The file is git-ignored and hash-recorded. + +**Pass 2** stores every archive row touching a **U victim** in +`unconfirmed/victim_subset.sqlite`. +- A U victim is the sender of an unconfirmed row. +- Excluded: Phase 12.1 payoff victims (the archive targets' `payoff_victims`), protected + wallets and incident victims. +- As in Phase 12.1, this is the source-kept rows only, never a full wallet history. + +## 3. Episodes (population U) + +Phase 12.1 eligibility applies, with the unconfirmed flag in place of the confirmed one: +- **T** is the block of the victim's first unconfirmed payoff row it sent; +- **c** = T − 1; +- **candidates** are the source plantings at or before c; +- **eligible** when exactly one lookalike was paid in T, it planted at or before c, and + k ≥ 2. + +Further rules: +- The victim's outgoing rows that are themselves unconfirmed payoffs are excluded from the + history B0 reads, as confirmed payoffs were in Phase 12.1. +- A victim with any confirmed payoff row is excluded. +- **Excluded upfront:** episodes that share an entity with a frozen review item. That means + a candidate, or a planting counterparty, that is a protected wallet or address under + review, or a planting transaction that is a protected transaction. All are read from the + blinded sheets. +- **Reported:** episodes that share a candidate lookalike or a planting transaction with any + Phase 12.1 episode (infrastructure overlap). + +## 4. Scorers + +Frozen and unchanged: +- **T0** (`lookalike-features/1`); +- **B0**, the production similarity; +- **OP0 / OP1** (`poisoning-warning-rank/1`, protocol 12.2 §2). + +Nothing is tuned. + +## 5. Tests and decision rules + +**U-H1 (primary):** `Δ_U = top-1(T0) − top-1(B0)` on all U episodes. +- Paired, clustered on U's own linkage groups (shared candidate lookalikes; protocol 12.1 + §7 fallback rule). +- 10,000 sign flips and 2,000 bootstrap draws, seed 20261104. +- Decided with protocol 12.2 §4: survives, explained or null, or inconclusive. + +**U-H2 (contrast):** `D = Δ_R − Δ_U`. +- `Δ_R = 0.3817` is the Phase 12.2 value on all 1,068 R episodes. +- Its 95% interval comes from an independent group bootstrap of both populations, 2,000 + draws. +- **Confirmation implicated:** the CI lower bound is above 0 and `D ≥ 0.19`, half of `Δ_R`. +- **Not implicated:** the CI upper bound is below 0.19. +- **Inconclusive:** otherwise. + +Holm is not applied: U-H2 is interpreted only together with U-H1. + +**Phase conclusion:** + +| U-H1 | U-H2 | Conclusion | +|---|---|---| +| survives | not implicated | the confirmation step does not explain recency | +| explained or null | implicated | recency is plausibly a confirmation artifact | +| any other combination | — | inconclusive | + +## 6. Exploratory analyses (no confirmatory claims) + +UE1. **The rule on U itself.** U episodes are split by whether the paid candidate satisfies +SR_any, and separately SR_latest. T0 and B0 are reported in each part. +- *Fails the rule* means these payoffs would not have passed the source's check, as we read + it. +- This split stratifies on an outcome attribute and is labelled so. + +UE2. Random, the within-episode permutation of T0, and oldest-first. + +UE3. Strata by year, paid subtype and k bin, with group counts. + +UE4. **Production replay:** OP1 against OP0 on production warnings over the archive rows at +or before c, as H2 in Phase 12.2. + +UE5. U-H1 without episodes that share infrastructure with Phase 12.1. + +UE6. Exclusion counts, k distribution, and the share of paid candidates warned by +production. + +## 7. Limitations fixed in advance + +1. **Unconfirmed labels are uncertain.** Some may be deliberate payments to a lookalike-like + address, or transfers the source did not check. A null result could therefore come from + label noise rather than from the confirmation step. +2. **Shared source.** The upstream flagging of payoff candidates is the same in U and R, so + U cannot test that stage. +3. **Victim-side history is source-selected**, as in R. + +## 8. Budgets + +| Run | Wall time | Memory | +|---|---|---| +| Each archive pass | under 75 min on this disk | under 512 MiB | +| Analysis | under 5 min | under 1 GB | + +0 RPC requests and no downloads. Outputs are aggregates only. From 89998d5a818da633f5bb9aa0260663eb616ed7bc Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 11:35:04 +0300 Subject: [PATCH 48/92] feat(ml): unconfirmed-payoff recency analysis (pre-registered, not yet run) Implements protocol-12.2-unconfirmed (8590366): pass 1 extracts the archive's unconfirmed payoff rows, pass 2 stores every row touching their victims (minus Phase 12.1 payoff victims, protected wallets and incident victims), then U-H1 (T0 vs B0), U-H2 (contrast with the Phase 12.2 effect) and UE1-UE6. episode_from_rows takes the payoff flag; the default is unchanged (tests). Committed before any U row or outcome exists. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 29 ++ src/cryptoguard/ml/lookalike_ranking.py | 15 +- src/cryptoguard/ml/unconfirmed_recency.py | 374 ++++++++++++++++++++++ tests/test_ml_lookalike_ranking.py | 124 +++++++ 4 files changed, 537 insertions(+), 5 deletions(-) create mode 100644 src/cryptoguard/ml/unconfirmed_recency.py diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 399b95e..585615c 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -119,6 +119,16 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None rv.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "recency-validation.json" ) + ur = ml.add_parser( + "unconfirmed-recency", + help="recency on the source's unconfirmed payoffs (two offline archive passes)", + ) + ur.add_argument("--data-dir", type=Path, default=DEFAULT_DATA_DIR) + ur.add_argument("--extract", action="store_true", help="run pass 1 (unconfirmed rows)") + ur.add_argument("--scan", action="store_true", help="run pass 2 (victim-side rows)") + ur.add_argument( + "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" + ) iv = ml.add_parser("inventory", help="hash and describe every local research data file") iv.add_argument("--root", type=Path, default=Path(".")) iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") @@ -235,6 +245,25 @@ def run(args: argparse.Namespace) -> int: print(key, json.dumps(report[key], indent=1)) print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") return 0 + if args.ml_command == "unconfirmed-recency": + import json + + from cryptoguard.ml import unconfirmed_recency as ur_ + + poisoning = ML_DIR / "poisoning" + if args.extract: + print(json.dumps(ur_.extract(args.data_dir, poisoning), indent=1)) + if args.scan: + summary = ur_.context_scan(args.data_dir, poisoning) + print(json.dumps({k: summary[k] for k in ("stored_target_rows", "runtime_seconds")})) + if not (args.extract or args.scan): + report = ur_.run(poisoning) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=1, default=str) + "\n", encoding="utf-8") + for key in ("episodes", "U_H1", "U_H2", "conclusion"): + print(key, json.dumps(report[key], indent=1)) + print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") + return 0 if args.ml_command == "inventory": import json diff --git a/src/cryptoguard/ml/lookalike_ranking.py b/src/cryptoguard/ml/lookalike_ranking.py index 434f486..61bce40 100644 --- a/src/cryptoguard/ml/lookalike_ranking.py +++ b/src/cryptoguard/ml/lookalike_ranking.py @@ -141,14 +141,19 @@ def protected_overlap( return [g in tainted for g in grp] -def episode_from_rows(victim: str, rows: Iterable[Row]) -> Episode | str: - """The episode for one victim, or the reason it is ineligible.""" +def episode_from_rows( + victim: str, rows: Iterable[Row], *, payoff_flag: int | None = None +) -> Episode | str: + """The episode for one victim, or the reason it is ineligible. ``payoff_flag`` selects + which source flag marks the payoff: confirmed (the default) or, for the follow-up + population, unconfirmed.""" from cryptoguard.ml.tsuchiya_archive import PAYOFF, POISONING + flag = PAYOFF if payoff_flag is None else payoff_flag ordered = sorted(set(rows), key=lambda r: (r.block, r.line)) - payoffs = [r for r in ordered if r.flags & PAYOFF and r.sender == victim] + payoffs = [r for r in ordered if r.flags & flag and r.sender == victim] if not payoffs: - return "no_confirmed_payoff_row" + return "no_confirmed_payoff_row" if flag == PAYOFF else "no_payoff_row" t = payoffs[0].block paid = {r.receiver for r in payoffs if r.block == t} if len(paid) != 1: @@ -164,7 +169,7 @@ def episode_from_rows(victim: str, rows: Iterable[Row]) -> Episode | str: same_block += 1 else: plantings.append(r) - elif r.sender == victim and not r.flags & PAYOFF and r.block < t: + elif r.sender == victim and not r.flags & flag and r.block < t: out.append(r) ep = Episode(victim, t, paid.pop(), tuple(plantings), tuple(out), same_block) if ep.paid not in ep.candidates: diff --git a/src/cryptoguard/ml/unconfirmed_recency.py b/src/cryptoguard/ml/unconfirmed_recency.py new file mode 100644 index 0000000..c0f5b41 --- /dev/null +++ b/src/cryptoguard/ml/unconfirmed_recency.py @@ -0,0 +1,374 @@ +"""Recency on the source's *unconfirmed* payoffs (``recency-unconfirmed/1``), as +pre-registered in docs/ml/protocol-12.2-unconfirmed.md. Two offline archive passes, then an +aggregate-only analysis; 0 RPC requests. + +The source confirmed a payoff only after checking that a poisoning transfer lies between the +intended transfer and the payoff. Its unconfirmed payoffs never went through that check, so +the population tests whether the confirmation step produced the Phase 12.1 recency effect. +Its labels are uncertain by the source's own account, and it shares the source's collection: +this is not independent validation. +""" + +from __future__ import annotations + +import hashlib +import json +import random +import statistics +import time +from collections import Counter +from pathlib import Path +from typing import Any + +from cryptoguard.ml import lookalike_ranking as lr + +STUDY_VERSION = "recency-unconfirmed/1" +PROTOCOL = "protocol-12.2-unconfirmed/1" +SEED = 20261104 +DELTA_R = 0.3817 # Phase 12.2 T0 - B0 on all R episodes (protocol section 5) +HALF = 0.19 +OUT_DIR = "unconfirmed" +ROWS = "rows.jsonl" +SUMMARY = "extract_summary.json" +TARGETS = "victim_targets.json" +SUBSET = "victim_subset.sqlite" +MAX_ROWS = 100_000 # the publisher's notebook implies 13,683 + + +# --- the two archive passes -------------------------------------------------------------- + + +def extract(data_dir: Path, poisoning_dir: Path) -> dict[str, Any]: + """Pass 1: every archive row flagged ``payoff_transfer_unconfirmed``.""" + from cryptoguard.ml.annotation import atomic_write + from cryptoguard.ml.fetch import TSUCHIYA_FILES, verify_local + from cryptoguard.ml.hard_negative_archive import ARCHIVE, row_dict + from cryptoguard.ml.tsuchiya_archive import ( + PARSER_VERSION, + PAYOFF_UNCONFIRMED, + ArchiveReader, + peak_rss_bytes, + ) + + archive = data_dir / "tsuchiya2025" / ARCHIVE + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + t0 = time.perf_counter() + reader = ArchiveReader(archive) + rows: list[dict[str, Any]] = [] + flags: Counter[int] = Counter() + for t in reader: + if t.flags & PAYOFF_UNCONFIRMED: + flags[t.flags] += 1 + rows.append(row_dict(t)) + if len(rows) > MAX_ROWS: + raise RuntimeError(f"more than {MAX_ROWS} unconfirmed rows: parser fault?") + out = poisoning_dir / OUT_DIR + out.mkdir(parents=True, exist_ok=True) + data = b"".join(json.dumps(r, sort_keys=True).encode() + b"\n" for r in rows) + atomic_write(out / ROWS, data) + summary = { + "parser_version": PARSER_VERSION, + "source_sha256": source["sha256"], + "rows_scanned": reader.stats.valid_rows, + "unconfirmed_rows": len(rows), + "flag_combinations": {str(k): v for k, v in sorted(flags.items())}, + "rows_sha256": hashlib.sha256(data).hexdigest(), + "runtime_seconds": round(time.perf_counter() - t0, 1), + "peak_rss_bytes": peak_rss_bytes(), + "rpc_requests": 0, + } + atomic_write(out / SUMMARY, json.dumps(summary, indent=1).encode() + b"\n") + return summary + + +def load_rows(poisoning_dir: Path) -> list[dict[str, Any]]: + out = poisoning_dir / OUT_DIR + summary = json.loads((out / SUMMARY).read_text(encoding="utf-8")) + data = (out / ROWS).read_bytes() + if hashlib.sha256(data).hexdigest() != summary["rows_sha256"]: + raise RuntimeError(f"{out / ROWS}: content differs from its summary; re-extract") + return [json.loads(line) for line in data.splitlines() if line] + + +def u_victims(poisoning_dir: Path) -> tuple[list[str], dict[str, int]]: + """Senders of unconfirmed rows, minus Phase 12.1 payoff victims, protected wallets and + incident victims (protocol section 2).""" + groups = json.loads((poisoning_dir / "archive_targets.json").read_text(encoding="utf-8")) + groups = groups["groups"] + studied = set(groups["payoff_victims"]) + incident = set(groups["incident_victims"]) + protected = lr.protected_wallets(poisoning_dir) + excluded: Counter[str] = Counter() + keep: set[str] = set() + for v in {r["sender"] for r in load_rows(poisoning_dir)}: + if v in studied: + excluded["phase12_1_payoff_victim"] += 1 + elif v in protected: + excluded["protected_review_wallet"] += 1 + elif v in incident: + excluded["incident_victim"] += 1 + else: + keep.add(v) + return sorted(keep), dict(sorted(excluded.items())) + + +def context_scan(data_dir: Path, poisoning_dir: Path) -> dict[str, Any]: + """Pass 2: every archive row touching a U victim.""" + from cryptoguard.ml.annotation import atomic_write + from cryptoguard.ml.fetch import TSUCHIYA_FILES, verify_local + from cryptoguard.ml.hard_negative_archive import ARCHIVE + from cryptoguard.ml.tsuchiya_archive import build_targets, load_targets, scan + + victims, _ = u_victims(poisoning_dir) + out = poisoning_dir / OUT_DIR + atomic_write(out / TARGETS, json.dumps(build_targets({"u_victims": victims})).encode()) + archive = data_dir / "tsuchiya2025" / ARCHIVE + source = verify_local(TSUCHIYA_FILES[ARCHIVE], archive, gzip_crc=False) + work = out / "spill" + summary = scan( + archive, + load_targets(out / TARGETS), + out / SUBSET, + work_dir=work, + source_sha256=source["sha256"], + ) + if work.exists() and not any(work.iterdir()): + work.rmdir() + return summary + + +# --- episodes ------------------------------------------------------------------------------- + + +def load_u_episodes(poisoning_dir: Path) -> tuple[list[lr.Episode], dict[str, int]]: + from cryptoguard.ml.tsuchiya_archive import PAYOFF, PAYOFF_UNCONFIRMED + + victims, excluded_c = u_victims(poisoning_dir) + excluded: Counter[str] = Counter(excluded_c) + addresses, txs = lr.protected_entities(poisoning_dir) + con = lr._connect(poisoning_dir / OUT_DIR / SUBSET) + episodes: list[lr.Episode] = [] + try: + for v in victims: + rows = [ + lr._row(t) + for t in con.execute(lr._ROWS + " where sender = ? or receiver = ?", (v, v)) + ] + if any(r.flags & PAYOFF for r in rows): + excluded["has_confirmed_payoff_row"] += 1 + continue + ep = lr.episode_from_rows(v, rows, payoff_flag=PAYOFF_UNCONFIRMED) + if isinstance(ep, str): + excluded[ep] += 1 + continue + if set(ep.candidates) & addresses or any( + r.tx in txs or {r.sender, r.receiver} & addresses for r in ep.plantings + ): + excluded["protected_entity_overlap"] += 1 + continue + episodes.append(ep) + finally: + con.close() + return episodes, dict(sorted(excluded.items())) + + +# --- analysis ------------------------------------------------------------------------------- + + +def _group_bootstrap_diff( + d_r: list[float], g_r: list[int], d_u: list[float], g_u: list[int], n: int = 2_000 +) -> list[float]: + """95% interval of mean(d_r) - mean(d_u), resampling groups of each population + independently.""" + import numpy as np + + rng = np.random.default_rng(SEED) + + def sums(d: list[float], g: list[int]) -> tuple[Any, Any]: + _ids, inv = np.unique(np.asarray(g), return_inverse=True) + return np.bincount(inv, weights=np.asarray(d, float)), np.bincount(inv) + + sr, cr = sums(d_r, g_r) + su, cu = sums(d_u, g_u) + pr = rng.integers(0, len(sr), size=(n, len(sr))) + pu = rng.integers(0, len(su), size=(n, len(su))) + boot = sr[pr].sum(1) / cr[pr].sum(1) - su[pu].sum(1) / cu[pu].sum(1) + lo, hi = np.percentile(boot, [2.5, 97.5]) + return [float(lo), float(hi)] + + +def _contrast(diff: float, ci: list[float]) -> str: + """Protocol section 5, U-H2.""" + lo, hi = ci + if lo > 0 and diff >= HALF: + return "confirmation_implicated" + if hi < HALF: + return "not_implicated" + return "inconclusive" + + +def _conclusion(h1: str, h2: str) -> str: + if h1 == "survives" and h2 == "not_implicated": + return "the confirmation step does not explain recency" + if h1 == "explained_or_null" and h2 == "confirmation_implicated": + return "recency is plausibly a confirmation artifact" + return "inconclusive" + + +def run(poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml import recency_validation as rv + from cryptoguard.ml.lookalike_study import _year, subtype + + t_start = time.perf_counter() + eps, excluded = load_u_episodes(poisoning_dir) + if len(eps) < 2: + raise RuntimeError(f"only {len(eps)} eligible U episodes") + tokens = lr.TokenIndex.build(eps) + feats: list[rv.Feats] = [] + for e in eps: + fe = lr.candidate_features(e, lr.View(), None, tokens) + if fe is None: + raise RuntimeError("an eligible U episode is not evaluable at its cutoff") + feats.append(fe) + grp, linkage = lr.protocol_groups(eps) + t0 = [rv._top1(rv._single(f, "T0"), e.paid, f) for f, e in zip(feats, eps, strict=True)] + b0 = [rv._top1(rv._single(f, "B0"), e.paid, f) for f, e in zip(feats, eps, strict=True)] + rnd = [1 / len(f) for f in feats] + h1 = lr.paired([a - b for a, b in zip(t0, b0, strict=True)], grp, seed=SEED) + h1 |= {"T0_top1": rv._mean(t0), "B0_top1": rv._mean(b0), "random_top1": rv._mean(rnd)} + h1["decision"] = rv._decision(h1, h1["p"]) + + # U-H2: contrast with Phase 12.2's R effect, recomputed per episode from the same code. + r_eps, _ = lr.load_episodes(poisoning_dir) + r_tokens = lr.TokenIndex.build(r_eps) + r_feats = [lr.candidate_features(e, lr.View(), None, r_tokens) for e in r_eps] + r_grp, _ = lr.protocol_groups(r_eps) + d_r = [ + rv._top1(rv._single(f, "T0"), e.paid, f) - rv._top1(rv._single(f, "B0"), e.paid, f) + for f, e in zip(r_feats, r_eps, strict=True) + if f is not None + ] + delta_r = statistics.fmean(d_r) + d_u = [a - b for a, b in zip(t0, b0, strict=True)] + diff = delta_r - h1["mean"] + ci = _group_bootstrap_diff(d_r, r_grp, d_u, grp) + h2 = { + "delta_R": round(delta_r, 4), + "delta_R_registered": DELTA_R, + "delta_U": round(h1["mean"], 4), + "D": round(diff, 4), + "ci95": ci, + "decision": _contrast(diff, ci), + } + report: dict[str, Any] = { + "task": STUDY_VERSION, + "protocol": PROTOCOL, + "classification": "same-source, never-examined, label-uncertain; not independent", + "episodes": len(eps), + "exclusions": excluded, + "groups": { + "linkage": linkage, + "count": len(set(grp)), + "largest": max(Counter(grp).values()), + }, + "k": { + "mean": round(statistics.fmean(len(f) for f in feats), 2), + "median": statistics.median(len(f) for f in feats), + "bins": dict(Counter(rv._kbin(len(f)) for f in feats)), + }, + "U_H1": h1, + "U_H2": h2, + "conclusion": _conclusion(h1["decision"], h2["decision"]), + } + + # UE1: the source's rule on U (stratified on an outcome attribute). + sr = [rv.confirmation_rule(e, e.payoff_block - 1) for e in eps] + ue1: dict[str, Any] = {"label": "stratified on an outcome attribute"} + for name, pos in (("SR_any", 0), ("SR_latest", 1)): + for value in (True, False): + ix = [ + i for i, (e, s) in enumerate(zip(eps, sr, strict=True)) if s[e.paid][pos] is value + ] + key = f"paid_{name}_{'passes' if value else 'fails'}" + ue1[key] = rv._cmp( + [t0[i] for i in ix], [b0[i] for i in ix], [grp[i] for i in ix], n_perm=2_000 + ) | {"random_top1": rv._mean([rnd[i] for i in ix])} + none = sum(1 for e, s in zip(eps, sr, strict=True) if s[e.paid][pos] is None) + ue1[f"paid_{name}_not_evaluable"] = none + report["UE1_rule_on_U"] = ue1 + + # UE2: controls. + rng = random.Random(SEED) # noqa: S311 - seeded research sampling, not security + perm: list[float] = [] + for f, e in zip(feats, eps, strict=True): + vals = [f[c]["T0"] for c in f] + acc = 0.0 + for _ in range(200): + rng.shuffle(vals) + acc += lr.top1( + {c: float(v or 0.0) for c, v in zip(f, vals, strict=True)}, e.paid, len(f) + ) + perm.append(acc / 200) + old = [ + rv._top1({c: -float(f[c]["T0"] or 0.0) for c in f}, e.paid, f) + for f, e in zip(feats, eps, strict=True) + ] + report["UE2_controls"] = { + "random_top1": rv._mean(rnd), + "within_episode_permutation_top1": rv._mean(perm), + "oldest_first_top1": rv._mean(old), + } + + # UE3: strata. + report["UE3_strata"] = { + "year": rv._strata([_year(e.payoff_block) for e in eps], grp, t0, b0, rnd), + "paid_subtype": rv._strata([subtype(e) for e in eps], grp, t0, b0, rnd), + "k": rv._strata([rv._kbin(len(f)) for f in feats], grp, t0, b0, rnd), + } + + # UE4 and UE6: production replay. + op0: list[float] = [] + op1: list[float] = [] + og: list[int] = [] + warned = Counter[str]() + for i, e in enumerate(eps): + cases = rv.production_cases(e, e.payoff_block - 1) + sus = {x.suspect.lower() for x in cases} + warned["paid"] += e.paid in sus + warned["rival"] += sum(1 for c in feats[i] if c != e.paid and c in sus) + warned["rival_candidates"] += len(feats[i]) - 1 + if e.paid in sus and len(cases) >= 2: + a, b = rv._op_top1(cases, e.paid, e.payoff_block - 1) + op0.append(a) + op1.append(b) + og.append(grp[i]) + ue4 = rv._cmp(op1, op0, og, n_perm=2_000) + report["UE4_production_warnings"] = { + **{k: v for k, v in ue4.items() if k not in ("T0_top1", "B0_top1")}, + "OP1_top1": ue4.get("T0_top1"), + "OP0_top1": ue4.get("B0_top1"), + } + report["UE6_warned_share"] = { + "paid": round(warned["paid"] / len(eps), 4), + "rival": round(warned["rival"] / warned["rival_candidates"], 4) + if warned["rival_candidates"] + else None, + } + + # UE5: without infrastructure shared with Phase 12.1. + r_keys = {c for e in r_eps for c in e.candidates} | {r.tx for e in r_eps for r in e.plantings} + shared = [bool(set(e.candidates) & r_keys or {r.tx for r in e.plantings} & r_keys) for e in eps] + ix = [i for i in range(len(eps)) if not shared[i]] + report["UE5_without_shared_infrastructure"] = rv._cmp( + [t0[i] for i in ix], [b0[i] for i in ix], [grp[i] for i in ix], n_perm=2_000 + ) | {"episodes_sharing": sum(shared), "random_top1": rv._mean([rnd[i] for i in ix])} + + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + peak = peak_rss_bytes() + report["resources"] = { + "total_seconds": round(time.perf_counter() - t_start, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + "rpc_requests": 0, + } + return report diff --git a/tests/test_ml_lookalike_ranking.py b/tests/test_ml_lookalike_ranking.py index 47fb1a0..2e3b625 100644 --- a/tests/test_ml_lookalike_ranking.py +++ b/tests/test_ml_lookalike_ranking.py @@ -604,3 +604,127 @@ def test_recency_validation_runs_end_to_end_on_synthetic_data( bg = report["E14_background"] assert bg["windows_warning_set_preserved"] == bg["windows"] assert report["resources"]["rpc_requests"] == 0 + + +def _add_unconfirmed(d: Path, n: int = 20) -> dict[str, str]: + """U population next to a synthetic R directory: victims 0x...1001.., with unconfirmed + payoffs. Victim i = 0 also has a confirmed payoff row (excluded), victim i = 1 planted by + a frozen item's address under review (excluded), and one Phase 12.1 victim also sent an + unconfirmed payoff (excluded). Returns the special addresses.""" + import hashlib + import json + import sqlite3 + + from cryptoguard.ml import unconfirmed_recency as ur + from cryptoguard.ml.tsuchiya_archive import _DDL, PAYOFF_UNCONFIRMED + + out = d / ur.OUT_DIR + out.mkdir() + rows: list[tuple[Any, ...]] = [] + line = 10_000_000 + + def add( + block: int, sender: str, receiver: str, siv: bool, flags: int, intended: str | None + ) -> None: + nonlocal line + line += 1 + rows.append( + ( + line, + block, + f"0x{line:064x}", + USDT, + sender, + receiver, + int(siv), + 0.0, + 0.0, + flags, + intended, + None, + None, + ) + ) + + special: dict[str, str] = {} + for i in range(n): + v = f"0x{0x1001 + i:040x}" + ref = f"0x{0xBCD000 + i:06x}" + "0" * 30 + f"{i:04x}" + good = ref[:8] + "f" * 30 + ref[-4:] + rival = ref[:5] + "e" * 33 + ref[-4:] + b = 2_000_000 + 10_000 * i + add(b, v, ref, True, INTENDED, None) + late, early = (good, rival) if i % 2 else (rival, good) + add(b + 100, early, v, False, ZERO, ref) + add(b + 200, late, v, False, TINY, ref) + add(b + 300, v, good, True, PAYOFF_UNCONFIRMED, None) + if i == 0: + add(b + 50, v, good, True, PAYOFF, None) + special["confirmed"] = v + if i == 1: + special["under_review"] = early + r_victim = f"0x{2:040x}" # a Phase 12.1 victim of _synthetic_dir + add(9_000_000, r_victim, "0x" + "7" * 40, True, PAYOFF_UNCONFIRMED, None) + con = sqlite3.connect(out / ur.SUBSET) + con.executescript(_DDL) + con.executemany("insert into transfers values (?,?,?,?,?,?,?,?,?,?,?,?,?)", rows) + con.commit() + con.close() + cols = ("line", "block", "tx", "token", "sender", "receiver", "sender_is_victim") + unconf = [dict(zip(cols, r[:7], strict=True)) for r in rows if r[9] & PAYOFF_UNCONFIRMED] + data = b"".join(json.dumps(r, sort_keys=True).encode() + b"\n" for r in unconf) + (out / ur.ROWS).write_bytes(data) + (out / ur.SUMMARY).write_text(json.dumps({"rows_sha256": hashlib.sha256(data).hexdigest()})) + return special + + +def test_unconfirmed_population_exclusions_and_study( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from cryptoguard.ml import unconfirmed_recency as ur + + d = _synthetic_dir(tmp_path) + special = _add_unconfirmed(d) + protected = "0x" + f"{1:040x}" + monkeypatch.setattr(lr, "protected_wallets", lambda _d: frozenset({protected})) + monkeypatch.setattr( + lr, + "protected_entities", + lambda _d: (frozenset({protected, special["under_review"]}), frozenset()), + ) + eps, excluded = ur.load_u_episodes(d) + assert excluded == { + "has_confirmed_payoff_row": 1, + "phase12_1_payoff_victim": 1, + "protected_entity_overlap": 1, + } + assert len(eps) == 18 + assert special["confirmed"] not in {e.victim for e in eps} + report = ur.run(d) + assert report["episodes"] == 18 + assert report["U_H1"]["decision"] in {"survives", "explained_or_null", "inconclusive"} + assert report["U_H2"]["decision"] in { + "confirmation_implicated", + "not_implicated", + "inconclusive", + } + # The paid lookalike planted last in the odd episodes i = 3, 5, ..., 19: 9 of 18. + assert report["U_H1"]["T0_top1"] == pytest.approx(9 / 18, abs=1e-4) + assert report["UE1_rule_on_U"]["paid_SR_any_passes"]["episodes"] == 18 + assert report["resources"]["rpc_requests"] == 0 + + +@pytest.mark.parametrize( + ("diff", "ci", "expected"), + [ + (0.30, [0.20, 0.40], "confirmation_implicated"), + (0.02, [-0.05, 0.10], "not_implicated"), + (0.15, [0.05, 0.25], "inconclusive"), + ], +) +def test_unconfirmed_contrast_rule(diff: float, ci: list[float], expected: str) -> None: + from cryptoguard.ml import unconfirmed_recency as ur + + assert ur._contrast(diff, ci) == expected + assert ur._conclusion("survives", "not_implicated").startswith("the confirmation step does not") + assert ur._conclusion("survives", "inconclusive") == "inconclusive" From b3f66ae1792b68016c9b5f2549a4e342f5400637 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 12:33:57 +0300 Subject: [PATCH 49/92] docs(ml): unconfirmed-payoff recency results (addendum to Phase 12.2) Pre-registered test (8590366) on the source's 13,683 unconfirmed payoffs: inconclusive. Only 7 of 507 victims are rankable (T0 0.714 vs B0 0.024, p = 0.064, all 7 failing the source's confirmation rule). A labelled post-hoc diagnostic shows why: in 488 of the 499 excluded victims the paid address never planted to the victim, so the confirmation step mainly requires a prior planting, which the study's eligibility already requires symmetrically. 0 RPC requests, no downloads. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++ ML_RECENCY_VALIDATION.md | 92 ++++++++++++++++++++++++++++++++-------- ML_RESEARCH_PLAN.md | 11 +++++ 3 files changed, 90 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61c3172..733443c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,11 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. ### Recency validation and experimental warning ordering (Phase 12.2) +- **Follow-up** `cryptoguard ml unconfirmed-recency`: two offline passes, then a + pre-registered test on the source's 13,683 unconfirmed payoffs. The result is + inconclusive, with only 7 rankable episodes. In 488 of the 499 excluded victims, the paid + address never planted to the victim at all. `episode_from_rows` now takes the payoff + flag; its default behaviour is unchanged. - **Pre-registered study** `recency-validation/1`, run with `cryptoguard ml recency-validation`. It produces aggregate output and makes 0 RPC requests. diff --git a/ML_RECENCY_VALIDATION.md b/ML_RECENCY_VALIDATION.md index df0f617..b871a78 100644 --- a/ML_RECENCY_VALIDATION.md +++ b/ML_RECENCY_VALIDATION.md @@ -463,28 +463,83 @@ uv run --offline cryptoguard ml recency-validation ## 25. Recommended next experiment -Pre-register and run recency on the archive's **13,683 unconfirmed payoff rows**: -- Their victims are disjoint from the study, apart from 143 rows. -- They were never examined. -- They were *not* subjected to the confirmation step. +**Done since this section was first written:** the unconfirmed-payoff test (addendum §25a). +It was inconclusive by its own pre-registered rule, for lack of rankable episodes, and it +largely answers why. -**What it tests.** If recency also orders lookalikes there, the confirmation step is ruled -out as its cause, and with it the documented selection mechanism. If recency is much -weaker there, the confirmation step is implicated. +**Remaining step.** A genuinely independent test needs **newly recorded incidents**: their +outcome is known from public reports, and their candidate sets come from CryptoGuard's own +warnings. This needs: +- an approved RPC budget to record wallet windows, sized with `ml plan-collection`; +- a pre-registered OP1-versus-OP0 comparison of the kind in §15. -**Limitations:** -- the labels are uncertain by the source's own account, so results must be reported per - confirmation status; -- it is the same collection, so it still is not independent of the source's flagging - rules. +Alternatively, the BSC payoff file would allow a second-chain replication, but it needs +download approval. -**Cost:** -- two offline archive passes, about 2 hours on this disk, under 512 MiB; -- 0 RPC requests, no download; -- then the preloaded study, about 5 minutes. +## 25a. Addendum: recency on the source's unconfirmed payoffs -A genuinely independent test needs **newly recorded incidents**. That requires an approved -RPC budget, or the BSC payoff file, which requires download approval. +| Item | Value | +|---|---| +| Protocol | [`docs/ml/protocol-12.2-unconfirmed.md`](docs/ml/protocol-12.2-unconfirmed.md) (`8590366`), frozen before either pass | +| Code | `ml/unconfirmed_recency.py` (`89998d5`), committed before any U row existed | +| Output (git-ignored) | `data/ml/research/phase12.2/unconfirmed-recency.json`, `unconfirmed-posthoc.json` | + +**Population:** +- **Pass 1** (12 min, 68 MiB) found exactly 13,683 unconfirmed rows, all flagged + unconfirmed only. +- Their senders, after removing 107 Phase 12.1 victims and 2 protected wallets, are **507 + U victims**. +- **Pass 2** (22 min) stored 1,362,584 rows touching those victims, about 2,700 per victim. + +**Eligibility: only 7 episodes.** + +| Exclusion | Victims | +|---|---| +| paid address planted no earlier transfer | 499 | +| single candidate | 1 | +| victim also had a confirmed payoff | 0 | +| protected-entity overlap | 0 | + +**Pre-registered results:** + +| Test | Result | Decision | +|---|---|---| +| U-H1 | T0 0.714, B0 0.024, random 0.256; Δ +0.690 [0.357, 1.0]; p = 0.064; 7 episodes, 7 groups | inconclusive | +| U-H2 | D = Δ_R − Δ_U = −0.309 [−0.628, 0.045] | *not implicated* by the letter of the rule, but driven by 7 episodes | +| Conclusion | — | **inconclusive** | + +**Exploratory results (7 episodes):** +- **Every one of the 7 paid lookalikes *fails* the source's rule** under both SR_any and + SR_latest. They planted only before the victim's intended transfer. Recency still ranks + them first in 5 of 7. +- Within-episode permutation scores 0.248, close to random (0.256). Oldest-first scores 0. +- Only 1 episode has at least 2 production warnings including the paid address, so the + operational comparison is uninformative. + +**Post-hoc diagnostic (not pre-registered)** on the 499 excluded victims: +- in 488, the paid address **never** planted to the victim; +- in 11, it planted only after the payment; +- in 489, the paid address is nonetheless a detector-lookalike of an earlier intended + recipient; +- in 284, other lookalikes had planted before the payment; in 215, none had. + +**What this shows.** The source's unconfirmed payoffs are overwhelmingly transfers to +lookalike-shaped addresses *without any prior planting by that address*. + +So the confirmation step's main effect is to require a planting by the paid address before +the payoff. The Phase 12.1 eligibility rule already requires that, for paid and rival +candidates alike. + +On the timing question, the step leaves almost nothing to test: within rankable episodes, +it acts on rival timing only as the H1 rule does, and H1 showed that rule barely selects. + +**What this does not show:** +- It cannot tell whether those 488 transfers were poisoning losses whose planting the dump + lacks, deliberate payments, or source artifacts. +- It does not make recency independently validated. + +**Cost:** 34 minutes for the two passes, and 225 s for the analysis at 167 MiB peak. 0 RPC +requests, no download. ## Research output table @@ -496,6 +551,7 @@ RPC budget, or the BSC payoff file, which requires download approval. | H2 | O-arch | 1,057 (1,049) | T − 1 | production warnings | OP0 0.267 | OP1 0.502 | +0.235 [0.208, 0.263] | operational replay diagnostic | source-selected stream, no signers | 13 s | | H3 | X-inc | 3 rankable | harm − 1 | production warnings, recorded streams | OP0: 1/3 first | OP1: 3/3 first | — | external source, descriptive (n = 3) | tiny n; detector developed on these fixtures | < 1 s | | E14 | P2 | 9 windows | window end | production warnings | — | — | warning set preserved 9/9 | operational diagnostic | no labels | 8 ms | +| U-H1 (addendum §25a) | U, unconfirmed payoffs | 7 (7) | T − 1 | source plantings | B0 0.024 | T0 0.714 | +0.690 [0.357, 1.0] | inconclusive (n = 7); same source, label-uncertain | 499 of 507 victims unrankable (no prior planting by the paid address) | 34 min passes + 225 s | | Independent validation | — | — | — | — | — | — | — | **unsupported due to missing data** | — | — | ## Decision gates diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 15c3427..4ab78f4 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -231,3 +231,14 @@ with 0 RPC requests. Results are in [ML_RECENCY_VALIDATION.md](ML_RECENCY_VALIDA A genuinely independent test needs newly recorded incidents, which need an approved RPC budget. +**Follow-up (done):** recency on the 13,683 unconfirmed payoffs, pre-registered in +`docs/ml/protocol-12.2-unconfirmed.md`, is **inconclusive**. +- Only 7 of 507 victims are rankable. In 488 of the excluded, the paid address never + planted to the victim at all. +- In the 7 rankable episodes, recency ranks the paid address first in 5, even though all 7 + fail the confirmation rule. +- So the confirmation step mainly requires a prior planting by the paid address, which the + study's eligibility already requires symmetrically. +- Details: ML_RECENCY_VALIDATION.md §25a. +- **Next:** newly recorded incidents. They need an approved RPC budget. + From f0e4dc1845f3c6f962544bce7cf4b3e6ef7b340c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 13:13:51 +0300 Subject: [PATCH 50/92] docs(ml): audit the 12.2 follow-up; pre-register the Phase 12.3 incident benchmark Audit (from saved derived data, no archive pass): the attrition is a complete partition (616 senders -> 507 victims -> 499 + 1 + 7 episodes); B0's 0.024 is (1/6)/7 under the same tie-averaged top-1 as T0; the exact sign-flip p is 0.0625 (128 patterns), the sign test 0.219, and the bootstrap interval is not meaningful at n = 7. Decision unchanged. protocol-12.3 is frozen before any incident is searched for: evidence levels I-IV, replay tiers A / A' / B / C, a mandatory overlap audit, frozen methods at b3f66ae, exact small-sample reporting and fixed gate rules. Co-Authored-By: Claude Opus 5.5 --- ML_RECENCY_VALIDATION.md | 8 + docs/ml/amendment-12.2-unconfirmed-audit.md | 52 +++++ docs/ml/protocol-12.3.md | 205 ++++++++++++++++++++ 3 files changed, 265 insertions(+) create mode 100644 docs/ml/amendment-12.2-unconfirmed-audit.md create mode 100644 docs/ml/protocol-12.3.md diff --git a/ML_RECENCY_VALIDATION.md b/ML_RECENCY_VALIDATION.md index b871a78..68a58ed 100644 --- a/ML_RECENCY_VALIDATION.md +++ b/ML_RECENCY_VALIDATION.md @@ -541,6 +541,14 @@ it acts on rival timing only as the H1 rule does, and H1 showed that rule barely **Cost:** 34 minutes for the two passes, and 225 s for the analysis at 167 MiB peak. 0 RPC requests, no download. +**Audit (Phase 12.3, +[`docs/ml/amendment-12.2-unconfirmed-audit.md`](docs/ml/amendment-12.2-unconfirmed-audit.md)):** +- The attrition is a complete partition: 616 senders → 507 victims → 499 + 1 + 7. +- B0's 0.024 is (1/6)/7, the same tie-averaged metric as T0. +- The exact p is 0.0625, not the Monte Carlo 0.064, and the bootstrap interval is not + meaningful at n = 7. +- The decision is unchanged. + ## Research output table | Analysis | Population | Episodes (groups) | Cutoff | Candidate set | Baseline | New | Difference [95% CI] | Status | Main bias limitation | Runtime | diff --git a/docs/ml/amendment-12.2-unconfirmed-audit.md b/docs/ml/amendment-12.2-unconfirmed-audit.md new file mode 100644 index 0000000..439e17f --- /dev/null +++ b/docs/ml/amendment-12.2-unconfirmed-audit.md @@ -0,0 +1,52 @@ +# Amendment: audit of the Phase 12.2 unconfirmed-payoff follow-up + +**Basis.** This audit was made at the start of Phase 12.3. It uses the saved derived +subset (`data/ml/poisoning/unconfirmed/`), with no archive pass. +- **Output:** `data/ml/research/phase12.3/audit-12.2-unconfirmed.json` (git-ignored, + aggregates and per-episode values without addresses). +- **Not changed:** the original results (`unconfirmed-recency.json`) and the decision. + +## A. Attrition: a complete partition + +| Stage | In | Excluded | Out | +|---|---|---|---| +| Unconfirmed payoff rows (pass 1) | 13,683 rows | — | 616 distinct senders | +| Phase 12.1 payoff victims | 616 | 107 | 509 | +| Protected review wallets | 509 | 2 | **507 U victims** | +| Victim also has a confirmed payoff row | 507 | 0 | 507 | +| Paid address planted no earlier transfer | 507 | 499 | 8 | +| Single candidate | 8 | 1 | 7 | +| Protected-entity overlap | 7 | 0 | **7 rankable episodes** (one per victim) | + +The post-hoc split of the 499 is 488 that never planted and 11 that planted only after the +payment. Its "planted before: 8" equals the 7 episodes plus the 1 single-candidate victim. + +The numbers in §25a were consistent. They were presented at different stages without this +table. + +## B. B0 top-1 = 0.0238 + +Both methods use the same tie-averaged per-episode top-1 (`1/m` when the paid candidate is +among the m tied at the top, else 0), with every episode weighted equally. + +| | Episodes | B0 top-1 | +|---|---|---| +| B0 ranks another candidate strictly first; the paid address scores 0 (it passes the detector against none of the victim's recorded recipients) | 6 | 0 each | +| B0 abstains: the victim has no observed outgoing row, so all 6 candidates tie at random | 1 | 1/6 | + +So `0.0238 = (1/6) / 7`, which is directly comparable with T0's `5/7 = 0.714`. That 5/7 +counts T0 as strictly first in 5 episodes; it is never tied there. + +## C. Statistical significance + +- **The reported p = 0.064** came from 10,000 random sign flips over 7 singleton groups. + Only `2^7 = 128` patterns exist. +- **The exact two-sided p is 0.0625** (8/128). The smallest attainable p is 0.0156. +- **The exact sign test** gives p = 0.219 (5 wins, 1 loss, 1 tie). +- **T0 strictly first in 5 of 7** has an exact Clopper–Pearson 95% interval of + [0.29, 0.96]. +- **The bootstrap interval [0.357, 1.0] is not meaningful at n = 7.** It should be read as + descriptive only. + +**Correction:** report exact p = 0.0625 and exact counts. The decision is unchanged +(inconclusive). Future small-sample analyses report exact enumeration (protocol 12.3 §9). diff --git a/docs/ml/protocol-12.3.md b/docs/ml/protocol-12.3.md new file mode 100644 index 0000000..85048db --- /dev/null +++ b/docs/ml/protocol-12.3.md @@ -0,0 +1,205 @@ +# Phase 12.3 protocol: independent incident benchmark + +- **Task:** `incident-benchmark/1`. +- **Frozen:** committed before any new incident is searched for, selected or replayed. +- **Frozen components:** those at commit `b3f66ae`. + +## 1. Objective and question + +Can CryptoGuard's unchanged deterministic poisoning detector, using only information +available before a documented harmful transfer, do three things? +- (a) surface the outcome-linked address as a candidate; +- (b) warn on it; +- (c) with several warnings, rank it first, under the production order and under the frozen + recency order. + +The benchmark answers this per incident. It does not estimate population precision, recall +or a false-positive rate. + +## 2. Threat model and scope + +| Item | Scope | +|---|---| +| Chain | Ethereum mainnet only (chain id 1) | +| Mechanisms | address poisoning: zero-value transfers, spoofed `transferFrom`, dust or tiny transfers, counterfeit tokens | +| Harm | a victim-signed transfer to the lookalike | + +Approval, drainer and signature phishing are out of scope. + +## 3. Evidence levels (never pooled) + +| Level | Meaning | +|---|---| +| **I** | a new incident from an independently maintained public source, with no event, victim, lookalike or outcome overlap with development data (§6) | +| **II** | a new incident whose observations come from a known source family (the Tsuchiya archive), or whose overlap is partial or unknown | +| **III** | the 4 existing replay incidents (`replay/cases`) and every Phase 12.1/12.2 episode | +| **IV** | synthetic fixtures: software correctness only | + +## 4. Incident discovery + +Discovery is bounded: at most 8 web searches and 15 page reads. Sources are taken in this +order: +1. original postmortems and security-firm incident reports; +2. research papers; +3. reputable news reporting that quotes on-chain identifiers. + +Social-media-only claims are not enough. + +**Inclusion criteria:** +- the incident is on Ethereum mainnet; +- the mechanism is address poisoning; +- a public source gives the **harmful transaction hash**, or the **victim address and the + lookalike address**, verbatim. These are never inferred. + +**Exclusion criteria:** +- the chain or mechanism is out of scope; +- the identifiers are missing or contradict each other; +- the only source is unverifiable; +- the incident duplicates an existing fixture. + +## 5. Verification and eligibility tiers + +No RPC request is made. A case's identifiers count as **verified on chain** only if they +appear in a local on-chain record: a recorded fixture, or the Tsuchiya archive, whose block +range is 15,053,226–20,208,032. + +| Tier | Requirement | What it supports | +|---|---|---| +| **A, full operational replay** | a complete recorded wallet stream at the cutoff (a `ReplayFixture` with `transfer_scan_complete`) | candidate generation, warnings, ranking, lead time | +| **A′, archive-observation replay** | the harmful transaction is verified in the archive. Observations are the victim's source-kept rows at or before the cutoff: no signers, values only zero or nonzero, line order within a block. | the same as A, but on a source-selected stream | +| **B, warning-only** | verified warnings already produced (existing fixtures) | ranking only | +| **C, mechanism regression** | verified individual transactions | rule behaviour only | +| **Not evaluable** | the identifiers are unverifiable locally | reported with the missing evidence and the RPC needed | + +A **targeted offline archive pass** gathers the A′ rows (§12). Its targets are the +discovered victims and harmful transactions. Nothing is fetched. + +## 6. Overlap audit (mandatory, before evaluation) + +Each case is compared with: +- the Phase 12.1 episodes (victims, candidates, planting transactions); +- the Phase 12.2 U victims; +- the archive's confirmed and unconfirmed payoff rows (victim, receiver, transaction); +- the 4 replay fixtures; +- Poison-Hunter's ground-truth addresses; +- the frozen cohorts (blinded sheets only: wallet, address under review, transaction). + +The dimensions compared are: +- transaction; +- victim; +- lookalike or recipient; +- intended recipient; +- the linkage group of an overlapping Phase 12.1 episode. + +**Rules:** +- A shared public token contract never counts as overlap. +- Unknown overlap is never independence. + +**Classification:** +- no overlap on every checked dimension, and an independent outcome source: Level I; +- any partial overlap, or observations from the archive: Level II; +- a frozen-cohort overlap: excluded. + +## 7. Point-in-time reconstruction + +- **Cutoff:** `c = harm block − 1`. +- **Inputs:** only records at or before c. Harmful and later rows never enter. +- **Outcome information** (the harmful transaction, the recipient, public reports) is used + only to score. +- **Never used as features:** campaign membership, threat tags or later reuse. + +## 8. Methods (frozen at `b3f66ae`) + +The detector receives the full reconstructed stream. It is never given the outcome address. + +| Id | Method | +|---|---| +| B0 | unchanged `detect_poisoning` (tier A: `replay.engine.detector_outputs`, ERC-20 plus wallet transactions; tier A′: `recency_validation.production_cases`) | +| B1 / OP0 | production order: severity tier, then prefix+suffix; remaining ties tied | +| B3 / OP1 | `poisoning-warning-rank/1`: severity tier, then the latest planting signal at or before c | +| B4 | random: exact expectation 1/k | +| T0 (tier A′ only) | Phase 12.1 recency over the source-flagged planting candidates, reported for continuity | + +Nothing is tuned. A defect found during the evaluation is reported, but the frozen result +remains the result of record (§11). + +## 9. Metrics (per case; aggregates are exact counts) + +- **Candidate recovered:** the outcome address is among the detector's suspects at c. +- **Warned:** a production case exists for it at c, with its severity tier. +- **Ranks** under OP0 and OP1 (tie-averaged expected rank), top-1 per case, and the number + of competing warnings k. +- **Lead:** + - the harm block minus the block of the outcome address's first planting signal at or + before c; + - the harm block minus the earliest cutoff at which it is warned, found by replaying the + detector at each of that address's planting-signal blocks. + - This is an on-chain opportunity window. It is not when a warning was delivered. +- **Alert burden** (tier A only): warnings and distinct suspects at c. + +**Small samples:** +- exact counts and per-case tables; +- paired OP1 versus OP0, reported as better / equal / worse; +- an exact sign test only when at least 6 cases are untied; +- no intervals from asymptotic or bootstrap methods below 10 independent cases. + +## 10. Decision rules (per evidence level, never pooled) + +**Gate H (ranking usefulness)**, per level: + +| Status | Condition | +|---|---| +| PASS | at least 10 independent rankable cases, OP1 better in more cases than worse, and the exact sign test p < 0.05 | +| PASS WITH LIMITATIONS | fewer cases, OP1 never worse and better in at least 1 | +| FAIL | OP1 worse in more cases than better | +| NOT EVALUATED | no rankable case | + +**Gate G (warning coverage):** reported as exact counts of cases warned before the harm. + +**Phase classification:** +- **Independently supported operational result:** Gate H passes at Level I. +- **Limited external case-study result:** Level I or II cases exist but do not pass. +- **Data-limited:** no Level I or II case is evaluable. + +## 11. Negative controls and failure taxonomy + +**No false-positive rate is computed**, because no verified negatives exist. + +**Controls:** +- tier A background windows (no outcome) report warning burden only; +- synthetic negatives serve only as invariants. + +**Failure categories:** + +| Area | Categories | +|---|---| +| Candidate | not observed in the available records; insufficient history; similarity threshold not met; unsupported token semantics; unknown signer | +| Warning | candidate without a warning; wrong tier; invalid cutoff | +| Ranking | ranked below a competitor; a recent distractor; a tie | +| Research | ambiguous outcome; insufficient metadata; overlap; post-outcome information needed | + +## 12. Resources and stop conditions + +| Run | Budget | +|---|---| +| Targeted archive pass | at most 1 pass, under 30 min, under 512 MiB | +| Benchmark | under 2 min | + +0 RPC requests and no downloads. + +**Stop:** when the discovery budget is spent, or when no in-range candidate can be verified. +A data-limited report is then the deliverable. + +## 13. Provenance and licensing + +The committed manifest `docs/ml/incident-benchmark/candidates.json` holds per-case records. +Each record gives: +- the public source URL and publication date; +- the identifiers quoted; +- the verification status; +- the tier, level and overlap results. + +Public chain identifiers and URLs are committed. Archive-derived rows and per-case +archive evidence are not (CC BY-NC-ND), and stay under `data/ml/research/phase12.3/`. + +Synthetic manifests carry `"synthetic": true` and can never be verified. From 57273fd663dded2ac4171768be8727e33c9d4e59 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 13:24:11 +0300 Subject: [PATCH 51/92] feat(ml): offline incident benchmark (verify / run / report), not yet run Implements protocol-12.3 (f0e4dc1): - candidates.json: the bounded discovery's 10 candidates with their public sources and verbatim identifiers (truncated or absent ones recorded as such). The schema has no field for a candidate list, so an oracle input is rejected. - verify: identifier completeness, chain, archive range, tier and evidence level, cross-check against existing fixtures, and an overlap audit against every local development and review set; unreadable sets are "unknown", never independence; synthetic cases can never be verified. - run: tier A operational replay on complete recorded streams: candidate generation, production warnings at the cutoff, OP0 vs OP1 expected ranks, replay-engine lead times, alert burden and 6 perturbations. - report: per-case tables. Co-Authored-By: Claude Opus 5.5 --- docs/ml/incident-benchmark/candidates.json | 137 ++++++ src/cryptoguard/ml/cli.py | 37 ++ src/cryptoguard/ml/incident_benchmark.py | 503 +++++++++++++++++++++ tests/test_ml_incident_benchmark.py | 218 +++++++++ 4 files changed, 895 insertions(+) create mode 100644 docs/ml/incident-benchmark/candidates.json create mode 100644 src/cryptoguard/ml/incident_benchmark.py create mode 100644 tests/test_ml_incident_benchmark.py diff --git a/docs/ml/incident-benchmark/candidates.json b/docs/ml/incident-benchmark/candidates.json new file mode 100644 index 0000000..efcc3d4 --- /dev/null +++ b/docs/ml/incident-benchmark/candidates.json @@ -0,0 +1,137 @@ +{ + "schema_version": "incident-candidates/1", + "protocol": "protocol-12.3/1", + "discovery": { + "date": "2026-11-03", + "searches": 7, + "page_reads": 7, + "note": "Bounded per protocol 12.3 section 4. Identifiers are quoted verbatim from the cited public source; none is inferred. Truncated or absent identifiers are recorded as such." + }, + "candidates": [ + { + "case_id": "wbtc-1155-poisoning-2024-05-03", + "source": {"publisher": "replay fixture manifest (Phase 9)", "url": "src/cryptoguard/replay/cases/wbtc-1155-poisoning-2024-05-03/manifest.json", "date": "2024-05-03"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": null}, + "identifier_status": "from_fixture", + "fixture_case_id": "wbtc-1155-poisoning-2024-05-03", + "synthetic": false + }, + { + "case_id": "eth-140-poisoning-2025-08-14", + "source": {"publisher": "replay fixture manifest (Phase 9)", "url": "src/cryptoguard/replay/cases/eth-140-poisoning-2025-08-14/manifest.json", "date": "2025-08-15"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": null}, + "identifier_status": "from_fixture", + "fixture_case_id": "eth-140-poisoning-2025-08-14", + "synthetic": false + }, + { + "case_id": "usdt-50m-poisoning-2025-12-19", + "source": {"publisher": "Bitquery (independent documentation of an existing fixture)", "url": "https://bitquery.io/investigations/address-poisoning-ethereum", "date": "2026"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": { + "victim": "0xcb80784ef74c98a89b6ab8d96ebe890859600819", + "lookalike": "0xbaff2f13638c04b10f8119760b2d2ae86b08f8b5", + "intended": "0xbaf4b1af7e3b560d937da0458514552b6495f8b5", + "harm_tx": "0xc0514a795f065fce8a3e1238a1ba480e8a792d45f6431ee4ba8d800bedd86a0f" + }, + "identifier_status": "verbatim", + "fixture_case_id": "usdt-50m-poisoning-2025-12-19", + "synthetic": false + }, + { + "case_id": "eth-4556-poisoning-2026-01-30", + "source": {"publisher": "Bitquery (independent documentation of an existing fixture)", "url": "https://bitquery.io/investigations/address-poisoning-ethereum", "date": "2026"}, + "chain_id": 1, + "mechanism": "spoofed_transfer_from", + "identifiers": { + "victim": "0xd6741220a947941bf290799811fcdcea8ae4a7da", + "lookalike": "0x6d9052b2df589de00324127fe2707eb34e592e48", + "intended": "0x6d90cc8ce83b6d0acf634ed45d4bcc37eddd2e48", + "harm_tx": "0x7facade9d4731a639c4f31e84f5dfef0ddce8d2dc4d8a4399b72cd66817a8ac7" + }, + "identifier_status": "verbatim", + "fixture_case_id": "eth-4556-poisoning-2026-01-30", + "synthetic": false + }, + { + "case_id": "usdt-counterfeit-39890-2026-08-09", + "source": {"publisher": "Bitquery", "url": "https://bitquery.io/investigations/address-poisoning-ethereum", "date": "2026"}, + "chain_id": 1, + "mechanism": "counterfeit_token", + "identifiers": { + "victim": "0xb83f1c98b6d799f8ec56a002f2c0a2c343a0f50e", + "lookalike": "0x053dc459bade1baf76aed6e8630823f8392fda3a", + "intended": "0x053dba7292957341779cb0e9aae1aa7b139ada3a", + "planting_tx": "0xf84dacfeb3a92ae3291120d954b86d89932fe31702103754cad4f8e8ac41a10d", + "harm_tx": "0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb" + }, + "identifier_status": "verbatim", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "usdt-700k-2025-04", + "source": {"publisher": "Decrypt (citing PeckShield, Cyvers, AMLBot, Bubblemaps)", "url": "https://decrypt.co/316412/crypto-user-loses-700000-to-address-poisoning-scam-heres-what-happened", "date": "2025-04-25"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": { + "victim": null, + "lookalike": null, + "planting_tx": "0x30714a52580828b27d69a711601c637c1e93b06414aed782272d73186b2c1919", + "harm_tx": "0xa80805c97f5008637c4706b03316f61429ca3243f84b1124630d32a9540915df" + }, + "identifier_status": "partial: victim and lookalike not given (derivable only from chain data)", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "wbtc-2.38-2025-12-18", + "source": {"publisher": "Bitquery", "url": "https://bitquery.io/investigations/address-poisoning-ethereum", "date": "2026"}, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": "0xfda53b40c3b3ed13dbacc0df8f81141f6dde7c86164a013ae7ef24d883554a11"}, + "identifier_status": "partial: victim not named; lookalike truncated (0x65f3...773c)", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "dea-usdt-55k-2023", + "source": {"publisher": "Cointelegraph / The Block (citing Forbes and an FBI search warrant)", "url": "https://cointelegraph.com/news/dea-loses-tether-in-address-poisoning-scam", "date": "2023-08-25"}, + "chain_id": 1, + "mechanism": "token_airdrop", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": null}, + "identifier_status": "absent", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "usdt-100k-2026-08", + "source": {"publisher": "crypto.news (citing a Cyvers alert on X)", "url": "https://crypto.news/address-poisoning-attack-drains-100k-dollars-usdt/", "date": "2026-08-11"}, + "chain_id": null, + "mechanism": "unknown", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": null}, + "identifier_status": "absent", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "usdt-50k-2026-10", + "source": {"publisher": "crypto.news (citing a Scam Sniffer post on X)", "url": "https://crypto.news/address-poisoning-user-loss-50000/", "date": "2026-10-28"}, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": {"victim": null, "lookalike": null, "harm_tx": null}, + "identifier_status": "absent", + "fixture_case_id": null, + "synthetic": false + } + ], + "not_usable_sources": [ + {"source": "Guan and Li, CCS 2024 (Poison-Hunter), https://par.nsf.gov/servlets/purl/10580433", "reason": "PDF text not extractable without installing tooling (not approved); Poison-Hunter source family, Level II at best"}, + {"source": "Webacy, $25K USDC poisoning", "reason": "Base, not Ethereum mainnet"} + ] +} diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 585615c..830760b 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,14 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + ib = ml.add_parser( + "incident-benchmark", help="Phase 12.3 independent incident benchmark (offline)" + ) + ib.add_argument("step", choices=("verify", "run", "report")) + ib.add_argument( + "--manifest", type=Path, default=Path("docs/ml/incident-benchmark/candidates.json") + ) + ib.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.3") iv = ml.add_parser("inventory", help="hash and describe every local research data file") iv.add_argument("--root", type=Path, default=Path(".")) iv.add_argument("--out", type=Path, default=ML_DIR / "inventory.json") @@ -264,6 +272,35 @@ def run(args: argparse.Namespace) -> int: print(key, json.dumps(report[key], indent=1)) print(f"Wrote {args.out} (aggregate only; 0 RPC requests).") return 0 + if args.ml_command == "incident-benchmark": + import json + + from cryptoguard.ml import incident_benchmark as ib_ + + args.out.mkdir(parents=True, exist_ok=True) + verified_path = args.out / "incident-verify.json" + run_path = args.out / "incident-benchmark.json" + if args.step == "verify": + rows = ib_.verify(ib_.load_manifest(args.manifest), ML_DIR / "poisoning") + verified_path.write_text(json.dumps(rows, indent=1) + "\n", encoding="utf-8") + for r in rows: + print(f"{r['case_id']:40} {r['tier']:18} {r['status']}") + elif args.step == "run": + result = ib_.run() + run_path.write_text(json.dumps(result, indent=1, default=str) + "\n", encoding="utf-8") + print(json.dumps(result["summary_level_III"], indent=1)) + else: + for p in (verified_path, run_path): + if not p.exists(): + print(f"{p} is missing: run the verify and run steps first.") + return 1 + md = ib_.report( + json.loads(verified_path.read_text(encoding="utf-8")), + json.loads(run_path.read_text(encoding="utf-8")), + ) + (args.out / "incident-benchmark.md").write_text(md, encoding="utf-8") + print(md) + return 0 if args.ml_command == "inventory": import json diff --git a/src/cryptoguard/ml/incident_benchmark.py b/src/cryptoguard/ml/incident_benchmark.py new file mode 100644 index 0000000..01230f4 --- /dev/null +++ b/src/cryptoguard/ml/incident_benchmark.py @@ -0,0 +1,503 @@ +"""Independent incident benchmark (``incident-benchmark/1``), as pre-registered in +docs/ml/protocol-12.3.md. Offline only: it never fetches chain data. + +- ``verify``: a provenance, identifier, tier and overlap audit of every discovered case. +- ``run``: tier A operational replay of the cases with a complete recorded wallet stream. + The unchanged detector sees only records at or before the cutoff and is never told the + outcome address. Then come the production order (OP0), the frozen recency order (OP1), + lead times, alert burden and controlled perturbations. +- ``report``: the per-case table. + +Evidence levels are never pooled. Nothing here estimates precision, recall or a +false-positive rate. +""" + +from __future__ import annotations + +import json +import re +import time +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, ConfigDict + +BENCHMARK_VERSION = "incident-benchmark/1" +PROTOCOL = "protocol-12.3/1" +FROZEN_AT = "b3f66ae" +MANIFEST = Path("docs/ml/incident-benchmark/candidates.json") +ARCHIVE_BLOCKS = (15_053_226, 20_208_032) +ARCHIVE_LAST_DATE = "2024-06-30" # the archive's last block (~20.2M) is late June 2024 +RECORDING_RPC = (503, 1_361) # requests per 21,600-block window, measured on the 4 fixtures +DAY = 7_200 +_ADDR = re.compile(r"^0x[0-9a-f]{40}$") +_TX = re.compile(r"^0x[0-9a-f]{64}$") + + +class Source(BaseModel): + model_config = ConfigDict(extra="forbid") + + publisher: str + url: str + date: str + + +class Candidate(BaseModel): + """One discovered incident. There is deliberately no field for a candidate list: a + replay must find its candidates itself, never take them from the outcome side.""" + + model_config = ConfigDict(extra="forbid") + + case_id: str + source: Source + chain_id: int | None + mechanism: str + identifiers: dict[str, str | None] + identifier_status: str + fixture_case_id: str | None + synthetic: bool + + +class CandidateManifest(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: str + protocol: str + discovery: dict[str, Any] + candidates: list[Candidate] + not_usable_sources: list[dict[str, str]] = [] + + +def load_manifest(path: Path = MANIFEST) -> CandidateManifest: + m = CandidateManifest.model_validate_json(path.read_text(encoding="utf-8")) + if m.schema_version != "incident-candidates/1": + raise ValueError(f"{path}: unexpected schema {m.schema_version}") + ids = [c.case_id for c in m.candidates] + if len(ids) != len(set(ids)): + raise ValueError(f"{path}: duplicate case ids") + return m + + +# --- verify ------------------------------------------------------------------------------- + + +def _complete(ids: Mapping[str, str | None]) -> bool: + v, lk, tx = ids.get("victim"), ids.get("lookalike"), ids.get("harm_tx") + return bool(v and lk and tx and _ADDR.match(v) and _ADDR.match(lk) and _TX.match(tx)) + + +def reference_sets(poisoning_dir: Path) -> dict[str, frozenset[str] | None]: + """Local development and review identifiers. A set that cannot be read is ``None`` + (unknown), never empty.""" + from cryptoguard.ml import lookalike_ranking as lr + + def read_json(p: Path) -> Any: + return json.loads(p.read_text(encoding="utf-8")) if p.exists() else None + + out: dict[str, frozenset[str] | None] = {} + targets = read_json(poisoning_dir / "archive_targets.json") + for g in ( + "payoff_victims", + "payoff_lookalikes", + "payoff_txs", + "incident_victims", + "incident_recipients", + "incident_txs", + "ph_victims", + "ph_lookalikes", + "ph_txs", + ): + out[f"archive:{g}"] = None if targets is None else frozenset(targets["groups"].get(g, ())) + graph = read_json(poisoning_dir / lr.RESEARCH_DIR / "graph_context_targets.json") + for g in ("candidate_lookalikes", "planting_txs"): + out[f"phase12_1:{g}"] = None if graph is None else frozenset(graph["groups"].get(g, ())) + u = read_json(poisoning_dir / "unconfirmed" / "victim_targets.json") + out["phase12_2:u_victims"] = None if u is None else frozenset(u["groups"].get("u_victims", ())) + gt = Path("data/external/poison-hunter/phishing_address_groundtruth.txt") + out["poison_hunter:groundtruth"] = ( + frozenset(x.strip().lower() for x in gt.read_text().split() if x.startswith("0x")) + if gt.exists() + else None + ) + try: + addrs, txs = lr.protected_entities(poisoning_dir) + out["frozen_cohorts:addresses"], out["frozen_cohorts:txs"] = addrs, txs + except FileNotFoundError: + out["frozen_cohorts:addresses"] = out["frozen_cohorts:txs"] = None + return out + + +def fixture_sets(cases: Sequence[Any], exclude: str | None) -> dict[str, frozenset[str]]: + others = [c for c in cases if c.manifest.case_id != exclude] + return { + "fixtures:victims": frozenset(c.manifest.victim.lower() for c in others), + "fixtures:recipients": frozenset(c.manifest.harm.recipient.lower() for c in others), + "fixtures:harm_txs": frozenset(c.manifest.harm.transaction_hash.lower() for c in others), + } + + +def overlap( + ids: Mapping[str, str | None], sets: Mapping[str, frozenset[str] | None] +) -> dict[str, list[str]]: + """For every identifier: the reference sets it is in, plus ``unknown:`` for sets + that could not be read. Token contracts are never compared.""" + out: dict[str, list[str]] = {} + for key, value in ids.items(): + if not value: + continue + v = value.lower() + out[key] = sorted( + name if s is not None else f"unknown:{name}" + for name, s in sets.items() + if s is None or v in s + ) + return out + + +def verify( + manifest: CandidateManifest, + poisoning_dir: Path, + cases: Sequence[Any] | None = None, +) -> list[dict[str, Any]]: + from cryptoguard.replay.models import load_cases + + cases = load_cases() if cases is None else cases + by_id = {c.manifest.case_id: c for c in cases} + refs = reference_sets(poisoning_dir) + out: list[dict[str, Any]] = [] + for cand in manifest.candidates: + row: dict[str, Any] = {"case_id": cand.case_id, "source": cand.source.url} + if cand.synthetic: + out.append( + row + | { + "level": "IV", + "tier": "synthetic", + "verified": False, + "status": "synthetic: software correctness only", + } + ) + continue + if cand.chain_id != 1: + out.append( + row + | { + "level": None, + "tier": "excluded", + "verified": False, + "status": "excluded: chain not Ethereum mainnet or not stated", + } + ) + continue + ids = dict(cand.identifiers) + fx = by_id.get(cand.fixture_case_id or "") + if cand.fixture_case_id and fx is None: + raise ValueError(f"{cand.case_id}: fixture {cand.fixture_case_id} is missing") + sets = {**refs, **fixture_sets(cases, cand.fixture_case_id)} + if fx is not None: + m = fx.manifest + local = { + "victim": m.victim.lower(), + "lookalike": m.harm.recipient.lower(), + "harm_tx": m.harm.transaction_hash.lower(), + } + mismatch = sorted( + k for k, v in ids.items() if v and k in local and v.lower() != local[k] + ) + ids = {**local, **{k: v for k, v in ids.items() if v and k not in local}} + complete = fx.fixture is not None and fx.fixture.transfer_scan_complete + row |= { + "level": "III", + "tier": "A" if complete else "B", + "verified": not mismatch, + "status": "existing replay fixture" + + ( + "; independent source agrees on every identifier" + if cand.identifier_status == "verbatim" and not mismatch + else "" + ) + + (f"; MISMATCH on {mismatch}" if mismatch else ""), + "history": "complete for the recorded window only" if complete else "incomplete", + } + elif not _complete(ids): + row |= { + "level": None, + "tier": "not_evaluable", + "verified": False, + "status": f"not evaluable: identifiers incomplete ({cand.identifier_status})", + } + elif cand.source.date > ARCHIVE_LAST_DATE: + lo, hi = RECORDING_RPC + row |= { + "level": "I (if overlap stays empty)", + "tier": "not_evaluable", + "verified": False, + "status": "not evaluable offline: after the archive's range and no " + f"recorded wallet stream; recording needs about {lo}-{hi} RPC requests " + "per 3-day window (not authorized)", + } + else: + row |= { + "level": "II", + "tier": "A_prime_candidate", + "verified": False, + "status": "in archive range: needs the targeted offline archive lookup", + } + row["overlap"] = overlap(ids, sets) + flagged = { + k: [n for n in v if not n.startswith("unknown:")] for k, v in row["overlap"].items() + } + row["overlap_found"] = sorted({n for v in flagged.values() for n in v}) + if any(n.startswith("frozen_cohorts") for n in row["overlap_found"]): + row |= {"tier": "excluded", "status": "excluded: frozen review cohort overlap"} + out.append(row) + return out + + +# --- run (tier A) --------------------------------------------------------------------------- + + +def expected_rank(scores: Mapping[str, float], target: str) -> float: + """Rank of ``target`` under random tie-breaking (1 = first).""" + s = scores[target] + better = sum(1 for v in scores.values() if v > s) + tied = sum(1 for v in scores.values() if v == s) + return better + (tied + 1) / 2 + + +def trim(fixture: Any, cutoff: int) -> Any: + """The fixture as it stood at ``cutoff``: later records removed.""" + return fixture.model_copy( + update={ + "transfers": [t for t in fixture.transfers if t.block_number <= cutoff], + "wallet_transactions": [ + t for t in fixture.wallet_transactions if t.block_number <= cutoff + ], + } + ) + + +def warnings_at(fixture: Any, cutoff: int, visibility: Any) -> tuple[list[Any], list[Any]]: + """All production cases and the warning-rule cases at ``cutoff``. Takes no outcome.""" + from cryptoguard.detectors.poisoning import PoisoningConfig + from cryptoguard.replay.engine import WARNING_RULES, detector_outputs + + cases, newest = detector_outputs(fixture, cutoff, visibility, PoisoningConfig()) + if newest > cutoff and newest != -1: # -1: no input at all + raise RuntimeError(f"detector saw block {newest} after cutoff {cutoff}") + return cases, [c for c in cases if c.rule_id in WARNING_RULES] + + +def ranking(warnings: Sequence[Any], target: str, cutoff: int) -> dict[str, Any]: + from cryptoguard.ml import lookalike_ranking as lr + from cryptoguard.ml.recency_validation import _pack + from cryptoguard.ml.warning_rank import baseline_score, rank_warnings, recency_score + + k = len(warnings) + sus = [w.suspect.lower() for w in warnings] + if target not in sus: + return {"k": k, "target_warned": False} + s0: dict[str, float] = {w.suspect.lower(): _pack(baseline_score(w)) for w in warnings} + s1: dict[str, float] = {w.suspect.lower(): _pack(recency_score(w, cutoff)) for w in warnings} + shown = rank_warnings(list(warnings), cutoff) + return { + "k": k, + "target_warned": True, + "OP0_expected_rank": expected_rank(s0, target), + "OP1_expected_rank": expected_rank(s1, target), + "random_expected_rank": (k + 1) / 2, + "OP0_top1": round(lr.top1(s0, target, k), 4), + "OP1_top1": round(lr.top1(s1, target, k), 4), + "OP1_display_rank": next(r.rank for r in shown if r.suspect.lower() == target), + "warning_set_preserved": sorted(r.suspect for r in shown) + == sorted(w.suspect for w in warnings), + } + + +def _variants(fixture: Any, c: int) -> dict[str, tuple[Any, int, Any]]: + from cryptoguard.replay.engine import Visibility + + full = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS + unsigned = fixture.model_copy( + update={ + "transfers": [t.model_copy(update={"tx_sender": None}) for t in fixture.transfers], + "wallet_transactions": [], + } + ) + lookback = fixture.model_copy( + update={"transfers": [t for t in fixture.transfers if t.block_number > c - DAY]} + ) + doubled = fixture.model_copy(update={"transfers": fixture.transfers + fixture.transfers}) + return { + "primary": (fixture, c, full), + "delayed_300_blocks": (fixture, c - 300, full), + "delayed_1_day": (fixture, c - DAY, full), + "history_last_day_only": (lookback, c, full), + "erc20_only": (fixture, c, Visibility.ERC20_ONLY), + "signers_unknown": (unsigned, c, Visibility.ERC20_ONLY), + "duplicate_records": (doubled, c, full), + } + + +def run_case(case: Any) -> dict[str, Any]: + from cryptoguard.ml import candidates as cand + from cryptoguard.ml.warning_rank import PLANTING_SIGNALS + from cryptoguard.replay.engine import replay + + m, fx = case.manifest, case.fixture + c = m.harm.block_number - 1 + target = m.harm.recipient.lower() + t = time.perf_counter() + gen = cand.generate(trim(fx, c)) + looks = {g.event.lookalike for g in gen} + rep = replay(m, fx) + out: dict[str, Any] = { + "case_id": m.case_id, + "level": "III", + "tier": "A", + "cutoff": c, + "harm_block": m.harm.block_number, + "window_blocks": fx.to_block - fx.from_block, + "history": "complete for the recorded window only", + "candidates": { + "generated": len(gen), + "distinct_lookalikes": len(looks), + "target_recovered": target in looks, + "target_methods": sorted( + {x for g in gen if g.event.lookalike == target for x in g.methods} + ), + }, + "visibilities": { + r.visibility.value: { + "outcome": r.outcome, + "first_warning_block": r.first_warning.block_number if r.first_warning else None, + "lead_time_blocks": r.lead_time_blocks, + "lead_time_seconds": r.lead_time_seconds, + "other_addresses_flagged_before_harm": r.other_addresses_flagged_before_harm, + } + for r in rep.results + }, + "leakage_checks_passed": all(ch.passed for ch in rep.leakage_checks), + } + variants: dict[str, Any] = {} + for name, (f, cut, vis) in _variants(fx, c).items(): + if cut < fx.from_block: + variants[name] = {"k": 0, "target_warned": None, "note": "cutoff before the window"} + continue + cases_all, warns = warnings_at(f, cut, vis) + entry = ranking(warns, target, cut) | {"production_cases": len(cases_all)} + if name == "primary": + mine = next((w for w in warns if w.suspect.lower() == target), None) + plants = ( + [ + s.block_number + for s in mine.signals + if s.code in PLANTING_SIGNALS + and s.block_number is not None + and s.block_number <= cut + ] + if mine + else [] + ) + entry["target_first_planting_signal_lead_blocks"] = ( + m.harm.block_number - min(plants) if plants else None + ) + entry["target_severity"] = mine.severity.value if mine else None + days = max(1.0, (cut - fx.from_block) / DAY) + entry["warnings_per_wallet_day"] = round(len(warns) / days, 3) + variants[name] = entry + out["ranking"] = variants + out["seconds"] = round(time.perf_counter() - t, 3) + return out + + +def run(cases: Sequence[Any] | None = None) -> dict[str, Any]: + from cryptoguard.ml.recency_validation import background + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + from cryptoguard.replay.models import load_cases + + t = time.perf_counter() + cases = load_cases() if cases is None else cases + tier_a = [c for c in cases if c.fixture is not None and c.fixture.transfer_scan_complete] + results = [run_case(c) for c in tier_a] + rankable = [ + r + for r in results + if r["ranking"]["primary"].get("target_warned") and r["ranking"]["primary"]["k"] >= 2 + ] + paired = {"better": 0, "equal": 0, "worse": 0} + for r in rankable: + p = r["ranking"]["primary"] + d = p["OP0_expected_rank"] - p["OP1_expected_rank"] + paired["better" if d > 0 else "worse" if d < 0 else "equal"] += 1 + peak = peak_rss_bytes() + return { + "benchmark": BENCHMARK_VERSION, + "protocol": PROTOCOL, + "methods_frozen_at": FROZEN_AT, + "evidence_level": ( + "III (existing replay incidents); no Level I or II case is evaluable offline" + ), + "cases": results, + "summary_level_III": { + "tier_A_cases": len(results), + "target_recovered_as_candidate": sum( + r["candidates"]["target_recovered"] for r in results + ), + "target_warned_at_cutoff": sum( + bool(r["ranking"]["primary"].get("target_warned")) for r in results + ), + "early_warning_full_visibility": sum( + r["visibilities"]["erc20_plus_wallet_transactions"]["outcome"] == "early_warning" + for r in results + ), + "rankable_cases": len(rankable), + "OP1_vs_OP0": paired, + "OP0_top1_cases": sum(r["ranking"]["primary"]["OP0_top1"] == 1.0 for r in rankable), + "OP1_top1_cases": sum(r["ranking"]["primary"]["OP1_top1"] == 1.0 for r in rankable), + }, + "background_alert_burden": background(), + "resources": { + "seconds": round(time.perf_counter() - t, 2), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + "rpc_requests": 0, + }, + } + + +# --- report --------------------------------------------------------------------------------- + + +def report(verified: Sequence[Mapping[str, Any]], result: Mapping[str, Any]) -> str: + """Markdown tables: every candidate's status, then the tier A per-case results.""" + + def cell(x: Any) -> str: + return "—" if x is None else str(x) + + lines = [ + "| Case | Level | Tier | Verified | Overlap found | Status |", + "|---|---|---|---|---|---|", + ] + for v in verified: + lines.append( + f"| {v['case_id']} | {cell(v.get('level'))} | {v['tier']} | {v['verified']} | " + f"{', '.join(v.get('overlap_found', [])) or 'none found'} | {v['status']} |" + ) + lines += [ + "", + "| Case | Candidate recovered | Warned at cutoff | Pre-harm warning | Lead blocks | k " + "| OP0 rank | OP1 rank | Random rank |", + "|---|---|---|---|---|---|---|---|---|", + ] + for r in result["cases"]: + p = r["ranking"]["primary"] + vis = r["visibilities"]["erc20_plus_wallet_transactions"] + lines.append( + f"| {r['case_id']} | {r['candidates']['target_recovered']} | " + f"{p.get('target_warned')} | " + f"{vis['outcome'] == 'early_warning'} | {cell(vis['lead_time_blocks'])} | {p['k']} | " + f"{cell(p.get('OP0_expected_rank'))} | {cell(p.get('OP1_expected_rank'))} | " + f"{cell(p.get('random_expected_rank'))} |" + ) + return "\n".join(lines) + "\n" diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py new file mode 100644 index 0000000..6e342e5 --- /dev/null +++ b/tests/test_ml_incident_benchmark.py @@ -0,0 +1,218 @@ +"""Phase 12.3 incident benchmark: manifest validation, provenance and overlap audit, tier +assignment, and an end-to-end operational replay on a synthetic incident (software +correctness only, never evidence).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from cryptoguard.ml import incident_benchmark as ib +from cryptoguard.replay.models import ReplayCase +from tests.integration.test_replay import HARM, fixture, manifest +from tests.unit.test_poisoning import ATTACKER_SIGNER, FAKE, REAL, WALLET, addr, transfer + +FAKE2 = addr("a1b2c" + "8" * 30 + "4e5f6") # a second lookalike of REAL + + +def cand(**over: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "case_id": "c1", + "source": {"publisher": "p", "url": "https://example.org", "date": "2026-08-09"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": { + "victim": "0x" + "a" * 40, + "lookalike": "0x" + "b" * 40, + "harm_tx": "0x" + "c" * 64, + }, + "identifier_status": "verbatim", + "fixture_case_id": None, + "synthetic": False, + } + base.update(over) + return base + + +def manifest_of(*cands: dict[str, Any]) -> ib.CandidateManifest: + return ib.CandidateManifest.model_validate( + { + "schema_version": "incident-candidates/1", + "protocol": "p", + "discovery": {}, + "candidates": list(cands), + } + ) + + +def no_refs(_d: Path) -> dict[str, frozenset[str] | None]: + return { + "frozen_cohorts:addresses": frozenset({"0x" + "f" * 40}), + "phase12_1:candidate_lookalikes": None, + } + + +# --- manifest ------------------------------------------------------------------------------- + + +def test_committed_manifest_is_valid_and_has_no_synthetic_case() -> None: + m = ib.load_manifest() + assert m.candidates + assert not any(c.synthetic for c in m.candidates) + + +def test_an_oracle_candidate_list_is_rejected(tmp_path: Path) -> None: + bad = cand() | {"candidate_list": ["0x" + "b" * 40]} + with pytest.raises(ValidationError): + manifest_of(bad) + p = tmp_path / "m.json" + p.write_text( + json.dumps( + { + "schema_version": "incident-candidates/1", + "protocol": "p", + "discovery": {}, + "candidates": [cand(), cand()], + } + ) + ) + with pytest.raises(ValueError, match="duplicate"): + ib.load_manifest(p) + + +# --- verify --------------------------------------------------------------------------------- + + +def test_tiers_follow_identifiers_chain_date_and_synthetic_flag( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(ib, "reference_sets", no_refs) + rows = { + r["case_id"]: r + for r in ib.verify( + manifest_of( + cand(case_id="late"), + cand( + case_id="in_range", source={"publisher": "p", "url": "u", "date": "2023-05-01"} + ), + cand(case_id="partial", identifiers={"victim": None, "harm_tx": "0x" + "c" * 64}), + cand( + case_id="truncated", + identifiers={ + "victim": "0x65f3...773c", + "lookalike": "0x" + "b" * 40, + "harm_tx": "0x" + "c" * 64, + }, + ), + cand(case_id="base", chain_id=8453), + cand(case_id="synth", synthetic=True), + ), + Path("unused"), + cases=[], + ) + } + assert rows["late"]["tier"] == "not_evaluable" + assert "RPC" in rows["late"]["status"] + assert rows["in_range"]["tier"] == "A_prime_candidate" + assert rows["partial"]["tier"] == rows["truncated"]["tier"] == "not_evaluable" + assert rows["base"]["tier"] == "excluded" + assert rows["synth"]["level"] == "IV" + assert rows["synth"]["verified"] is False # synthetic can never be verified real + # A set that could not be read is unknown, never evidence of independence. + assert rows["late"]["overlap"]["lookalike"] == ["unknown:phase12_1:candidate_lookalikes"] + assert rows["late"]["overlap_found"] == [] + + +def test_frozen_cohort_overlap_excludes_a_case(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ib, "reference_sets", no_refs) + [row] = ib.verify( + manifest_of( + cand( + identifiers={ + "victim": "0x" + "f" * 40, + "lookalike": "0x" + "b" * 40, + "harm_tx": "0x" + "c" * 64, + } + ) + ), + Path("unused"), + cases=[], + ) + assert row["tier"] == "excluded" + assert row["overlap_found"] == ["frozen_cohorts:addresses"] + + +def test_fixture_identifiers_are_cross_checked(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ib, "reference_sets", no_refs) + case = ReplayCase(manifest=manifest(), fixture=fixture([]), fixture_sha256=None) + ok = cand( + fixture_case_id="synthetic", + identifiers={"victim": WALLET.lower(), "lookalike": FAKE.lower(), "harm_tx": None}, + ) + bad = cand( + case_id="c2", + fixture_case_id="synthetic", + identifiers={"victim": "0x" + "1" * 40, "lookalike": None, "harm_tx": None}, + ) + rows = ib.verify(manifest_of(ok, bad), Path("unused"), cases=[case]) + assert rows[0]["verified"] is True + assert rows[0]["level"] == "III" + assert rows[0]["tier"] == "A" + assert rows[1]["verified"] is False + assert "MISMATCH" in rows[1]["status"] + + +# --- run -------------------------------------------------------------------------------------- + + +def incident(extra: list[Any] | None = None) -> ReplayCase: + """Legitimate payments to REAL, an older lookalike FAKE2 (block 105), a newer one FAKE + (block 120), and the theft to FAKE at HARM.""" + ts = [ + transfer(WALLET, REAL, 5, 100, signer=WALLET), + transfer(WALLET, FAKE2, 0, 105, signer=ATTACKER_SIGNER), + transfer(WALLET, FAKE, 0, 120, signer=ATTACKER_SIGNER), + transfer(WALLET, FAKE, 1000, HARM, signer=WALLET), + *(extra or []), + ] + return ReplayCase(manifest=manifest(), fixture=fixture(ts), fixture_sha256=None) + + +def test_end_to_end_replay_finds_warns_and_ranks_without_the_outcome() -> None: + r = ib.run_case(incident()) + assert r["candidates"]["target_recovered"] is True + full = r["visibilities"]["erc20_plus_wallet_transactions"] + assert full["outcome"] == "early_warning" + assert full["lead_time_blocks"] == HARM - 120 + p = r["ranking"]["primary"] + assert p["target_warned"] is True + assert p["k"] == 2 + assert p["OP1_expected_rank"] == 1.0 # the most recent planting + assert p["OP0_expected_rank"] == 1.5 # same tier and similarity: tied + assert p["warning_set_preserved"] is True + assert p["target_first_planting_signal_lead_blocks"] == HARM - 120 + assert r["leakage_checks_passed"] is True + # Observed 300 blocks late, the window holds nothing yet; a day late, it is unobservable. + assert r["ranking"]["delayed_1_day"]["note"] == "cutoff before the window" + assert r["ranking"]["duplicate_records"]["OP1_expected_rank"] == 1.0 + md = ib.report([], {"cases": [r]}) + assert "| synthetic | True | True | True | 10 | 2 | 1.5 | 1.0 | 1.5 |" in md + + +def test_future_records_cannot_change_the_ranking_at_the_cutoff() -> None: + later = transfer(WALLET, FAKE2, 0, HARM + 5, signer=ATTACKER_SIGNER) + a = ib.run_case(incident())["ranking"]["primary"] + b = ib.run_case(incident([later]))["ranking"]["primary"] + assert a == b + + +def test_expected_rank_and_trim() -> None: + assert ib.expected_rank({"a": 3, "b": 3, "c": 1}, "a") == 1.5 + assert ib.expected_rank({"a": 1, "b": 3, "c": 3}, "a") == 3.0 + f = incident().fixture + assert f is not None + assert max(t.block_number for t in ib.trim(f, 110).transfers) == 105 From f3477f52a984777ebc65fa6f079f3710d362e1d5 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 13:38:51 +0300 Subject: [PATCH 52/92] fix(ml): never compute on recorded windows that hold frozen review items The Phase 12.3 overlap audit found that frozen Cohort B holds 2 items in each of the 4 recorded incident windows (and 3 of 9 background windows belong to protected wallets); frozen addresses even appeared among the competing warnings in 3 incidents. Phase 12.1 availability and Phase 12.2 H3 and E14 therefore computed on frozen items, against protocol 12.1 section 3. No label exists and nothing was tuned, but the results are withdrawn. - recency_validation.touches_frozen: a window whose wallet, transfer party or transaction is frozen; skipped by incidents(), background() and lookalike_study.availability(). - incident_benchmark.run now takes verify's output and computes only the cases it admitted, and never a window holding a frozen item. - Tests cover each exclusion. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/cli.py | 10 ++++++- src/cryptoguard/ml/incident_benchmark.py | 29 ++++++++++++++++--- src/cryptoguard/ml/lookalike_study.py | 11 +++++-- src/cryptoguard/ml/recency_validation.py | 36 +++++++++++++++++++---- tests/test_ml_incident_benchmark.py | 37 ++++++++++++++++++++++++ 5 files changed, 110 insertions(+), 13 deletions(-) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 830760b..9dff331 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -286,7 +286,15 @@ def run(args: argparse.Namespace) -> int: for r in rows: print(f"{r['case_id']:40} {r['tier']:18} {r['status']}") elif args.step == "run": - result = ib_.run() + from cryptoguard.ml import lookalike_ranking + + if not verified_path.exists(): + print(f"{verified_path} is missing: run the verify step first.") + return 1 + result = ib_.run( + json.loads(verified_path.read_text(encoding="utf-8")), + lookalike_ranking.protected_entities(ML_DIR / "poisoning"), + ) run_path.write_text(json.dumps(result, indent=1, default=str) + "\n", encoding="utf-8") print(json.dumps(result["summary_level_III"], indent=1)) else: diff --git a/src/cryptoguard/ml/incident_benchmark.py b/src/cryptoguard/ml/incident_benchmark.py index 01230f4..69311e3 100644 --- a/src/cryptoguard/ml/incident_benchmark.py +++ b/src/cryptoguard/ml/incident_benchmark.py @@ -412,14 +412,34 @@ def run_case(case: Any) -> dict[str, Any]: return out -def run(cases: Sequence[Any] | None = None) -> dict[str, Any]: - from cryptoguard.ml.recency_validation import background +def run( + verified: Sequence[Mapping[str, Any]], + blind: tuple[frozenset[str], frozenset[str]], + cases: Sequence[Any] | None = None, +) -> dict[str, Any]: + """Tier A replay of the cases ``verify`` admitted. A case it excluded, or one whose + recorded window holds a frozen review item, is never computed.""" + from cryptoguard.ml.recency_validation import background, touches_frozen from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes from cryptoguard.replay.models import load_cases t = time.perf_counter() cases = load_cases() if cases is None else cases - tier_a = [c for c in cases if c.fixture is not None and c.fixture.transfer_scan_complete] + admitted = {v["case_id"] for v in verified if v["tier"] == "A"} + by_fixture = {v["case_id"]: v for v in verified} + skipped: list[dict[str, str]] = [] + tier_a = [] + for c in cases: + if c.fixture is None or not c.fixture.transfer_scan_complete: + continue + cid = c.manifest.case_id + if cid not in admitted: + status = by_fixture.get(cid, {}).get("status", "not in the verified manifest") + skipped.append({"case_id": cid, "reason": status}) + elif touches_frozen(c.fixture, blind): + skipped.append({"case_id": cid, "reason": "recorded window holds a frozen review item"}) + else: + tier_a.append(c) results = [run_case(c) for c in tier_a] rankable = [ r @@ -440,6 +460,7 @@ def run(cases: Sequence[Any] | None = None) -> dict[str, Any]: "III (existing replay incidents); no Level I or II case is evaluable offline" ), "cases": results, + "not_computed": skipped, "summary_level_III": { "tier_A_cases": len(results), "target_recovered_as_candidate": sum( @@ -457,7 +478,7 @@ def run(cases: Sequence[Any] | None = None) -> dict[str, Any]: "OP0_top1_cases": sum(r["ranking"]["primary"]["OP0_top1"] == 1.0 for r in rankable), "OP1_top1_cases": sum(r["ranking"]["primary"]["OP1_top1"] == 1.0 for r in rankable), }, - "background_alert_burden": background(), + "background_alert_burden": background(blind), "resources": { "seconds": round(time.perf_counter() - t, 2), "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), diff --git a/src/cryptoguard/ml/lookalike_study.py b/src/cryptoguard/ml/lookalike_study.py index bae264e..cf5114b 100644 --- a/src/cryptoguard/ml/lookalike_study.py +++ b/src/cryptoguard/ml/lookalike_study.py @@ -246,9 +246,11 @@ def coverage(poisoning_dir: Path, protected: frozenset[str]) -> dict[str, Any]: # --- P2 and P3 ------------------------------------------------------------------------------ -def availability() -> dict[str, Any]: - """Which ranking features a production-like recording can compute (P2, P3).""" +def availability(blind: tuple[frozenset[str], frozenset[str]]) -> dict[str, Any]: + """Which ranking features a production-like recording can compute (P2, P3). Windows + holding a frozen review item are skipped (amendment 12.2-cohort-overlap).""" from cryptoguard.ml import candidates as cand + from cryptoguard.ml.recency_validation import touches_frozen from cryptoguard.replay.background import load_background from cryptoguard.replay.models import load_cases @@ -257,6 +259,8 @@ def availability() -> dict[str, Any]: ("P2_background", [b.fixture for b in load_background() if b.fixture]), ("P3_incidents", [c.fixture for c in load_cases() if c.fixture]), ): + skipped = sum(touches_frozen(fx, blind) for fx in fixtures) + fixtures = [fx for fx in fixtures if not touches_frozen(fx, blind)] n = with_ref = multi = 0 per_wallet: list[int] = [] t0 = time.perf_counter() @@ -269,6 +273,7 @@ def availability() -> dict[str, Any]: multi += len(looks) >= 2 out[label] = { "windows": len(fixtures), + "windows_excluded_frozen_cohort": skipped, "candidates": n, "candidates_with_reference": with_ref, "windows_with_2plus_lookalikes": multi, @@ -752,7 +757,7 @@ def run(poisoning_dir: Path, *, lazy_graph: bool = False) -> dict[str, Any]: report["recency_gap_posthoc"] = recency_gap_diagnostic(episodes) report["coverage_task1"] = coverage(poisoning_dir, lr.protected_wallets(poisoning_dir)) - report["availability"] = availability() + report["availability"] = availability(lr.protected_entities(poisoning_dir)) from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes peak = peak_rss_bytes() diff --git a/src/cryptoguard/ml/recency_validation.py b/src/cryptoguard/ml/recency_validation.py index d106607..65ed2f1 100644 --- a/src/cryptoguard/ml/recency_validation.py +++ b/src/cryptoguard/ml/recency_validation.py @@ -167,7 +167,25 @@ def _pack(t: tuple[int, ...]) -> int: # --- recorded incidents (H3) and background windows (E14) --------------------------------- -def incidents() -> list[dict[str, Any]]: +Blind = tuple[frozenset[str], frozenset[str]] # frozen-cohort (addresses, transactions) + + +def touches_frozen(fixture: Any, blind: Blind) -> bool: + """A recorded window that holds a frozen review item: its wallet, or any transfer whose + party or transaction is a frozen address or transaction. Such a window never enters a + computation (protocol 12.1 section 3; amendment 12.2-cohort-overlap).""" + addrs, txs = blind + if fixture.wallet.lower() in addrs: + return True + return any( + t.sender.lower() in addrs + or t.recipient.lower() in addrs + or t.transaction_hash.lower() in txs + for t in fixture.transfers + ) + + +def incidents(blind: Blind) -> list[dict[str, Any]]: from cryptoguard.detectors.poisoning import PoisoningConfig from cryptoguard.ml.warning_rank import rank_warnings from cryptoguard.replay.engine import Visibility, detector_outputs @@ -178,6 +196,9 @@ def incidents() -> list[dict[str, Any]]: if case.fixture is None: continue m = case.manifest + if touches_frozen(case.fixture, blind): + out.append({"case": m.case_id, "excluded": "holds a frozen review item"}) + continue c = m.harm.block_number - 1 cases, _ = detector_outputs( case.fixture, c, Visibility.ERC20_PLUS_WALLET_TRANSACTIONS, PoisoningConfig() @@ -196,17 +217,20 @@ def incidents() -> list[dict[str, Any]]: return out -def background() -> dict[str, Any]: +def background(blind: Blind) -> dict[str, Any]: from cryptoguard.detectors.poisoning import PoisoningConfig from cryptoguard.ml.warning_rank import baseline_score, rank_warnings from cryptoguard.replay.background import load_background from cryptoguard.replay.engine import Visibility, detector_outputs t = time.perf_counter() - windows = multi = changed = preserved = no_basis = n = 0 + windows = multi = changed = preserved = no_basis = n = excluded = 0 for b in load_background(): if b.fixture is None: continue + if touches_frozen(b.fixture, blind): + excluded += 1 + continue windows += 1 c = b.fixture.to_block cases, _ = detector_outputs( @@ -227,6 +251,7 @@ def background() -> dict[str, Any]: "windows_order_changed": changed, "windows_warning_set_preserved": preserved, "warnings_without_recency_basis": no_basis, + "windows_excluded_frozen_cohort": excluded, "seconds": round(time.perf_counter() - t, 3), } @@ -430,7 +455,8 @@ def sr_keep(i: int, c: str) -> bool: report["H1_SR_none_included"] = _restricted( episodes, feats, grp, lambda i, c: sr[i][c][0] is not False ) - report["H3_incidents"] = incidents() + blind = lr.protected_entities(poisoning_dir) + report["H3_incidents"] = incidents(blind) # E1 within-episode permutation of T0; E2 reversed time. rng = random.Random(SEED) # noqa: S311 - seeded research sampling, not security @@ -635,7 +661,7 @@ def reorder(e: lr.Episode) -> lr.Episode: cat["B0_tied_at_top"] += 0 < b0[i] < 1 report["E12_errors"] = {k: {"episodes": v, **cats[k]} for k, v in sorted(cells.items())} - report["E14_background"] = background() + report["E14_background"] = background(blind) from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes peak = peak_rss_bytes() diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py index 6e342e5..0bb589d 100644 --- a/tests/test_ml_incident_benchmark.py +++ b/tests/test_ml_incident_benchmark.py @@ -216,3 +216,40 @@ def test_expected_rank_and_trim() -> None: f = incident().fixture assert f is not None assert max(t.block_number for t in ib.trim(f, 110).transfers) == 105 + + +def test_run_never_computes_excluded_or_frozen_cases() -> None: + case = incident() + admitted = [{"case_id": "synthetic", "tier": "A", "status": "ok"}] + none: tuple[frozenset[str], frozenset[str]] = (frozenset(), frozenset()) + assert len(ib.run(admitted, none, cases=[case])["cases"]) == 1 + excluded = [ + { + "case_id": "synthetic", + "tier": "excluded", + "status": "excluded: frozen review cohort overlap", + } + ] + r = ib.run(excluded, none, cases=[case]) + assert r["cases"] == [] + assert r["not_computed"][0]["reason"].startswith("excluded") + # Even when admitted, a window holding a frozen address (here a competing lookalike) is + # never computed. + frozen = (frozenset({FAKE2.lower()}), frozenset()) + r = ib.run(admitted, frozen, cases=[case]) + assert r["cases"] == [] + assert r["not_computed"][0]["reason"] == "recorded window holds a frozen review item" + + +def test_phase_12_2_replays_skip_windows_with_frozen_items() -> None: + from cryptoguard.ml import recency_validation as rv + from cryptoguard.replay.models import load_cases + + cases = [c for c in load_cases() if c.fixture is not None] + victims = frozenset(c.manifest.victim.lower() for c in cases) + out = rv.incidents((victims, frozenset())) + assert all(e.get("excluded") == "holds a frozen review item" for e in out) + f = cases[0].fixture + assert f is not None + assert rv.touches_frozen(f, (frozenset(), frozenset({f.transfers[0].transaction_hash.lower()}))) + assert not rv.touches_frozen(f, (frozenset(), frozenset())) From c9e328ecfc6d755227ec212000f3b6dcf1db48ff Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 13:38:53 +0300 Subject: [PATCH 53/92] docs(ml): Phase 12.3 incident benchmark report (data-limited); cohort amendment ML_INDEPENDENT_INCIDENT_BENCHMARK.md: bounded discovery found 10 candidates; the only new case with complete identifiers (Aug 2026, counterfeit USDT) is after the local archive and needs an RPC recording; the others lack identifiers; the 4 recorded fixtures are excluded for frozen-cohort overlap. No Level I or II case is evaluable: data-limited. The amendment withdraws Phase 12.2 H3 and E14; a corrected re-run shows every archive result unchanged. Earlier reports carry a pointer, their text otherwise kept. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + ML.md | 9 + ML_INDEPENDENT_INCIDENT_BENCHMARK.md | 338 +++++++++++++++++++++++ ML_RECENCY_VALIDATION.md | 8 + ML_RESEARCH_PLAN.md | 15 + ML_TEMPORAL_GRAPH_RESEARCH.md | 6 + docs/ml/amendment-12.2-cohort-overlap.md | 63 +++++ 7 files changed, 451 insertions(+) create mode 100644 ML_INDEPENDENT_INCIDENT_BENCHMARK.md create mode 100644 docs/ml/amendment-12.2-cohort-overlap.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 733443c..5f27f20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,18 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Independent incident benchmark (Phase 12.3) +- **New command:** `cryptoguard ml incident-benchmark verify / run / report`. It runs + offline and is bound to a protocol: + - a provenance, tier and overlap audit of discovered incidents; + - tier A replay with candidates, warnings, both orderings, lead time and perturbations. + The result is data-limited: no Level I or II case is evaluable without RPC. +- **Fixed:** recorded replay windows holding frozen Cohort B items were used by Phase 12.1 + availability and by Phase 12.2's H3 and E14. Those results are withdrawn, and the + exclusion is now enforced everywhere. See docs/ml/amendment-12.2-cohort-overlap.md. +- **Audit of the 12.2 follow-up:** the attrition is a complete partition, and the exact + p-value is 0.0625. See docs/ml/amendment-12.2-unconfirmed-audit.md. + ### Recency validation and experimental warning ordering (Phase 12.2) - **Follow-up** `cryptoguard ml unconfirmed-recency`: two offline passes, then a pre-registered test on the source's 13,683 unconfirmed payoffs. The result is diff --git a/ML.md b/ML.md index a5592c5..261bacf 100644 --- a/ML.md +++ b/ML.md @@ -284,6 +284,15 @@ so they are not independent validation. removes or re-tiers a warning. - **Details:** [ML_RECENCY_VALIDATION.md](ML_RECENCY_VALIDATION.md). +## Phase 12.3: independent incident benchmark (research only) + +- **Delivered:** an offline incident benchmark (`ml incident-benchmark`). +- **Not yet answered:** no independently documented incident can be evaluated without an + approved RPC recording. +- **Withdrawn:** the 4 recorded incidents hold frozen review items, so Phase 12.2's + incident result is withdrawn. +- **Details:** [ML_INDEPENDENT_INCIDENT_BENCHMARK.md](ML_INDEPENDENT_INCIDENT_BENCHMARK.md). + ## Limitations - One labelled source, with a benign class of prominent accounts; precision on real traffic diff --git a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md new file mode 100644 index 0000000..7513db4 --- /dev/null +++ b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md @@ -0,0 +1,338 @@ +# Independent incident benchmark (Phase 12.3) + +| Item | Value | +|---|---| +| Protocol (frozen before discovery) | [`docs/ml/protocol-12.3.md`](docs/ml/protocol-12.3.md), `f0e4dc1` | +| Code (committed before it ran) | `57273fd`: `ml/incident_benchmark.py`, `cryptoguard ml incident-benchmark verify / run / report` | +| Candidate manifest (public identifiers and URLs only) | [`docs/ml/incident-benchmark/candidates.json`](docs/ml/incident-benchmark/candidates.json) | +| Amendments | [12.2 follow-up audit](docs/ml/amendment-12.2-unconfirmed-audit.md); [frozen-cohort overlap](docs/ml/amendment-12.2-cohort-overlap.md) | +| Outputs (git-ignored) | `data/ml/research/phase12.3/` | +| RPC requests / downloads | 0 / none | + +## 1. Executive summary + +**Classification: data-limited.** No incident at evidence Level I or II can be evaluated +with the authorized data, and the 4 recorded Level III incidents are excluded by the frozen +protocol. + +- **Discovery.** A bounded search (7 searches, 7 page reads) found 10 candidate incidents. + - The only *new* incident with complete verbatim identifiers is a counterfeit-USDT theft + of 9 August 2026. That is after the local archive ends (June 2024), and there is no + recorded wallet stream for it. Evaluating it needs an RPC recording of about 500–1,400 + requests, which is not authorized. + - Every other new candidate lacks identifiers. Article sources rarely quote the victim + and lookalike in full. +- **Overlap audit.** It found a **real protection defect**: all 4 recorded incident windows + hold frozen Cohort B items. + - Frozen addresses even appeared among the competing warnings in 3 incidents. + - Phase 12.2's incident result (H3) and background diagnostic (E14) therefore broke the + cohort rules. Both are withdrawn, and the code now enforces the exclusion everywhere. + - Archive results are unaffected, as a corrected re-run confirms. +- **Phase 12.2 audit.** The follow-up's numbers are consistent, and its exact p is 0.0625 + (§3). +- **Software delivered:** an offline, reproducible benchmark (`verify / run / report`). + - **Ready:** it can evaluate new incidents as soon as their windows are recorded. + - **Tested:** it is tested end to end on a synthetic incident. + - **Safe:** it rejects oracle candidate lists, and never computes a case that holds + frozen items. + +## 2. Research questions + +| Task | Question | Answerable here? | +|---|---|---| +| A | candidate generation | not on real Level I/II cases | +| B | warning generation | not on real Level I/II cases | +| C | prioritization | not on real Level I/II cases | +| D | lead time | not on real Level I/II cases | +| E | robustness | implemented; synthetic only | +| F | generalization | blocked by data | + +## 3. Phase 12.2 consistency audit + +The details are in [`amendment-12.2-unconfirmed-audit.md`](docs/ml/amendment-12.2-unconfirmed-audit.md). + +**Attrition** is a complete partition: + +| Stage | In | Out | +|---|---|---| +| Unconfirmed rows | 13,683 | 616 distinct senders | +| Phase 12.1 victims and protected wallets removed (107 + 2) | 616 | 507 | +| No earlier planting by the paid address | 507 | 8 (499 removed: 488 never planted, 11 only after) | +| Single candidate | 8 | **7 episodes** | + +**B0 = 0.0238** is (1/6)/7, under the same equal-weight, tie-averaged top-1 as T0: +- in 6 episodes, another candidate is strictly first; +- in 1, B0 abstains (no outgoing history) and scores 1/6 at random. + +It is directly comparable with T0's 5/7. + +**Statistics:** + +| Measure | Value | +|---|---| +| Exact two-sided sign flip (2⁷ = 128 patterns) | p = 0.0625 (reported Monte Carlo: 0.064) | +| Exact sign test (5 wins, 1 loss, 1 tie) | p = 0.219 | +| T0 strictly first in 5/7 | 95% Clopper–Pearson [0.29, 0.96] | +| Bootstrap interval | not meaningful at n = 7 | + +The decision is unchanged: inconclusive. + +## 4. Incident discovery methodology + +The search was bounded and pre-registered (protocol §4). Sources were preferred in this +order: security-firm investigations and postmortems, then research papers, then news that +quotes identifiers. + +- **No identifier was inferred.** A truncated or absent identifier is recorded as such. +- **Not used:** social-media posts (X), since they could not be read, and they are + secondary sources. + +## 5. Evidence sources + +| Source | Cases | +|---|---| +| Bitquery on-chain investigation | 4 cases, with full identifiers for 3 | +| Decrypt (citing PeckShield, Cyvers, AMLBot, Bubblemaps) | 1 | +| Cointelegraph / The Block (citing Forbes and an FBI warrant) | 1 | +| crypto.news (citing Cyvers and Scam Sniffer posts) | 2 | +| The project's own replay manifests | 4 | +| Guan & Li, CCS 2024 | not readable without new tooling; Poison-Hunter family | + +## 6. Inclusion criteria + +- **Chain:** Ethereum mainnet. +- **Mechanism:** address poisoning. +- **Identifiers:** a verbatim harmful transaction hash, or the victim and lookalike. +- **Verification:** a local on-chain record (a recorded fixture, or the archive for blocks + 15,053,226–20,208,032). + +## 7. Exclusion criteria + +A case is excluded when any of these holds: +- the chain is wrong or unstated; +- identifiers are absent or truncated; +- it duplicates a fixture; +- it overlaps a frozen review cohort. + +## 8. Benchmark independence assessment + +| Level | Cases found | Evaluable | +|---|---|---| +| I (new, independent) | 1 with full identifiers (Aug 2026) | 0: not recorded locally; needs RPC | +| II (archive range or source family) | 1 in range (DEA, 2023), no identifiers | 0 | +| III (existing fixtures) | 4 | 0: excluded for frozen Cohort B overlap | +| IV (synthetic) | tests only | software correctness only | + +**Overlap results:** +- **The new full-identifier case** overlaps none of the 17 local reference sets. Every set + was readable. +- **The 4 fixtures** overlap `archive:incident_*` (expected: these are the archive targets + built from them) and `frozen_cohorts:addresses` (the victim wallet). + +## 9. Incident provenance + +`candidates.json` holds every case: source URL, publisher and date, mechanism, verbatim +identifiers or their status, fixture link, and synthetic flag. + +**Cross-source check:** Bitquery's identifiers for the 50M USDT and 4,556 ETH incidents +match the fixture manifests exactly (victim, recipient, harmful transaction). That is +independent confirmation of their provenance. + +## 10. Available historical observations + +| Source | Coverage | +|---|---| +| Recorded fixtures | complete transfer scans for a 21,600-block (about 3-day) window, with signers and the wallet's transactions; earlier history is missing (Bitquery reports the 4,556 ETH lookalike forging transfers 11 months earlier) | +| Archive | source-selected rows only, July 2022 – June 2024 | +| Incidents after June 2024 | no local record | + +## 11. Point-in-time reconstruction + +Implemented and tested: +- `trim(fixture, cutoff)`; +- `warnings_at(fixture, cutoff)`, which takes no outcome and fails if the detector sees a + later block; +- the replay engine's leakage checks. + +**Tests confirm:** +- rows after the cutoff cannot change the ranking; +- delayed cutoffs before the recorded window are reported as unobservable, not as misses. + +## 12. Candidate-generation evaluation + +**Not evaluated on real cases:** no Level I or II case is evaluable, and the Level III +cases are excluded. + +On the synthetic incident, the generator recovers the outcome address from the stream alone. + +## 13. Warning-generation evaluation + +Not evaluated on real cases (§12). + +## 14. Recency ranking evaluation + +- **Not evaluated on real cases.** +- **Phase 12.2's H3 is withdrawn.** It was the only real-incident ranking evidence. +- **The archive evidence of Phase 12.2 still stands:** H2, recency ordering of production + warnings on 1,057 episodes. It remains source-conditional and retrospective. + +## 15. Historical lead-time analysis + +Not evaluated on real cases. The method (the replay engine's first pre-harm warning, and the +first planting-signal lead) is implemented and tested. + +## 16. Attack-subtype coverage + +| Subtype | Candidates found | Evaluable | +|---|---|---| +| zero-value transfer | 3 (2 fixtures, Decrypt) | 0 | +| spoofed `transferFrom` | 1 (fixture) | 0 | +| counterfeit token | 1 (Aug 2026, full identifiers) | 0 | +| token airdrop | 1 (DEA) | 0 | +| unknown | 3 | 0 | + +## 17. Negative controls + +**No false-positive rate:** there are no verified negatives. + +**Background windows,** with frozen items excluded: +- 6 windows produce 0 warnings; +- the 3 windows that produced warnings hold frozen items and are excluded. + +Synthetic negatives serve only as invariants. + +## 18. Temporal and graph feature analysis + +No real-case evidence was produced. No hypothesis was tested on new data, and none is +claimed. + +## 19. Failure taxonomy + +| Case | Category | +|---|---| +| Aug 2026 counterfeit USDT | research failure: no recorded stream (post-archive; RPC not authorized) | +| Apr 2025, $700K | research failure: identifiers incomplete (victim and lookalike not given) | +| Dec 2025, 2.38 WBTC | research failure: identifiers incomplete (victim absent, lookalike truncated) | +| DEA 2023 and two 2026 cases | research failure: no identifiers | +| 2026-08, $100K | excluded: chain not stated | +| The 4 fixtures | research failure: overlap with a frozen review cohort | + +No case reached a detector, warning or ranking failure category. + +## 20. Statistical uncertainty + +- **Evaluable real cases:** 0, so no statistic is reported. +- **Gate H's PASS rule** needs at least 10 independent rankable cases (protocol §10). + +## 21. Software improvements + +- **New:** `ml/incident_benchmark.py`. + - manifest schema with `extra="forbid"`, so there is no oracle candidate field; + - the provenance, tier and overlap audit; + - tier A replay, with candidates, warnings, OP0/OP1 expected ranks, lead times, alert + burden and 6 perturbations; + - the report renderer and the CLI. +- **Defects fixed:** + 1. **The frozen-cohort leak in replay windows** (amendment). `touches_frozen` is now + enforced in H3, E14, availability and the benchmark. + 2. **`run` ignored `verify`'s exclusions.** It now computes only admitted cases. + 3. **The no-input sentinel (−1)** was mistaken for a future block. Cutoffs before the + window are now reported as unobservable. +- **Tests:** 10 new benchmark tests, covering: + - manifest validity and oracle rejection; + - tiers by identifier, chain, date and synthetic flag; + - unknown sets never counting as independence; + - cohort exclusion, and fixture cross-checks with a mismatch; + - end-to-end replay with exact ranks and lead time; + - future-record invariance, and exclusion enforcement. + +## 22. Runtime and memory + +| Step | Time | +|---|---| +| `verify` | under 5 s | +| `run` (tier A on 4 fixtures, before exclusion) | 9 s | +| 12.2 corrected re-run | 38 s | + +Every step stays under 400 MiB. No archive pass was needed. + +## 23. Reproducibility + +```bash +uv run --offline cryptoguard ml incident-benchmark verify +``` + +```bash +uv run --offline cryptoguard ml incident-benchmark run +``` + +```bash +uv run --offline cryptoguard ml incident-benchmark report +``` + +A missing input fails with a data-availability message. Nothing is fetched. + +## 24. Licensing constraints + +- **Committed:** public chain identifiers and source URLs. +- **Kept local:** archive-derived rows (CC BY-NC-ND) and per-case results. +- **Not reproduced:** article text, beyond identifiers and facts. + +## 25. Limitations + +1. **Discovery was bounded.** Better sources, such as firm alert feeds and X, were not + readable here. +2. **Fixture windows are 3 days long,** so older plantings are invisible. +3. **No verified negatives.** +4. **Archive-range incidents** need identifiers that the reachable sources did not give. + +## 26. Conclusions + +- **No independent evaluation of real historical warning behaviour is possible** with the + authorized data. This phase does not claim one. +- **The defensible evidence remains** Phase 12.2's source-conditional archive results (H1, + H2). +- **Corrected in this phase:** the one piece of evidence that looked independent (H3) is + withdrawn because it broke the frozen-cohort rules. +- **The benchmark is ready.** It is protocol-bound, offline, and enforces the exclusions. + +## 27. Next research action + +**Record and evaluate new incidents.** This is the precise, cheapest independent test: +- **Approve a capped RPC budget** to record pre-harm windows with the existing recorder: + - the Aug 2026 counterfeit-USDT case, which has full identifiers; + - newly sourced incidents, gathered from firm alert feeds by a person, since this + environment can't read those feeds. +- **Pre-register** the first 10 rankable cases before recording. +- **Size:** 503–1,361 requests per 3-day window, measured. Ten cases need about 7,000–14,000 + requests, plus about 2 minutes of offline benchmark time. +- **Contribution:** the first Level I test of warning coverage, lead time, and OP1 against + OP0, with Gate H decided by the frozen rule. + +## Benchmark result table + +| Case | Level | Subtype | Outcome status | Mode | Candidate | Warning | Pre-harm | OP0 rank | OP1 rank | Lead | History | Main limitation | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| usdt-counterfeit-39890-2026-08-09 | I (pending) | counterfeit token | documented (Bitquery) | not evaluable | unknown | unknown | unknown | — | — | — | none local | needs RPC recording | +| usdt-700k-2025-04 | — | zero-value | documented (Decrypt) | not evaluable | unknown | unknown | unknown | — | — | — | none local | identifiers incomplete | +| wbtc-2.38-2025-12-18 | — | unknown | documented (Bitquery) | not evaluable | unknown | unknown | unknown | — | — | — | none local | identifiers incomplete | +| dea-usdt-55k-2023 | — | airdrop | documented (Forbes, via press) | not evaluable | unknown | unknown | unknown | — | — | — | archive range | no identifiers | +| usdt-100k-2026-08 | — | unknown | reported | excluded | — | — | — | — | — | — | — | chain not stated | +| usdt-50k-2026-10 | — | unknown | reported | not evaluable | unknown | unknown | unknown | — | — | — | — | no identifiers | +| 4 recorded fixtures | III | various | confirmed | excluded | not computed | not computed | not computed | — | — | — | 3-day windows | frozen Cohort B overlap | + +## Decision gates + +| Gate | Status | Evidence | +|---|---|---| +| A. New evidence | PASS WITH LIMITATIONS | 1 new case with full identifiers; 5 new without | +| B. Independent provenance | BLOCKED BY DATA | the new case is independent on all readable sets, but unverifiable on chain offline | +| C. Transaction verification | BLOCKED BY DATA | no local record for the new case; no RPC | +| D. Point-in-time validity | PASS | implemented and tested (trim, cutoff guard, leakage checks) | +| E. Candidate availability | NOT EVALUATED | no evaluable real case | +| F. Operational replay | BLOCKED BY DATA | no admissible recorded stream | +| G. Warning coverage | NOT EVALUATED | — | +| H. Ranking usefulness | NOT EVALUATED | H3 withdrawn; 0 rankable admissible cases | +| I. Statistical support | FAIL | 0 independent cases, against the 10 required | +| J. Production safety | PASS | no detector, service or risk change; ranker isolated | +| K. Reproducibility | PASS WITH LIMITATIONS | offline commands; the inputs cannot be redistributed | diff --git a/ML_RECENCY_VALIDATION.md b/ML_RECENCY_VALIDATION.md index 68a58ed..42b80d8 100644 --- a/ML_RECENCY_VALIDATION.md +++ b/ML_RECENCY_VALIDATION.md @@ -9,6 +9,14 @@ | RPC requests / downloads | 0 / none | | Production detector | unchanged; nothing is wired into it | +**Amendment (2026-11-03, +[`docs/ml/amendment-12.2-cohort-overlap.md`](docs/ml/amendment-12.2-cohort-overlap.md)).** +- **Withdrawn:** H3 (the recorded incidents) and E14 (background windows). Their recorded + windows hold frozen Cohort B items, and those items appeared among the competing warnings. + "3 of 3 rankable incidents" is withdrawn, and E14 reduces to 6 windows with 0 warnings. +- **Unchanged:** every archive result (H1, H2, E1–E13), confirmed by a corrected re-run. +- **Below:** the original text is kept as written. + **Scope.** This phase re-examines the archive episodes whose outcomes Phase 12.1 already saw. Every archive result below is therefore a **retrospective internal sensitivity analysis, not independent validation**. "Top-1" means the paid lookalike ranked first among diff --git a/ML_RESEARCH_PLAN.md b/ML_RESEARCH_PLAN.md index 4ab78f4..d354b86 100644 --- a/ML_RESEARCH_PLAN.md +++ b/ML_RESEARCH_PLAN.md @@ -242,3 +242,18 @@ budget. - Details: ML_RECENCY_VALIDATION.md §25a. - **Next:** newly recorded incidents. They need an approved RPC budget. +## 10. Done (Phase 12.3): independent incident benchmark (data-limited) + +The study is pre-registered in `docs/ml/protocol-12.3.md` (`f0e4dc1`). Results are in +[ML_INDEPENDENT_INCIDENT_BENCHMARK.md](ML_INDEPENDENT_INCIDENT_BENCHMARK.md). + +- **Discovery:** 10 candidate incidents. Only one new case has complete identifiers, and it + happened after the local archive ends, so it needs an RPC recording. +- **Overlap audit:** the 4 recorded incident windows hold frozen Cohort B items. Phase + 12.2's H3 and E14 are withdrawn + ([amendment](docs/ml/amendment-12.2-cohort-overlap.md)), and the exclusion is now enforced + in code. +- **Delivered:** an offline benchmark (`ml incident-benchmark`). +- **Next:** an approved, capped RPC budget to record about 10 new incident windows. That is + about 7,000–14,000 requests, measured. + diff --git a/ML_TEMPORAL_GRAPH_RESEARCH.md b/ML_TEMPORAL_GRAPH_RESEARCH.md index 4fdca1b..b996d74 100644 --- a/ML_TEMPORAL_GRAPH_RESEARCH.md +++ b/ML_TEMPORAL_GRAPH_RESEARCH.md @@ -15,6 +15,12 @@ theft-prevention effect, and every number below is an aggregate. | RPC requests | 0. No downloads. Nothing paid. | | Production detector | unchanged; nothing here is wired into it | +**Amendment (2026-11-03, +[`docs/ml/amendment-12.2-cohort-overlap.md`](docs/ml/amendment-12.2-cohort-overlap.md)).** +- **Affected:** the P2 and P3 availability counts in §21 included recorded windows that + hold frozen Cohort B items. Future re-runs exclude those windows. +- **Not affected:** no confirmatory result. + ## 1. Summary The task: rank the k ≥ 2 lookalikes that had planted transfers to a victim, at the block diff --git a/docs/ml/amendment-12.2-cohort-overlap.md b/docs/ml/amendment-12.2-cohort-overlap.md new file mode 100644 index 0000000..b0e1dc9 --- /dev/null +++ b/docs/ml/amendment-12.2-cohort-overlap.md @@ -0,0 +1,63 @@ +# Amendment: frozen-cohort overlap in the recorded replay windows + +**Found:** 2026-11-03, by the Phase 12.3 overlap audit (`cryptoguard ml incident-benchmark +verify`). This is a confirmed protection defect, and it is corrected below. + +## What was wrong + +Frozen **Cohort B** (`hard-negative-candidates/1`, 35 items) was drawn in Phase 11.5 partly +from recorded wallet windows. +- **8 of its items** have as their wallet the victim of a recorded incident: 2 for each of + the 4 incidents in `replay/cases`. +- **3 of the 9 background windows** belong to protected wallets. +- **Competing warnings:** frozen addresses under review appear among the production + detector's warnings at the cutoff in 3 of the 4 incidents, 4 warnings in total. + +Protocol 12.1 §3 requires that no event of a frozen wallet enter any computation. Three +analyses broke that rule: + +| Analysis | What it computed on those windows | +|---|---| +| Phase 12.1 `availability` (report §21) | candidate counts for P2 and P3 | +| Phase 12.2 **H3** (report §1, §15) | warning rankings, with frozen items among the competitors | +| Phase 12.2 **E14** (report §15) | warning burden on background windows; all 5 counted warnings came from protected windows | + +Phase 12.3's first `run` had the same problem. It did not consume `verify`'s exclusions. + +## What was not affected + +- **No frozen item's label was used.** None exists: 0 human submissions. +- **Nothing was tuned, selected or fitted** on these windows. +- **Cohort files and hashes are unchanged.** `ml verify-research` passes. +- **The archive analyses are unaffected:** H1, H2, every E1–E13 result, and all of Phase + 12.1's confirmatory results. They already excluded protected wallets as episodes and as + graph edges. +- **A corrected re-run confirms this:** + `data/ml/research/phase12.2/recency-validation-corrected.json` differs from the original + only in H3, E14 and timing fields. + +## Correction + +- **New check:** `recency_validation.touches_frozen` flags a recorded window when its wallet + is a frozen address, or when any transfer's party or transaction is frozen. +- **Applied in:** + - `incidents()` (H3); + - `background()` (E14); + - `lookalike_study.availability()`; + - `incident_benchmark.run()`, which now also computes only the cases `verify` admitted. +- **Corrected values:** + - **H3: all 4 incidents are excluded.** The Phase 12.2 statement "3 of 3 rankable incidents + rank the recipient first" is **withdrawn**. + - **E14:** 6 windows remain, with 0 warnings; 3 windows are excluded. + - **12.1 availability:** recomputed with the exclusion on any re-run. The saved Phase 12.1 + output is preserved as it was. +- **Superseded output:** the unenforced Phase 12.3 run output is preserved locally as + `data/ml/research/phase12.3/incident-benchmark.SUPERSEDED-unenforced-exclusions.json`. It + is not reported and not used. +- **Tests** cover each exclusion. + +## Consequence + +The 4 recorded incidents cannot serve as benchmark cases while Cohort B is frozen. They +become usable again as Level III regression cases only after the human review of Cohort B +is complete and its protocol releases the items. From 61ad1af5dfac423df95e5a8bfbd168a85413627c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 15:54:23 +0300 Subject: [PATCH 54/92] feat(replay): hard request cap for live recording; Stage 0 of the incident pilot The replay recorders had no total request cap: per-step limits only, so one busy wallet could spend thousands of requests and a killed run lost its count. replay record, sample-background and record-background now reserve every attempt (retries included) in the durable RequestLedger first, require --ledger and --cap, and write no fixture when the cap is reached. The ledger moves to cryptoguard.blockchain.budget (re-exported by ml.collect). Adds, with no RPC requests made: - replay locate (capped receipt lookup) and replay record --cases-dir; - ml incident-benchmark prepare: a case manifest built by rule from located receipts, refusing identifiers the chain does not confirm; - Level I bookkeeping in verify/run: on-chain identifier check, per-level summaries; - the RPC budget plan and the pre-registration of the Stage 1 pilot case. The offline overlap check finds no overlap for the pilot case; verify output is identical to Phase 12.3. 859 tests pass. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ README.md | 10 +- .../preregistration-pilot.md | 111 ++++++++ docs/ml/incident-recording-budget-plan.md | 136 ++++++++++ src/cryptoguard/blockchain/budget.py | 203 +++++++++++++++ src/cryptoguard/cli.py | 125 ++++++++- src/cryptoguard/ml/annotation.py | 4 +- src/cryptoguard/ml/cli.py | 46 +++- src/cryptoguard/ml/collect.py | 176 +------------ src/cryptoguard/ml/incident_benchmark.py | 246 +++++++++++++++--- src/cryptoguard/replay/record.py | 34 +++ tests/fakenode.py | 3 + tests/integration/test_replay_budget.py | 243 +++++++++++++++++ tests/test_ml_incident_benchmark.py | 88 +++++++ 14 files changed, 1219 insertions(+), 222 deletions(-) create mode 100644 docs/ml/incident-benchmark/preregistration-pilot.md create mode 100644 docs/ml/incident-recording-budget-plan.md create mode 100644 src/cryptoguard/blockchain/budget.py create mode 100644 tests/integration/test_replay_budget.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f27f20..75d105a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,22 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Incident recording, Stage 0 (no RPC requests) +- **Fixed:** the replay recorders (`replay record`, `sample-background`, `record-background`) + had no total request cap. They now reserve every attempt, retries included, in the durable + request ledger, and need `--ledger` and `--cap`. A run that reaches the cap writes no + fixture. The ledger moved to `cryptoguard.blockchain.budget`, and `ml.collect` + re-exports it. +- **Added:** + - `replay locate`, a capped receipt lookup; + - `replay record --cases-dir`; + - `ml incident-benchmark prepare`, which builds a case manifest by rule from located + receipts and refuses identifiers the chain does not confirm; + - Level I bookkeeping in `verify` and `run`, with an on-chain identifier check and + per-level summaries. +- **Plan and pre-registration:** `docs/ml/incident-recording-budget-plan.md` and + `docs/ml/incident-benchmark/preregistration-pilot.md`. + ### Independent incident benchmark (Phase 12.3) - **New command:** `cryptoguard ml incident-benchmark verify / run / report`. It runs offline and is bound to a protocol: diff --git a/README.md b/README.md index 3804b3a..081b7ab 100644 --- a/README.md +++ b/README.md @@ -201,13 +201,15 @@ uv run cryptoguard graph
# relationships from the latest s # Historical incident replay (offline, from packaged fixtures) uv run cryptoguard replay list uv run cryptoguard replay run --write-report EVALUATION.md -# Re-record a fixture (needs historical logs + state, e.g. https://eth.drpc.org): -uv run cryptoguard replay record --rpc-url +# Re-record a fixture (needs historical logs + state, e.g. https://eth.drpc.org). Every live +# replay command needs a request ledger and an approved cap; retries count, and a run that +# reaches the cap writes nothing: +uv run cryptoguard replay record --rpc-url --ledger --cap # Evaluate the experimental analyses too (incidents + background wallets; analytics extra): uv run --extra analytics cryptoguard replay run --analytics --write-report EVALUATION.md # Background wallets: seeded random sample, then record their fixtures -uv run cryptoguard replay sample-background --rpc-url --seed --from-block --to-block -uv run cryptoguard replay record-background --rpc-url +uv run cryptoguard replay sample-background --rpc-url --seed --from-block --to-block --ledger --cap +uv run cryptoguard replay record-background --rpc-url --ledger --cap --max-requests # Cross-wallet campaigns (CRYPTOGUARD_CAMPAIGN_ANALYSIS=shadow) uv run cryptoguard campaigns analyze # cluster stored attempts, no RPC calls diff --git a/docs/ml/incident-benchmark/preregistration-pilot.md b/docs/ml/incident-benchmark/preregistration-pilot.md new file mode 100644 index 0000000..e29feae --- /dev/null +++ b/docs/ml/incident-benchmark/preregistration-pilot.md @@ -0,0 +1,111 @@ +# Pre-registration: incident-recording pilot (Stage 1) + +**Frozen:** 2026-11-03, in the commit that adds this file. That is before any RPC request for +the case, before its window exists, and before any detector output on it. + +**Budget plan:** `docs/ml/incident-recording-budget-plan.md`, Stage 1. + +**Status:** Stage 0 is complete, and 0 requests have been made. Stage 1 runs only after you +explicitly approve its cap. + +## 1. The case + +| Field | Value (copied from `candidates.json`; never given to the recorder) | +|---|---| +| Case | `usdt-counterfeit-39890-2026-08-09` | +| Source | Bitquery, https://bitquery.io/investigations/address-poisoning-ethereum (2026; read 2026-11-03) | +| Mechanism | counterfeit token | +| Victim | `0xb83f1c98b6d799f8ec56a002f2c0a2c343a0f50e` | +| Lookalike | `0x053dc459bade1baf76aed6e8630823f8392fda3a` | +| Intended | `0x053dba7292957341779cb0e9aae1aa7b139ada3a` | +| Planting tx | `0xf84dacfeb3a92ae3291120d954b86d89932fe31702103754cad4f8e8ac41a10d` | +| Harmful tx | `0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb` | + +**Overlap check** (`ml incident-benchmark verify`, run offline in Stage 0): no identifier +appears in any local reference set. The sets covered are: +- both frozen review cohorts (A: 60 items, B: 35 items); +- every archive group; +- the Phase 12.1 and 12.2 target sets; +- Poison-Hunter. + +No set was unreadable. The case therefore enters as a Level I candidate. The verify output is +byte-identical to Phase 12.3's, which shows that the Stage 0 code changes alter no existing +result. + +## 2. Fixed before any request + +- **Window rule:** the 21,600 blocks before and including the harmful block, H − 21,600 to H. + This is the same rule as the 4 replay cases. The window is not widened or moved after + anything is seen. +- **Recorder input:** the victim and the window only. The recorder never receives the + lookalike, the intended recipient or any hash. +- **Methods:** the Phase 12.3 benchmark, unchanged in what it computes: + - the production detector; + - OP0 (severity, then similarity); + - OP1 (the frozen recency order); + - lead time; + - 6 perturbations. + + Stage 0 only adds Level I bookkeeping, `prepare`, and the on-chain identifier check. +- **Case location:** `docs/ml/incident-benchmark/cases//`, kept apart from the packaged + replay cases. `EVALUATION.md`, the replay cases and the frozen cohorts' source windows are + unchanged. + +## 3. Stage 1 commands (in this order, nothing else) + +Every command uses `--rpc-url https://eth.drpc.org`, ledger +`data/ml/rpc/ledger-incident-pilot.json`, and `--cap 2000`. + +1. **Locate** both transactions, at most 20 requests. Output goes to + `data/ml/research/incident-pilot/located.json`. + `cryptoguard replay locate --max-requests 20 --out …` +2. **Prepare** the manifest, offline: + `cryptoguard ml incident-benchmark prepare --case usdt-counterfeit-39890-2026-08-09 + --located … --title "Counterfeit-USDT poisoning theft, Aug 2026" --first-report 2026-11-03`. + - The first-report field uses the read date as an upper bound, since the page shows no + publication date. + - **If `prepare` refuses**, Stage 1 ends there. The case is then reported as + *identifiers not confirmed on chain* and no window is recorded. `prepare` refuses when + the harmful transaction is not found, failed, was not signed by the victim, or carries + no Transfer from the victim to the lookalike. +3. **Record** the window, with the rest of the cap: + `cryptoguard replay record usdt-counterfeit-39890-2026-08-09 + --cases-dir docs/ml/incident-benchmark/cases`. +4. **Evaluate** offline: `cryptoguard ml incident-benchmark verify`, then `run` and `report`, + with `--out data/ml/research/incident-pilot`. + +## 4. What is reported, whatever the outcome + +**Gate C for this case:** `verify`'s on-chain check. It passes when two things hold: +- the harmful transfer from the victim to the lookalike is in the recorded window; +- the planting transaction, if inside the window, has the lookalike as a party. + +A planting transaction before the window is reported as such. It is not a failure, and the +window is not extended. + +**The case row:** +- whether the candidate was recovered; +- whether the detector warned at the cutoff, and the outcome per visibility; +- the lead time; +- k (the number of warnings); +- the OP0, OP1 and random ranks; +- the perturbations. + +**What is not claimed:** +- **No ranking gate is decided.** Gate H needs at least 10 rankable cases, and an exact sign + test needs at least 6 untied ones. One case is descriptive only. +- **No rates.** There is no detection rate, precision, recall or false-positive rate from a + single positive case. + +**No tuning.** Nothing is changed in response to the outcome. Any defect found is fixed in +the open, and the case is re-run with the original output kept. + +## 5. Stop rules + +- **The cap:** stop at the cap (2,000 in total, retries included). A run that hits it is + *not evaluable: budget* and writes no fixture. +- **Restarts:** at most one restart per step after a transport error. A second failure is + *not evaluable: RPC*. +- **No substitutes:** no other endpoint, no paid API, and no other RPC or ML process at the + same time. +- **Leftover requests** are not authorization for anything else. diff --git a/docs/ml/incident-recording-budget-plan.md b/docs/ml/incident-recording-budget-plan.md new file mode 100644 index 0000000..0b58f48 --- /dev/null +++ b/docs/ml/incident-recording-budget-plan.md @@ -0,0 +1,136 @@ +# Plan: RPC budget for recording new incident windows + +**Status:** +- **Stage 0 is complete:** the recorder cap, the pre-registration + (`incident-benchmark/preregistration-pilot.md`) and the overlap check are all done. +- **No RPC request** has been made for this plan, and none is authorized by this document. Each stage below needs its own explicit approval of a request cap, and unused +requests from one approval do not carry over to the next. + +**Purpose:** give the Phase 12.3 benchmark its first independently documented (Level I) cases. +This is the next action recommended in `ML_INDEPENDENT_INCIDENT_BENCHMARK.md` §27. + +## 1. What one window costs (measured) + +These are all 13 recorded windows. Each covers 21,601 blocks (about 3 days), was recorded on +`https://eth.drpc.org` with 100-block log chunks, and counts retries. + +| Window type | n | Requests (min / median / max) | Mean | +|---|---|---|---| +| Incident (`replay/cases`) | 4 | 503 / 732 / 1,361 | 832 | +| Background (`replay/background_cases`) | 9 | 443 / 450 / 534 | 462 | +| All | 13 | 443 / 474 / 1,361 | 576 | + +**Why the counts vary:** +- **The floor is about 443 requests.** That is two log scans (outgoing and incoming) of 216 + chunks each, plus about 11 calls for the chain check, nonce bisection, code and timestamps. +- **Activity adds cost:** a timestamp read per referenced block, a sender lookup per outgoing + transfer, and a block read per wallet transaction. The WBTC window, with 340 transfers, + cost 756. +- **The largest cost came from retries, not activity.** The 1,361-request window had only + 4 transfers and 2 transactions. Rate limiting on the free endpoint can multiply a window's + cost by up to 4, since the client is set to 3 retries. + +## 2. Defect found while planning: the recorder has no hard total cap + +`cryptoguard replay record` (`replay/record.py`) builds a plain RPC provider. It does not use +the durable `RequestLedger` / `BudgetedTransport` that `ml collect` uses +(`ml/collect.py`, audited in `ML_GENERALIZATION_AUDIT.md` §14). + +Its only limits are per step: +- up to 2,000 log requests, shared between the two scans; +- up to 500 sender lookups; +- up to 10,000 wallet transactions; +- one timestamp read per referenced block, with no upper bound. + +So a single busy wallet could spend several thousand requests, more than any cap proposed +below, and a killed run would lose its count. + +**Fixed in Stage 0:** `replay record`, `sample-background` and `record-background` now route +every attempt through `RequestLedger`, failing closed. They require `--ledger` and `--cap`, +with an optional per-run `--max-requests`. + +A window that hits the cap is reported as *not evaluable: budget*, and no partial fixture is +written. Tests with counting mock transports cover this, along with a mocked dry run of the +whole Stage 1 chain. + +## 3. Stages + +### Stage 0: preparation (0 requests) + +1. Add the recorder cap described in §2, with tests. +2. **Pre-register** the case manifest for `usdt-counterfeit-39890-2026-08-09`. The manifest + gives only: + - the victim; + - the rule for the window: the 21,600 blocks before and including the harmful block, the + same convention as the 4 existing incident manifests. + + It is committed before any request. Its identifiers come from `candidates.json` and are + never given to the recorder. +3. **Run the offline overlap check (`incident-benchmark verify`) again.** The victim and both + counterparties must touch neither frozen cohort, nor any other reference set. + +### Stage 1: pilot, one Level I case + +| Step | Requests | +|---|---| +| Locate the harmful block (`eth_getTransactionByHash`, harm tx; planting tx as a cross-check) | 2 (up to 8 with retries) | +| Record one 21,601-block window | 443–1,361 measured; about 2 min | +| **Proposed cap** | **2,000** | + +**Endpoint and ledger:** the same free endpoint as before (`eth.drpc.org`), with a separate +ledger file (`data/ml/rpc/ledger-incident-pilot.json`). + +**This stage settles:** +- whether the identifiers are verified on chain (Gate C for this case); +- whether the production detector warned before the harm; +- the lead time; +- the ranks under OP0 and OP1. + +A single case decides no ranking gate. The protocol needs 10, and an exact sign test needs at +least 6 untied cases. + +### Stage 2: nine more cases, which need you + +- **Sourcing:** this environment cannot read firm alert feeds, so the 9 further cases need + identifiers sourced by a person. Each needs a victim, a lookalike, and a harm tx with a + public write-up. +- **Pre-registration:** all 9 are pre-registered and checked offline before any request. +- **Size:** 9 windows at a measured incident mean of 832 is about 7,500 requests expected, + and about 12,250 at the measured maximum. + +| Proposed cap | Value | +|---|---| +| Per window | 2,000 (fail closed) | +| Stage total | **14,000** | + +With Stage 1, the 10 cases cost about 8,300 requests expected and at most 16,000 under the +caps. + +### Stage 3 (optional): background windows for warning burden + +Phase 12.3 excluded 3 of the 9 background windows because of the frozen-cohort overlap. Ten +fresh background wallets would restore a warning-burden estimate (E14) at the new incidents' +dates. The cost is about 460 requests each plus seeded sampling: a cap of **6,000**. + +This stage is not needed for the ranking gate, and it is asked separately. + +## 4. Stop rules (all stages) + +- **The cap:** stop at the cap. A window that hits the per-window cap is not retried within + the same approval. +- **One restart:** at most one restart per window after a transport error. A second failure + marks the case *not evaluable: RPC*. +- **Endpoint:** no change of endpoint or provider, and no paid API, without a new approval. +- **Isolation:** no other ML or RPC process runs at the same time. +- **After recording:** fixtures are hashed and recorded in the run ledger. The benchmark then + runs offline (`incident-benchmark verify → run → report`), and nothing is tuned on the + outcome. + +## 5. Approvals requested + +| Approval | Cap | Required for | +|---|---|---| +| Stage 0 | 0 requests (code and docs only) | all later stages | +| Stage 1 | 2,000 | the first Level I case | +| Stage 2 | 14,000, after you supply 9 sourced cases | the ranking gate (Gate H) | +| Stage 3 | 6,000 | the warning-burden estimate (optional) | diff --git a/src/cryptoguard/blockchain/budget.py b/src/cryptoguard/blockchain/budget.py new file mode 100644 index 0000000..f9fc533 --- /dev/null +++ b/src/cryptoguard/blockchain/budget.py @@ -0,0 +1,203 @@ +"""Durable request budgets for live RPC work. + +Every HTTP attempt, retries included, reserves one unit in a ledger file *before* it is sent +(``RequestLedger``, ``BudgetedTransport``). The cap therefore holds under retries, crashes and +concurrent processes. Used by the ML collector and by the replay recorders. +""" + +from __future__ import annotations + +import json +import os +import sys +import threading +import time +from pathlib import Path +from typing import Any, ClassVar + +import httpx + + +class BudgetExhaustedError(RuntimeError): + """The request ledger has no room for another attempt.""" + + +class LedgerCorruptError(RuntimeError): + """The request ledger cannot be read; collection refuses to guess (fail closed).""" + + +def _try_os_lock(fd: int) -> bool: + """Non-blocking exclusive lock on byte 0 of ``fd``; the OS drops it when the process dies.""" + try: + if sys.platform == "win32": + import msvcrt + + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + return True + + +def _os_unlock(fd: int) -> None: + if sys.platform == "win32": + import msvcrt + + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(fd, fcntl.LOCK_UN) + + +class RequestLedger: + """Durable, cross-process request budget: one unit is *reserved before* every HTTP + attempt (retries included), under an exclusive OS file lock, with an fsynced atomic write. + + Guarantee: the recorded count is never below the number of attempts budgeted clients + have sent. A crash after reserving over-counts by the attempts it never sent (safe); it + cannot under-count. Collectors in any number of threads or processes on the same ledger + cannot together exceed the cap. The lock is an OS lock (``msvcrt``/``flock``), released + by the OS if its holder dies, so no stale-lock breaking (and its race) is needed. What the + provider bills is not reconstructed: an attempt cut off in flight may or may not have + reached it, and the ledger counts it either way. Each reservation is fsynced before the + request is sent (about 50 ms on a desktop disk), which caps one ledger at roughly 20 + reservations per second: far above free-endpoint rate limits, and the price of surviving + power loss. A lock timeout raises before anything is sent. The file keeps the Phase 11 format + (``{"requests": n, "notes": [...]}``) so earlier usage still counts. + """ + + def __init__(self, path: Path, cap: int, *, lock_timeout: float = 30.0) -> None: + self.path = path + self.cap = cap + self.lock_timeout = lock_timeout + self._lock = path.with_name(path.name + ".lock") + + _local_locks: ClassVar[dict[str, threading.Lock]] = {} + _local_guard: ClassVar[threading.Lock] = threading.Lock() + + def _local(self) -> threading.Lock: + key = os.path.abspath(self._lock) + with self._local_guard: + return self._local_locks.setdefault(key, threading.Lock()) + + def _acquire(self) -> int: + """Threads of one process queue on a blocking in-process lock (no polling, so none + starves under load); the OS lock then excludes other processes.""" + deadline = time.monotonic() + self.lock_timeout + local = self._local() + if not local.acquire(timeout=self.lock_timeout): + raise TimeoutError(f"request ledger lock {self._lock} is held") + try: + fd = os.open(self._lock, os.O_CREAT | os.O_RDWR) + while not _try_os_lock(fd): + if time.monotonic() > deadline: + os.close(fd) + raise TimeoutError(f"request ledger lock {self._lock} is held") + time.sleep(0.005) + except BaseException: + local.release() + raise + return fd + + def _release(self, fd: int) -> None: + try: + _os_unlock(fd) + finally: + os.close(fd) + self._local().release() + + def _read(self) -> dict[str, Any]: + if not self.path.exists(): + return {"requests": 0} + try: + state = json.loads(self.path.read_text(encoding="utf-8")) + int(state["requests"]) + except (ValueError, KeyError, TypeError): + raise LedgerCorruptError(f"{self.path} is unreadable; fix it by hand") from None + return dict(state) + + def _write(self, state: dict[str, Any]) -> None: + tmp = self.path.with_name(self.path.name + f".{os.getpid()}.{threading.get_ident()}.tmp") + with tmp.open("w", encoding="utf-8") as fh: + fh.write(json.dumps(state, indent=1)) + fh.flush() + os.fsync(fh.fileno()) # the count is on disk before it can be relied on + for attempt in range(50): + try: + os.replace(tmp, self.path) # atomic on Windows and POSIX + return + except PermissionError: # Windows: a scanner may hold the target for a moment + if attempt == 49: + raise + time.sleep(0.01) + + def used(self) -> int: + fd = self._acquire() # never read while another process replaces the file + try: + return int(self._read()["requests"]) + finally: + self._release(fd) + + def reserve(self, n: int = 1) -> int: + """Reserve ``n`` attempts or raise; returns the total reserved afterwards.""" + fd = self._acquire() + try: + state = self._read() + total = int(state["requests"]) + n + if total > self.cap: + raise BudgetExhaustedError(f"{state['requests']} of {self.cap} requests used") + state["requests"] = total + self._write(state) + return total + finally: + self._release(fd) + + def note(self, text: str, requests: int = 0) -> int: + """Record a manual charge (e.g. requests made outside the collector).""" + fd = self._acquire() + try: + state = self._read() + state["requests"] = int(state["requests"]) + requests + state.setdefault("notes", []).append(text) + self._write(state) + return int(state["requests"]) + finally: + self._release(fd) + + +class BudgetedTransport(httpx.AsyncBaseTransport): + """Reserves one ledger unit before handing each HTTP attempt to the real transport.""" + + def __init__(self, inner: httpx.AsyncBaseTransport, ledger: RequestLedger) -> None: + self.inner = inner + self.ledger = ledger + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + self.ledger.reserve(1) + return await self.inner.handle_async_request(request) + + async def aclose(self) -> None: + await self.inner.aclose() + + +def run_ledger(path: Path, cap: int, *, per_run: int | None = None) -> RequestLedger: + """The ledger for one run: never past ``cap`` in total (one approval), and never more than + ``per_run`` attempts beyond what the ledger already holds.""" + if cap < 1 or (per_run is not None and per_run < 1): + raise ValueError("request caps must be positive") + if per_run is None: + return RequestLedger(path, cap) + used = RequestLedger(path, cap).used() + return RequestLedger(path, min(cap, used + per_run)) + + +def budgeted_transport( + ledger: RequestLedger, inner: httpx.AsyncBaseTransport | None = None +) -> BudgetedTransport: + return BudgetedTransport(inner or httpx.AsyncHTTPTransport(), ledger) diff --git a/src/cryptoguard/cli.py b/src/cryptoguard/cli.py index aa296f3..b15c534 100644 --- a/src/cryptoguard/cli.py +++ b/src/cryptoguard/cli.py @@ -16,6 +16,7 @@ import json import sys from collections.abc import Sequence +from typing import TYPE_CHECKING, Any from pydantic import SecretStr, ValidationError @@ -39,6 +40,9 @@ from cryptoguard.services.providers import build_provider, require_provider from cryptoguard.services.snapshots import DetectionOptions, SnapshotOutcome, take_snapshot +if TYPE_CHECKING: + from cryptoguard.blockchain.budget import RequestLedger + def _load_settings(demo: bool) -> Settings: settings = Settings() @@ -322,6 +326,7 @@ def _print_findings(settings: Settings, address: str, show_all: bool) -> None: def _replay_command(args: argparse.Namespace, settings: Settings) -> int: from pathlib import Path + from cryptoguard.blockchain.budget import BudgetExhaustedError, budgeted_transport from cryptoguard.blockchain.provider import build_rpc_provider from cryptoguard.core.config import validate_rpc_url from cryptoguard.replay.engine import replay @@ -336,11 +341,17 @@ def _replay_command(args: argparse.Namespace, settings: Settings) -> int: print(f"{case.manifest.case_id} [{status}] {case.manifest.title}") return 0 + if args.replay_command == "locate": + return _locate_command(args, settings) + if args.replay_command == "record": + if args.cases_dir: + cases = load_cases(Path(args.cases_dir)) manifest = next((c.manifest for c in cases if c.manifest.case_id == args.case_id), None) if manifest is None: print(f"error: unknown case {args.case_id}", file=sys.stderr) return 1 + ledger = _replay_ledger(args) record_settings = settings.model_copy( update={ "rpc_url": SecretStr(validate_rpc_url(args.rpc_url)), @@ -350,12 +361,24 @@ def _replay_command(args: argparse.Namespace, settings: Settings) -> int: ) async def run_recording() -> str: - provider = build_rpc_provider(record_settings) + provider = build_rpc_provider(record_settings, transport=budgeted_transport(ledger)) + before = ledger.used() try: fixture = await record_fixture(provider, manifest, chunk_blocks=args.chunk_blocks) + except BudgetExhaustedError as exc: # fail closed: no partial fixture is written + ledger.note(f"replay record {manifest.case_id}: stopped at the cap ({exc})") + raise finally: await provider.aclose() - path = case_directory(manifest.case_id) / "fixture.json" + ledger.note( + f"replay record {manifest.case_id}: {ledger.used() - before} requests reserved" + ) + case_dir = ( + Path(args.cases_dir) / manifest.case_id + if args.cases_dir + else case_directory(manifest.case_id) + ) + path = case_dir / "fixture.json" path.write_bytes(fixture.canonical_bytes() + b"\n") return ( f"Recorded {len(fixture.transfers)} transfers and " @@ -363,7 +386,14 @@ async def run_recording() -> str: f"({fixture.rpc_requests} RPC requests) to {path}" ) - print(asyncio.run(run_recording())) + try: + print(asyncio.run(run_recording())) + except BudgetExhaustedError as exc: + print( + f"{manifest.case_id}: not evaluable: budget ({exc}); no fixture written", + file=sys.stderr, + ) + return 2 return 0 if args.replay_command in ("sample-background", "record-background"): @@ -432,9 +462,69 @@ async def run_recording() -> str: return 0 +def _replay_ledger(args: argparse.Namespace) -> RequestLedger: + """Every live replay request is reserved in a durable ledger first (fail closed).""" + from pathlib import Path + + from cryptoguard.blockchain.budget import run_ledger + + return run_ledger(Path(args.ledger), args.cap, per_run=args.max_requests) + + +def _add_rpc_budget(parser: argparse.ArgumentParser, *, per_run_help: str) -> None: + parser.add_argument( + "--ledger", required=True, help="request ledger file for this approval (one per budget)" + ) + parser.add_argument( + "--cap", type=int, required=True, help="approved total for the ledger, retries included" + ) + parser.add_argument("--max-requests", type=int, default=None, help=per_run_help) + + +def _locate_command(args: argparse.Namespace, settings: Settings) -> int: + from pathlib import Path + + from cryptoguard.blockchain.budget import BudgetExhaustedError, budgeted_transport + from cryptoguard.blockchain.provider import build_rpc_provider + from cryptoguard.core.config import validate_rpc_url + from cryptoguard.replay.record import locate_transaction + + ledger = _replay_ledger(args) + rpc_settings = settings.model_copy( + update={ + "rpc_url": SecretStr(validate_rpc_url(args.rpc_url)), + "chain_id": args.chain_id, + "rpc_max_concurrency": 1, + } + ) + + async def run() -> list[dict[str, Any]]: + provider = build_rpc_provider(rpc_settings, transport=budgeted_transport(ledger)) + before = ledger.used() + try: + return [await locate_transaction(provider, h) for h in args.tx_hash] + finally: + await provider.aclose() + ledger.note(f"replay locate {len(args.tx_hash)} tx: {ledger.used() - before} reserved") + + try: + found = asyncio.run(run()) + except BudgetExhaustedError as exc: + print(f"error: not located: budget ({exc})", file=sys.stderr) + return 2 + text = json.dumps(found, indent=1) + if args.out: + Path(args.out).write_text(text + "\n", encoding="utf-8") + print(f"Wrote {args.out}") + else: + print(text) + return 0 + + def _background_command(args: argparse.Namespace, settings: Settings) -> int: from datetime import UTC, datetime + from cryptoguard.blockchain.budget import BudgetExhaustedError, budgeted_transport from cryptoguard.blockchain.provider import build_rpc_provider from cryptoguard.core.config import validate_rpc_url from cryptoguard.replay.background import ( @@ -450,7 +540,9 @@ def _background_command(args: argparse.Namespace, settings: Settings) -> int: ) async def sample() -> str: - provider = build_rpc_provider(rpc_settings) + provider = build_rpc_provider( + rpc_settings, transport=budgeted_transport(_replay_ledger(args)) + ) try: chosen, log = await sample_background( provider, @@ -475,7 +567,11 @@ async def record() -> str: pending = [c for c in load_background() if c.fixture is None][: args.limit] for case in pending: m = case.manifest - provider = build_rpc_provider(rpc_settings.model_copy(update={"chain_id": m.chain_id})) + ledger = _replay_ledger(args) # per window: --max-requests more, never past --cap + provider = build_rpc_provider( + rpc_settings.model_copy(update={"chain_id": m.chain_id}), + transport=budgeted_transport(ledger), + ) try: fixture = await record_window( provider, @@ -488,6 +584,11 @@ async def record() -> str: all_timestamps=False, max_wallet_transactions=200, ) + except BudgetExhaustedError as exc: # fail closed: no partial fixture is written + lines.append(f"{m.case_id}: not evaluable: budget ({exc}); no fixture written") + if ledger.cap >= args.cap: + break # the approval itself is spent + continue except Exception as exc: # report and continue with the next wallet lines.append(f"{m.case_id}: FAILED ({type(exc).__name__}: {exc})") continue @@ -760,6 +861,18 @@ def main(argv: Sequence[str] | None = None) -> int: "--rpc-url", required=True, help="RPC endpoint with historical logs and state" ) p_record.add_argument("--chunk-blocks", type=int, default=100) + p_record.add_argument( + "--cases-dir", help="read the manifest from and write the fixture to this case folder" + ) + _add_rpc_budget(p_record, per_run_help="most requests this window may reserve") + p_locate = replay_sub.add_parser( + "locate", help="read reported transactions' receipts (block, parties, transfers)" + ) + p_locate.add_argument("tx_hash", nargs="+") + p_locate.add_argument("--rpc-url", required=True) + p_locate.add_argument("--chain-id", type=int, default=1) + p_locate.add_argument("--out", metavar="PATH", help="write the JSON here") + _add_rpc_budget(p_locate, per_run_help="most requests this run may reserve") p_sample = replay_sub.add_parser( "sample-background", help="draw unlabelled background wallets (seeded) from an RPC" ) @@ -770,12 +883,14 @@ def main(argv: Sequence[str] | None = None) -> int: p_sample.add_argument("--to-block", type=int, required=True) p_sample.add_argument("--window-blocks", type=int, default=21_601) p_sample.add_argument("--max-nonce-delta", type=int, default=100) + _add_rpc_budget(p_sample, per_run_help="most requests this run may reserve") p_bg = replay_sub.add_parser( "record-background", help="record fixtures for background wallets that have none" ) p_bg.add_argument("--rpc-url", required=True) p_bg.add_argument("--chunk-blocks", type=int, default=1_000) p_bg.add_argument("--limit", type=int, default=None, help="record at most this many") + _add_rpc_budget(p_bg, per_run_help="most requests each window may reserve") p_run = replay_sub.add_parser("run", help="replay recorded cases offline") p_run.add_argument("case_id", nargs="?", help="one case (default: all recorded cases)") p_run.add_argument("--json", action="store_true") diff --git a/src/cryptoguard/ml/annotation.py b/src/cryptoguard/ml/annotation.py index 91a6260..5b4307a 100644 --- a/src/cryptoguard/ml/annotation.py +++ b/src/cryptoguard/ml/annotation.py @@ -241,7 +241,7 @@ def __init__(self, root: Path, reviewer: str, items: Mapping[int, str]) -> None: self._load() def __enter__(self) -> ReviewerStore: - from cryptoguard.ml.collect import _try_os_lock + from cryptoguard.blockchain.budget import _try_os_lock fd = os.open(self.root / LOCK, os.O_RDWR | os.O_CREAT) if not _try_os_lock(fd): @@ -251,7 +251,7 @@ def __enter__(self) -> ReviewerStore: return self def __exit__(self, *exc: object) -> None: - from cryptoguard.ml.collect import _os_unlock + from cryptoguard.blockchain.budget import _os_unlock if self._fd is not None: _os_unlock(self._fd) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 9dff331..6612d9f 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -132,7 +132,11 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ib = ml.add_parser( "incident-benchmark", help="Phase 12.3 independent incident benchmark (offline)" ) - ib.add_argument("step", choices=("verify", "run", "report")) + ib.add_argument("step", choices=("verify", "prepare", "run", "report")) + ib.add_argument("--case", help="prepare: the pre-registered case id") + ib.add_argument("--located", type=Path, help="prepare: `replay locate` JSON for the case") + ib.add_argument("--title", help="prepare: the case title") + ib.add_argument("--first-report", help="prepare: ISO date of the first public report") ib.add_argument( "--manifest", type=Path, default=Path("docs/ml/incident-benchmark/candidates.json") ) @@ -285,6 +289,37 @@ def run(args: argparse.Namespace) -> int: verified_path.write_text(json.dumps(rows, indent=1) + "\n", encoding="utf-8") for r in rows: print(f"{r['case_id']:40} {r['tier']:18} {r['status']}") + elif args.step == "prepare": + if not (args.case and args.located and args.title and args.first_report): + print("prepare needs --case, --located, --title and --first-report.") + return 1 + cand = next( + (c for c in ib_.load_manifest(args.manifest).candidates if c.case_id == args.case), + None, + ) + if cand is None: + print(f"{args.case} is not in {args.manifest}.") + return 1 + case_dir = ib_.NEW_CASES / cand.case_id + if (case_dir / "manifest.json").exists(): + print(f"{case_dir / 'manifest.json'} exists; it is never overwritten.") + return 1 + try: + m = ib_.prepare( + cand, + json.loads(args.located.read_text(encoding="utf-8")), + title=args.title, + first_report=args.first_report, + ) + except ValueError as exc: + print(f"not prepared: {exc}") + return 1 + case_dir.mkdir(parents=True) + (case_dir / "manifest.json").write_text(m.model_dump_json(indent=2) + "\n") + print( + f"Wrote {case_dir / 'manifest.json'}: window {m.evaluation.from_block}.." + f"{m.evaluation.to_block}" + ) elif args.step == "run": from cryptoguard.ml import lookalike_ranking @@ -296,7 +331,11 @@ def run(args: argparse.Namespace) -> int: lookalike_ranking.protected_entities(ML_DIR / "poisoning"), ) run_path.write_text(json.dumps(result, indent=1, default=str) + "\n", encoding="utf-8") - print(json.dumps(result["summary_level_III"], indent=1)) + print( + json.dumps( + {k: result[k] for k in ("summary_level_I", "summary_level_III")}, indent=1 + ) + ) else: for p in (verified_path, run_path): if not p.exists(): @@ -384,7 +423,8 @@ def run(args: argparse.Namespace) -> int: if args.ml_command == "collect": import pandas as pd - from cryptoguard.ml.collect import RequestLedger, budget_path, collect + from cryptoguard.blockchain.budget import RequestLedger + from cryptoguard.ml.collect import budget_path, collect sample = pd.read_csv(args.sample, dtype={"tx_hash": str}) if args.limit is not None: diff --git a/src/cryptoguard/ml/collect.py b/src/cryptoguard/ml/collect.py index 9295ca9..56ec470 100644 --- a/src/cryptoguard/ml/collect.py +++ b/src/cryptoguard/ml/collect.py @@ -22,18 +22,16 @@ import asyncio import json -import os import random -import sys -import threading -import time from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any import httpx +from cryptoguard.blockchain.budget import BudgetedTransport, BudgetExhaustedError, RequestLedger +from cryptoguard.blockchain.budget import LedgerCorruptError as LedgerCorruptError # re-export from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy from cryptoguard.core.errors import RpcError @@ -144,174 +142,6 @@ async def collect_one(client: JsonRpcClient, tx_hash: str) -> dict[str, Any]: } -class BudgetExhaustedError(RuntimeError): - """The request ledger has no room for another attempt.""" - - -class LedgerCorruptError(RuntimeError): - """The request ledger cannot be read; collection refuses to guess (fail closed).""" - - -def _try_os_lock(fd: int) -> bool: - """Non-blocking exclusive lock on byte 0 of ``fd``; the OS drops it when the process dies.""" - try: - if sys.platform == "win32": - import msvcrt - - os.lseek(fd, 0, os.SEEK_SET) - msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) - else: - import fcntl - - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: - return False - return True - - -def _os_unlock(fd: int) -> None: - if sys.platform == "win32": - import msvcrt - - os.lseek(fd, 0, os.SEEK_SET) - msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) - else: - import fcntl - - fcntl.flock(fd, fcntl.LOCK_UN) - - -class RequestLedger: - """Durable, cross-process request budget: one unit is *reserved before* every HTTP - attempt (retries included), under an exclusive OS file lock, with an fsynced atomic write. - - Guarantee: the recorded count is never below the number of attempts budgeted clients - have sent. A crash after reserving over-counts by the attempts it never sent (safe); it - cannot under-count. Collectors in any number of threads or processes on the same ledger - cannot together exceed the cap. The lock is an OS lock (``msvcrt``/``flock``), released - by the OS if its holder dies, so no stale-lock breaking (and its race) is needed. What the - provider bills is not reconstructed: an attempt cut off in flight may or may not have - reached it, and the ledger counts it either way. Each reservation is fsynced before the - request is sent (about 50 ms on a desktop disk), which caps one ledger at roughly 20 - reservations per second: far above free-endpoint rate limits, and the price of surviving - power loss. A lock timeout raises before anything is sent. The file keeps the Phase 11 format - (``{"requests": n, "notes": [...]}``) so earlier usage still counts. - """ - - def __init__(self, path: Path, cap: int, *, lock_timeout: float = 30.0) -> None: - self.path = path - self.cap = cap - self.lock_timeout = lock_timeout - self._lock = path.with_name(path.name + ".lock") - - _local_locks: ClassVar[dict[str, threading.Lock]] = {} - _local_guard: ClassVar[threading.Lock] = threading.Lock() - - def _local(self) -> threading.Lock: - key = os.path.abspath(self._lock) - with self._local_guard: - return self._local_locks.setdefault(key, threading.Lock()) - - def _acquire(self) -> int: - """Threads of one process queue on a blocking in-process lock (no polling, so none - starves under load); the OS lock then excludes other processes.""" - deadline = time.monotonic() + self.lock_timeout - local = self._local() - if not local.acquire(timeout=self.lock_timeout): - raise TimeoutError(f"request ledger lock {self._lock} is held") - try: - fd = os.open(self._lock, os.O_CREAT | os.O_RDWR) - while not _try_os_lock(fd): - if time.monotonic() > deadline: - os.close(fd) - raise TimeoutError(f"request ledger lock {self._lock} is held") - time.sleep(0.005) - except BaseException: - local.release() - raise - return fd - - def _release(self, fd: int) -> None: - try: - _os_unlock(fd) - finally: - os.close(fd) - self._local().release() - - def _read(self) -> dict[str, Any]: - if not self.path.exists(): - return {"requests": 0} - try: - state = json.loads(self.path.read_text(encoding="utf-8")) - int(state["requests"]) - except (ValueError, KeyError, TypeError): - raise LedgerCorruptError(f"{self.path} is unreadable; fix it by hand") from None - return dict(state) - - def _write(self, state: dict[str, Any]) -> None: - tmp = self.path.with_name(self.path.name + f".{os.getpid()}.{threading.get_ident()}.tmp") - with tmp.open("w", encoding="utf-8") as fh: - fh.write(json.dumps(state, indent=1)) - fh.flush() - os.fsync(fh.fileno()) # the count is on disk before it can be relied on - for attempt in range(50): - try: - os.replace(tmp, self.path) # atomic on Windows and POSIX - return - except PermissionError: # Windows: a scanner may hold the target for a moment - if attempt == 49: - raise - time.sleep(0.01) - - def used(self) -> int: - fd = self._acquire() # never read while another process replaces the file - try: - return int(self._read()["requests"]) - finally: - self._release(fd) - - def reserve(self, n: int = 1) -> int: - """Reserve ``n`` attempts or raise; returns the total reserved afterwards.""" - fd = self._acquire() - try: - state = self._read() - total = int(state["requests"]) + n - if total > self.cap: - raise BudgetExhaustedError(f"{state['requests']} of {self.cap} requests used") - state["requests"] = total - self._write(state) - return total - finally: - self._release(fd) - - def note(self, text: str, requests: int = 0) -> int: - """Record a manual charge (e.g. requests made outside the collector).""" - fd = self._acquire() - try: - state = self._read() - state["requests"] = int(state["requests"]) + requests - state.setdefault("notes", []).append(text) - self._write(state) - return int(state["requests"]) - finally: - self._release(fd) - - -class BudgetedTransport(httpx.AsyncBaseTransport): - """Reserves one ledger unit before handing each HTTP attempt to the real transport.""" - - def __init__(self, inner: httpx.AsyncBaseTransport, ledger: RequestLedger) -> None: - self.inner = inner - self.ledger = ledger - - async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - self.ledger.reserve(1) - return await self.inner.handle_async_request(request) - - async def aclose(self) -> None: - await self.inner.aclose() - - def _repair_tail(out: Path) -> bool: """Drop a final checkpoint line cut off by a crash (its transaction is fetched again).""" if not out.exists(): diff --git a/src/cryptoguard/ml/incident_benchmark.py b/src/cryptoguard/ml/incident_benchmark.py index 69311e3..5de3317 100644 --- a/src/cryptoguard/ml/incident_benchmark.py +++ b/src/cryptoguard/ml/incident_benchmark.py @@ -2,6 +2,8 @@ docs/ml/protocol-12.3.md. Offline only: it never fetches chain data. - ``verify``: a provenance, identifier, tier and overlap audit of every discovered case. +- ``prepare``: a pre-registered new case's manifest, built from its located receipts + (``cryptoguard replay locate``); it refuses identifiers the chain does not confirm. - ``run``: tier A operational replay of the cases with a complete recorded wallet stream. The unchanged detector sees only records at or before the cutoff and is never told the outcome address. Then come the production order (OP0), the frozen recency order (OP1), @@ -27,6 +29,9 @@ PROTOCOL = "protocol-12.3/1" FROZEN_AT = "b3f66ae" MANIFEST = Path("docs/ml/incident-benchmark/candidates.json") +# Newly recorded cases (Level I), kept apart from the packaged replay cases. +NEW_CASES = Path("docs/ml/incident-benchmark/cases") +WINDOW_BLOCKS = 21_600 # before and including the harmful block, as in the 4 replay cases ARCHIVE_BLOCKS = (15_053_226, 20_208_032) ARCHIVE_LAST_DATE = "2024-06-30" # the archive's last block (~20.2M) is late June 2024 RECORDING_RPC = (503, 1_361) # requests per 21,600-block window, measured on the 4 fixtures @@ -155,15 +160,63 @@ def overlap( return out +def load_new_cases(directory: Path = NEW_CASES) -> list[Any]: + from cryptoguard.replay.models import load_cases + + if not directory.is_dir() or not any(p.is_dir() for p in directory.iterdir()): + return [] + return load_cases(directory) + + +def onchain_check(ids: Mapping[str, str | None], case: Any) -> dict[str, Any]: + """Do the reported identifiers appear in the recorded window? The harmful transfer must + be in it, from the victim to the lookalike; the planting transaction must be in it with + the lookalike as a party, unless it falls before the window.""" + m, fx = case.manifest, case.fixture + victim, look = (ids.get("victim") or "").lower(), (ids.get("lookalike") or "").lower() + by_tx: dict[str, list[Any]] = {} + for tr in fx.transfers: + by_tx.setdefault(tr.transaction_hash.lower(), []).append(tr) + harm_tx = (ids.get("harm_tx") or "").lower() + harm = by_tx.get(harm_tx, []) + same_case = m.victim.lower() == victim and m.harm.transaction_hash.lower() == harm_tx + harm_ok = same_case and any( + tr.sender.lower() == victim and tr.recipient.lower() == look + for tr in harm + if tr.block_number == m.harm.block_number + ) + plant_tx = (ids.get("planting_tx") or "").lower() + plants = by_tx.get(plant_tx, []) + if not plant_tx: + planting = "not reported" + elif any(look in (tr.sender.lower(), tr.recipient.lower()) for tr in plants): + planting = "confirmed in the window" + elif not plants: + planting = "not in the window (earlier, or not a transfer of this wallet)" + else: + planting = "MISMATCH: in the window without the lookalike" + return { + "harm_transfer_confirmed": harm_ok, + "planting": planting, + "verified": harm_ok and not planting.startswith("MISMATCH"), + } + + def verify( manifest: CandidateManifest, poisoning_dir: Path, cases: Sequence[Any] | None = None, + new_cases: Sequence[Any] | None = None, ) -> list[dict[str, Any]]: from cryptoguard.replay.models import load_cases + if new_cases is None: # the committed folder, unless the caller supplies its own cases + new_cases = load_new_cases() if cases is None else [] cases = load_cases() if cases is None else cases by_id = {c.manifest.case_id: c for c in cases} + new_by_id = {c.manifest.case_id: c for c in new_cases} + if set(by_id) & set(new_by_id): + raise ValueError(f"case ids in both case sets: {sorted(set(by_id) & set(new_by_id))}") refs = reference_sets(poisoning_dir) out: list[dict[str, Any]] = [] for cand in manifest.candidates: @@ -194,8 +247,35 @@ def verify( fx = by_id.get(cand.fixture_case_id or "") if cand.fixture_case_id and fx is None: raise ValueError(f"{cand.case_id}: fixture {cand.fixture_case_id} is missing") - sets = {**refs, **fixture_sets(cases, cand.fixture_case_id)} - if fx is not None: + new = new_by_id.get(cand.case_id) + sets = { + **refs, + **fixture_sets([*cases, *new_cases], cand.fixture_case_id or (new and cand.case_id)), + } + if new is not None and fx is None: + if new.fixture is None: + row |= { + "level": "I (if overlap stays empty)", + "tier": "not_evaluable", + "verified": False, + "status": "pre-registered; window not recorded", + } + else: + check = onchain_check(ids, new) + complete = new.fixture.transfer_scan_complete + row |= { + "level": "I", + "tier": "A" if complete and check["verified"] else "B", + "verified": check["verified"], + "onchain": check, + "status": "newly recorded window" + + ("" if check["verified"] else "; identifiers NOT confirmed on chain") + + ("" if complete else "; transfer scan incomplete"), + "history": "complete for the recorded window only" + if complete + else "incomplete", + } + elif fx is not None: m = fx.manifest local = { "victim": m.victim.lower(), @@ -255,6 +335,98 @@ def verify( return out +# --- prepare (new cases) -------------------------------------------------------------------- + + +def prepare( + cand: Candidate, located: Sequence[Mapping[str, Any]], *, title: str, first_report: str +) -> Any: + """The replay manifest of a pre-registered case, from ``replay locate`` output for its + harmful (and planting) transaction. The window is fixed by rule, never by inspection. + Refuses when the chain does not show the reported harmful transfer.""" + from datetime import date + + from cryptoguard.core.address import to_checksum_address + from cryptoguard.replay.models import ( + EvaluationWindow, + HarmfulTransaction, + IncidentManifest, + SourceRef, + ) + + ids = cand.identifiers + if cand.synthetic or cand.chain_id != 1 or not _complete(ids): + raise ValueError(f"{cand.case_id}: not a mainnet case with complete identifiers") + by_tx = {str(x["transaction_hash"]).lower(): x for x in located} + harm = by_tx.get(str(ids["harm_tx"]).lower()) + if harm is None or not harm.get("found"): + raise ValueError(f"{cand.case_id}: the harmful transaction was not located") + victim, look = str(ids["victim"]).lower(), str(ids["lookalike"]).lower() + paid = [ + tr for tr in harm["transfers"] if tr["from"].lower() == victim and tr["to"].lower() == look + ] + if not harm.get("succeeded") or str(harm.get("from") or "").lower() != victim or not paid: + raise ValueError( + f"{cand.case_id}: identifiers not confirmed on chain (the harmful transaction is " + "not a successful transfer signed by the victim to the lookalike)" + ) + block = int(harm["block_number"]) + checks = [ + f"Harmful transaction {ids['harm_tx']}: block {block}, signed by the victim, " + f"{len(paid)} Transfer log(s) from the victim to the lookalike (replay locate)." + ] + plant = by_tx.get(str(ids.get("planting_tx") or "").lower()) + if plant is not None: + checks.append( + f"Planting transaction {ids['planting_tx']}: " + + (f"block {plant['block_number']}" if plant.get("found") else "not found") + + " (replay locate)." + ) + intended = ids.get("intended") + return IncidentManifest( + case_id=cand.case_id, + title=title, + category="address_poisoning", + chain_id=1, + summary=f"Pre-registered Phase 12.3 benchmark case ({cand.mechanism}); see " + "docs/ml/incident-benchmark/candidates.json.", + first_public_report=date.fromisoformat(first_report), + public_sources=[ + SourceRef( + publisher=cand.source.publisher, + title=title, + url=cand.source.url, + accessed=date.fromisoformat(first_report), + used_for="victim, lookalike, intended recipient, planting and harmful " + "transaction hashes", + ) + ], + victim=to_checksum_address(victim), + intended_recipient=to_checksum_address(intended) if intended else None, + harm=HarmfulTransaction( + transaction_hash=str(ids["harm_tx"]).lower(), + block_number=block, + recipient=to_checksum_address(look), + token=to_checksum_address(paid[0]["token"]), + value_base_units=str(paid[0]["value_base_units"]), + description="The victim's transfer to the lookalike, as located on chain.", + ), + evaluation=EvaluationWindow( + from_block=block - WINDOW_BLOCKS, + to_block=block, + rationale=f"The {WINDOW_BLOCKS:,} blocks (about 3 days) before and including the " + "harmful block: the rule pre-registered before any request, the same as the " + "4 replay cases.", + ), + onchain_verification=checks, + ground_truth_limitations=[ + "One public write-up; the recipient is a lookalike by the source's account and by " + "the located transfer, not by an independent label.", + "The recorded window is 3 days; earlier history is not observed.", + ], + ) + + # --- run (tier A) --------------------------------------------------------------------------- @@ -340,7 +512,7 @@ def _variants(fixture: Any, c: int) -> dict[str, tuple[Any, int, Any]]: } -def run_case(case: Any) -> dict[str, Any]: +def run_case(case: Any, level: str = "III") -> dict[str, Any]: from cryptoguard.ml import candidates as cand from cryptoguard.ml.warning_rank import PLANTING_SIGNALS from cryptoguard.replay.engine import replay @@ -354,7 +526,7 @@ def run_case(case: Any) -> dict[str, Any]: rep = replay(m, fx) out: dict[str, Any] = { "case_id": m.case_id, - "level": "III", + "level": level, "tier": "A", "cutoff": c, "harm_block": m.harm.block_number, @@ -412,6 +584,34 @@ def run_case(case: Any) -> dict[str, Any]: return out +def _summary(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + rankable = [ + r + for r in results + if r["ranking"]["primary"].get("target_warned") and r["ranking"]["primary"]["k"] >= 2 + ] + paired = {"better": 0, "equal": 0, "worse": 0} + for r in rankable: + p = r["ranking"]["primary"] + d = p["OP0_expected_rank"] - p["OP1_expected_rank"] + paired["better" if d > 0 else "worse" if d < 0 else "equal"] += 1 + return { + "tier_A_cases": len(results), + "target_recovered_as_candidate": sum(r["candidates"]["target_recovered"] for r in results), + "target_warned_at_cutoff": sum( + bool(r["ranking"]["primary"].get("target_warned")) for r in results + ), + "early_warning_full_visibility": sum( + r["visibilities"]["erc20_plus_wallet_transactions"]["outcome"] == "early_warning" + for r in results + ), + "rankable_cases": len(rankable), + "OP1_vs_OP0": paired, + "OP0_top1_cases": sum(r["ranking"]["primary"]["OP0_top1"] == 1.0 for r in rankable), + "OP1_top1_cases": sum(r["ranking"]["primary"]["OP1_top1"] == 1.0 for r in rankable), + } + + def run( verified: Sequence[Mapping[str, Any]], blind: tuple[frozenset[str], frozenset[str]], @@ -424,7 +624,8 @@ def run( from cryptoguard.replay.models import load_cases t = time.perf_counter() - cases = load_cases() if cases is None else cases + if cases is None: + cases = [*load_cases(), *load_new_cases()] admitted = {v["case_id"] for v in verified if v["tier"] == "A"} by_fixture = {v["case_id"]: v for v in verified} skipped: list[dict[str, str]] = [] @@ -440,44 +641,19 @@ def run( skipped.append({"case_id": cid, "reason": "recorded window holds a frozen review item"}) else: tier_a.append(c) - results = [run_case(c) for c in tier_a] - rankable = [ - r - for r in results - if r["ranking"]["primary"].get("target_warned") and r["ranking"]["primary"]["k"] >= 2 + results = [ + run_case(c, str(by_fixture[c.manifest.case_id].get("level") or "III")) for c in tier_a ] - paired = {"better": 0, "equal": 0, "worse": 0} - for r in rankable: - p = r["ranking"]["primary"] - d = p["OP0_expected_rank"] - p["OP1_expected_rank"] - paired["better" if d > 0 else "worse" if d < 0 else "equal"] += 1 peak = peak_rss_bytes() return { "benchmark": BENCHMARK_VERSION, "protocol": PROTOCOL, "methods_frozen_at": FROZEN_AT, - "evidence_level": ( - "III (existing replay incidents); no Level I or II case is evaluable offline" - ), + "evidence_level": "levels are reported separately and never pooled", "cases": results, "not_computed": skipped, - "summary_level_III": { - "tier_A_cases": len(results), - "target_recovered_as_candidate": sum( - r["candidates"]["target_recovered"] for r in results - ), - "target_warned_at_cutoff": sum( - bool(r["ranking"]["primary"].get("target_warned")) for r in results - ), - "early_warning_full_visibility": sum( - r["visibilities"]["erc20_plus_wallet_transactions"]["outcome"] == "early_warning" - for r in results - ), - "rankable_cases": len(rankable), - "OP1_vs_OP0": paired, - "OP0_top1_cases": sum(r["ranking"]["primary"]["OP0_top1"] == 1.0 for r in rankable), - "OP1_top1_cases": sum(r["ranking"]["primary"]["OP1_top1"] == 1.0 for r in rankable), - }, + "summary_level_I": _summary([r for r in results if r["level"] == "I"]), + "summary_level_III": _summary([r for r in results if r["level"] == "III"]), "background_alert_burden": background(blind), "resources": { "seconds": round(time.perf_counter() - t, 2), diff --git a/src/cryptoguard/replay/record.py b/src/cryptoguard/replay/record.py index ee7521b..427bfa3 100644 --- a/src/cryptoguard/replay/record.py +++ b/src/cryptoguard/replay/record.py @@ -16,7 +16,9 @@ from __future__ import annotations from datetime import UTC, datetime +from typing import Any +from cryptoguard.blockchain.abi import TRANSFER_TOPIC from cryptoguard.blockchain.provider import RpcEthereumProvider from cryptoguard.core.address import to_checksum_address from cryptoguard.core.errors import RpcInvalidResponseError @@ -146,3 +148,35 @@ async def record_window( transfers=[RecordedTransfer.from_event(t) for t in transfers.transfers], wallet_transactions=transactions, ) + + +async def locate_transaction(provider: RpcEthereumProvider, tx_hash: str) -> dict[str, Any]: + """One receipt read: the block, sender, recipient, status and ERC-20 Transfer logs of a + publicly reported transaction. Used to fix a pre-registered case's window from its + harmful block and to check its reported identifiers; the recorder never receives it.""" + receipt = await provider.get_transaction_receipt(tx_hash) + if receipt is None: + return {"transaction_hash": tx_hash, "found": False} + + def word_address(topic: str) -> str: + return to_checksum_address("0x" + topic[-40:]) + + transfers = [ + { + "token": to_checksum_address(log["address"]), + "from": word_address(log["topics"][1]), + "to": word_address(log["topics"][2]), + "value_base_units": str(int(log.get("data") or "0x0", 16)), + } + for log in receipt.get("logs") or [] + if len(log.get("topics") or []) == 3 and log["topics"][0].lower() == TRANSFER_TOPIC + ] + return { + "transaction_hash": tx_hash, + "found": True, + "block_number": int(receipt["blockNumber"], 16), + "from": to_checksum_address(receipt["from"]) if receipt.get("from") else None, + "to": to_checksum_address(receipt["to"]) if receipt.get("to") else None, + "succeeded": receipt.get("status") == "0x1", + "transfers": transfers, + } diff --git a/tests/fakenode.py b/tests/fakenode.py index 851edb0..723a8d9 100644 --- a/tests/fakenode.py +++ b/tests/fakenode.py @@ -297,6 +297,9 @@ def _dispatch(self, method: str, params: list[Any]) -> Any: sent = next((t for t in self.sent_txs if t["hash"] == tx_hash), None) return { "transactionHash": tx_hash, + "blockNumber": sent["blockNumber"] if sent else logs[0]["blockNumber"], + "from": self.tx_senders[tx_hash], + "to": sent["to"] if sent else (logs[0]["address"] if logs else None), "blockHash": sent["blockHash"] if sent else (logs[0]["blockHash"] if logs else None), diff --git a/tests/integration/test_replay_budget.py b/tests/integration/test_replay_budget.py new file mode 100644 index 0000000..c4a2109 --- /dev/null +++ b/tests/integration/test_replay_budget.py @@ -0,0 +1,243 @@ +"""Replay recorders under a hard request cap: every attempt is reserved first, a window that +hits the cap writes nothing, and the cap is required on every live replay command. + +Mock transports only (no RPC). +""" + +from __future__ import annotations + +import hashlib +import random +from pathlib import Path + +import httpx +import pytest + +from cryptoguard import cli +from cryptoguard.blockchain import budget as budget_mod +from cryptoguard.blockchain.budget import ( + BudgetExhaustedError, + RequestLedger, + budgeted_transport, + run_ledger, +) +from cryptoguard.blockchain.provider import RpcEthereumProvider +from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy +from cryptoguard.replay.models import case_directory +from cryptoguard.replay.record import locate_transaction, record_fixture +from tests.fakenode import FakeNode +from tests.integration.test_replay import HARM, manifest +from tests.unit.test_poisoning import ATTACKER_SIGNER, FAKE, REAL, TOKEN, WALLET + + +class Counting(httpx.AsyncBaseTransport): + def __init__(self, inner: httpx.AsyncBaseTransport) -> None: + self.inner = inner + self.attempts = 0 + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + self.attempts += 1 + return await self.inner.handle_async_request(request) + + +async def _no_sleep(_: float) -> None: + return None + + +def _provider(node: FakeNode, ledger: RequestLedger) -> tuple[RpcEthereumProvider, Counting]: + counting = Counting(node.transport()) + client = JsonRpcClient( + "https://rpc.example.invalid", + retry=RetryPolicy(max_retries=3, base_delay=0.0, max_delay=0.0), + transport=budgeted_transport(ledger, counting), + sleep=_no_sleep, + rng=random.Random(0), + ) + provider = RpcEthereumProvider( + client, expected_chain_id=1, endpoint_display="test", max_log_block_range=1000 + ) + return provider, counting + + +def _incident(node: FakeNode) -> str: + node.add_token(TOKEN) + node.head = 200 + node.send_native(WALLET, REAL, 10**16, block=100) + node.add_transfer_log(TOKEN, WALLET, FAKE, 0, block=110, signer=ATTACKER_SIGNER) + theft = node.add_transfer_log(TOKEN, WALLET, FAKE, 1000, block=HARM, signer=WALLET) + node.send_native(WALLET, TOKEN, 0, block=HARM) + return str(theft["transactionHash"]) + + +async def test_recording_within_the_cap_counts_every_attempt(tmp_path: Path) -> None: + node = FakeNode() + _incident(node) + ledger = RequestLedger(tmp_path / "ledger.json", cap=10_000) + provider, counting = _provider(node, ledger) + try: + fixture = await record_fixture(provider, manifest(), chunk_blocks=50) + finally: + await provider.aclose() + assert fixture.transfer_scan_complete + assert counting.attempts > 0 + assert ledger.used() == counting.attempts == fixture.rpc_requests + + +async def test_recording_stops_at_the_cap_and_never_exceeds_it(tmp_path: Path) -> None: + node = FakeNode() + _incident(node) + ledger = RequestLedger(tmp_path / "ledger.json", cap=5) + provider, counting = _provider(node, ledger) + try: + with pytest.raises(BudgetExhaustedError): + await record_fixture(provider, manifest(), chunk_blocks=50) + finally: + await provider.aclose() + assert counting.attempts <= 5 + assert ledger.used() == counting.attempts == 5 + + +def test_run_ledger_applies_the_per_run_and_total_caps(tmp_path: Path) -> None: + path = tmp_path / "ledger.json" + RequestLedger(path, cap=10).reserve(4) + assert run_ledger(path, 10).cap == 10 + assert run_ledger(path, 10, per_run=3).cap == 7 # 4 used + 3 for this run + assert run_ledger(path, 10, per_run=100).cap == 10 # never past the approval + for bad in ({"cap": 0}, {"cap": 10, "per_run": 0}): + with pytest.raises(ValueError, match="positive"): + run_ledger(path, **bad) # type: ignore[arg-type] + + +async def test_locate_reads_block_parties_and_transfers(tmp_path: Path) -> None: + node = FakeNode() + theft = _incident(node) + ledger = RequestLedger(tmp_path / "ledger.json", cap=20) + provider, counting = _provider(node, ledger) + try: + found = await locate_transaction(provider, theft) + missing = await locate_transaction(provider, "0x" + "cd" * 32) + finally: + await provider.aclose() + assert found["found"] + assert found["block_number"] == HARM + assert found["succeeded"] + assert [(t["from"], t["to"], t["value_base_units"]) for t in found["transfers"]] == [ + (WALLET, FAKE, "1000") + ] + assert missing == {"transaction_hash": "0x" + "cd" * 32, "found": False} + assert ledger.used() == counting.attempts + + +@pytest.mark.parametrize( + "argv", + [ + ["replay", "record", "usdt-50m-poisoning-2025-12-19", "--rpc-url", "https://x.invalid"], + ["replay", "locate", "0x" + "ab" * 32, "--rpc-url", "https://x.invalid"], + ["replay", "record-background", "--rpc-url", "https://x.invalid"], + [ + "replay", + "sample-background", + "--rpc-url", + "https://x.invalid", + "--seed", + "1", + "--from-block", + "1", + "--to-block", + "2", + ], + ], +) +def test_live_replay_commands_require_a_ledger_and_cap(argv: list[str]) -> None: + with pytest.raises(SystemExit) as exc: + cli.main(argv) + assert exc.value.code == 2 + + +def test_record_cli_fails_closed_at_the_cap( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + case = "usdt-50m-poisoning-2025-12-19" + fixture_path = case_directory(case) / "fixture.json" + before = hashlib.sha256(fixture_path.read_bytes()).hexdigest() + node = FakeNode() + monkeypatch.setattr(budget_mod.httpx, "AsyncHTTPTransport", node.transport) + ledger = tmp_path / "ledger.json" + argv = ["replay", "record", case, "--rpc-url", "https://rpc.example.invalid"] + code = cli.main([*argv, "--ledger", str(ledger), "--cap", "1"]) + assert code == 2 + assert "not evaluable: budget" in capsys.readouterr().err + assert hashlib.sha256(fixture_path.read_bytes()).hexdigest() == before # nothing written + assert RequestLedger(ledger, cap=1).used() == 1 + + +def test_stage_1_dry_run_prepare_record_verify( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pilot's whole chain on a mock node: prepare the manifest from a located receipt, + record the window into a separate case folder under a cap, then verify it as Level I.""" + import json + + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.replay.models import load_cases + + harm_block, plant_block = 30_000, 29_000 + node = FakeNode() + node.add_token(TOKEN) + node.head = 31_000 + node.send_native(WALLET, REAL, 10**16, block=25_000) + plant = node.add_transfer_log(TOKEN, WALLET, FAKE, 0, block=plant_block, signer=ATTACKER_SIGNER) + theft = node.add_transfer_log(TOKEN, WALLET, FAKE, 1000, block=harm_block, signer=WALLET) + monkeypatch.setattr(budget_mod.httpx, "AsyncHTTPTransport", node.transport) + + ledger = tmp_path / "ledger.json" + url = ["--rpc-url", "https://rpc.example.invalid", "--ledger", str(ledger), "--cap", "3000"] + hashes = [str(theft["transactionHash"]), str(plant["transactionHash"])] + out = tmp_path / "located.json" + assert cli.main(["replay", "locate", *hashes, "--out", str(out), *url]) == 0 + cand = ib.Candidate.model_validate( + { + "case_id": "dry-run", + "source": {"publisher": "p", "url": "https://example.org", "date": "2026-08-09"}, + "chain_id": 1, + "mechanism": "zero_value_transfer", + "identifiers": { + "victim": WALLET.lower(), + "lookalike": FAKE.lower(), + "intended": REAL.lower(), + "planting_tx": hashes[1], + "harm_tx": hashes[0], + }, + "identifier_status": "verbatim", + "fixture_case_id": None, + "synthetic": True, + } + ) + m = ib.prepare( + cand.model_copy(update={"synthetic": False}), + json.loads(out.read_text(encoding="utf-8")), + title="t", + first_report="2026-11-03", + ) + cases_dir = tmp_path / "cases" + (cases_dir / "dry-run").mkdir(parents=True) + (cases_dir / "dry-run" / "manifest.json").write_text(m.model_dump_json(indent=2)) + record = ["replay", "record", "dry-run", "--cases-dir", str(cases_dir), *url] + assert cli.main([*record, "--max-requests", "2000"]) == 0 + [case] = load_cases(cases_dir) + assert case.fixture is not None + assert case.fixture.transfer_scan_complete + assert (case.fixture.from_block, case.fixture.to_block) == (harm_block - 21_600, harm_block) + assert RequestLedger(ledger, cap=3000).used() <= 3000 + monkeypatch.setattr(ib, "reference_sets", lambda _d: {}) + manifest_ = ib.CandidateManifest.model_validate( + { + "schema_version": "incident-candidates/1", + "protocol": "p", + "discovery": {}, + "candidates": [cand.model_copy(update={"synthetic": False}).model_dump()], + } + ) + [row] = ib.verify(manifest_, Path("unused"), cases=[], new_cases=[case]) + assert (row["level"], row["tier"], row["verified"]) == ("I", "A", True) + assert row["onchain"]["planting"] == "confirmed in the window" diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py index 0bb589d..5689fe8 100644 --- a/tests/test_ml_incident_benchmark.py +++ b/tests/test_ml_incident_benchmark.py @@ -253,3 +253,91 @@ def test_phase_12_2_replays_skip_windows_with_frozen_items() -> None: assert f is not None assert rv.touches_frozen(f, (frozenset(), frozenset({f.transfers[0].transaction_hash.lower()}))) assert not rv.touches_frozen(f, (frozenset(), frozenset())) + + +# --- new (Level I) cases ---------------------------------------------------------------------- + + +def new_cand(**over: Any) -> ib.Candidate: + """The synthetic incident's identifiers, as a public source would report them.""" + theft = transfer(WALLET, FAKE, 1000, HARM, signer=WALLET) + plant = transfer(WALLET, FAKE, 0, 120, signer=ATTACKER_SIGNER) + ids = { + "victim": WALLET.lower(), + "lookalike": FAKE.lower(), + "intended": REAL.lower(), + "planting_tx": plant.transaction_hash, + "harm_tx": theft.transaction_hash, + } + return ib.Candidate.model_validate(cand(case_id="synthetic", identifiers=ids) | over) + + +def located(c: ib.Candidate, **over: Any) -> list[dict[str, Any]]: + harm = { + "transaction_hash": c.identifiers["harm_tx"], + "found": True, + "block_number": HARM, + "from": WALLET, + "to": "0x" + "e" * 40, + "succeeded": True, + "transfers": [ + {"token": "0x" + "e" * 40, "from": WALLET, "to": FAKE, "value_base_units": "1000"} + ], + } + return [harm | over] + + +def test_prepare_fixes_the_window_by_rule_and_refuses_unconfirmed_identifiers() -> None: + c = new_cand() + m = ib.prepare(c, located(c), title="t", first_report="2026-11-03") + assert (m.evaluation.from_block, m.evaluation.to_block) == (HARM - ib.WINDOW_BLOCKS, HARM) + assert m.harm.recipient == FAKE + assert m.victim == WALLET + assert m.harm.value_base_units == "1000" + for bad in ( + {"found": False}, + {"succeeded": False}, + {"from": REAL}, # not signed by the victim + { + "transfers": [ + {"token": "0x" + "e" * 40, "from": WALLET, "to": FAKE2, "value_base_units": "1"} + ] + }, + ): + with pytest.raises(ValueError, match=r"not located|not confirmed"): + ib.prepare(c, located(c, **bad), title="t", first_report="2026-11-03") + with pytest.raises(ValueError, match="complete identifiers"): + ib.prepare(new_cand(chain_id=None), located(c), title="t", first_report="2026-11-03") + + +def test_a_new_case_is_level_i_only_when_the_chain_confirms_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(ib, "reference_sets", no_refs) + c = new_cand() + prepared = ib.prepare(c, located(c), title="t", first_report="2026-11-03") + case = ReplayCase(manifest=prepared, fixture=incident().fixture, fixture_sha256=None) + rows = ib.verify(manifest_of(c.model_dump()), Path("unused"), cases=[], new_cases=[case]) + assert rows[0]["level"] == "I" + assert rows[0]["tier"] == "A" + assert rows[0]["onchain"]["planting"] == "confirmed in the window" + wrong = new_cand(identifiers={**c.identifiers, "lookalike": FAKE2.lower()}) + rows = ib.verify(manifest_of(wrong.model_dump()), Path("unused"), cases=[], new_cases=[case]) + assert rows[0]["verified"] is False + assert rows[0]["tier"] == "B" + assert "NOT confirmed" in rows[0]["status"] + unrecorded = ReplayCase(manifest=prepared, fixture=None, fixture_sha256=None) + rows = ib.verify(manifest_of(c.model_dump()), Path("unused"), cases=[], new_cases=[unrecorded]) + assert rows[0]["status"] == "pre-registered; window not recorded" + with pytest.raises(ValueError, match="both case sets"): + ib.verify(manifest_of(c.model_dump()), Path("unused"), cases=[case], new_cases=[case]) + + +def test_levels_are_summarised_separately() -> None: + admitted = [{"case_id": "synthetic", "tier": "A", "level": "I", "status": "ok"}] + none: tuple[frozenset[str], frozenset[str]] = (frozenset(), frozenset()) + r = ib.run(admitted, none, cases=[incident()]) + assert r["cases"][0]["level"] == "I" + assert r["summary_level_I"]["tier_A_cases"] == 1 + assert r["summary_level_I"]["OP1_vs_OP0"] == {"better": 1, "equal": 0, "worse": 0} + assert r["summary_level_III"]["tier_A_cases"] == 0 From 0aa189211a6141f206155593771fde3b0ad39776 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 19:06:56 +0300 Subject: [PATCH 55/92] docs(ml): Stage 1 incident pilot, one Level I case (475 RPC requests) Recorded the Aug 2026 counterfeit-USDT case exactly as pre-registered (locate 3 + record 472 requests of an approved 2,000; eth.drpc.org). Gate C passes: harm transfer and planting confirmed in the window. Production detector warned 48 blocks before the theft; k=6; OP1 rank 2.0, OP0 4.0, random 3.5. Descriptive only: no gate decided, no rates. Deviation: an unrelated light Python job was running; the user replaced the idle rule with a bounded resource preflight. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + ML_INDEPENDENT_INCIDENT_BENCHMARK.md | 45 +++- .../fixture.json | 203 ++++++++++++++++++ .../manifest.json | 40 ++++ docs/ml/incident-benchmark/pilot-result.md | 137 ++++++++++++ .../preregistration-pilot.md | 4 +- docs/ml/incident-recording-budget-plan.md | 4 +- 7 files changed, 430 insertions(+), 12 deletions(-) create mode 100644 docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/fixture.json create mode 100644 docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/manifest.json create mode 100644 docs/ml/incident-benchmark/pilot-result.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 75d105a..6849d81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,15 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Incident recording, Stage 1 pilot (475 RPC requests of an approved 2,000) +- The Aug 2026 counterfeit-USDT case was recorded as pre-registered, in + `docs/ml/incident-benchmark/cases/`: + - **Verified:** the harmful transaction and the planting are confirmed on chain. + - **Detector:** it warned 48 blocks before the theft. + - **Ranks:** OP1 2.0, OP0 4.0, random 3.5, with 6 warnings. +- This is descriptive only; no gate is decided. Report: + `docs/ml/incident-benchmark/pilot-result.md`. + ### Incident recording, Stage 0 (no RPC requests) - **Fixed:** the replay recorders (`replay record`, `sample-background`, `record-background`) had no total request cap. They now reserve every attempt, retries included, in the durable diff --git a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md index 7513db4..bacf23a 100644 --- a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md +++ b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md @@ -7,7 +7,8 @@ | Candidate manifest (public identifiers and URLs only) | [`docs/ml/incident-benchmark/candidates.json`](docs/ml/incident-benchmark/candidates.json) | | Amendments | [12.2 follow-up audit](docs/ml/amendment-12.2-unconfirmed-audit.md); [frozen-cohort overlap](docs/ml/amendment-12.2-cohort-overlap.md) | | Outputs (git-ignored) | `data/ml/research/phase12.3/` | -| RPC requests / downloads | 0 / none | +| RPC requests / downloads | 0 / none (Phase 12.3); 475 in the Stage 1 pilot (§28) | +| Stage 1 pilot result | [`docs/ml/incident-benchmark/pilot-result.md`](docs/ml/incident-benchmark/pilot-result.md) | ## 1. Executive summary @@ -309,11 +310,37 @@ A missing input fails with a data-availability message. Nothing is fetched. - **Contribution:** the first Level I test of warning coverage, lead time, and OP1 against OP0, with Gate H decided by the frozen rule. +## 28. Addendum: Stage 1 pilot (2026-11-03) + +The Aug 2026 counterfeit-USDT case was recorded exactly as pre-registered. That took +475 RPC requests of an approved 2,000. Details: +[`docs/ml/incident-benchmark/pilot-result.md`](docs/ml/incident-benchmark/pilot-result.md). + +**The case:** +- It is now Level I, tier A. +- Gate C passes for it: the harmful transfer and the planting are both confirmed in the + window. + +**The detector, on pre-theft data only:** +- It recovered the theft recipient as a candidate. +- It warned 48 blocks (576 s) before the theft. +- The warning was one of 6, all of them lookalikes of the same intended recipient. + +**The ranks:** +- OP1 (recency): expected rank 2.0. +- OP0: 4.0. +- Random: 3.5. + +**What this changes:** this is one descriptive observation. +- **Gates G and H:** still not decided. Ten rankable cases are needed. +- **Gate I:** still FAIL (1 of the 10 required). +- **Not claimed:** a rate or independent ML validation. + ## Benchmark result table | Case | Level | Subtype | Outcome status | Mode | Candidate | Warning | Pre-harm | OP0 rank | OP1 rank | Lead | History | Main limitation | |---|---|---|---|---|---|---|---|---|---|---|---|---| -| usdt-counterfeit-39890-2026-08-09 | I (pending) | counterfeit token | documented (Bitquery) | not evaluable | unknown | unknown | unknown | — | — | — | none local | needs RPC recording | +| usdt-counterfeit-39890-2026-08-09 | I | counterfeit token | documented (Bitquery); confirmed on chain (§28) | evaluated | recovered | yes | yes | 4.0 | 2.0 | 48 blocks | 3-day window, planting inside | single source; 3-day history | | usdt-700k-2025-04 | — | zero-value | documented (Decrypt) | not evaluable | unknown | unknown | unknown | — | — | — | none local | identifiers incomplete | | wbtc-2.38-2025-12-18 | — | unknown | documented (Bitquery) | not evaluable | unknown | unknown | unknown | — | — | — | none local | identifiers incomplete | | dea-usdt-55k-2023 | — | airdrop | documented (Forbes, via press) | not evaluable | unknown | unknown | unknown | — | — | — | archive range | no identifiers | @@ -325,14 +352,14 @@ A missing input fails with a data-availability message. Nothing is fetched. | Gate | Status | Evidence | |---|---|---| -| A. New evidence | PASS WITH LIMITATIONS | 1 new case with full identifiers; 5 new without | +| B. Independent provenance | PASS FOR 1 CASE | the new case is independent on all readable sets and, since §28, confirmed on chain | | B. Independent provenance | BLOCKED BY DATA | the new case is independent on all readable sets, but unverifiable on chain offline | -| C. Transaction verification | BLOCKED BY DATA | no local record for the new case; no RPC | +| C. Transaction verification | PASS FOR 1 CASE | §28: the Stage 1 pilot confirmed harm and planting on chain; the others lack identifiers | | D. Point-in-time validity | PASS | implemented and tested (trim, cutoff guard, leakage checks) | -| E. Candidate availability | NOT EVALUATED | no evaluable real case | -| F. Operational replay | BLOCKED BY DATA | no admissible recorded stream | -| G. Warning coverage | NOT EVALUATED | — | -| H. Ranking usefulness | NOT EVALUATED | H3 withdrawn; 0 rankable admissible cases | -| I. Statistical support | FAIL | 0 independent cases, against the 10 required | +| E. Candidate availability | NOT EVALUATED (1 case observed) | §28: theft recipient recovered in 1 of 1 case; no rate from one case | +| F. Operational replay | PASS FOR 1 CASE | §28: one admissible recorded stream; leakage checks pass | +| G. Warning coverage | NOT EVALUATED (1 case observed) | §28: warned 48 blocks before the theft in 1 of 1 case | +| H. Ranking usefulness | NOT EVALUATED | H3 withdrawn; 1 rankable admissible case (§28), against the 10 required | +| I. Statistical support | FAIL | 1 independent case (§28), against the 10 required | | J. Production safety | PASS | no detector, service or risk change; ranker isolated | | K. Reproducibility | PASS WITH LIMITATIONS | offline commands; the inputs cannot be redistributed | diff --git a/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/fixture.json b/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/fixture.json new file mode 100644 index 0000000..338110d --- /dev/null +++ b/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/fixture.json @@ -0,0 +1,203 @@ +{ + "block_timestamps": { + "25696797": 1786029959, + "25707876": 1786163495, + "25718331": 1786289447, + "25718332": 1786289459, + "25718340": 1786289555, + "25718345": 1786289615, + "25718349": 1786289663, + "25718351": 1786289687, + "25718360": 1786289795, + "25718361": 1786289807, + "25718391": 1786290167, + "25718397": 1786290239 + }, + "case_id": "usdt-counterfeit-39890-2026-08-09", + "chain_id": 1, + "from_block": 25696797, + "method": [ + "ERC-20 Transfer logs to and from the wallet, all tokens, the whole window (eth_getLogs).", + "Signer (tx.from) of every outgoing transfer's transaction (eth_getTransactionByHash).", + "Every wallet-signed transaction in the window, located by nonce bisection (eth_getTransactionCount) and read from its block (eth_getBlockByNumber).", + "Wallet code at the window start and one block before the harmful block (eth_getCode).", + "Timestamps of all referenced blocks (eth_getBlockByNumber)." + ], + "recorded_at": "2026-11-03T15:54:24.973504Z", + "recorded_with": "https://eth.drpc.org", + "rpc_requests": 472, + "sender_lookups_skipped": 0, + "to_block": 25718397, + "transfer_scan_complete": true, + "transfers": [ + { + "block_hash": "0x56c49d38fdd06c49fcc76d4b7f375d0afff8252d5ca739734155249e3221bfce", + "block_number": 25707876, + "log_index": 1115, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x2767ae7E0C205425a7B7F7583c512513C527F482", + "token": "0x6051C1354Ccc51b4d561e43b02735DEaE64768B8", + "transaction_hash": "0xeb4a5e28acf1296828e9cb623d282393d557618e7043bb213e373ed50029ab9d", + "transaction_index": 94, + "tx_sender": null, + "value": "90000000000000" + }, + { + "block_hash": "0x2e01abe7f3c65db2852175d22adc3a7d8e8a09aa753f96aa0e7670b769625eb9", + "block_number": 25718331, + "log_index": 226, + "recipient": "0x053DBA7292957341779cB0e9aae1AA7B139aDa3A", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x9f8f6ecc7b3a2f294818dcb504b1667d44e1bfec4288bb8174c6740d9851c33d", + "transaction_index": 111, + "tx_sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "value": "115147641" + }, + { + "block_hash": "0xb59bd2c3bf8d1e5643c04bfd9f7522b8303b329cf68570a6dad59659e691bebf", + "block_number": 25718332, + "log_index": 406, + "recipient": "0x053599Fa536be6c5dd2d240104334244f21DDa3a", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0xaA8A56638b9f91fffa3188693731A8FCBCF40a3B", + "transaction_hash": "0xcfb1f0c00c464bfe645feb6ff7cd9f1888d33bd7fd6ef8973dfd09ffded004b0", + "transaction_index": 139, + "tx_sender": "0x5565F17657Cef60A02295eEdaa52d0041cEb52D6", + "value": "115147641" + }, + { + "block_hash": "0x389fa86a0958d8cd66f99a727e624a20187ea5b2b98c281197ceed964a150e1b", + "block_number": 25718340, + "log_index": 617, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x053dcd29d6Eae2a61b800848492Ba82a008BDA3A", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x5753fdb4670a59bcb47b6badfe7b28c4927b86de1298bd82a9b67aee7cbf634c", + "transaction_index": 110, + "tx_sender": null, + "value": "115" + }, + { + "block_hash": "0x389fa86a0958d8cd66f99a727e624a20187ea5b2b98c281197ceed964a150e1b", + "block_number": 25718340, + "log_index": 650, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x057fb29C6aFEF919810e1C2aD89F7FB5F89ADA3A", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x3b3f3976afe5041a4b4d38e7deeb25a4201b56e3501807fa3f7f7cc619c80792", + "transaction_index": 138, + "tx_sender": null, + "value": "115" + }, + { + "block_hash": "0xd95bdd69cd1ad26834d26f5ee39ce573089f500d1b50cadd5ec710934f9708fe", + "block_number": 25718345, + "log_index": 408, + "recipient": "0x053D505aa083c6A36510D294354821B7329adA3a", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0xd0a0d3d5bd0dcad02b58202a139a41300709da0c6d3d9be324067ab9370e9879", + "transaction_index": 180, + "tx_sender": "0x09CfEe647fA339133380191C8DB6b44F24500c9D", + "value": "0" + }, + { + "block_hash": "0xadd115c03b4eaec77bc7b7ae3c39c57610b4a6ca6d85ca0c56768bb2ac90d1d6", + "block_number": 25718349, + "log_index": 808, + "recipient": "0x053dc459bade1baf76AEd6E8630823f8392FDA3A", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0x647A139B234dCF9f91B1B749993604e715D3ACB8", + "transaction_hash": "0xf84dacfeb3a92ae3291120d954b86d89932fe31702103754cad4f8e8ac41a10d", + "transaction_index": 142, + "tx_sender": "0x1584a8EE67789d1fE161065388657Ad2f2A3c7DD", + "value": "115147641" + }, + { + "block_hash": "0xf264bbf1261079bd85f0630f3c12ff0eb3d34994bca196ec527f38372093ab3e", + "block_number": 25718351, + "log_index": 581, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x0539231b1A6C9d9be57329df965773f97d9AdA3A", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x099bb38aee6b28d934d1732c395e8ffe2ec27ee1e6a1cd6ce1a5e0bfb36ae93a", + "transaction_index": 177, + "tx_sender": null, + "value": "115" + }, + { + "block_hash": "0x2168e70df44e9b1159b36f2d8801c6cd4f0a1688e0008e49d86eb4afee1479ff", + "block_number": 25718360, + "log_index": 662, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x053dcd29d6Eae2a61b800848492Ba82a008BDA3A", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x2d784f2728c51778a71f1874130ed596863e4d8b8c9f1ac36ab75e452ff0fb60", + "transaction_index": 158, + "tx_sender": null, + "value": "115" + }, + { + "block_hash": "0x7bc2d6f22b283e82dd5dae382d7e397b075498657d00d077b45a1603191fdfdc", + "block_number": 25718361, + "log_index": 527, + "recipient": "0x053dc459bade1baf76AEd6E8630823f8392FDA3A", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0xa34574cc067e5e9c8ad46cb5bfa8441f68bdec64b43c4a62722a2cdc4155ad99", + "transaction_index": 353, + "tx_sender": "0xD6434D157f254276D69eDE3bd9fC805482206908", + "value": "0" + }, + { + "block_hash": "0x2606589669d43dbe2fba9b82f97cd0fb03f5a96f495453e8de3ddd03bf011e5a", + "block_number": 25718391, + "log_index": 629, + "recipient": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "sender": "0x053D505aa083c6A36510D294354821B7329adA3a", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0xc216fa46e2d24cbed6a5936d8c8c195a03fbf7d5a79337ec725dbbbeaa8a24ce", + "transaction_index": 231, + "tx_sender": null, + "value": "115" + }, + { + "block_hash": "0x335279d3e0808dfae9d454d8f012918a10485b7aff8a1b8279d15b8b99c3fe02", + "block_number": 25718397, + "log_index": 276, + "recipient": "0x053dc459bade1baf76AEd6E8630823f8392FDA3A", + "sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb", + "transaction_index": 101, + "tx_sender": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "value": "39889952535" + } + ], + "wallet": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "wallet_code_hex": { + "25696797": "0x", + "25718396": "0x" + }, + "wallet_transactions": [ + { + "block_number": 25718331, + "nonce": 5, + "succeeded": null, + "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x9f8f6ecc7b3a2f294818dcb504b1667d44e1bfec4288bb8174c6740d9851c33d", + "transaction_index": 111, + "value": "0" + }, + { + "block_number": 25718397, + "nonce": 6, + "succeeded": null, + "to": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "transaction_hash": "0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb", + "transaction_index": 101, + "value": "0" + } + ] +} diff --git a/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/manifest.json b/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/manifest.json new file mode 100644 index 0000000..92154d1 --- /dev/null +++ b/docs/ml/incident-benchmark/cases/usdt-counterfeit-39890-2026-08-09/manifest.json @@ -0,0 +1,40 @@ +{ + "case_id": "usdt-counterfeit-39890-2026-08-09", + "title": "Counterfeit-USDT poisoning theft, Aug 2026", + "category": "address_poisoning", + "chain_id": 1, + "summary": "Pre-registered Phase 12.3 benchmark case (counterfeit_token); see docs/ml/incident-benchmark/candidates.json.", + "first_public_report": "2026-11-03", + "public_sources": [ + { + "publisher": "Bitquery", + "title": "Counterfeit-USDT poisoning theft, Aug 2026", + "url": "https://bitquery.io/investigations/address-poisoning-ethereum", + "accessed": "2026-11-03", + "used_for": "victim, lookalike, intended recipient, planting and harmful transaction hashes" + } + ], + "victim": "0xB83f1c98b6D799f8eC56a002f2C0A2C343A0F50e", + "intended_recipient": "0x053DBA7292957341779cB0e9aae1AA7B139aDa3A", + "harm": { + "transaction_hash": "0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb", + "block_number": 25718397, + "recipient": "0x053dc459bade1baf76AEd6E8630823f8392FDA3A", + "token": "0xdAC17F958D2ee523a2206206994597C13D831ec7", + "value_base_units": "39889952535", + "description": "The victim's transfer to the lookalike, as located on chain." + }, + "evaluation": { + "from_block": 25696797, + "to_block": 25718397, + "rationale": "The 21,600 blocks (about 3 days) before and including the harmful block: the rule pre-registered before any request, the same as the 4 replay cases." + }, + "onchain_verification": [ + "Harmful transaction 0x374076fa28ed745227c28f42c5054a0bcd024c51ad7a41c17d52e7c6c24980eb: block 25718397, signed by the victim, 1 Transfer log(s) from the victim to the lookalike (replay locate).", + "Planting transaction 0xf84dacfeb3a92ae3291120d954b86d89932fe31702103754cad4f8e8ac41a10d: block 25718349 (replay locate)." + ], + "ground_truth_limitations": [ + "One public write-up; the recipient is a lookalike by the source's account and by the located transfer, not by an independent label.", + "The recorded window is 3 days; earlier history is not observed." + ] +} diff --git a/docs/ml/incident-benchmark/pilot-result.md b/docs/ml/incident-benchmark/pilot-result.md new file mode 100644 index 0000000..648a9d2 --- /dev/null +++ b/docs/ml/incident-benchmark/pilot-result.md @@ -0,0 +1,137 @@ +# Incident-recording pilot (Stage 1): result + +**Run:** 2026-11-03, under `preregistration-pilot.md`. The pre-registration and the methods +were unchanged. **Evidence:** one Level I case. The result is descriptive only: it decides no +gate, and it gives no rate. + +## 1. RPC usage (exact) + +| Step | Requests (retries included) | Ledger total | +|---|---|---| +| `replay locate` (harm tx, planting tx) | 3 | 3 | +| `replay record` (21,601-block window) | 472 | 475 | +| `prepare`, `verify`, `run`, `report` (offline) | 0 | 475 | +| **Approved cap** | | **2,000** | + +**Endpoint and ledger:** `https://eth.drpc.org`, ledger `data/ml/rpc/ledger-incident-pilot.json`. + +**What did not happen:** +- no restart and no transport error; +- no other endpoint, no paid API. + +The 1,525 unused requests do not carry over. + +**Timing:** locate ran at 15:51:46Z; recording ran from 15:52:16Z to 15:54:25Z. + +## 2. Preflight and deviation + +**Preflight checks.** Recording began after a bounded, read-only resource check, taken twice: +- free RAM, at least 2.1 GiB; +- CPU load, 9–38 %; +- disk queue, at most 1.7. + +Before any request, I also checked four things: +- The ledger was absent, so 0 requests had been used. +- The ledger tests passed (29 tests, covering retries, crashes and concurrent processes). +- The endpoint completed a TLS 1.3 handshake. No HTTP request was sent. +- Both frozen cohort sheets match the hashes recorded when they were sent to reviewers: + A `a0ec4b6e…`, 60 items; B `121c112d…`, 35 items. + +**Deviation from §5.** One unrelated Python job was running (causalverse, about 60 MiB). The +pre-registration forbids "no other RPC or ML process at the same time". The user replaced that +rule with this resource-aware preflight. The job made no RPC requests and used a different +ledger. No process was stopped or changed. + +## 3. Incident verification (Gate C for this case: PASS) + +| Check | Result | +|---|---| +| Harmful tx `0x3740…80eb` | block 25,718,397; succeeded; signed by the victim; a USDT Transfer of 39,889.952535 from the victim to the lookalike `0x053dc459…da3a` | +| Planting tx `0xf84d…a10d` | block 25,718,349, 48 blocks before the harm, inside the window. It is a batch of 187 Transfer logs. One is a counterfeit-token (`0x647a…`) transfer of 115.147641 shown as from the victim to the lookalike. The batch was signed by `0x1584…c7DD`, not by the victim. | +| `prepare` | accepted; window 25,696,797 to 25,718,397 by the frozen rule | +| Overlap (all reference sets, both frozen cohorts) | none | +| Harm timestamp | 1786290239 (2026-08-09 UTC), as the source dates it | + +## 4. Data completeness + +- **The window is complete.** + - The transfer scan is complete, with 0 sender lookups skipped. + - The window holds 12 Transfer logs, 2 wallet transactions and 12 block timestamps. + - Fixture: canonical SHA-256 `62b3744c…0573b8`. +- **The planting is inside the window**, so there is no coverage gap for it. +- **The legitimate-recipient history is only partly observed.** + - The victim's real transfer to the intended recipient `0x053dba72…da3a` is inside the window, at block 25,718,331, 66 blocks before the harm. This is the use the attack copies. + - Earlier history with that address, before block 25,696,797, is **not observed**. This report does not claim there was none. +- **What the window cannot show:** + - planting attempts, or campaign activity, before the window; + - earlier interactions of the victim with these addresses. + +## 5. Point-in-time correctness + +- **Cutoff:** harm block − 1 (25,718,396). + - The whole harm block is excluded, so a same-block earlier transaction would also be hidden. This is conservative. + - The detector's newest input was checked against the cutoff, and the replay leakage checks passed. +- **What the detector receives:** no manifest. + - The harmful transaction, the victim label and the lookalike label are used only to look up the outcome afterwards. + - Candidate generation runs on the trimmed fixture, in (block, tx index, log index) order. +- **The recorder** received only the victim and the window. +- **The theft recipient was never injected as a candidate.** It was recovered by the + detector's own `spoofed_out` method. + +## 6. Results (one case) + +| Measure | Value | +|---|---| +| Candidates generated / distinct lookalikes | 9 / 6 | +| Theft recipient recovered as a candidate | yes (`spoofed_out`) | +| Warned at the cutoff | yes, `elevated_risk` | +| Outcome, ERC-20 only and full visibility | early warning in both | +| Lead time | **48 blocks (576 s, about 10 min)**, first warning at the planting block | +| Warnings at the cutoff (k) | 6 | +| OP0 (severity, then similarity) expected rank | 4.0 | +| OP1 (frozen recency) expected rank | **2.0** | +| Random expected rank | 3.5 | +| Top-1 under OP0 / OP1 | no / no | +| Warning set preserved by the ranker | yes | + +**The other 5 warned addresses** all end in `…da3a`, the intended recipient's suffix, and two +also share its `0x053d` prefix, as the theft recipient does. They appeared in the same 60 blocks: a swarm of lookalikes of one +address. +- They are **unlabelled**. They are counted neither as false positives nor as true positives. +- OP1 put the most recent of them (`0x053d505a…`, an incoming 115-unit USDT transfer at block + 25,718,391) first, and the theft recipient second. + +**Perturbations:** +- **No effect:** ERC-20 only, history limited to the last day, and duplicate records. + Each gives the same k = 6 and the same ranks. +- **Signers unknown:** k = 5, OP0 4.5, OP1 2.0. +- **Cutoff delayed by 300 blocks or 1 day:** k = 0. The whole swarm arrived within 66 blocks of + the harm, so no earlier cutoff had anything to warn about. + +## 7. What this shows, and what it does not + +**Shown, for this one wallet:** +- the production detector warned on the eventual theft recipient 48 blocks before the theft, + from pre-theft data only; +- OP1 placed that recipient above OP0's expected position and above random. + +**Not shown:** +- **No ranking gate.** Gate H needs at least 10 rankable cases, and an exact sign test needs at least 6 untied cases. + This is 1 case, so OP1 "better" here is a single observation, not evidence of superiority. +- **No rates.** There is no detection rate, precision, recall or false-positive rate. +- **Not independent ML validation.** OP1 is a frozen ranking rule. It was not trained or tuned here, and nothing was tuned on this outcome. +- **No claim on warning burden.** The 6 background windows from Phase 12.3 hold 0 warnings. They are other wallets at other dates and are not a control for this one. + +**Limitations:** +- **Source:** one public write-up (Bitquery). The lookalike label comes from that source and the on-chain transfer, not from an independent label. +- **History:** 3 days only; pre-window history is unobserved. +- **Lead time:** 48 blocks is short. Any realistic delay before showing a warning (300 blocks or more) would remove it entirely in this case. +- **Cutoff:** the cutoff has block resolution. + +## 8. Reproduce (offline, from the committed case) + +``` +cryptoguard ml incident-benchmark verify --out data/ml/research/incident-pilot +cryptoguard ml incident-benchmark run --out data/ml/research/incident-pilot +cryptoguard ml incident-benchmark report --out data/ml/research/incident-pilot +``` diff --git a/docs/ml/incident-benchmark/preregistration-pilot.md b/docs/ml/incident-benchmark/preregistration-pilot.md index e29feae..8813361 100644 --- a/docs/ml/incident-benchmark/preregistration-pilot.md +++ b/docs/ml/incident-benchmark/preregistration-pilot.md @@ -5,8 +5,8 @@ the case, before its window exists, and before any detector output on it. **Budget plan:** `docs/ml/incident-recording-budget-plan.md`, Stage 1. -**Status:** Stage 0 is complete, and 0 requests have been made. Stage 1 runs only after you -explicitly approve its cap. +**Status:** Stage 1 ran on 2026-11-03 under an approved 2,000 cap. It used 475 requests. +Result: `pilot-result.md`. This file was not changed before or during the run. ## 1. The case diff --git a/docs/ml/incident-recording-budget-plan.md b/docs/ml/incident-recording-budget-plan.md index 0b58f48..0d71c9e 100644 --- a/docs/ml/incident-recording-budget-plan.md +++ b/docs/ml/incident-recording-budget-plan.md @@ -3,7 +3,9 @@ **Status:** - **Stage 0 is complete:** the recorder cap, the pre-registration (`incident-benchmark/preregistration-pilot.md`) and the overlap check are all done. -- **No RPC request** has been made for this plan, and none is authorized by this document. Each stage below needs its own explicit approval of a request cap, and unused +- **Stage 1 is complete** (2026-11-03): **475 of 2,000 approved requests** used + (`incident-benchmark/pilot-result.md`). The other 1,525 do not carry over. +- **No further request is authorized** by this document. Each stage below needs its own explicit approval of a request cap, and unused requests from one approval do not carry over to the next. **Purpose:** give the Phase 12.3 benchmark its first independently documented (Level I) cases. From 95a7740e62a2589d57948edafe8a1dbe04161157 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 19:40:16 +0300 Subject: [PATCH 56/92] docs(ml): Stage 1 audit and Stage 2 incident shortlist (no RPC) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CI for 0aa1892 passed (9/9 jobs); lead time measured from recorded header timestamps (48 blocks, 576 s). - Freeze the pilot case: a regression test pins its canonical hashes and its result (k=6, OP0 4.0, OP1 2.0, early warning). - Correct the Gate G/H labels to the frozen protocol 12.3 §10 rule (G: 1 of 1; H at Level I: PASS WITH LIMITATIONS, n=1). - Bounded public discovery (8 searches, 12 reads): no fully eligible new case; 3 near-misses deduplicated offline (no overlap; one in the unscanned archive range). Shortlist, measured-cost budget (Stage 2a cap 5,840; 2b 14,000) and a statistical review with a proposed pre-outcome amendment. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 + ML_INDEPENDENT_INCIDENT_BENCHMARK.md | 17 +- docs/ml/incident-benchmark/pilot-result.md | 5 +- .../incident-benchmark/stage2-candidates.json | 106 +++++++ .../ml/incident-benchmark/stage2-shortlist.md | 284 ++++++++++++++++++ docs/ml/incident-recording-budget-plan.md | 3 + tests/test_ml_incident_benchmark.py | 32 ++ 7 files changed, 451 insertions(+), 7 deletions(-) create mode 100644 docs/ml/incident-benchmark/stage2-candidates.json create mode 100644 docs/ml/incident-benchmark/stage2-shortlist.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6849d81..a61d152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,17 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Incident recording, Stage 2 preparation (no RPC requests) +- **Stage 1 audit:** + - CI passed for `0aa1892`; + - the lead time is measured from header timestamps (576 s); + - the pilot case is frozen by a hash-and-result regression test; + - the Gate G and Gate H labels are corrected to the frozen §10 rule. +- **Bounded public discovery** (8 searches, 12 reads) and an offline deduplication: + - no fully eligible new case; + - 3 near-misses are assessed in `docs/ml/incident-benchmark/stage2-candidates.json`. +- **Shortlist, budget and statistical review:** `docs/ml/incident-benchmark/stage2-shortlist.md`. + ### Incident recording, Stage 1 pilot (475 RPC requests of an approved 2,000) - The Aug 2026 counterfeit-USDT case was recorded as pre-registered, in `docs/ml/incident-benchmark/cases/`: diff --git a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md index bacf23a..4d41bda 100644 --- a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md +++ b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md @@ -332,8 +332,15 @@ The Aug 2026 counterfeit-USDT case was recorded exactly as pre-registered. That - Random: 3.5. **What this changes:** this is one descriptive observation. -- **Gates G and H:** still not decided. Ten rankable cases are needed. -- **Gate I:** still FAIL (1 of the 10 required). +- **Gate labels under §10 of the frozen protocol:** + - Gate G is reported as an exact count: 1 of 1 warned before the harm. + - Gate H at Level I is **PASS WITH LIMITATIONS**: fewer than 10 cases, OP1 never worse and + better in 1. + - The phase classification becomes a **limited external case-study result**. +- **Correction (2026-11-03, Stage 2 preparation):** this section first said that Gates G and H + were "not decided". That misapplied §10, and both labels are corrected above. +- **The labels are weak evidence.** The pilot pre-registration's statement that one case decides nothing still stands, and Gate I is still FAIL (1 of the 10 required). `docs/ml/incident-benchmark/stage2-shortlist.md` §7 proposes reporting + fewer than 6 untied cases as DESCRIPTIVE, never PASS. - **Not claimed:** a rate or independent ML validation. ## Benchmark result table @@ -356,10 +363,10 @@ The Aug 2026 counterfeit-USDT case was recorded exactly as pre-registered. That | B. Independent provenance | BLOCKED BY DATA | the new case is independent on all readable sets, but unverifiable on chain offline | | C. Transaction verification | PASS FOR 1 CASE | §28: the Stage 1 pilot confirmed harm and planting on chain; the others lack identifiers | | D. Point-in-time validity | PASS | implemented and tested (trim, cutoff guard, leakage checks) | -| E. Candidate availability | NOT EVALUATED (1 case observed) | §28: theft recipient recovered in 1 of 1 case; no rate from one case | +| E. Candidate availability | 1 of 1 (exact count) | §28: theft recipient recovered in 1 of 1 Level I case; no rate from one case | | F. Operational replay | PASS FOR 1 CASE | §28: one admissible recorded stream; leakage checks pass | -| G. Warning coverage | NOT EVALUATED (1 case observed) | §28: warned 48 blocks before the theft in 1 of 1 case | -| H. Ranking usefulness | NOT EVALUATED | H3 withdrawn; 1 rankable admissible case (§28), against the 10 required | +| G. Warning coverage | 1 of 1 (exact count, per §10) | §28: warned 48 blocks (576 s, measured) before the theft in 1 of 1 Level I case | +| H. Ranking usefulness | PASS WITH LIMITATIONS (Level I, n = 1) | §28: OP1 better in 1, worse in 0; the §10 rule allows this label below 10 cases; descriptive only. H3 withdrawn. | | I. Statistical support | FAIL | 1 independent case (§28), against the 10 required | | J. Production safety | PASS | no detector, service or risk change; ranker isolated | | K. Reproducibility | PASS WITH LIMITATIONS | offline commands; the inputs cannot be redistributed | diff --git a/docs/ml/incident-benchmark/pilot-result.md b/docs/ml/incident-benchmark/pilot-result.md index 648a9d2..bbd354a 100644 --- a/docs/ml/incident-benchmark/pilot-result.md +++ b/docs/ml/incident-benchmark/pilot-result.md @@ -86,7 +86,7 @@ ledger. No process was stopped or changed. | Theft recipient recovered as a candidate | yes (`spoofed_out`) | | Warned at the cutoff | yes, `elevated_risk` | | Outcome, ERC-20 only and full visibility | early warning in both | -| Lead time | **48 blocks (576 s, about 10 min)**, first warning at the planting block | +| Lead time | **48 blocks, 576 s (9 min 36 s), measured** from recorded block-header timestamps (15:34:23Z to 15:43:59Z). The first warning is at the planting block. | | Warnings at the cutoff (k) | 6 | | OP0 (severity, then similarity) expected rank | 4.0 | | OP1 (frozen recency) expected rank | **2.0** | @@ -116,8 +116,9 @@ address. - OP1 placed that recipient above OP0's expected position and above random. **Not shown:** -- **No ranking gate.** Gate H needs at least 10 rankable cases, and an exact sign test needs at least 6 untied cases. +- **No reliable ranking result.** Gate H needs at least 10 rankable cases for a PASS, and an exact sign test needs at least 6 untied cases. This is 1 case, so OP1 "better" here is a single observation, not evidence of superiority. + - **Correction:** §10 of the frozen protocol labels this outcome PASS WITH LIMITATIONS at Level I, and Gate G is the exact count 1 of 1. See `stage2-shortlist.md` §1 and §7, which also proposes closing this loophole. - **No rates.** There is no detection rate, precision, recall or false-positive rate. - **Not independent ML validation.** OP1 is a frozen ranking rule. It was not trained or tuned here, and nothing was tuned on this outcome. - **No claim on warning burden.** The 6 background windows from Phase 12.3 hold 0 warnings. They are other wallets at other dates and are not a control for this one. diff --git a/docs/ml/incident-benchmark/stage2-candidates.json b/docs/ml/incident-benchmark/stage2-candidates.json new file mode 100644 index 0000000..ed596a0 --- /dev/null +++ b/docs/ml/incident-benchmark/stage2-candidates.json @@ -0,0 +1,106 @@ +{ + "schema_version": "incident-candidates/1", + "protocol": "protocol-12.3/1 (discovery rules of section 4, applied to Stage 2 discovery)", + "discovery": { + "date": "2026-11-03", + "searches": 8, + "page_reads": 12, + "note": "Bounded by protocol 12.3 section 4: at most 8 searches and 15 page reads; 3 page reads unused. Identifiers are copied verbatim from the cited page. Truncated identifiers are stored as null, with the visible characters in identifier_status. A role is never assigned unless the page states it. No RPC request, explorer query or paid API was used." + }, + "candidates": [ + { + "case_id": "scamsniffer-763k-2025-02-20", + "source": { + "publisher": "ForkLog (citing Scam Sniffer, X post of 2025-02-26)", + "url": "https://forklog.com/en/user-loses-over-760000-due-to-address-poisoning/", + "date": "2025-02-26" + }, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": { + "etherscan_filter_fadd": "0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4", + "etherscan_filter_tadd": "0x804051b0cbc20443943c4f363573ef9bb7793375" + }, + "identifier_status": "partial: two full addresses, taken from an Etherscan advanced-filter link (fadd, tadd); the page does not state which is the victim or the lookalike; no transaction hash; token not stated", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "pink-drainer-10eth-2024-06-27", + "source": { + "publisher": "ForkLog (citing MistTrack, X post of 2024-07-07)", + "url": "https://forklog.com/en/pink-drainer-hackers-fall-victim-to-address-poisoning-scam/", + "date": "2024-07-08" + }, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": { + "victim": "0x8980ab6d185af9bcc10292d4e91ae4c0b4f14213", + "intended": "0xeff0e5244d5c78ba4dd6bc01082576280558f58a", + "lookalike": null + }, + "identifier_status": "partial: victim and intended recipient given in full; lookalike not given in full; no transaction hash; 10 ETH (native)", + "fixture_case_id": null, + "synthetic": false + }, + { + "case_id": "webacy-6.88m-usdt-2025-09", + "source": { + "publisher": "Webacy (From the CTO's Desk, September 2025)", + "url": "https://www.webacy.com/blog/from-the-ctos-desk-september-2025", + "date": "2025-09 (month of the report; no exact publication date read)" + }, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": { + "victim": "0xee7ada00c9e5f654c8f8ea0f355a1f3c50942732", + "lookalike": null + }, + "identifier_status": "partial: victim given in full; four scam addresses given only as prefixes (0x418e0ddb..., 0x4186a058..., 0x4186a666..., 0x4186b115...); no transaction hash; about 6,880,000 USDT over 15 and 18 Sep 2025", + "fixture_case_id": null, + "synthetic": false + } + ], + "not_usable_sources": [ + { + "case": "Cyvers, 2.6M USDT (843k + 1.75M), 2025-05-26", + "url": "https://forklog.com/en/crypto-investor-loses-2-6-million-in-zero-transfer-scam/", + "reason": "no identifiers; chain not stated; primary source is a social-media alert" + }, + { + "case": "Cyvers, about 100k USDT, 2026-08", + "url": "https://www.chaincatcher.com/en/article/2282116", + "reason": "no identifiers; chain not stated (already listed as usdt-100k-2026-08)" + }, + { + "case": "Cyvers, 509k USDT, 2026-01, and 600k USDT, 2026-02", + "url": "https://www.chaincatcher.com/en/article/2282116", + "reason": "search summary only; no identifiers; social-media primary source" + }, + { + "case": "Tether freeze, 20M, 2023-08-01", + "url": "https://www.web3isgoinggreat.com/single/20m-zero-transfer-attack", + "reason": "no identifiers; inside the Tsuchiya archive range" + }, + { + "case": "Address-poisoning wave, about 1.6M, 2025-08", + "url": "https://cointelegraph.com/news/1-6m-lost-wave-crypto-address-poisonings-this-week", + "reason": "no identifiers; the 140 ETH case is the existing fixture eth-140-poisoning-2025-08-14" + }, + { + "case": "ETH variant with real ETH, 47.6k victim, 2024-02", + "url": "https://crypto.news/scammers-target-victims-with-real-crypto-in-new-address-poisoning-attack/", + "reason": "no identifiers; social-media primary source" + }, + { + "case": "50M USDT, 2025-12-20 (several outlets)", + "url": "https://cointelegraph.com/news/address-poisoning-copy-paste-mistake-50m-usdt-loss", + "reason": "duplicate of the existing fixture usdt-50m-poisoning-2025-12-19 (frozen Cohort B overlap)" + }, + { + "case": "Guan and Li, CCS 2024 (Poison-Hunter) case studies", + "url": "https://par.nsf.gov/servlets/purl/10580433", + "reason": "addresses deliberately shortened by the authors; data already a reference set" + } + ] +} diff --git a/docs/ml/incident-benchmark/stage2-shortlist.md b/docs/ml/incident-benchmark/stage2-shortlist.md new file mode 100644 index 0000000..73cfcfa --- /dev/null +++ b/docs/ml/incident-benchmark/stage2-shortlist.md @@ -0,0 +1,284 @@ +# Stage 2 preparation: Stage 1 audit, incident shortlist, budget and protocol review + +**Date:** 2026-11-03. + +**No RPC request was made**, and no paid API, explorer query or download was used. Stage 2 has +not started. Every request below is a proposal, and each needs explicit approval. + +**Inputs:** +- `stage2-candidates.json`: the candidates, with identifiers copied verbatim; +- the offline overlap check (`ml incident-benchmark verify --manifest + docs/ml/incident-benchmark/stage2-candidates.json`), written to the git-ignored + `data/ml/research/stage2-shortlist/`; +- the Stage 1 result (`pilot-result.md`). + +## 1. Stage 1 audit (completed) + +| Item | Result | +|---|---| +| CI for `0aa1892` | **Passed.** One workflow run, `pull_request` event, 16:07:11Z–16:10:17Z. All 9 required jobs succeeded: 3 backend, 2 frontend, browser e2e, dependency audit, 2 package. | +| CI for `61ad1af` (Stage 0) | Passed. It had been unverified when Stage 0 was reported. | +| Lead time | **48 blocks, 576 s, measured.** Both endpoints are block-header timestamps recorded by `eth_getBlockByNumber` in the fixture: planting block 25,718,349 at 2026-08-09T15:34:23Z, harm block 25,718,397 at 15:43:59Z. 576 s equals 48 × 12 s, so no slot was missed in between. Nothing is estimated from an average block time. | +| What the lead time means | An on-chain opportunity window (protocol 12.3 §9), not when a warning would have reached the user: it does not include indexing or delivery latency. The protocol's two lead measures agree. The first planting signal and the earliest warned cutoff are both block 25,718,349. | +| Other times, measured | The victim's legitimate transfer to the intended recipient came 792 s before the harm. The first lookalike arrived 12 s after that transfer. The last competing warning came 72 s before the harm. | +| Frozen case | **Done.** `test_stage_1_pilot_case_is_frozen_and_reproduces_exactly` pins the canonical hashes: fixture `62b3744c…0573b8`, manifest `ef903fbb…095e39`. It also pins the result: early warning, 48 blocks, 576 s, k = 6, OP0 4.0, OP1 2.0. A change to the detector or the ranker that moves the case now fails CI, so it has to be disclosed. Neither the detector nor Recency was changed. | +| **Gate label correction** | Under protocol 12.3 §10, Gate H at Level I is **PASS WITH LIMITATIONS**: fewer than 10 cases, OP1 never worse and better in 1. Gate G is reported as an exact count, **1 of 1**. The Stage 1 report had said "not evaluated" for both. It is corrected here, and in §28 of `ML_INDEPENDENT_INCIDENT_BENCHMARK.md`. The phase classification under §10 becomes a **limited external case-study result** (Level I cases exist, but Gate H does not PASS). The pilot pre-registration's own statement still applies: a single case decides nothing. §6.2 below proposes closing this loophole in the rule. | + +## 2. Discovery (bounded, same rules as protocol 12.3 §4) + +**Budget:** at most 8 searches and 15 page reads. 8 searches and 12 page reads were used; one +read was a redirect, and one was a PDF. The PDF was a research paper whose text was extracted +locally. + +**Source order:** +1. primary forensic and firm reports; +2. papers; +3. news that quotes identifiers. + +Social-media-only claims are insufficient. X posts were not read. + +**Inclusion rule (unchanged):** the source must give, verbatim, either: +- the harmful transaction hash; or +- the victim **and** the lookalike. + +Identifiers are never inferred, and a role is never assigned unless the source states it. + +**Outcome:** **no new case meets the inclusion rule in full.** Three cases come close, each with +some full identifiers; §4 lists them. Everything else found has no identifiers, or duplicates an +existing fixture: +- the $50M Dec 2025 theft is `usdt-50m-poisoning-2025-12-19`, which is excluded (Cohort B); +- the 140 ETH Aug 2025 theft is `eth-140-poisoning-2025-08-14`, which is excluded. + +All rejections are listed in `stage2-candidates.json`, `not_usable_sources`. + +**Why public discovery is thin:** +- **News:** it repeats firm alerts on X without identifiers. +- **Firm reports:** + - they truncate addresses: Webacy, Bitquery; + - Guan and Li (CCS 2024) shorten every case-study address on purpose. + +## 3. Deduplication (offline) + +**What each full identifier was compared with:** +- **Frozen cohorts:** A (60) and B (35), blinded sheets. +- **Archive target groups:** payoff victims, lookalikes and transactions; incident groups. +- **Earlier phases:** Phase 12.1 lookalikes and planting transactions; Phase 12.2 U victims. +- **Poison-Hunter** ground truth. +- **Fixtures:** the 4 replay fixtures and the Stage 1 case. + +No set was unreadable. + +**A full-text search** for the 5 full addresses found no match in: +- every JSON file under `src/cryptoguard/replay/`: incident, background and campaign cases; +- `docs/ml/`; +- all of `data/`, about 1.5 GB. That includes the uncompressed Tsuchiya payoff CSV and the + Poison-Hunter ground truth. + +| Candidate | Full identifiers | Overlap found | Unknown overlap | +|---|---|---|---| +| scamsniffer-763k-2025-02-20 | 2 addresses | none | none: after the archive's range | +| webacy-6.88m-usdt-2025-09 | victim | none | none: after the archive's range | +| pink-drainer-10eth-2024-06-27 | victim, intended | none | **the compressed attempt archive** (2.3 GB `.sql.gz`, blocks to 20,208,032). This case lies inside its range. Ruling out overlap needs the offline archive pass (about 1 h on the shared HDD), so for now it is Level II at best. | + +## 4. Candidate assessment + +Selection used only identifier completeness and provenance. No candidate was chosen or +dropped for how Recency is expected to do on it. + +| | scamsniffer-763k-2025-02-20 | webacy-6.88m-usdt-2025-09 | pink-drainer-10eth-2024-06-27 | +|---|---|---|---| +| Source (organization) | Scam Sniffer, via ForkLog | Webacy (firm report) | MistTrack (SlowMist), via ForkLog | +| Source type | firm alert, quoted by news with an Etherscan filter link | firm's monthly analysis | firm alert, quoted by news | +| Identifiers | `0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4` (Etherscan filter `fadd`) and `0x804051b0cbc20443943c4f363573ef9bb7793375` (`tadd`); **roles not stated**; no tx hash; token not stated | victim `0xee7ada00c9e5f654c8f8ea0f355a1f3c50942732`; lookalikes only as prefixes `0x418e0ddb…`, `0x4186a058…`, `0x4186a666…`, `0x4186b115…`; no tx hash | victim `0x8980ab6d185af9bcc10292d4e91ae4c0b4f14213`; intended `0xeff0e5244d5c78ba4dd6bc01082576280558f58a`; lookalike truncated; no tx hash | +| Date / amount | 2025-02-20 / $763,662 | 2025-09-15 and 2025-09-18 / about 6.88M USDT in two bursts | 2024-06-27 / 10 ETH | +| Subtype | not stated | not stated. The source reports weak similarity (0.50–0.52; Levenshtein 25–28) | not stated. The source says first and last 5 characters match | +| Outcome confidence | medium: a firm alert; the loss is in the source, the roles are not | medium-high: a firm's own analysis with a full victim | medium: a firm alert; atypical victim (a drainer's own wallet) | +| Independence | Level I if resolved (no overlap; post-archive) | Level I if resolved (no overlap; post-archive) | Level II at best until the archive pass | +| Historical data | full chain history is available | available | available | +| Expected wallet activity (drives cost) | unknown | probably high (a large holder) | very high (a drainer hub) | +| Replay suitability | good if the loss is an ERC-20 transfer; **not resolvable from logs if native ETH** | good. Two bursts and several lookalikes; the first harmful transfer sets the cutoff. | poor. A native ETH transfer means the harm must be found from transactions, not logs. A hub wallet's 3-day window may exceed any per-window cap. | +| What would need resolving on chain | the transfer `fadd → tadd` on 2025-02-19..21 (direct; no similarity used) | USDT transfers from the victim on 2025-09-14..19 to the source's stated prefixes | a 10 ETH send from the victim on 2024-06-27 to an address matching the intended one's first and last 5 characters. **That rule uses lookalike similarity, the detector's own feature.** | + +**Already listed in Phase 12.3 and still rejected:** +- `usdt-700k-2025-04`: no victim or lookalike is given; +- `wbtc-2.38-2025-12-18`: the victim is not named, and the lookalike is truncated; +- `dea-usdt-55k-2023` and `usdt-50k-2026-10`: no identifiers; +- `usdt-100k-2026-08`: the chain is not stated. + +## 5. Ranked shortlist + +1. **scamsniffer-763k-2025-02-20: include in Stage 2a.** + - It is the only case with two full addresses. + - Resolving it needs no similarity criterion, since the transfer between the two given + addresses is looked up directly. + - The roles follow Etherscan's filter semantics (`fadd` is "from", `tadd` is "to"). That + is an interpretation, so it is pre-registered as such. It is falsified, and the case ends, + if no transfer from `fadd` to `tadd` exists in the stated dates. + - It adds a source organization (Scam Sniffer) and a pre-Fusaka 2025 period. +2. **webacy-6.88m-usdt-2025-09: include in Stage 2a, with a high-activity cap.** + - A full victim, a firm analysis, and the largest loss in the list. + - Resolution uses only the source's own prefixes. + - Risks: + - Webacy is an ML-detection vendor, so the case was selected by a detector, which favours + visible poisoning; + - the stated similarity is weak, so the lookalike subtype is atypical; + - a busy wallet may exceed the per-window cap. That fails closed as *not evaluable: + budget*, and it is reported. +3. **pink-drainer-10eth-2024-06-27: defer** (not in Stage 2a). Four reasons: + - the archive overlap is unresolved; + - the harm is a native ETH transfer; + - the resolution rule would rely on similarity, which is circular with the detector; + - the cost is likely beyond any reasonable cap. + + It can be reconsidered only after the offline archive pass, as a Level II case. + +**Diversity achieved:** +- **Organizations:** Bitquery (Stage 1), Scam Sniffer, Webacy. +- **Periods:** Feb 2025, Sep 2025, Aug 2026. +- **Mechanisms:** counterfeit token (Stage 1), plus at least one unknown subtype. + +That is too few to cover subtypes: zero-value, dust and native ETH are absent at Level I. + +## 6. Budget, from measured costs + +### 6.1 Measured basis + +| Window | Requests | Activity | +|---|---|---| +| Stage 1 pilot (incident) | 472, plus 3 for locate | 12 transfers, 2 wallet transactions, 0 retries | +| Earlier incident windows (n = 4) | 503 / 732 / 1,361 (min / median / max) | the 1,361 came from retries | +| Background windows (n = 9) | 443 / 450 / 534 | quiet wallets | + +**The cost model:** +- **Fixed floor:** about 443. That is two log scans of 216 chunks each, plus about 11 calls. +- **Activity:** one timestamp per referenced block, one sender lookup per outgoing transfer (at most 500), and one block read per wallet transaction. +- **Retries:** up to ×4 on the free endpoint. + +A quiet wallet such as the pilot's costs 470–500. A busy wallet can cost several thousand. + +### 6.2 Per-case limits (proposed) + +Each case gets its own hard cap, set by expected activity rather than a flat figure. A case that +reaches its cap is *not evaluable: budget*, and its leftover requests are not reused. + +| Case | Resolution step | Recording | Case cap | Expected | +|---|---|---|---|---| +| scamsniffer-763k | timestamp bisection for the date bounds (≤ 60), then a Transfer-log query filtered on `from = fadd, to = tadd` over about 21,600 blocks in 100-block chunks (≤ 240) | activity unknown: 2,000 | **2,300** | about 750 | +| webacy-6.88m | timestamp bisection (≤ 60), then USDT Transfer logs filtered on `from = victim` over about 43,200 blocks (≤ 480) | probably busy: 3,000 | **3,540** | about 1,500 | +| **Stage 2a total** | | | **5,840** | **about 2,250** | + +**Stage 2b (user-sourced cases).** These need full identifiers including the harm tx, so +`locate` takes at most 20 requests each. +- **Per case:** 20 for locate plus a 2,000 recording cap. +- **For 8 cases:** an expected 8 × (20 + 832) ≈ 6,800 at the measured incident mean, under a stage cap of **14,000**. That leaves room for retries. +- **Busy wallets:** if they push cases into the cap, the stage stops when the cap is reached, and the rest are *not evaluable: budget*. + +**Cumulative:** +- **Spent:** 475 (Stage 1). +- **Proposed:** + - Stage 2a: 5,840 at most, about 2,250 expected; + - Stage 2b: 14,000 at most, about 6,800 expected. +- **Total:** at most 20,315, about 9,500 expected. + +**The fail-closed cap introduces a bias.** It drops busy wallets, so the evaluated sample leans +towards quiet wallets, where the detector's job is easier. The number of cases dropped at the +cap is reported in every summary. + +**Prerequisite (0 RPC, code only):** Stage 2a needs a small command that finds Transfer logs +between given addresses in a date range, under the ledger. `replay locate` reads only by hash. +It is mock-tested like the Stage 0 tools, and nothing else is added. + +## 7. Statistical protocol review + +**Ten cases are a feasibility threshold, not a basis for generalization.** + +| Question | n = 10 untied cases | What reliability would need | +|---|---|---| +| **Sign test** (OP1 vs OP0, one-sided α = 0.05) | needs ≥ 9 of 10 better (p = 0.011). Power if OP1 is truly better in 70 / 80 / 90 % of cases: **0.15 / 0.38 / 0.74** | 80 % power needs n = 37 (70 %), 23 (75 %), 18 (80 %) | +| **Warning coverage** (exact 95 % Clopper–Pearson) | 10 of 10 → [0.69, 1.00]; 7 of 10 → [0.35, 0.93] | n = 40 at 32 of 40 → [0.64, 0.91] | +| **Rankable vs recorded** | cases with k = 1, or with the target unwarned, are ties or unrankable. Ten recorded may give fewer than 10 rankable | report both counts; Gate H counts only untied, rankable cases | + +**Further threats the current protocol does not address:** +1. **Clustered cases.** Guan and Li attribute 98 % of phishing addresses to four entities. + Cases from one campaign are not independent, so the sign test overstates n. + - **Proposed:** record each case's funding or signer infrastructure from the fixture + (pre-cutoff data only). + - Report the number of distinct clusters. + - Make the sign test cluster-level, one vote per cluster. +2. **Selection on outcome and on detectability.** + - Public cases are large losses that firms' own tools noticed, which favours visible + poisoning. + - Results describe *documented* thefts, not all thefts. + - With no negatives there is no false-positive rate, precision or recall. +3. **Censoring.** The 3-day window caps the observable lead time, and plantings before the + window are missed. One Cyvers alert reports a planting 66 days before the theft. Lead + times are therefore reported as censored at the window start, and the share of cases whose + first planting falls before the window is reported. +4. **The budget-cap bias**, described in §6.2. +5. **The rule allows a pass on one case.** Protocol 12.3 §10 gives PASS WITH LIMITATIONS + with one case. + - **Proposed amendment, frozen before any Stage 2 request:** below 6 untied rankable + cases, Gate H is reported as **DESCRIPTIVE**, never PASS. The Stage 1 label above stays + on record. +6. **The effect measure depends on k.** Expected ranks are not comparable across different k. + - **Proposed, pre-registered:** the normalized rank (r − 1)/(k − 1) and the paired + difference OP0 − OP1 per case, with the raw ranks. + - None of this changes OP0, OP1 or the detector. + +**Recommendation:** +- Keep 10 untied, rankable Level I cases as the **feasibility** threshold for Gate H. +- State in advance that a PASS at n = 10 supports only "consistent with an advantage in + documented cases". +- Treat roughly 25–40 clustered-independent cases as the scale for a reliability claim. Public + sources alone cannot supply that at present (§2). + +## 8. Recommended Stage 2 execution plan + +**Step 0: no RPC; this approval is for code and documents.** +1. Commit the protocol amendment of §7, before any Stage 2 request: + - DESCRIPTIVE below 6 untied cases; + - cluster-level sign test; + - normalized rank; + - censored lead times; + - count of cases dropped at the cap. +2. Add the capped transfer-finding command, with mock tests. +3. Pre-register Stage 2a: + - the case manifests for `scamsniffer-763k-2025-02-20` and `webacy-6.88m-usdt-2025-09`; + - the resolution rules of §5; + - the date ranges; + - the per-case caps of §6.2. + + A resolution that fails ends that case (*identifiers not confirmed on chain*), with no + retry under another rule. + +**Step 1: Stage 2a, needs approval of a 5,840 cap.** +- Sequence per case: resolve → `prepare` → `record` → offline `verify / run / report`. +- One ledger per stage. One restart per step after a transport error. +- Runs only after the same bounded resource preflight as Stage 1. + +**Step 2: Stage 2b, needs a 14,000 cap and cases you source.** +- At least 8 incidents, each with a harm tx hash and a public write-up. +- Prefer: + - zero-value, dust and native-ETH subtypes; + - different source organizations; + - 2024–2026. +- I check and pre-register them offline before any request. + +**Step 3, optional and separately approved:** the offline archive pass (about 1 h of HDD, no +RPC). It would turn the Pink Drainer case into a Level II candidate, or rule it out. + +**Never:** recording before pre-registration, changing the detector or Recency in response to +an outcome, or pooling levels. + +## 9. Remaining uncertainties + +- **763k case:** whether `fadd` / `tadd` are the victim and the lookalike. It is falsifiable at + resolution. Whether the loss was an ERC-20 transfer is also unknown. +- **Webacy case:** + - whether the victim's window fits a 3,000 cap; + - whether its weak-similarity lookalikes are poisoning in the protocol's sense, or the + output of a vendor's model. +- **Stage 2b:** whether 8 or more fully identified incidents can be sourced at all. Public + sourcing gave 0 fully eligible new cases out of 3 near-misses. +- **External validity of any 10-case result:** limited by clustering, selection on detection + and loss size, and the 3-day censoring. diff --git a/docs/ml/incident-recording-budget-plan.md b/docs/ml/incident-recording-budget-plan.md index 0d71c9e..ad28176 100644 --- a/docs/ml/incident-recording-budget-plan.md +++ b/docs/ml/incident-recording-budget-plan.md @@ -5,6 +5,9 @@ (`incident-benchmark/preregistration-pilot.md`) and the overlap check are all done. - **Stage 1 is complete** (2026-11-03): **475 of 2,000 approved requests** used (`incident-benchmark/pilot-result.md`). The other 1,525 do not carry over. +- **Stage 2 preparation** (0 requests): `incident-benchmark/stage2-shortlist.md`. Public + discovery found no fully eligible new case. It proposes Stage 2a (2 public cases, cap + 5,840) and Stage 2b (user-sourced, cap 14,000), plus a protocol amendment. - **No further request is authorized** by this document. Each stage below needs its own explicit approval of a request cap, and unused requests from one approval do not carry over to the next. diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py index 5689fe8..34e44fd 100644 --- a/tests/test_ml_incident_benchmark.py +++ b/tests/test_ml_incident_benchmark.py @@ -341,3 +341,35 @@ def test_levels_are_summarised_separately() -> None: assert r["summary_level_I"]["tier_A_cases"] == 1 assert r["summary_level_I"]["OP1_vs_OP0"] == {"better": 1, "equal": 0, "worse": 0} assert r["summary_level_III"]["tier_A_cases"] == 0 + + +PILOT = "usdt-counterfeit-39890-2026-08-09" + + +def test_stage_1_pilot_case_is_frozen_and_reproduces_exactly() -> None: + """The first Level I case is a frozen benchmark input: its recorded data and its result + may not change silently (a detector or ranker change that moves it must be disclosed).""" + import hashlib + + [case] = [c for c in ib.load_new_cases() if c.manifest.case_id == PILOT] + assert case.fixture_sha256 == ( + "62b3744c496cca63bdef6e34e8881718f9f9a125cb14c6c8af7656255f0573b8" + ) + assert hashlib.sha256(case.manifest.model_dump_json().encode()).hexdigest() == ( + "ef903fbbcd94837188a6624310eef8f6eda9abcee7d5fc4baa43362d45095e39" + ) + row = ib.run_case(case, level="I") + primary = row["ranking"]["primary"] + full = row["visibilities"]["erc20_plus_wallet_transactions"] + assert row["candidates"]["target_recovered"] + assert row["leakage_checks_passed"] + assert (full["outcome"], full["lead_time_blocks"], full["lead_time_seconds"]) == ( + "early_warning", + 48, + 576, + ) + assert (primary["k"], primary["OP0_expected_rank"], primary["OP1_expected_rank"]) == ( + 6, + 4.0, + 2.0, + ) From fdffc059675acc366909768a7b2b50d56449f17f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 20:14:16 +0300 Subject: [PATCH 57/92] feat(ml): Stage 2 Step 0 - amendment 12.3-A1, resolution tools, Stage 2a pre-registration (no RPC) - Amendment 12.3-A1, frozen before any Stage 2 request: rule-bound identifier resolution (no similarity scoring), Gate H DESCRIPTIVE below 6 untied clusters with a cluster-level exact sign test, normalized ranks, a censoring flag, cases not recorded, and Level I summarized with and without resolved cases. - replay find-transfers: capped Transfer-log search between reported addresses over UTC days (timestamp bisection, receipts of the first 10 matches). ml incident-benchmark resolve: frozen per-case rules; refuses a different query, an incomplete scan, or an attacker-signed transfer. verify/prepare merge candidates.json and stage2-resolved.json. - Pre-register Stage 2a: 2 cases, caps 2,400 / 3,600 (6,000 total). - Mock-node tests only; detector, OP0 and OP1 unchanged; the frozen Stage 1 case reproduces exactly. 866 passed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++ README.md | 1 + docs/ml/amendment-12.3-A1.md | 98 +++++++ .../preregistration-stage2a.md | 112 ++++++++ .../ml/incident-benchmark/stage2-shortlist.md | 10 +- docs/ml/incident-recording-budget-plan.md | 5 +- src/cryptoguard/cli.py | 53 +++- src/cryptoguard/ml/cli.py | 52 +++- src/cryptoguard/ml/incident_benchmark.py | 257 +++++++++++++++++- src/cryptoguard/replay/record.py | 90 ++++++ tests/integration/test_replay_budget.py | 108 ++++++++ tests/test_ml_incident_benchmark.py | 106 ++++++++ 12 files changed, 886 insertions(+), 22 deletions(-) create mode 100644 docs/ml/amendment-12.3-A1.md create mode 100644 docs/ml/incident-benchmark/preregistration-stage2a.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a61d152..8aec2dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,22 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Incident recording, Stage 2 Step 0 (no RPC requests) +- **Amendment 12.3-A1** (`docs/ml/amendment-12.3-A1.md`), frozen before any Stage 2 request: + - **R1, identifier resolution:** a frozen on-chain rule, with no similarity scoring. + - **R2, Gate H:** DESCRIPTIVE below 6 untied clusters; clusters are cases sharing a planting signer. + - **R3, added measures:** normalized ranks, the censoring flag, and cases not recorded. + - Level I is also summarized without resolved cases. +- **Added:** + - `replay find-transfers`: capped; finds block bounds by header timestamps; reads receipts of the first 10 matches. + - `ml incident-benchmark resolve`; + - multi-manifest `verify` and `prepare`. + - All are tested on mock nodes only. The detector, OP0 and OP1 are unchanged, and the Stage 1 case reproduces exactly. +- **Pre-registered:** Stage 2a (`docs/ml/incident-benchmark/preregistration-stage2a.md`): + - 2 cases; + - caps of 2,400 / 3,600 per case, 6,000 total; + - not approved. + ### Incident recording, Stage 2 preparation (no RPC requests) - **Stage 1 audit:** - CI passed for `0aa1892`; diff --git a/README.md b/README.md index 081b7ab..7f3680b 100644 --- a/README.md +++ b/README.md @@ -205,6 +205,7 @@ uv run cryptoguard replay run --write-report EVALUATION.md # replay command needs a request ledger and an approved cap; retries count, and a run that # reaches the cap writes nothing: uv run cryptoguard replay record --rpc-url --ledger --cap +uv run cryptoguard replay find-transfers --sender [--recipient ] --since --until --rpc-url --ledger --cap # Evaluate the experimental analyses too (incidents + background wallets; analytics extra): uv run --extra analytics cryptoguard replay run --analytics --write-report EVALUATION.md # Background wallets: seeded random sample, then record their fixtures diff --git a/docs/ml/amendment-12.3-A1.md b/docs/ml/amendment-12.3-A1.md new file mode 100644 index 0000000..9b82d36 --- /dev/null +++ b/docs/ml/amendment-12.3-A1.md @@ -0,0 +1,98 @@ +# Amendment 12.3-A1: Stage 2 reporting and identifier resolution + +**Frozen:** 2026-11-03, in the commit that adds this file. That is before any Stage 2 RPC +request and before any Stage 2 window exists. The only Level I outcome known at freezing is the +Stage 1 pilot (`incident-benchmark/pilot-result.md`). + +**Amends:** `protocol-12.3.md`, §5, §9 and §10. + +**Motivation:** `incident-benchmark/stage2-shortlist.md` §7. + +**What is unchanged:** +- the detector, OP0, OP1 (Recency) and the perturbations; +- the window rule (H − 21,600 to H) and the cutoff (H − 1); +- the overlap audit and the evidence levels. + +Everything here changes **reporting**, plus one new, rule-bound way to obtain identifiers. +Every metric of protocol 12.3 is still reported unchanged, beside the amended ones. + +**Code:** `ml/incident_benchmark.py`: `RESOLUTION_RULES`, `resolve`, `amended_gate_h`, +`sign_test_p`, and the new fields of `ranking`, `run_case` and `run`. Also `replay +find-transfers` (`replay/record.py`: `find_transfers`, `block_at_time`). All of it is tested +on mock nodes only. + +## R1. Identifier resolution (amends §5) + +Protocol 12.3 admits only identifiers a source gives verbatim. A case whose source gives full +addresses but no harmful transaction may still enter, under four conditions: + +1. **The rule is frozen in code before any request.** It lives in `RESOLUTION_RULES` and + fixes: + - which reported identifier is the sender and which the recipient, or the reported recipient prefixes; + - the token, if the source names it; + - inclusive UTC dates around the reported date. +2. **The query is exact.** `replay find-transfers` returns ERC-20 Transfer logs from the + sender (to the recipient, if given), with nonzero value, oldest first, and reads the + receipts of the first 10. + - `resolve` refuses output whose query differs from the rule, or whose scan is incomplete. +3. **The harmful transaction** is the oldest match whose transaction succeeded and was signed by + the sender, and which carries the Transfer. + - A transfer that an attacker signed "from" the victim (a counterfeit-token or + `transferFrom` spoof) is therefore never taken as the theft. + - If no match qualifies, the case ends as *identifiers not confirmed on chain*. No second + rule and no other dates are tried. +4. **No similarity is scored.** The rule uses only the source's identifiers and dates. A case + whose resolution would need a lookalike-similarity criterion is not admitted under R1. + +**Reporting:** a resolved case carries `identifier_source: resolved` in `verify`. Level I is +summarized twice, with resolved cases (`summary_level_I`) and without them +(`summary_level_I_verbatim_only`). + +The overlap audit runs again on the resolved identifiers (lookalike and harmful transaction) +before anything is recorded. + +## R2. Gate H (amends §10) + +| Status | Condition | +|---|---| +| NOT EVALUATED | no rankable case | +| **DESCRIPTIVE** | fewer than 6 untied clusters. This replaces "PASS WITH LIMITATIONS", which a single case could reach. | +| FAIL | more clusters worse than better | +| PASS | at least 10 rankable clusters, more better than worse, and an exact one-sided sign test over the untied clusters with p < 0.05 | +| NOT PASSED | otherwise | + +**Clusters:** +- Two cases share a cluster when the planting transfers involving their outcome address have a transaction signer in common. + - The signers come from the recorded fixture, at or before the cutoff, with the victim excluded. + - The link is transitive. +- A cluster votes better, worse or equal by the majority of its cases' paired differences. +- A case with no known signer is its own cluster, and is counted as `linkage_unknown_cases`. + +Rankable is unchanged: the target is warned and k ≥ 2. + +**What a PASS supports.** A PASS at the minimum of 10 clusters supports only this statement: +*consistent with an advantage of OP1 over OP0 on documented thefts*. It is not a reliable +generalization; `stage2-shortlist.md` §7 gives the power. + +**The Stage 1 label stays on record.** Under protocol 12.3 it was PASS WITH LIMITATIONS +(Level I, n = 1). Under this amendment it is DESCRIPTIVE. + +## R3. Added per-case measures (amend §9) + +- **Normalized ranks:** (r − 1)/(k − 1) for OP0 and OP1, where 0 is first and 1 is last. + Also the paired difference OP0 − OP1 in expected rank. +- **`cluster_signers`:** see R2. +- **`lead_possibly_censored`:** true when the outcome address's first record in the window + lies within the window's first day (7,200 blocks). + - Plantings before the window are unobservable, so any lead time is only a lower bound on the time since the attack began. + - The number of censored cases is reported. +- **`new_cases_not_recorded`:** pre-registered cases with no complete window. These include runs that stopped at the cap (*not evaluable: budget*) or after a second transport error (*not evaluable: RPC*). + - The cause of each is taken from the ledger notes and the stage report. + +## R4. Unchanged prohibitions + +- No outcome may change the detector, OP0, OP1, the rules above, or which cases are reported. +- No pooling of levels. +- No rates: no detection rate, precision, recall or false-positive rate. +- No interval methods below 10 independent clusters, other than the exact counts and the + Clopper–Pearson intervals stated in advance in `stage2-shortlist.md` §7. diff --git a/docs/ml/incident-benchmark/preregistration-stage2a.md b/docs/ml/incident-benchmark/preregistration-stage2a.md new file mode 100644 index 0000000..fdc5ff3 --- /dev/null +++ b/docs/ml/incident-benchmark/preregistration-stage2a.md @@ -0,0 +1,112 @@ +# Pre-registration: Stage 2a (two resolved public cases) + +**Frozen:** 2026-11-03, in the commit that adds this file. That is before any Stage 2 request, +and before any detector output on these cases. + +**Governing rules:** +- `protocol-12.3.md` and `../amendment-12.3-A1.md`; +- the shortlist and statistical review in `stage2-shortlist.md`. + +**Status: not approved.** Stage 2a runs only after the user explicitly approves its cap. + +## 1. Cases + +The identifiers are copied verbatim from `stage2-candidates.json`. The resolution rules are +those frozen in `RESOLUTION_RULES` (`ml/incident_benchmark.py`). + +| Order | Case | Source | Rule: sender → recipient | Token | UTC days | +|---|---|---|---|---|---| +| 1 | `scamsniffer-763k-2025-02-20` | Scam Sniffer via ForkLog | `0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4` (Etherscan `fadd`) → `0x804051b0cbc20443943c4f363573ef9bb7793375` (`tadd`) | any | 2025-02-19 to 2025-02-21 | +| 2 | `webacy-6.88m-usdt-2025-09` | Webacy | `0xee7ada00c9e5f654c8f8ea0f355a1f3c50942732` → prefixes `0x418e0ddb`, `0x4186a058`, `0x4186a666`, `0x4186b115` | USDT `0xdac17f958d2ee523a2206206994597c13d831ec7` | 2025-09-14 to 2025-09-19 | + +Deferred and **not** part of Stage 2a: `pink-drainer-10eth-2024-06-27`. Its resolution would +need a similarity criterion, which R1 excludes, and its overlap with the archive is unresolved. + +## 2. Caps + +Revised before any request from `stage2-shortlist.md` §6.2: the resolution caps now include +the chain check, the head read and up to 10 receipt reads. + +| Case | `find-transfers` | `record` | Case cap | +|---|---|---|---| +| scamsniffer-763k | 400 (about 52 bisection + 216 log chunks + ≤ 10 receipts) | 2,000 | 2,400 | +| webacy-6.88m | 600 (about 52 + 432 log chunks + ≤ 10) | 3,000 | 3,600 | +| **Stage 2a** | | | **6,000** | + +- **Ledger:** `data/ml/rpc/ledger-incident-stage2a.json`, with `--cap 6000` on every + command. Each command also carries the `--max-requests` above. +- **No reuse:** the per-case caps add up to the stage cap, so no case can use another's + leftover. +- **Endpoint:** `https://eth.drpc.org` only. + +## 3. Commands (in this order, nothing else) + +`RPC` stands for `--rpc-url https://eth.drpc.org --ledger data/ml/rpc/ledger-incident-stage2a.json --cap 6000`. +`OUT` stands for `data/ml/research/stage2a`. + +**Preflight**, before the first command: the same bounded, read-only resource check as +Stage 1. +- At least 1.5 GiB of free RAM, with CPU and disk load moderate. +- Other projects' processes are never touched. +- At most 5 checks; then stop and report the blocker. + +**Case 1:** +1. `cryptoguard replay find-transfers --sender 0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4 + --recipient 0x804051b0cbc20443943c4f363573ef9bb7793375 --since 2025-02-19 --until + 2025-02-21 --max-requests 400 --out OUT/scamsniffer-763k-2025-02-20/found.json RPC` +2. `cryptoguard ml incident-benchmark resolve --case scamsniffer-763k-2025-02-20 --found + OUT/scamsniffer-763k-2025-02-20/found.json`. **If it refuses**, case 1 ends and is reported + as *identifiers not confirmed on chain*. +3. `cryptoguard ml incident-benchmark prepare --case scamsniffer-763k-2025-02-20 --located + OUT/scamsniffer-763k-2025-02-20/found.json --title "Scam Sniffer-reported poisoning loss, + Feb 2025" --first-report 2025-02-26` +4. `cryptoguard replay record scamsniffer-763k-2025-02-20 --cases-dir + docs/ml/incident-benchmark/cases --max-requests 2000 RPC` + +**Case 2:** the same four steps, with these values: +- `find-transfers`: `--sender 0xee7ada00c9e5f654c8f8ea0f355a1f3c50942732 --token + 0xdac17f958d2ee523a2206206994597c13d831ec7`, then `--recipient-prefix` once for each of + `0x418e0ddb`, `0x4186a058`, `0x4186a666` and `0x4186b115`, then `--since 2025-09-14 --until + 2025-09-19 --max-requests 600`. +- `prepare`: `--title "Webacy-reported USDT poisoning loss, Sep 2025" --first-report + 2026-11-03`. The first-report date is the read date, used as an upper bound, because no + exact publication date was read. +- `record`: `--max-requests 3000`. + +**Evaluation, offline:** +- `cryptoguard ml incident-benchmark verify`, then `run`, then `report`, each with `--out + OUT`. +- The default manifests are `candidates.json` and `stage2-resolved.json`, so the Stage 1 case + is evaluated with them. + +## 4. What is reported, whatever the outcome + +**Per case:** +- RPC usage per step; +- whether the case was resolved, refused or stopped at the cap; +- the resolved identifiers; +- the overlap audit on them; +- Gate C; +- the planting status. No planting transaction was reported, so it is "not reported". +- data completeness; +- candidate recovery; +- warning and lead time, measured from header timestamps, with the censoring flag; +- k, the OP0 / OP1 / random ranks and the normalized ranks; +- the perturbations; +- `cluster_signers`. + +**Summaries:** +- Level I with and without resolved cases; +- Gate H under amendment A1. With at most 3 Level I cases it is DESCRIPTIVE by construction. +- the protocol 12.3 labels alongside; +- `new_cases_not_recorded`. + +**Not claimed:** any rate, any generalization, or independent ML validation. + +## 5. Stop rules + +- **Caps:** stop at each per-command cap and at the stage cap. A case that hits a cap is *not evaluable: budget*, and its leftover is not reused. +- **Restarts:** one restart per step after a transport error. A second failure is *not evaluable: RPC*. +- **Falsified resolution:** if `resolve` refuses, the case ends. There is no role swap, no wider dates and no other rule. +- **No substitutes:** no other endpoint, no paid API, and no other RPC process at the same time. +- **No tuning:** nothing is tuned on the outcome. A defect found is fixed in the open, and the original output is kept. diff --git a/docs/ml/incident-benchmark/stage2-shortlist.md b/docs/ml/incident-benchmark/stage2-shortlist.md index 73cfcfa..40b1c9b 100644 --- a/docs/ml/incident-benchmark/stage2-shortlist.md +++ b/docs/ml/incident-benchmark/stage2-shortlist.md @@ -167,6 +167,8 @@ reaches its cap is *not evaluable: budget*, and its leftover requests are not re | webacy-6.88m | timestamp bisection (≤ 60), then USDT Transfer logs filtered on `from = victim` over about 43,200 blocks (≤ 480) | probably busy: 3,000 | **3,540** | about 1,500 | | **Stage 2a total** | | | **5,840** | **about 2,250** | +**Revised in Step 0, before any request:** the caps are **2,400 / 3,600 / 6,000**, as given in `preregistration-stage2a.md` §2. The resolution caps above left out the chain check, the head read and up to 10 receipt reads; the resolution steps are now 400 and 600. + **Stage 2b (user-sourced cases).** These need full identifiers including the harm tx, so `locate` takes at most 20 requests each. - **Per case:** 20 for locate plus a 2,000 recording cap. @@ -176,9 +178,9 @@ reaches its cap is *not evaluable: budget*, and its leftover requests are not re **Cumulative:** - **Spent:** 475 (Stage 1). - **Proposed:** - - Stage 2a: 5,840 at most, about 2,250 expected; + - Stage 2a: 6,000 at most (revised), about 2,250 expected; - Stage 2b: 14,000 at most, about 6,800 expected. -- **Total:** at most 20,315, about 9,500 expected. +- **Total:** at most 20,475, about 9,500 expected. **The fail-closed cap introduces a bias.** It drops busy wallets, so the evaluated sample leans towards quiet wallets, where the detector's job is easier. The number of cases dropped at the @@ -234,7 +236,7 @@ It is mock-tested like the Stage 0 tools, and nothing else is added. ## 8. Recommended Stage 2 execution plan -**Step 0: no RPC; this approval is for code and documents.** +**Step 0: no RPC; this approval is for code and documents.** Done: `../amendment-12.3-A1.md`, `replay find-transfers` and `ml incident-benchmark resolve`, and `preregistration-stage2a.md`. 1. Commit the protocol amendment of §7, before any Stage 2 request: - DESCRIPTIVE below 6 untied cases; - cluster-level sign test; @@ -251,7 +253,7 @@ It is mock-tested like the Stage 0 tools, and nothing else is added. A resolution that fails ends that case (*identifiers not confirmed on chain*), with no retry under another rule. -**Step 1: Stage 2a, needs approval of a 5,840 cap.** +**Step 1: Stage 2a, needs approval of a 6,000 cap** (revised in Step 0). - Sequence per case: resolve → `prepare` → `record` → offline `verify / run / report`. - One ledger per stage. One restart per step after a transport error. - Runs only after the same bounded resource preflight as Stage 1. diff --git a/docs/ml/incident-recording-budget-plan.md b/docs/ml/incident-recording-budget-plan.md index ad28176..34590c4 100644 --- a/docs/ml/incident-recording-budget-plan.md +++ b/docs/ml/incident-recording-budget-plan.md @@ -7,7 +7,10 @@ (`incident-benchmark/pilot-result.md`). The other 1,525 do not carry over. - **Stage 2 preparation** (0 requests): `incident-benchmark/stage2-shortlist.md`. Public discovery found no fully eligible new case. It proposes Stage 2a (2 public cases, cap - 5,840) and Stage 2b (user-sourced, cap 14,000), plus a protocol amendment. + 6,000 after the Step 0 revision) and Stage 2b (user-sourced, cap 14,000), plus a protocol + amendment. +- **Stage 2 Step 0 is complete** (0 requests): amendment `amendment-12.3-A1.md`, the + resolution tools, and `incident-benchmark/preregistration-stage2a.md`. - **No further request is authorized** by this document. Each stage below needs its own explicit approval of a request cap, and unused requests from one approval do not carry over to the next. diff --git a/src/cryptoguard/cli.py b/src/cryptoguard/cli.py index b15c534..42527bb 100644 --- a/src/cryptoguard/cli.py +++ b/src/cryptoguard/cli.py @@ -341,7 +341,7 @@ def _replay_command(args: argparse.Namespace, settings: Settings) -> int: print(f"{case.manifest.case_id} [{status}] {case.manifest.title}") return 0 - if args.replay_command == "locate": + if args.replay_command in ("locate", "find-transfers"): return _locate_command(args, settings) if args.replay_command == "record": @@ -487,7 +487,7 @@ def _locate_command(args: argparse.Namespace, settings: Settings) -> int: from cryptoguard.blockchain.budget import BudgetExhaustedError, budgeted_transport from cryptoguard.blockchain.provider import build_rpc_provider from cryptoguard.core.config import validate_rpc_url - from cryptoguard.replay.record import locate_transaction + from cryptoguard.replay.record import find_transfers, locate_transaction ledger = _replay_ledger(args) rpc_settings = settings.model_copy( @@ -498,14 +498,31 @@ def _locate_command(args: argparse.Namespace, settings: Settings) -> int: } ) - async def run() -> list[dict[str, Any]]: + async def run() -> Any: provider = build_rpc_provider(rpc_settings, transport=budgeted_transport(ledger)) before = ledger.used() try: + if args.replay_command == "find-transfers": + return await find_transfers( + provider, + sender=args.sender, + recipient=args.recipient, + recipient_prefixes=tuple(args.recipient_prefix), + token=args.token, + since=_utc_day(args.since), + until=_utc_day(args.until) + 86_399, + chunk_blocks=args.chunk_blocks, + locate_first=args.locate_first, + ) return [await locate_transaction(provider, h) for h in args.tx_hash] finally: await provider.aclose() - ledger.note(f"replay locate {len(args.tx_hash)} tx: {ledger.used() - before} reserved") + what = ( + f"find-transfers from {args.sender}" + if args.replay_command == "find-transfers" + else f"locate {len(args.tx_hash)} tx" + ) + ledger.note(f"replay {what}: {ledger.used() - before} reserved") try: found = asyncio.run(run()) @@ -521,6 +538,13 @@ async def run() -> list[dict[str, Any]]: return 0 +def _utc_day(day: str) -> int: + """Midnight UTC of a YYYY-MM-DD date, as a Unix timestamp.""" + from datetime import UTC, datetime + + return int(datetime.fromisoformat(day).replace(tzinfo=UTC).timestamp()) + + def _background_command(args: argparse.Namespace, settings: Settings) -> int: from datetime import UTC, datetime @@ -873,6 +897,27 @@ def main(argv: Sequence[str] | None = None) -> int: p_locate.add_argument("--chain-id", type=int, default=1) p_locate.add_argument("--out", metavar="PATH", help="write the JSON here") _add_rpc_budget(p_locate, per_run_help="most requests this run may reserve") + p_find = replay_sub.add_parser( + "find-transfers", + help="find a pre-registered case's harmful transfer from reported addresses and dates", + ) + p_find.add_argument("--sender", required=True, help="the reported victim (Transfer from)") + p_find.add_argument("--recipient", help="the reported recipient (Transfer to), if given") + p_find.add_argument( + "--recipient-prefix", + action="append", + default=[], + help="keep only recipients starting with this reported prefix (repeatable)", + ) + p_find.add_argument("--token", help="limit to one token contract") + p_find.add_argument("--since", required=True, help="first UTC day, YYYY-MM-DD") + p_find.add_argument("--until", required=True, help="last UTC day (inclusive), YYYY-MM-DD") + p_find.add_argument("--chunk-blocks", type=int, default=100) + p_find.add_argument("--locate-first", type=int, default=10) + p_find.add_argument("--rpc-url", required=True) + p_find.add_argument("--chain-id", type=int, default=1) + p_find.add_argument("--out", metavar="PATH", help="write the JSON here") + _add_rpc_budget(p_find, per_run_help="most requests this run may reserve") p_sample = replay_sub.add_parser( "sample-background", help="draw unlabelled background wallets (seeded) from an RPC" ) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 6612d9f..fa8a2a5 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -132,13 +132,23 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ib = ml.add_parser( "incident-benchmark", help="Phase 12.3 independent incident benchmark (offline)" ) - ib.add_argument("step", choices=("verify", "prepare", "run", "report")) + ib.add_argument("step", choices=("verify", "resolve", "prepare", "run", "report")) ib.add_argument("--case", help="prepare: the pre-registered case id") - ib.add_argument("--located", type=Path, help="prepare: `replay locate` JSON for the case") + ib.add_argument( + "--located", type=Path, help="prepare: `replay locate` or `find-transfers` JSON" + ) + ib.add_argument("--found", type=Path, help="resolve: `replay find-transfers` JSON") ib.add_argument("--title", help="prepare: the case title") ib.add_argument("--first-report", help="prepare: ISO date of the first public report") ib.add_argument( - "--manifest", type=Path, default=Path("docs/ml/incident-benchmark/candidates.json") + "--manifest", + type=Path, + nargs="+", + default=[ + Path("docs/ml/incident-benchmark/candidates.json"), + Path("docs/ml/incident-benchmark/stage2-resolved.json"), + ], + help="candidate manifests, merged (missing files are skipped)", ) ib.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.3") iv = ml.add_parser("inventory", help="hash and describe every local research data file") @@ -285,16 +295,48 @@ def run(args: argparse.Namespace) -> int: verified_path = args.out / "incident-verify.json" run_path = args.out / "incident-benchmark.json" if args.step == "verify": - rows = ib_.verify(ib_.load_manifest(args.manifest), ML_DIR / "poisoning") + rows = ib_.verify(ib_.load_manifests(args.manifest), ML_DIR / "poisoning") verified_path.write_text(json.dumps(rows, indent=1) + "\n", encoding="utf-8") for r in rows: print(f"{r['case_id']:40} {r['tier']:18} {r['status']}") + elif args.step == "resolve": + if not (args.case and args.found): + print("resolve needs --case and --found.") + return 1 + stage2 = ib_.load_manifest(ib_.STAGE2) + cand = next((c for c in stage2.candidates if c.case_id == args.case), None) + if cand is None: + print(f"{args.case} is not in {ib_.STAGE2}.") + return 1 + out = ( + ib_.load_manifest(ib_.RESOLVED) + if ib_.RESOLVED.exists() + else stage2.model_copy( + update={ + "protocol": f"{ib_.PROTOCOL} with {ib_.AMENDMENT}", + "discovery": {"resolved_from": str(ib_.STAGE2)}, + "candidates": [], + "not_usable_sources": [], + } + ) + ) + if any(c.case_id == args.case for c in out.candidates): + print(f"{args.case} is already resolved in {ib_.RESOLVED}; never overwritten.") + return 1 + try: + done = ib_.resolve(cand, json.loads(args.found.read_text(encoding="utf-8"))) + except ValueError as exc: + print(f"not resolved: {exc}") + return 1 + out = out.model_copy(update={"candidates": [*out.candidates, done]}) + ib_.RESOLVED.write_text(out.model_dump_json(indent=2) + "\n", encoding="utf-8") + print(f"Resolved {args.case}: harm {done.identifiers['harm_tx']} -> {ib_.RESOLVED}") elif args.step == "prepare": if not (args.case and args.located and args.title and args.first_report): print("prepare needs --case, --located, --title and --first-report.") return 1 cand = next( - (c for c in ib_.load_manifest(args.manifest).candidates if c.case_id == args.case), + (c for c in ib_.load_manifests(args.manifest).candidates if c.case_id == args.case), None, ) if cand is None: diff --git a/src/cryptoguard/ml/incident_benchmark.py b/src/cryptoguard/ml/incident_benchmark.py index 5de3317..6e52403 100644 --- a/src/cryptoguard/ml/incident_benchmark.py +++ b/src/cryptoguard/ml/incident_benchmark.py @@ -9,6 +9,9 @@ outcome address. Then come the production order (OP0), the frozen recency order (OP1), lead times, alert burden and controlled perturbations. - ``report``: the per-case table. +- ``resolve`` (Stage 2, amendment A1): a near-miss case's harmful transaction and lookalike, + found on chain by a rule frozen below before any request (``RESOLUTION_RULES``) from the + identifiers its source gave. The rule never scores similarity. Evidence levels are never pooled. Nothing here estimates precision, recall or a false-positive rate. @@ -31,6 +34,9 @@ MANIFEST = Path("docs/ml/incident-benchmark/candidates.json") # Newly recorded cases (Level I), kept apart from the packaged replay cases. NEW_CASES = Path("docs/ml/incident-benchmark/cases") +STAGE2 = Path("docs/ml/incident-benchmark/stage2-candidates.json") # as discovered +RESOLVED = Path("docs/ml/incident-benchmark/stage2-resolved.json") # written by ``resolve`` +AMENDMENT = "amendment-12.3-A1" WINDOW_BLOCKS = 21_600 # before and including the harmful block, as in the 4 replay cases ARCHIVE_BLOCKS = (15_053_226, 20_208_032) ARCHIVE_LAST_DATE = "2024-06-30" # the archive's last block (~20.2M) is late June 2024 @@ -84,6 +90,117 @@ def load_manifest(path: Path = MANIFEST) -> CandidateManifest: return m +def load_manifests(paths: Sequence[Path]) -> CandidateManifest: + """The candidates of every manifest that exists, merged; a case id may appear once.""" + found = [load_manifest(path) for path in paths if path.exists()] + if not found: + raise FileNotFoundError(f"none of {[str(p) for p in paths]} exists") + merged = found[0].model_copy(update={"candidates": [c for m in found for c in m.candidates]}) + ids = [c.case_id for c in merged.candidates] + if len(ids) != len(set(ids)): + raise ValueError("a case id appears in more than one manifest") + return merged + + +# --- resolve (Stage 2, amendment A1) -------------------------------------------------------- + +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +# Frozen before any Stage 2 request. ``sender``/``recipient`` name identifier keys of the +# case as discovered; dates are inclusive UTC days around the source's reported date. +RESOLUTION_RULES: dict[str, dict[str, Any]] = { + "scamsniffer-763k-2025-02-20": { + "sender": "etherscan_filter_fadd", # Etherscan's advanced filter: fadd is "from" + "recipient": "etherscan_filter_tadd", # and tadd is "to" + "prefixes": [], + "token": None, + "since": "2025-02-19", + "until": "2025-02-21", + }, + "webacy-6.88m-usdt-2025-09": { + "sender": "victim", + "recipient": None, + "prefixes": ["0x418e0ddb", "0x4186a058", "0x4186a666", "0x4186b115"], + "token": USDT, + "since": "2025-09-14", + "until": "2025-09-19", + }, +} + + +def _utc(day: str, end: bool = False) -> int: + from datetime import UTC, datetime + + return int(datetime.fromisoformat(day).replace(tzinfo=UTC).timestamp()) + (86_399 * end) + + +def resolution_query(cand: Candidate) -> dict[str, Any]: + """The exact ``replay find-transfers`` query the frozen rule allows for this case.""" + rule = RESOLUTION_RULES.get(cand.case_id) + if rule is None: + raise ValueError(f"{cand.case_id}: no pre-registered resolution rule") + ids = cand.identifiers + + def key(name: str | None) -> str | None: + if name is None: + return None + value = ids.get(name) + if not value or not _ADDR.match(value): + raise ValueError(f"{cand.case_id}: identifier {name} is not a full address") + return value + + return { + "sender": key(rule["sender"]), + "recipient": key(rule["recipient"]), + "recipient_prefixes": [x.lower() for x in rule["prefixes"]], + "token": rule["token"], + "since": _utc(rule["since"]), + "until": _utc(rule["until"], end=True), + } + + +def resolve(cand: Candidate, found: Mapping[str, Any]) -> Candidate: + """The harmful transaction by the frozen rule: the oldest nonzero Transfer the query + returned whose transaction succeeded and was signed by the sender. Refuses a query that + differs from the rule, an incomplete scan, or no such transfer (no second rule is tried).""" + want = resolution_query(cand) + if dict(found.get("query") or {}) != want: + raise ValueError(f"{cand.case_id}: the query differs from the pre-registered rule") + if not found.get("scan_complete"): + raise ValueError(f"{cand.case_id}: not evaluable: the resolution scan is incomplete") + sender = str(want["sender"]) + located = {str(x["transaction_hash"]).lower(): x for x in found.get("located") or []} + for m in found.get("transfers") or []: + rec = located.get(str(m["transaction_hash"]).lower()) + if rec is None: + break # beyond the located prefix: the rule stops rather than guess + to = str(m["to"]).lower() + paid = rec.get("found") and any( + str(tr["from"]).lower() == sender and str(tr["to"]).lower() == to + for tr in rec.get("transfers") or [] + ) + if paid and rec.get("succeeded") and str(rec.get("from") or "").lower() == sender: + rule = RESOLUTION_RULES[cand.case_id] + return cand.model_copy( + update={ + "identifiers": { + "victim": sender, + "lookalike": to, + "intended": cand.identifiers.get("intended"), + "planting_tx": None, + "harm_tx": str(m["transaction_hash"]).lower(), + }, + "identifier_status": f"resolved on chain ({AMENDMENT}): oldest nonzero " + f"Transfer signed by {rule['sender']} " + + (f"to {rule['recipient']}" if rule["recipient"] else "to a reported prefix") + + f", {rule['since']}..{rule['until']} UTC", + } + ) + raise ValueError( + f"{cand.case_id}: identifiers not confirmed on chain (no nonzero Transfer from the " + "sender, signed by it, among the located matches)" + ) + + # --- verify ------------------------------------------------------------------------------- @@ -220,7 +337,14 @@ def verify( refs = reference_sets(poisoning_dir) out: list[dict[str, Any]] = [] for cand in manifest.candidates: - row: dict[str, Any] = {"case_id": cand.case_id, "source": cand.source.url} + row: dict[str, Any] = { + "case_id": cand.case_id, + "source": cand.source.url, + # amendment A1: identifiers found by a frozen on-chain rule, not given verbatim + "identifier_source": "resolved" + if cand.identifier_status.startswith("resolved") + else "verbatim", + } if cand.synthetic: out.append( row @@ -339,7 +463,11 @@ def verify( def prepare( - cand: Candidate, located: Sequence[Mapping[str, Any]], *, title: str, first_report: str + cand: Candidate, + located: Sequence[Mapping[str, Any]] | Mapping[str, Any], + *, + title: str, + first_report: str, ) -> Any: """The replay manifest of a pre-registered case, from ``replay locate`` output for its harmful (and planting) transaction. The window is fixed by rule, never by inspection. @@ -357,6 +485,9 @@ def prepare( ids = cand.identifiers if cand.synthetic or cand.chain_id != 1 or not _complete(ids): raise ValueError(f"{cand.case_id}: not a mainnet case with complete identifiers") + if isinstance(located, Mapping): # ``replay find-transfers`` output carries its receipts + located = list(located.get("located") or []) + resolved = cand.identifier_status.startswith("resolved") by_tx = {str(x["transaction_hash"]).lower(): x for x in located} harm = by_tx.get(str(ids["harm_tx"]).lower()) if harm is None or not harm.get("found"): @@ -389,7 +520,7 @@ def prepare( category="address_poisoning", chain_id=1, summary=f"Pre-registered Phase 12.3 benchmark case ({cand.mechanism}); see " - "docs/ml/incident-benchmark/candidates.json.", + f"docs/ml/incident-benchmark/{RESOLVED.name if resolved else 'candidates.json'}.", first_public_report=date.fromisoformat(first_report), public_sources=[ SourceRef( @@ -397,8 +528,13 @@ def prepare( title=title, url=cand.source.url, accessed=date.fromisoformat(first_report), - used_for="victim, lookalike, intended recipient, planting and harmful " - "transaction hashes", + used_for=( + f"the reported addresses and dates; the harmful transaction was resolved " + f"on chain by the rule frozen in {AMENDMENT}" + if resolved + else "victim, lookalike, intended recipient, planting and harmful " + "transaction hashes" + ), ) ], victim=to_checksum_address(victim), @@ -473,11 +609,16 @@ def ranking(warnings: Sequence[Any], target: str, cutoff: int) -> dict[str, Any] s0: dict[str, float] = {w.suspect.lower(): _pack(baseline_score(w)) for w in warnings} s1: dict[str, float] = {w.suspect.lower(): _pack(recency_score(w, cutoff)) for w in warnings} shown = rank_warnings(list(warnings), cutoff) + r0, r1 = expected_rank(s0, target), expected_rank(s1, target) return { "k": k, "target_warned": True, - "OP0_expected_rank": expected_rank(s0, target), - "OP1_expected_rank": expected_rank(s1, target), + "OP0_expected_rank": r0, + "OP1_expected_rank": r1, + # amendment A1: comparable across k; 0 is first, 1 is last; None when k == 1 + "OP0_normalized_rank": round((r0 - 1) / (k - 1), 4) if k > 1 else None, + "OP1_normalized_rank": round((r1 - 1) / (k - 1), 4) if k > 1 else None, + "paired_difference_OP0_minus_OP1": r0 - r1, "random_expected_rank": (k + 1) / 2, "OP0_top1": round(lr.top1(s0, target, k), 4), "OP1_top1": round(lr.top1(s1, target, k), 4), @@ -552,6 +693,13 @@ def run_case(case: Any, level: str = "III") -> dict[str, Any]: }, "leakage_checks_passed": all(ch.passed for ch in rep.leakage_checks), } + # amendment A1 (scoring side only; the detector never sees these): + seen = [tr for tr in fx.transfers if tr.block_number <= c and target in _parties(tr)] + out["cluster_signers"] = sorted( + {tr.tx_sender.lower() for tr in seen if tr.tx_sender} - {m.victim.lower()} + ) + first = min((tr.block_number for tr in seen), default=None) + out["lead_possibly_censored"] = None if first is None else first - fx.from_block < DAY variants: dict[str, Any] = {} for name, (f, cut, vis) in _variants(fx, c).items(): if cut < fx.from_block: @@ -584,6 +732,78 @@ def run_case(case: Any, level: str = "III") -> dict[str, Any]: return out +def _parties(tr: Any) -> set[str]: + return {tr.sender.lower(), tr.recipient.lower()} + + +def sign_test_p(better: int, worse: int) -> float: + """Exact one-sided sign test: P(at least ``better`` of ``better + worse`` | p = 1/2).""" + from math import comb + + n = better + worse + return sum(comb(n, i) for i in range(better, n + 1)) / (1 << n) + + +def amended_gate_h(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + """Gate H under amendment A1: cases linked by a shared planting signer (pre-cutoff, + from the fixture) form one cluster with one vote; below 6 untied clusters the result is + DESCRIPTIVE; PASS needs at least 10 rankable clusters, more better than worse, and an + exact one-sided sign test p < 0.05. A case without a known signer is its own cluster + and is counted as linkage unknown.""" + rankable = [ + r + for r in results + if r["ranking"]["primary"].get("target_warned") and r["ranking"]["primary"]["k"] >= 2 + ] + parent = list(range(len(rankable))) + + def root(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + owner: dict[str, int] = {} + for i, r in enumerate(rankable): + for s in r.get("cluster_signers") or []: + if s in owner: + parent[root(i)] = root(owner[s]) + else: + owner[s] = i + clusters: dict[int, list[float]] = {} + for i, r in enumerate(rankable): + clusters.setdefault(root(i), []).append( + r["ranking"]["primary"]["OP0_expected_rank"] + - r["ranking"]["primary"]["OP1_expected_rank"] + ) + votes = {"better": 0, "equal": 0, "worse": 0} + for diffs in clusters.values(): + b, w = sum(d > 0 for d in diffs), sum(d < 0 for d in diffs) + votes["better" if b > w else "worse" if w > b else "equal"] += 1 + untied = votes["better"] + votes["worse"] + p = sign_test_p(votes["better"], votes["worse"]) if untied >= 6 else None + if not rankable: + status = "NOT EVALUATED" + elif untied < 6: + status = "DESCRIPTIVE" + elif votes["worse"] > votes["better"]: + status = "FAIL" + elif len(clusters) >= 10 and votes["better"] > votes["worse"] and p is not None and p < 0.05: + status = "PASS" + else: + status = "NOT PASSED" + return { + "rule": AMENDMENT, + "rankable_cases": len(rankable), + "clusters": len(clusters), + "linkage_unknown_cases": sum(not r.get("cluster_signers") for r in rankable), + "cluster_votes": votes, + "sign_test_p_one_sided": p, + "status": status, + "lead_possibly_censored_cases": sum(bool(r.get("lead_possibly_censored")) for r in results), + } + + def _summary(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: rankable = [ r @@ -609,6 +829,7 @@ def _summary(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: "OP1_vs_OP0": paired, "OP0_top1_cases": sum(r["ranking"]["primary"]["OP0_top1"] == 1.0 for r in rankable), "OP1_top1_cases": sum(r["ranking"]["primary"]["OP1_top1"] == 1.0 for r in rankable), + "gate_H_amended": amended_gate_h(results), } @@ -629,9 +850,13 @@ def run( admitted = {v["case_id"] for v in verified if v["tier"] == "A"} by_fixture = {v["case_id"]: v for v in verified} skipped: list[dict[str, str]] = [] + not_recorded: list[str] = [] # amendment A1: pre-registered, no complete window + new_ids = {x.manifest.case_id for x in load_new_cases()} tier_a = [] for c in cases: if c.fixture is None or not c.fixture.transfer_scan_complete: + if c.manifest.case_id in new_ids: + not_recorded.append(c.manifest.case_id) continue cid = c.manifest.case_id if cid not in admitted: @@ -642,7 +867,9 @@ def run( else: tier_a.append(c) results = [ - run_case(c, str(by_fixture[c.manifest.case_id].get("level") or "III")) for c in tier_a + run_case(c, str(by_fixture[c.manifest.case_id].get("level") or "III")) + | {"identifier_source": by_fixture[c.manifest.case_id].get("identifier_source")} + for c in tier_a ] peak = peak_rss_bytes() return { @@ -652,7 +879,11 @@ def run( "evidence_level": "levels are reported separately and never pooled", "cases": results, "not_computed": skipped, + "new_cases_not_recorded": not_recorded, "summary_level_I": _summary([r for r in results if r["level"] == "I"]), + "summary_level_I_verbatim_only": _summary( + [r for r in results if r["level"] == "I" and r["identifier_source"] == "verbatim"] + ), "summary_level_III": _summary([r for r in results if r["level"] == "III"]), "background_alert_burden": background(blind), "resources": { @@ -697,4 +928,14 @@ def cell(x: Any) -> str: f"{cell(p.get('OP0_expected_rank'))} | {cell(p.get('OP1_expected_rank'))} | " f"{cell(p.get('random_expected_rank'))} |" ) + lines.append("") + for level in ("I", "III"): + g = result.get(f"summary_level_{level}", {}).get("gate_H_amended") + if g: + lines.append( + f"Gate H, Level {level} ({g['rule']}): {g['status']}; {g['rankable_cases']} " + f"rankable cases in {g['clusters']} clusters; cluster votes {g['cluster_votes']}" + ) + if result.get("new_cases_not_recorded"): + lines.append(f"Pre-registered, not recorded: {', '.join(result['new_cases_not_recorded'])}") return "\n".join(lines) + "\n" diff --git a/src/cryptoguard/replay/record.py b/src/cryptoguard/replay/record.py index 427bfa3..811e499 100644 --- a/src/cryptoguard/replay/record.py +++ b/src/cryptoguard/replay/record.py @@ -180,3 +180,93 @@ def word_address(topic: str) -> str: "succeeded": receipt.get("status") == "0x1", "transfers": transfers, } + + +async def block_at_time(provider: RpcEthereumProvider, ts: int, *, after: bool) -> int: + """By bisection on header timestamps: the first block with timestamp >= ``ts`` (``after``) + or the last block with timestamp <= ``ts``. About log2(head) block reads.""" + lo, hi = 0, await provider.block_number() + while lo < hi: + mid = (lo + hi + (0 if after else 1)) // 2 + stamp = (await provider.get_block(mid)).timestamp + if after: + lo, hi = (mid + 1, hi) if stamp < ts else (lo, mid) + else: + lo, hi = (mid, hi) if stamp <= ts else (lo, mid - 1) + return lo + + +async def find_transfers( + provider: RpcEthereumProvider, + *, + sender: str, + since: int, + until: int, + recipient: str | None = None, + recipient_prefixes: tuple[str, ...] = (), + token: str | None = None, + chunk_blocks: int = 100, + max_log_requests: int = 500, + locate_first: int = 10, +) -> dict[str, Any]: + """ERC-20 Transfer logs from ``sender`` (to ``recipient``, if given) between two UTC + timestamps, filtered to nonzero values and to the given recipient prefixes, oldest first; + the first ``locate_first`` matches are read with ``locate_transaction``. Resolves a + pre-registered Stage 2 case's harmful transaction from the identifiers a source gave; it + never scores similarity, and the detector never sees its output.""" + from cryptoguard.blockchain.abi import address_topic + from cryptoguard.blockchain.logscan import scan_logs + + await provider.verify_chain() + start = await block_at_time(provider, since, after=True) + end = await block_at_time(provider, until, after=False) + topics: list[str | list[str] | None] = [TRANSFER_TOPIC, address_topic(sender)] + if recipient is not None: + topics.append(address_topic(recipient)) + scan = await scan_logs( + provider, + topics=topics, + from_block=start, + to_block=end, + chunk_blocks=chunk_blocks, + max_requests=max_log_requests, + address=[token] if token else None, + ) + prefixes = tuple(p.lower() for p in recipient_prefixes) + matches: list[dict[str, Any]] = [] + for log in scan.logs: + if len(log.get("topics") or []) != 3: + continue + to = "0x" + log["topics"][2][-40:].lower() + value = int(log.get("data") or "0x0", 16) + if value == 0 or (prefixes and not to.startswith(prefixes)): + continue + matches.append( + { + "transaction_hash": str(log["transactionHash"]).lower(), + "block_number": int(log["blockNumber"], 16), + "log_index": int(log["logIndex"], 16), + "token": to_checksum_address(log["address"]), + "from": to_checksum_address(sender), + "to": to_checksum_address(to), + "value_base_units": str(value), + } + ) + matches.sort(key=lambda m: (m["block_number"], m["log_index"])) + hashes = list(dict.fromkeys(m["transaction_hash"] for m in matches))[:locate_first] + return { + "query": { + "sender": sender.lower(), + "recipient": recipient.lower() if recipient else None, + "recipient_prefixes": list(prefixes), + "token": token.lower() if token else None, + "since": since, + "until": until, + }, + "from_block": start, + "to_block": end, + "scan_complete": scan.complete, + "log_requests": scan.requests, + "transfers": matches, + "located": [await locate_transaction(provider, h) for h in hashes], + } diff --git a/tests/integration/test_replay_budget.py b/tests/integration/test_replay_budget.py index c4a2109..a90dd93 100644 --- a/tests/integration/test_replay_budget.py +++ b/tests/integration/test_replay_budget.py @@ -133,6 +133,18 @@ async def test_locate_reads_block_parties_and_transfers(tmp_path: Path) -> None: [ ["replay", "record", "usdt-50m-poisoning-2025-12-19", "--rpc-url", "https://x.invalid"], ["replay", "locate", "0x" + "ab" * 32, "--rpc-url", "https://x.invalid"], + [ + "replay", + "find-transfers", + "--sender", + "0x" + "ab" * 20, + "--since", + "2025-01-01", + "--until", + "2025-01-02", + "--rpc-url", + "https://x.invalid", + ], ["replay", "record-background", "--rpc-url", "https://x.invalid"], [ "replay", @@ -241,3 +253,99 @@ def test_stage_1_dry_run_prepare_record_verify( [row] = ib.verify(manifest_, Path("unused"), cases=[], new_cases=[case]) assert (row["level"], row["tier"], row["verified"]) == ("I", "A", True) assert row["onchain"]["planting"] == "confirmed in the window" + + +async def test_block_at_time_bisects_header_timestamps(tmp_path: Path) -> None: + from cryptoguard.replay.record import block_at_time + + node = FakeNode() + node.head = 5_000 # FakeNode: timestamp = 1_700_000_000 + 12 * block + provider, counting = _provider(node, RequestLedger(tmp_path / "l.json", cap=100)) + try: + ts = 1_700_000_000 + 12 * 1_234 + assert await block_at_time(provider, ts, after=True) == 1_234 + assert await block_at_time(provider, ts + 5, after=True) == 1_235 + assert await block_at_time(provider, ts + 5, after=False) == 1_234 + finally: + await provider.aclose() + assert counting.attempts <= 3 * (13 + 2) # about log2(head) reads per call + + +def test_stage_2a_dry_run_find_resolve_prepare_record_verify( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A near-miss case on a mock node: the frozen rule finds the harmful transfer from the + two reported addresses, skips a counterfeit transfer the attacker signed "from" the + victim, and the case then records and verifies as Level I like any other.""" + import json + + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.replay.models import load_cases + + node = FakeNode() + node.add_token(TOKEN) + node.head = 31_000 + node.send_native(WALLET, REAL, 10**16, block=25_000) + node.add_transfer_log(TOKEN, WALLET, FAKE, 0, block=28_900, signer=ATTACKER_SIGNER) + fake_from_victim = node.add_transfer_log( + TOKEN, WALLET, FAKE, 115, block=29_000, signer=ATTACKER_SIGNER + ) + theft = node.add_transfer_log(TOKEN, WALLET, FAKE, 1000, block=30_000, signer=WALLET) + monkeypatch.setattr(budget_mod.httpx, "AsyncHTTPTransport", node.transport) + rule = { + "sender": "etherscan_filter_fadd", + "recipient": "etherscan_filter_tadd", + "prefixes": [], + "token": None, + "since": "2023-11-18", # blocks 22,134.. (FakeNode clock) + "until": "2023-11-19", + } + monkeypatch.setitem(ib.RESOLUTION_RULES, "dry-2a", rule) + cand = ib.Candidate.model_validate( + { + "case_id": "dry-2a", + "source": {"publisher": "p", "url": "https://example.org", "date": "2023-11-19"}, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": { + "etherscan_filter_fadd": WALLET.lower(), + "etherscan_filter_tadd": FAKE.lower(), + }, + "identifier_status": "partial: roles not stated", + "fixture_case_id": None, + "synthetic": False, + } + ) + ledger = tmp_path / "ledger.json" + url = ["--rpc-url", "https://rpc.example.invalid", "--ledger", str(ledger), "--cap", "3000"] + out = tmp_path / "found.json" + find = ["replay", "find-transfers", "--sender", WALLET, "--recipient", FAKE] + dates = ["--since", rule["since"], "--until", rule["until"], "--out", str(out)] + assert cli.main([*find, *dates, *url, "--max-requests", "300"]) == 0 + found = json.loads(out.read_text(encoding="utf-8")) + assert found["scan_complete"] + assert [t["transaction_hash"] for t in found["transfers"]] == [ + str(fake_from_victim["transactionHash"]), # nonzero, but signed by the attacker + str(theft["transactionHash"]), + ] + done = ib.resolve(cand, found) + assert done.identifiers["harm_tx"] == str(theft["transactionHash"]) + assert (done.identifiers["victim"], done.identifiers["lookalike"]) == ( + WALLET.lower(), + FAKE.lower(), + ) + m = ib.prepare(done, found, title="t", first_report="2026-11-03") + assert m.harm.block_number == 30_000 + cases_dir = tmp_path / "cases" + (cases_dir / "dry-2a").mkdir(parents=True) + (cases_dir / "dry-2a" / "manifest.json").write_text(m.model_dump_json(indent=2)) + assert cli.main(["replay", "record", "dry-2a", "--cases-dir", str(cases_dir), *url]) == 0 + [case] = load_cases(cases_dir) + monkeypatch.setattr(ib, "reference_sets", lambda _d: {}) + manifest_ = ib.CandidateManifest( + schema_version="incident-candidates/1", protocol="p", discovery={}, candidates=[done] + ) + [row] = ib.verify(manifest_, Path("unused"), cases=[], new_cases=[case]) + assert (row["level"], row["tier"], row["verified"]) == ("I", "A", True) + assert row["onchain"]["planting"] == "not reported" + assert RequestLedger(ledger, cap=3000).used() <= 3000 diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py index 34e44fd..9db8c1b 100644 --- a/tests/test_ml_incident_benchmark.py +++ b/tests/test_ml_incident_benchmark.py @@ -373,3 +373,109 @@ def test_stage_1_pilot_case_is_frozen_and_reproduces_exactly() -> None: 4.0, 2.0, ) + + +def _stage2(**over: Any) -> ib.Candidate: + return ib.Candidate.model_validate( + cand( + case_id="webacy-6.88m-usdt-2025-09", + identifiers={"victim": "0x" + "e" * 40, "lookalike": None}, + identifier_status="partial", + ) + | over + ) + + +def _found(c: ib.Candidate, **over: Any) -> dict[str, Any]: + v, look = "0x" + "e" * 40, "0x4186a058" + "0" * 32 + harm = "0x" + "1" * 64 + base: dict[str, Any] = { + "query": ib.resolution_query(c), + "scan_complete": True, + "transfers": [{"transaction_hash": harm, "to": look}], + "located": [ + { + "transaction_hash": harm, + "found": True, + "succeeded": True, + "from": v, + "transfers": [{"from": v, "to": look, "token": ib.USDT, "value_base_units": "5"}], + } + ], + } + return base | over + + +def test_resolve_follows_only_the_frozen_rule() -> None: + c = _stage2() + done = ib.resolve(c, _found(c)) + assert done.identifiers["harm_tx"] == "0x" + "1" * 64 + assert done.identifiers["lookalike"] == "0x4186a058" + "0" * 32 + assert done.identifier_status.startswith("resolved on chain (amendment-12.3-A1)") + other_dates = _found(c) | {"query": ib.resolution_query(c) | {"until": 0}} + with pytest.raises(ValueError, match="differs from the pre-registered rule"): + ib.resolve(c, other_dates) + with pytest.raises(ValueError, match="scan is incomplete"): + ib.resolve(c, _found(c, scan_complete=False)) + signed_by_attacker = _found(c) + signed_by_attacker["located"][0]["from"] = "0x" + "a" * 40 + with pytest.raises(ValueError, match="identifiers not confirmed on chain"): + ib.resolve(c, signed_by_attacker) + with pytest.raises(ValueError, match="no pre-registered resolution rule"): + ib.resolution_query(_stage2(case_id="unknown-case")) + + +def _ranked(better: bool | None, signers: list[str]) -> dict[str, Any]: + r1 = {True: 1.0, False: 3.0, None: 2.0}[better] + return { + "ranking": { + "primary": { + "target_warned": True, + "k": 3, + "OP0_expected_rank": 2.0, + "OP1_expected_rank": r1, + } + }, + "cluster_signers": signers, + "lead_possibly_censored": False, + } + + +def test_amended_gate_h_is_descriptive_below_six_clusters_and_votes_by_cluster() -> None: + assert ib.amended_gate_h([_ranked(True, ["0xs"])])["status"] == "DESCRIPTIVE" + # ten cases, all better, but sharing one signer: one cluster, one vote + same = ib.amended_gate_h([_ranked(True, ["0xs"]) for _ in range(10)]) + assert (same["clusters"], same["cluster_votes"]["better"], same["status"]) == ( + 1, + 1, + "DESCRIPTIVE", + ) + distinct = ib.amended_gate_h([_ranked(True, [f"0x{i}"]) for i in range(10)]) + assert distinct["status"] == "PASS" + assert distinct["sign_test_p_one_sided"] == pytest.approx(1 / 1024) + unknown = ib.amended_gate_h([_ranked(True, []) for _ in range(10)]) + assert (unknown["clusters"], unknown["linkage_unknown_cases"]) == (10, 10) + mixed = [_ranked(True, [f"0x{i}"]) for i in range(7)] + [ + _ranked(False, [f"0xw{i}"]) for i in range(3) + ] + assert ib.amended_gate_h(mixed)["status"] == "NOT PASSED" # p = 0.172 + assert ib.sign_test_p(9, 1) == pytest.approx(11 / 1024) + + +def test_manifests_merge_and_reject_duplicate_case_ids(tmp_path: Path) -> None: + def write(name: str, ids: list[str]) -> Path: + p = tmp_path / name + body = { + "schema_version": "incident-candidates/1", + "protocol": "p", + "discovery": {}, + "candidates": [cand(case_id=i) for i in ids], + } + p.write_text(json.dumps(body), encoding="utf-8") + return p + + a, b = write("a.json", ["x"]), write("b.json", ["y"]) + merged = ib.load_manifests([a, b, tmp_path / "missing.json"]) + assert [c.case_id for c in merged.candidates] == ["x", "y"] + with pytest.raises(ValueError, match="more than one manifest"): + ib.load_manifests([a, write("c.json", ["x"])]) From 72cfaf336e545a035b86e4cd22eeb2be53449909 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 3 Nov 2026 21:40:13 +0300 Subject: [PATCH 58/92] docs(ml): Stage 2a result - one resolved Level I case (a miss), one not evaluable (1,433 RPC) Run exactly as pre-registered under amendment 12.3-A1 (approved cap 6,000): - scamsniffer-763k-2025-02-20: harmful transfer resolved by the frozen rule (find 275 + record 645 requests); Level I, tier A, no overlap. The detector did not warn on the theft recipient before the harm (post_incident_only): its first record in the window is the theft; two other lookalikes of the same reference address were warned. Frozen by a hash-and-result regression test. - webacy-6.88m-usdt-2025-09: eth_getLogs rejected twice (72 + 441 requests); not evaluable: RPC per the stop rule. - Level I: warned 1 of 2; Gate H DESCRIPTIVE under A1. No rates. - resolve now records a POSIX source path. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + ML_INDEPENDENT_INCIDENT_BENCHMARK.md | 30 +- .../scamsniffer-763k-2025-02-20/fixture.json | 263 ++++++++++++++++++ .../scamsniffer-763k-2025-02-20/manifest.json | 39 +++ .../preregistration-stage2a.md | 2 +- .../incident-benchmark/stage2-resolved.json | 30 ++ docs/ml/incident-benchmark/stage2a-result.md | 125 +++++++++ docs/ml/incident-recording-budget-plan.md | 2 + src/cryptoguard/ml/cli.py | 2 +- tests/test_ml_incident_benchmark.py | 24 ++ 10 files changed, 518 insertions(+), 6 deletions(-) create mode 100644 docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/fixture.json create mode 100644 docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/manifest.json create mode 100644 docs/ml/incident-benchmark/stage2-resolved.json create mode 100644 docs/ml/incident-benchmark/stage2a-result.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 8aec2dc..6baeaf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,13 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Incident recording, Stage 2a (1,433 RPC requests of an approved 6,000) +- **Case 1, `scamsniffer-763k-2025-02-20`:** + - resolved on chain by the frozen rule, recorded, and frozen by test; + - Level I, but the detector **missed** it. The theft recipient never appears in the recorded stream before the harm, while two other lookalikes were warned. +- **Case 2, `webacy-6.88m-usdt-2025-09`:** *not evaluable: RPC* (rejected twice; stop rule). +- **Level I:** warned 1 of 2; Gate H DESCRIPTIVE. Report: `docs/ml/incident-benchmark/stage2a-result.md`. + ### Incident recording, Stage 2 Step 0 (no RPC requests) - **Amendment 12.3-A1** (`docs/ml/amendment-12.3-A1.md`), frozen before any Stage 2 request: - **R1, identifier resolution:** a frozen on-chain rule, with no similarity scoring. diff --git a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md index 4d41bda..2b52bb5 100644 --- a/ML_INDEPENDENT_INCIDENT_BENCHMARK.md +++ b/ML_INDEPENDENT_INCIDENT_BENCHMARK.md @@ -343,6 +343,28 @@ The Aug 2026 counterfeit-USDT case was recorded exactly as pre-registered. That fewer than 6 untied cases as DESCRIPTIVE, never PASS. - **Not claimed:** a rate or independent ML validation. +## 29. Addendum: Stage 2a (2026-11-03) + +Run under amendment 12.3-A1 and `docs/ml/incident-benchmark/preregistration-stage2a.md`. It +used 1,433 of an approved 6,000 RPC requests. Details: +[`docs/ml/incident-benchmark/stage2a-result.md`](docs/ml/incident-benchmark/stage2a-result.md). + +- **`scamsniffer-763k-2025-02-20`:** resolved on chain by the frozen rule, recorded, Level I, + tier A. + - The detector **did not** warn on the theft recipient before the harm + (`post_incident_only`). + - The recipient's first appearance in the recorded stream is the theft itself. + - Two other lookalikes of the same reference address were warned. + - This is a coverage miss (the planting channel was not observed), not a ranking result. +- **`webacy-6.88m-usdt-2025-09`:** *not evaluable: RPC*. The provider rejected the request + twice, and the stop rule applied. +- **Level I:** + - 2 tier A cases; + - warned before the harm in 1 of 2 (Gate G, exact count); + - 1 rankable; + - Gate H under A1 is **DESCRIPTIVE**; under §10 it stays PASS WITH LIMITATIONS. +- **Not claimed:** a rate or independent ML validation. + ## Benchmark result table | Case | Level | Subtype | Outcome status | Mode | Candidate | Warning | Pre-harm | OP0 rank | OP1 rank | Lead | History | Main limitation | @@ -363,10 +385,10 @@ The Aug 2026 counterfeit-USDT case was recorded exactly as pre-registered. That | B. Independent provenance | BLOCKED BY DATA | the new case is independent on all readable sets, but unverifiable on chain offline | | C. Transaction verification | PASS FOR 1 CASE | §28: the Stage 1 pilot confirmed harm and planting on chain; the others lack identifiers | | D. Point-in-time validity | PASS | implemented and tested (trim, cutoff guard, leakage checks) | -| E. Candidate availability | 1 of 1 (exact count) | §28: theft recipient recovered in 1 of 1 Level I case; no rate from one case | +| E. Candidate availability | 1 of 2 (exact count) | §28, §29: theft recipient recovered in 1 of 2 Level I cases; the miss was never observed before the harm; no rate | | F. Operational replay | PASS FOR 1 CASE | §28: one admissible recorded stream; leakage checks pass | -| G. Warning coverage | 1 of 1 (exact count, per §10) | §28: warned 48 blocks (576 s, measured) before the theft in 1 of 1 Level I case | -| H. Ranking usefulness | PASS WITH LIMITATIONS (Level I, n = 1) | §28: OP1 better in 1, worse in 0; the §10 rule allows this label below 10 cases; descriptive only. H3 withdrawn. | -| I. Statistical support | FAIL | 1 independent case (§28), against the 10 required | +| G. Warning coverage | 1 of 2 (exact count, per §10) | §28: warned 48 blocks (576 s, measured) before the pilot theft; §29: no pre-harm warning on the Stage 2a case | +| H. Ranking usefulness | DESCRIPTIVE under A1 (§10: PASS WITH LIMITATIONS) | 1 rankable Level I case, 1 cluster, OP1 better; descriptive only. H3 withdrawn. | +| I. Statistical support | FAIL | 2 independent tier A cases, 1 rankable (§28, §29), against the 10 required | | J. Production safety | PASS | no detector, service or risk change; ranker isolated | | K. Reproducibility | PASS WITH LIMITATIONS | offline commands; the inputs cannot be redistributed | diff --git a/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/fixture.json b/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/fixture.json new file mode 100644 index 0000000..6bedd66 --- /dev/null +++ b/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/fixture.json @@ -0,0 +1,263 @@ +{ + "block_timestamps": { + "21869297": 1739833907, + "21871900": 1739865299, + "21871908": 1739865395, + "21873695": 1739886995, + "21873870": 1739889095, + "21873872": 1739889119, + "21882651": 1739995079, + "21882656": 1739995139, + "21886653": 1740043415, + "21888842": 1740069971, + "21888868": 1740070283, + "21890495": 1740089963, + "21890508": 1740090119, + "21890558": 1740090743, + "21890867": 1740094475, + "21890871": 1740094523, + "21890874": 1740094559, + "21890897": 1740094835 + }, + "case_id": "scamsniffer-763k-2025-02-20", + "chain_id": 1, + "from_block": 21869297, + "method": [ + "ERC-20 Transfer logs to and from the wallet, all tokens, the whole window (eth_getLogs).", + "Signer (tx.from) of every outgoing transfer's transaction (eth_getTransactionByHash).", + "Every wallet-signed transaction in the window, located by nonce bisection (eth_getTransactionCount) and read from its block (eth_getBlockByNumber).", + "Wallet code at the window start and one block before the harmful block (eth_getCode).", + "Timestamps of all referenced blocks (eth_getBlockByNumber)." + ], + "recorded_at": "2026-11-03T18:18:43.641466Z", + "recorded_with": "https://eth.drpc.org", + "rpc_requests": 645, + "sender_lookups_skipped": 0, + "to_block": 21890897, + "transfer_scan_complete": true, + "transfers": [ + { + "block_hash": "0x73097c6c1eb2729116639401fe5dbbdc9d94dc825491bc9225e1ae232b48474e", + "block_number": 21871900, + "log_index": 150, + "recipient": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "sender": "0xaCB55C530Acdb2849e6d4f36992Cd8c9D50ED8F7", + "token": "0xec53bF9167f50cDEB3Ae105f56099aaaB9061F83", + "transaction_hash": "0xb6334cb05425f722fd86af6b4a8a8a2a93d221a55d88b9f0cc5ac4a0758311e3", + "transaction_index": 45, + "tx_sender": null, + "value": "12641373444958369372782" + }, + { + "block_hash": "0x1ad6944a5f13cf90634e4ec18c9decf4c14e0763886ef3c7203f675045958a25", + "block_number": 21873695, + "log_index": 206, + "recipient": "0xe2353eedCDd2d858dd8d0a373D931974f087aFe1", + "sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "token": "0xec53bF9167f50cDEB3Ae105f56099aaaB9061F83", + "transaction_hash": "0xbdded0c63d8efb418a12a162ebbc822d18b8755e03eb329ce27cf3558b4a8cda", + "transaction_index": 115, + "tx_sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "value": "12641991160446296541406" + }, + { + "block_hash": "0x6146b793241138a901677a59e8899e220ff53004d6302420f08020bb8f61c5f4", + "block_number": 21873872, + "log_index": 167, + "recipient": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "sender": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0xe7434848a49395cd40fc21b4f2eeb2cfcec0e234e9d6a5c244e40181f5f43a0a", + "transaction_index": 32, + "tx_sender": null, + "value": "22018798660418080827354" + }, + { + "block_hash": "0x7e17dc7e2a92fdded253ce66c07dccb00ee788fad0062f5e933ffa382b8319a1", + "block_number": 21882656, + "log_index": 388, + "recipient": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "sender": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x9655fdbfeaeef63b55af9dcd0f6756fc1c8084cf7304dcc056c3bc19b007e70a", + "transaction_index": 154, + "tx_sender": null, + "value": "27821411220647477840" + }, + { + "block_hash": "0x4da62ee9d37a5d9ccd289211cbadaf3b8d3528eba29de37747e226f5ca999e34", + "block_number": 21890495, + "log_index": 135, + "recipient": "0x80404F3eb7fEd80349954e8285eC8A9365793375", + "sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x175e6421407c56dec5b407db8b66d86712294693fd2ea32a121b4d381f8b0507", + "transaction_index": 65, + "tx_sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "value": "103442634767106904305019" + }, + { + "block_hash": "0x1b76b0fa6acb3f76fcb38bbdd17dc3bcd6dd76d207564e9f459d3a5ac50023b1", + "block_number": 21890558, + "log_index": 264, + "recipient": "0x8045233Dedd5caaD640AE85B1Dc540E5C7793375", + "sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "token": "0x29F7bbBc757aBB299Dd18e70f0D0F08CC7d570E6", + "transaction_hash": "0x8e5b00548aa78467e381e4993dbdc93207ce4fc89d2045fe044698f0c47f9c2c", + "transaction_index": 112, + "tx_sender": "0x7730b1C005d8b3c42784b98264B45Fd71E47Ba3f", + "value": "600000000000000000000" + }, + { + "block_hash": "0x35ef4df4d95b42cc35532eb12b19b897dbe188ffa7b5553be4ada7e2eed1ff67", + "block_number": 21890871, + "log_index": 441, + "recipient": "0x804041C8a67e3A909908C988fBEfE0dc1C1f3375", + "sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "token": "0x669507921B89C11536Fe28FB2b955fbC23Dbe86D", + "transaction_hash": "0x44232fbc007f806cddce5803d36994cc6003a1347f59e1bb595d6fe00613aa7f", + "transaction_index": 72, + "tx_sender": "0x0C0b9e3A2daefC4731826C5D877eBc0324F72bb9", + "value": "600000000000000000000" + }, + { + "block_hash": "0x1faad81d6d2ef75a4b74b8466cdc93de3f74a9c15bda9ce56bf3dc03bacbfa87", + "block_number": 21890874, + "log_index": 247, + "recipient": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "sender": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x7680f21cfbbcc347d38a1b6f0ea38f3d53f86c61c47e4c72873dffad62e25709", + "transaction_index": 75, + "tx_sender": null, + "value": "96517394555617036350647" + }, + { + "block_hash": "0xa9854bd83f5a00e57c7c6be0d3c35efb1137c8a74b989b4604c93d5e635a155a", + "block_number": 21890897, + "log_index": 363, + "recipient": "0x804051B0cbc20443943C4F363573eF9bB7793375", + "sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced", + "transaction_index": 96, + "tx_sender": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "value": "96517394555617036350647" + } + ], + "wallet": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "wallet_code_hex": { + "21869297": "0x", + "21890896": "0x" + }, + "wallet_transactions": [ + { + "block_number": 21871900, + "nonce": 124, + "succeeded": null, + "to": "0x39053D51B77DC0d36036Fc1fCc8Cb819df8Ef37A", + "transaction_hash": "0xb6334cb05425f722fd86af6b4a8a8a2a93d221a55d88b9f0cc5ac4a0758311e3", + "transaction_index": 45, + "value": "0" + }, + { + "block_number": 21871908, + "nonce": 125, + "succeeded": null, + "to": "0x39053D51B77DC0d36036Fc1fCc8Cb819df8Ef37A", + "transaction_hash": "0x8b6eacd9b508e044002a512cd91311a5ef1624d4b0fe90e5411197a1b000590f", + "transaction_index": 33, + "value": "0" + }, + { + "block_number": 21873695, + "nonce": 126, + "succeeded": null, + "to": "0xec53bF9167f50cDEB3Ae105f56099aaaB9061F83", + "transaction_hash": "0xbdded0c63d8efb418a12a162ebbc822d18b8755e03eb329ce27cf3558b4a8cda", + "transaction_index": 115, + "value": "0" + }, + { + "block_number": 21873870, + "nonce": 127, + "succeeded": true, + "to": "0xbA3cB449bD2B4ADddBc894D8697F5170800EAdeC", + "transaction_hash": "0xb322bd6f138392d00afc98116157dee39b33784685d5f51939d28de616419ebd", + "transaction_index": 70, + "value": "9000000000000000000" + }, + { + "block_number": 21882651, + "nonce": 128, + "succeeded": true, + "to": "0xbA3cB449bD2B4ADddBc894D8697F5170800EAdeC", + "transaction_hash": "0xd4a67110c9522fd2e54d37940e75e85e60b2b7c0b51ff53addad067dd760f997", + "transaction_index": 53, + "value": "10000000000000000" + }, + { + "block_number": 21886653, + "nonce": 129, + "succeeded": null, + "to": "0x03BC21ED21deB503202ce6A85ca4856AE8007Cfe", + "transaction_hash": "0x17867cff38846cb9d09db869f004e386cc58cb7de4cde982c86c2c1d88176472", + "transaction_index": 88, + "value": "0" + }, + { + "block_number": 21888842, + "nonce": 130, + "succeeded": null, + "to": "0x03BC21ED21deB503202ce6A85ca4856AE8007Cfe", + "transaction_hash": "0xd45aa7aa28d9343a7e0244504fdaeab14fd1d486ca17c5fb5a5d28200739f9b8", + "transaction_index": 3, + "value": "0" + }, + { + "block_number": 21888868, + "nonce": 131, + "succeeded": null, + "to": "0x39053D51B77DC0d36036Fc1fCc8Cb819df8Ef37A", + "transaction_hash": "0x08bd2734fee1eaf80d57e271f3ab4fae201a36e81cfdf72d4d35f94a1478dccd", + "transaction_index": 73, + "value": "0" + }, + { + "block_number": 21890495, + "nonce": 132, + "succeeded": null, + "to": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x175e6421407c56dec5b407db8b66d86712294693fd2ea32a121b4d381f8b0507", + "transaction_index": 65, + "value": "0" + }, + { + "block_number": 21890508, + "nonce": 133, + "succeeded": true, + "to": "0x80404F3eb7fEd80349954e8285eC8A9365793375", + "transaction_hash": "0x31a0592989e26f608e861ec78023199cb96262cda796e6db74a320fa236f9525", + "transaction_index": 139, + "value": "600000000000000000000" + }, + { + "block_number": 21890867, + "nonce": 134, + "succeeded": true, + "to": "0xbA3cB449bD2B4ADddBc894D8697F5170800EAdeC", + "transaction_hash": "0xcb02d6747e524c1a7440075b1af5ca5a1637cfb62beffa27bfd97f95d16ee9db", + "transaction_index": 62, + "value": "40300089886720680510" + }, + { + "block_number": 21890897, + "nonce": 135, + "succeeded": null, + "to": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "transaction_hash": "0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced", + "transaction_index": 96, + "value": "0" + } + ] +} diff --git a/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/manifest.json b/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/manifest.json new file mode 100644 index 0000000..c596277 --- /dev/null +++ b/docs/ml/incident-benchmark/cases/scamsniffer-763k-2025-02-20/manifest.json @@ -0,0 +1,39 @@ +{ + "case_id": "scamsniffer-763k-2025-02-20", + "title": "Scam Sniffer-reported poisoning loss, Feb 2025", + "category": "address_poisoning", + "chain_id": 1, + "summary": "Pre-registered Phase 12.3 benchmark case (unknown); see docs/ml/incident-benchmark/stage2-resolved.json.", + "first_public_report": "2025-02-26", + "public_sources": [ + { + "publisher": "ForkLog (citing Scam Sniffer, X post of 2025-02-26)", + "title": "Scam Sniffer-reported poisoning loss, Feb 2025", + "url": "https://forklog.com/en/user-loses-over-760000-due-to-address-poisoning/", + "accessed": "2025-02-26", + "used_for": "the reported addresses and dates; the harmful transaction was resolved on chain by the rule frozen in amendment-12.3-A1" + } + ], + "victim": "0xf6B1539cc562C0cA5151825488eb8c3cdaf2b6E4", + "intended_recipient": null, + "harm": { + "transaction_hash": "0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced", + "block_number": 21890897, + "recipient": "0x804051B0cbc20443943C4F363573eF9bB7793375", + "token": "0x44ff8620b8cA30902395A7bD3F2407e1A091BF73", + "value_base_units": "96517394555617036350647", + "description": "The victim's transfer to the lookalike, as located on chain." + }, + "evaluation": { + "from_block": 21869297, + "to_block": 21890897, + "rationale": "The 21,600 blocks (about 3 days) before and including the harmful block: the rule pre-registered before any request, the same as the 4 replay cases." + }, + "onchain_verification": [ + "Harmful transaction 0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced: block 21890897, signed by the victim, 1 Transfer log(s) from the victim to the lookalike (replay locate)." + ], + "ground_truth_limitations": [ + "One public write-up; the recipient is a lookalike by the source's account and by the located transfer, not by an independent label.", + "The recorded window is 3 days; earlier history is not observed." + ] +} diff --git a/docs/ml/incident-benchmark/preregistration-stage2a.md b/docs/ml/incident-benchmark/preregistration-stage2a.md index fdc5ff3..de963db 100644 --- a/docs/ml/incident-benchmark/preregistration-stage2a.md +++ b/docs/ml/incident-benchmark/preregistration-stage2a.md @@ -7,7 +7,7 @@ and before any detector output on these cases. - `protocol-12.3.md` and `../amendment-12.3-A1.md`; - the shortlist and statistical review in `stage2-shortlist.md`. -**Status: not approved.** Stage 2a runs only after the user explicitly approves its cap. +**Status:** run on 2026-11-03 under an approved 6,000 cap. It used 1,433 requests. Result: `stage2a-result.md`. This file was not changed before or during the run. ## 1. Cases diff --git a/docs/ml/incident-benchmark/stage2-resolved.json b/docs/ml/incident-benchmark/stage2-resolved.json new file mode 100644 index 0000000..882a82d --- /dev/null +++ b/docs/ml/incident-benchmark/stage2-resolved.json @@ -0,0 +1,30 @@ +{ + "schema_version": "incident-candidates/1", + "protocol": "protocol-12.3/1 with amendment-12.3-A1", + "discovery": { + "resolved_from": "docs/ml/incident-benchmark/stage2-candidates.json" + }, + "candidates": [ + { + "case_id": "scamsniffer-763k-2025-02-20", + "source": { + "publisher": "ForkLog (citing Scam Sniffer, X post of 2025-02-26)", + "url": "https://forklog.com/en/user-loses-over-760000-due-to-address-poisoning/", + "date": "2025-02-26" + }, + "chain_id": 1, + "mechanism": "unknown", + "identifiers": { + "victim": "0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4", + "lookalike": "0x804051b0cbc20443943c4f363573ef9bb7793375", + "intended": null, + "planting_tx": null, + "harm_tx": "0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced" + }, + "identifier_status": "resolved on chain (amendment-12.3-A1): oldest nonzero Transfer signed by etherscan_filter_fadd to etherscan_filter_tadd, 2025-02-19..2025-02-21 UTC", + "fixture_case_id": null, + "synthetic": false + } + ], + "not_usable_sources": [] +} diff --git a/docs/ml/incident-benchmark/stage2a-result.md b/docs/ml/incident-benchmark/stage2a-result.md new file mode 100644 index 0000000..9a9301d --- /dev/null +++ b/docs/ml/incident-benchmark/stage2a-result.md @@ -0,0 +1,125 @@ +# Stage 2a: result + +**Run:** 2026-11-03, under `preregistration-stage2a.md` and `../amendment-12.3-A1.md`, which +were frozen in `fdffc05` before any request. CI passed on that commit: 9 of 9 jobs. + +**Outcome:** +- **Case 1** (`scamsniffer-763k-2025-02-20`): resolved and recorded. It is a Level I case, + and the detector **missed** it. +- **Case 2** (`webacy-6.88m-usdt-2025-09`): **not evaluable: RPC**. Two provider rejections, + so the stop rule applied. +- **Overall:** descriptive only, with no rates. + +## 1. RPC usage (exact; ledger `data/ml/rpc/ledger-incident-stage2a.json`) + +| Step | Limit | Used | Result | +|---|---|---|---| +| Case 1 `find-transfers` | 400 | 275 (one `eth_chainId` timeout, retried) | scan complete; 6 matches | +| Case 1 `record` | 2,000 | 645 | complete: 9 transfers, 12 wallet transactions | +| Case 2 `find-transfers`, attempt 1 | 600 | 72 | `eth_getLogs` rejected by the provider (`rpc_request_rejected`) | +| Case 2 `find-transfers`, the one permitted restart | 528 (the step's remaining limit) | 441 | rejected again, much later in the scan | +| **Stage 2a total** | **6,000** | **1,433** | 4,567 unused. They do not carry over. | + +**Endpoint:** `https://eth.drpc.org` only. No paid API was used. + +**Why case 2 failed.** The two rejections came at very different points in the scan: about +chunk 20, then about chunk 390 of 432. That points to transient throttling on the free +endpoint, not a malformed query. The client does not keep the provider's error message, so +this is not confirmed. + +The pre-registered rule allows no third attempt, and no other endpoint. Case 2 has no +manifest and no fixture. Its stage-total requests were not reused. + +**Preflight.** The bounded resource check passed on the 4th of 5 checks before case 1: 1.7 GiB +free, disk queue 0.2. It passed on the 3rd check before case 2: 1.66 GiB free. +- Checks 1–3, and 1–2 before case 2, failed. Free RAM was 1.1–1.4 GiB, CPU 77–100 %, and the + disk queue was up to 11. Unrelated netsentinel and causalverse jobs were running. +- No process was touched. +- CPU stayed high (78 %) when case 2 started. That step is network-bound. + +## 2. Case 1: verification and resolution + +| Check | Result | +|---|---| +| Rule (frozen) | oldest nonzero Transfer from `0xf6b1…b6e4` (`fadd`) to `0x8040…3375` (`tadd`) on 2025-02-19..21 UTC, signed by `fadd` | +| Found | 6 transfers of token `0x44ff8620…bf73` from `fadd` to `tadd`, blocks 21,890,897–21,891,033 (about 27 min). All succeeded, and all were signed by `fadd`. That fits the source's single "victim lost $763,662" (it names no token), and the Etherscan filter link's from→to reading. **The role reading was not falsified.** | +| Harmful transaction (rule) | `0x05ea701d3d53976632b228127cafedc84abe7dec8054051ebcc070f9ecd81ced`, block 21,890,897, 96,517,394,555,617,036,350,647 base units (96,517.39 if the token has 18 decimals, which was not read) | +| Overlap, re-run on the resolved identifiers before recording | none (victim, recipient, harm tx) | +| Gate C | PASS: the harmful transfer is in the window. The planting status is "not reported", since the source gave none. | +| Window | 21,869,297–21,890,897, complete scan, fixture `67e44177…5674f1`, now frozen by test | + +## 3. Case 1: what the detector saw (pre-harm data only) + +All times are measured from recorded block-header timestamps. + +| Block | Time (UTC) | Event | +|---|---|---| +| 21,890,495 | 2025-02-20 22:19:23 | The victim sends token `0x44ff…` to `0x80404f3e…793375`. A wallet transaction 13 blocks later sends that address 600 ETH. This is the reference use. | +| 21,890,558 | 22:32:23 | A spoofed "from victim" transfer of a fake token, signed by `0x7730…Ba3f`, to `0x8045233d…793375`. **Warned.** | +| 21,890,871 | 23:35:23 | Another spoofed transfer, signed by `0x0C0b…2bb9`, to `0x804041c8…1f3375`. **Warned.** | +| 21,890,897 | 23:40:35 | **Theft:** to `0x804051b0…793375`. This is its **first** appearance in the recorded window. | + +**Outcome:** +- **Candidates:** 2 were generated (the two warned lookalikes). The theft recipient was + **not recovered**. +- **Classification:** `post_incident_only` under both visibilities. The case is recognised + only once the theft itself is visible. +- **The two warned addresses** are lookalikes of the same reference address, and they are + unlabelled. The victim paid a *third* lookalike of it. +- **Not rankable:** the target was not warned, so there are no OP0 or OP1 ranks. k = 2. +- **Gaps:** + - `cluster_signers` is empty, since the target has no pre-harm record. + - `lead_possibly_censored` does not apply. + +**Why it was missed.** This is a coverage miss, not a ranking failure. The theft recipient +leaves no ERC-20 Transfer to or from this wallet before the theft. The recorder stores Transfer +logs in both directions and the wallet's own transactions, but **not incoming native-ETH +transfers or internal transactions**. + +**A hypothesis, not a finding:** a planting by native-ETH dust, a known variant, would be +invisible to this recorder. It is not tested here, because that needs data the pre-registration +did not collect. Planting before the window is unlikely, since the reference use itself lies +inside the window, 402 blocks before the theft. Whether the victim had used the reference +address before the window is not observed. + +## 4. Benchmark summaries (offline, `data/ml/research/stage2a/`) + +| Level I | All (pilot + case 1) | Verbatim-only (pilot) | +|---|---|---| +| Tier A cases | 2 | 1 | +| Target recovered as a candidate | 1 of 2 | 1 of 1 | +| Warned before the harm (Gate G, exact count) | 1 of 2 | 1 of 1 | +| Rankable (target warned, k ≥ 2) | 1 | 1 | +| OP1 vs OP0 (better / equal / worse) | 1 / 0 / 0 | 1 / 0 / 0 | +| Gate H, amendment A1 | **DESCRIPTIVE** (1 cluster) | DESCRIPTIVE | +| Gate H, protocol 12.3 §10 (kept on record) | PASS WITH LIMITATIONS | PASS WITH LIMITATIONS | + +Level III: no case is admitted (frozen-cohort overlap). + +The pilot's result is unchanged, and its frozen regression test passes. + +## 5. What this shows, and what it does not + +**Shown:** of two independent documented thefts, the detector warned on the eventual recipient +before the harm in one. In the other it warned on two other lookalikes of the same address, but +never saw the one that was paid. + +That second case is informative. Coverage depends on what the recorded stream contains, and +attackers can plant through channels the recorder does not observe. The same may hold for +wallets using CryptoGuard live. That is a hypothesis for the product, not a measured rate. + +**Not shown:** +- **No rates.** There is no detection rate, precision, recall or false-positive rate, and 1 of 2 is not an estimate of coverage. +- **No ranking evidence.** One rankable case is DESCRIPTIVE under A1. +- **Not independent ML validation.** + +**Limitations:** +- **Case 1's identifiers** were resolved on chain (R1). The roles came from Etherscan's filter semantics, which the chain did not contradict. The source gives no intended address and no planting. +- **Case 2:** its loss is not evaluated. The RPC failure is not a result about the case. +- **Selection:** both cases are public, large and firm-noticed. + +## 6. Reproduce (offline) + +`cryptoguard ml incident-benchmark verify`, then `run` and `report`, each with `--out +data/ml/research/stage2a`. The default manifests are `candidates.json` and +`stage2-resolved.json`. diff --git a/docs/ml/incident-recording-budget-plan.md b/docs/ml/incident-recording-budget-plan.md index 34590c4..058727b 100644 --- a/docs/ml/incident-recording-budget-plan.md +++ b/docs/ml/incident-recording-budget-plan.md @@ -9,6 +9,8 @@ discovery found no fully eligible new case. It proposes Stage 2a (2 public cases, cap 6,000 after the Step 0 revision) and Stage 2b (user-sourced, cap 14,000), plus a protocol amendment. +- **Stage 2a is complete** (2026-11-03): **1,433 of 6,000** used (`incident-benchmark/stage2a-result.md`). + It produced 1 Level I case, and 1 case was *not evaluable: RPC*. - **Stage 2 Step 0 is complete** (0 requests): amendment `amendment-12.3-A1.md`, the resolution tools, and `incident-benchmark/preregistration-stage2a.md`. - **No further request is authorized** by this document. Each stage below needs its own explicit approval of a request cap, and unused diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index fa8a2a5..4529b7d 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -314,7 +314,7 @@ def run(args: argparse.Namespace) -> int: else stage2.model_copy( update={ "protocol": f"{ib_.PROTOCOL} with {ib_.AMENDMENT}", - "discovery": {"resolved_from": str(ib_.STAGE2)}, + "discovery": {"resolved_from": ib_.STAGE2.as_posix()}, "candidates": [], "not_usable_sources": [], } diff --git a/tests/test_ml_incident_benchmark.py b/tests/test_ml_incident_benchmark.py index 9db8c1b..521a8ec 100644 --- a/tests/test_ml_incident_benchmark.py +++ b/tests/test_ml_incident_benchmark.py @@ -479,3 +479,27 @@ def write(name: str, ids: list[str]) -> Path: assert [c.case_id for c in merged.candidates] == ["x", "y"] with pytest.raises(ValueError, match="more than one manifest"): ib.load_manifests([a, write("c.json", ["x"])]) + + +def test_stage_2a_case_is_frozen_and_reproduces_exactly() -> None: + """The first resolved Level I case: frozen like the pilot, including its miss (the theft + recipient never appears in the recorded stream before the harm).""" + import hashlib + + [case] = [c for c in ib.load_new_cases() if c.manifest.case_id == "scamsniffer-763k-2025-02-20"] + assert case.fixture_sha256 == ( + "67e44177ad7785bd5779bb3db205f3175ee8aca404f6d29e0dc1e6f3d95674f1" + ) + assert hashlib.sha256(case.manifest.model_dump_json().encode()).hexdigest() == ( + "770b1200f3d4dd3231232533beb1cfc2900f68d2a00ef899cfd2c732644192f1" + ) + row = ib.run_case(case, level="I") + assert row["leakage_checks_passed"] + assert not row["candidates"]["target_recovered"] + assert row["visibilities"]["erc20_plus_wallet_transactions"]["outcome"] == ( + "post_incident_only" + ) + assert (row["ranking"]["primary"]["k"], row["ranking"]["primary"]["target_warned"]) == ( + 2, + False, + ) From 3a79b74d0c81ce3d35007ce816e2c86c281b2514 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 4 Nov 2026 17:42:56 +0300 Subject: [PATCH 59/92] docs(ml): freeze protocol 12.4 (observation completeness, candidate discovery) Frozen before the extended observation code exists and before any C1/C2 output on a recorded window. Records the development analysis already done (code audit; the Stage 2a miss reconstructed from its fixture), hypotheses H1-H6 with failure criteria, populations P1-P5 (P2 excluded: frozen-cohort overlap), the contamination policy for the two known Level I cases, and the fairness rules. 0 RPC requests. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.4.md | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 docs/ml/protocol-12.4.md diff --git a/docs/ml/protocol-12.4.md b/docs/ml/protocol-12.4.md new file mode 100644 index 0000000..5913a53 --- /dev/null +++ b/docs/ml/protocol-12.4.md @@ -0,0 +1,84 @@ +# Protocol 12.4: observation completeness and candidate discovery + +**Frozen:** 2026-11-04, in the commit that adds this file. That is before the extended observation code exists, and before any C1 or C2 output is computed on a recorded window. + +**Development analyses already performed:** the code audit, and the reconstruction of the missed Stage 2a case from its recorded fixture (§3). They are labelled as such. + +**RPC:** 0 requests. No budget is open, and none is requested here. + +## 1. Question + +Does observing more of the historically available chain evidence, and stating explicitly what was *not* observed, let CryptoGuard find poisoning candidates the frozen pipeline misses? And can it do so without unsupported claims or a flood of warnings? + +## 2. Contamination policy + +- **Original results stay fixed.** The two Level I cases (`usdt-counterfeit-39890-2026-08-09`, `scamsniffer-763k-2025-02-20`) keep their original results as recorded in Phase 12.3. Those results are frozen by regression tests and are never rewritten. +- **The cases are now known.** For any method written after their outcomes were known, they are **development cases (P3)**. A method that recovers the missed address on them is a **development-case regression success**, never independent validation. +- **Five records are kept apart:** + 1. the frozen detector and generator (C0) and their original outcomes; + 2. the extended observation pipeline (`observation/2`); + 3. the new candidate rules (C1, C2); + 4. changes motivated by the known cases, marked `motivated-by: P3`; + 5. future untouched data. None exists yet. + +## 3. Development analysis already done (not confirmatory) + +**The Stage 2a miss**, from its fixture only: +- The victim paid the reference `0x80404f3e…793375` at block 21,890,495. +- Two fake-token lookalikes were planted after that, and both were warned. +- The paid address `0x804051b0…793375` appears **nowhere in any local artifact** before the theft. + +**The recorder (`observation/1`) does not collect:** +- inbound native ETH; +- zero-value native transactions; +- internal value transfers (no trace access); +- ERC-1155 events. + +It also fetches ERC-721-shaped and malformed `Transfer` logs, then **discards** them without persisting even their counts. + +**The cause of the miss is therefore not identifiable from local data.** Native-ETH dust is one hypothesis among several. + +## 4. Hypotheses + +| ID | Hypothesis | Population | Baseline | Measure | Fails if | +|---|---|---|---|---|---| +| H1 | `observation/1` omits event classes used by documented poisoning mechanisms | P1 and the code audit | — | event classes present in a controlled source but absent from `observation/1` | every class used in P1 is recorded | +| H2 | Correctly recording those classes recovers candidates invisible to C0, with the rules unchanged | P1 | C0 on `observation/1` | exact count of oracle candidates recovered by C1 on `observation/2` and not by C0 | C1 recovers no extra oracle candidate, or adds any non-oracle candidate in P1 | +| H3 | Category-scoped completeness prevents unobserved activity being reported as zero | P1, plus all local fixtures (metadata only) | `wallet-history/1` (one window-wide boolean) | features that are a number under `/1` but undefined under strict scope, for the same input | strict scope changes no feature on any input where a category was not collected | +| H4 | Keeping signer, event-sender, token and transaction provenance prevents false equivalences | P1 cases B, C, G, J, K, L | — | oracle agreement | any case disagrees with its oracle | +| H5 | Temporal or graph context adds information beyond the deterministic signals, on a valid diagnostic task | P3, P5 | C0 order | — | **pre-declared NOT EVALUATED unless a labelled population exists.** None does for the new classes: P4 has no native or NFT observations. P3 and P5 are only described. | +| H6 | The extension runs in bounded memory and acceptable time | P1, P3, P5 | C0 | runtime, peak traced memory, candidates per wallet-day | peak > 200 MiB, or more than 10× C0's runtime | + +**C2** is the experimental semantic rule set. It is motivated by P3, as recorded in §2. +- **Payment-time screen:** at the moment of a wallet-signed payment, the recipient is checked against the wallet's own pre-payment references, using the same similarity rule as C0. It needs no planting observation. The recipient is the user's own pending input, never an outcome label. +- **Abstention:** when the reference history is unavailable, C2 reports *insufficient history* instead of "no candidates". + +C2's alert volume on P5 is **reported**, never called a false-positive rate, because P5 is unlabelled. + +## 5. Populations (never pooled) + +| ID | What it is | Supports | +|---|---|---| +| P1 | Synthetic cases A–L, with oracles written independently of the implementation in the test file | correctness and mechanism coverage only; no rates | +| P2 | The 4 packaged replay fixtures | **excluded from computation**: they hold frozen Cohort B items. Coverage metadata only. | +| P3 | The 2 Level I cases | development-case replay and diagnosis | +| P4 | Research archives | not used: no native or NFT observations, and an expensive pass | +| P5 | Background windows without frozen items (6 of 9) | candidate and alert volume, coverage, runtime. Unlabelled: not benign. | + +## 6. Fairness + +Within a window, every variant gets: +- the same cutoff, `(block, tx index)` strictly before; +- the same window; +- the same deduplication key, `(chain, tx hash, log index)`, or `(chain, tx hash, -1)` for a transaction's own value; +- the same similarity rule as C0 (`MIN_AFFIX` 6, `MIN_SUFFIX` 3). + +Changes to the candidate set are reported as set differences: added, removed and kept. + +## 7. Stop and integrity rules + +- The detector, OP0, OP1 and `ml.candidates` (C0) are unchanged, and production findings are unchanged. +- `observation/2` is opt-in. `observation/1` fixtures keep their bytes and hashes. +- No new RPC request, no download, no paid API, and no change to the frozen cohorts. +- No label is created. Nothing unknown is treated as benign. +- Gates are labelled PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA or NOT EVALUATED. A gate never passes merely because code exists. From 391795760176496b942cc1d6c3417a0300549f0d Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 4 Nov 2026 17:54:27 +0300 Subject: [PATCH 60/92] feat(replay,ml): observation/2 (native inbound, ERC-721, per-category coverage) and shadow candidate discovery Implementation for protocol 12.4, committed before the outcome-based study runs. No RPC. - replay/observation.py: per-category completeness (complete, partial, not_collected, unsupported, ...); legacy_coverage() states what observation/1 really did (native inbound and ERC-721 not collected, internal transfers unsupported). - services/native_inbound.py: native ETH received by a plain EOA, found by balance bisection over runs without own transactions; exact accounting per increase block; unexplained increases kept as unattributed (sender unknown without traces); zero-value native and wallets with code declared, not guessed. - record_window(observation=2) / replay record --observation 2: keeps ERC-721-shaped logs (previously fetched and discarded), counts malformed logs, records native inbound and coverage. Default stays 1; observation/1 fixtures keep their bytes and hashes. - ml/candidate_discovery.py (poisoning-candidate-discovery/1, shadow): typed provenance-preserving observations; C0 frozen generator, C1 same rules over every observed class, C2 abstention and a payment-time screen; scoped history that never reports unobserved inbound as zero. - ml/observation_study.py + ml observation-study: offline study entry. - Tests: synthetic cases A-L with hand-written oracles, invariance, observation/2 recorder end to end on a mock node, detector isolation. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/cli.py | 11 +- src/cryptoguard/ml/candidate_discovery.py | 439 +++++++++++++++++++++ src/cryptoguard/ml/cli.py | 19 + src/cryptoguard/ml/observation_study.py | 280 +++++++++++++ src/cryptoguard/replay/models.py | 64 ++- src/cryptoguard/replay/observation.py | 116 ++++++ src/cryptoguard/replay/record.py | 138 ++++++- src/cryptoguard/services/native_inbound.py | 219 ++++++++++ src/cryptoguard/services/transfers.py | 6 + tests/fakenode.py | 25 +- tests/integration/test_observation_v2.py | 208 ++++++++++ tests/test_ml_candidate_discovery.py | 387 ++++++++++++++++++ 12 files changed, 1905 insertions(+), 7 deletions(-) create mode 100644 src/cryptoguard/ml/candidate_discovery.py create mode 100644 src/cryptoguard/ml/observation_study.py create mode 100644 src/cryptoguard/replay/observation.py create mode 100644 src/cryptoguard/services/native_inbound.py create mode 100644 tests/integration/test_observation_v2.py create mode 100644 tests/test_ml_candidate_discovery.py diff --git a/src/cryptoguard/cli.py b/src/cryptoguard/cli.py index 42527bb..9d8dedd 100644 --- a/src/cryptoguard/cli.py +++ b/src/cryptoguard/cli.py @@ -364,7 +364,9 @@ async def run_recording() -> str: provider = build_rpc_provider(record_settings, transport=budgeted_transport(ledger)) before = ledger.used() try: - fixture = await record_fixture(provider, manifest, chunk_blocks=args.chunk_blocks) + fixture = await record_fixture( + provider, manifest, chunk_blocks=args.chunk_blocks, observation=args.observation + ) except BudgetExhaustedError as exc: # fail closed: no partial fixture is written ledger.note(f"replay record {manifest.case_id}: stopped at the cap ({exc})") raise @@ -888,6 +890,13 @@ def main(argv: Sequence[str] | None = None) -> int: p_record.add_argument( "--cases-dir", help="read the manifest from and write the fixture to this case folder" ) + p_record.add_argument( + "--observation", + type=int, + choices=(1, 2), + default=1, + help="2 also records native ETH received, ERC-721 transfers and per-category coverage", + ) _add_rpc_budget(p_record, per_run_help="most requests this window may reserve") p_locate = replay_sub.add_parser( "locate", help="read reported transactions' receipts (block, parties, transfers)" diff --git a/src/cryptoguard/ml/candidate_discovery.py b/src/cryptoguard/ml/candidate_discovery.py new file mode 100644 index 0000000..d86916c --- /dev/null +++ b/src/cryptoguard/ml/candidate_discovery.py @@ -0,0 +1,439 @@ +"""Shadow poisoning-candidate discovery (``poisoning-candidate-discovery/1``), research only. + +Protocol 12.4 compares three variants on one wallet window, at one cutoff: + +- **C0**: the frozen generator (``ml.candidates.generate``, ``candidates/2``) on the fixture + trimmed to the cutoff. Unchanged. +- **C1**: C0's own rules (``similar``, ``zero_value_in``, ``spoofed_out``, + ``untrusted_token_in``, ``dust_in``) applied to every class the window actually observed: + ERC-20 transfers, and with ``observation/2`` also native ETH received and ERC-721-shaped + transfers. No rule is new, so C1 minus C0 is what the extra observations buy. +- **C2**: C1 plus two semantic rules motivated by the Stage 2a miss (``motivated-by: P3``): + *abstention* (when the wallet's references are not fully observed, say so instead of + reporting "no candidate") and a *payment-time screen* (``screen_payment``): at the moment + the wallet signs a payment, its recipient is checked against the wallet's own earlier + references with the same similarity rule. The recipient there is the user's pending input, + never an outcome label, and the screen needs no planting observation. + +Observations keep their type and provenance: a counterfeit token emitting a Transfer "from" +the wallet is an ERC-20 log with a foreign signer, not a wallet-signed payment, and a +balance increase without an external sender (``unattributed_inbound``) names no one, so it +is reported but never becomes a candidate. Events are identified by (transaction hash, log +index), with -1 for a transaction's own value, and duplicates are dropped. + +Nothing here is a probability or a verdict: a candidate is a *suspicious lookalike +candidate*. The production detector stays authoritative and is not called or changed. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field +from typing import Any, Literal + +from cryptoguard.ml.candidates import ( + DUST_MAX_BASE_UNITS, + MIN_SUFFIX, + STABLECOINS, + similar, +) +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.replay.observation import coverage_of + +DISCOVERY_VERSION = "poisoning-candidate-discovery/1" +SCOPED_HISTORY_VERSION = "wallet-history/2-scoped" +Kind = Literal["erc20", "native", "nft"] +Variant = Literal["C0", "C1", "C2"] +# Categories a complete *inbound* history needs: without them, "never received from X" is +# not an observed zero. Zero-value native transactions and internal transfers can never be +# fully observed here (no balance change; no traces), so even a complete inbound scope says +# nothing about them (``INBOUND_SCOPE``). +INBOUND_CATEGORIES = ("erc20_transfer_logs", "erc721_transfer_logs", "native_inbound_external") +INBOUND_SCOPE = ( + "ERC-20, ERC-721-shaped and nonzero native transfers; zero-value native transactions " + "and internal transfers unobserved" +) +REFERENCE_CATEGORIES = ( + "erc20_transfer_logs", + "erc20_outgoing_signers", + "wallet_signed_transactions", +) + + +@dataclass(frozen=True) +class Observation: + kind: Kind + direction: Literal["in", "out"] + counterparty: str + value: int + block: int + tx_index: int + log_index: int # -1: the transaction's own value + tx_hash: str + signer: str | None # the transaction's tx.from, when known + wallet_signed: bool | None + emitter: str | None # the log's contract; None for a native value + succeeded: bool | None # None: not read (logs exist only for executed transactions) + + @property + def identity(self) -> tuple[str, int]: + return (self.tx_hash.lower(), self.log_index) + + @property + def position(self) -> tuple[int, int, int]: + return (self.block, self.tx_index, self.log_index) + + +def observations(fixture: Any) -> list[Observation]: + """Every observed wallet event, typed, deduplicated by identity, in chain order.""" + wallet = fixture.wallet.lower() + out: list[Observation] = [] + for t in fixture.transfers: + s, r = t.sender.lower(), t.recipient.lower() + if s == r: + continue # a self-transfer names no counterparty + signer = None if t.tx_sender is None else t.tx_sender.lower() + if s == wallet: + direction, party = "out", r + elif r == wallet: + direction, party = "in", s + else: + continue + out.append( + Observation( + "erc20", + direction, # type: ignore[arg-type] + party, + int(t.value), + t.block_number, + t.transaction_index, + t.log_index, + t.transaction_hash, + signer, + None if signer is None or direction == "in" else signer == wallet, + t.token.lower(), + None, + ) + ) + for tx in fixture.wallet_transactions: + if tx.to and int(tx.value): + out.append( + Observation( + "native", + "out", + tx.to.lower(), + int(tx.value), + tx.block_number, + tx.transaction_index, + -1, + tx.transaction_hash, + wallet, + True, + None, + tx.succeeded, + ) + ) + for n in getattr(fixture, "native_inbound", None) or []: + if n.sender.lower() == wallet: + continue + out.append( + Observation( + "native", + "in", + n.sender.lower(), + int(n.value), + n.block_number, + n.transaction_index, + -1, + n.transaction_hash, + n.sender.lower(), + False, + None, + n.succeeded, + ) + ) + for f in getattr(fixture, "nft_transfers", None) or []: + s, r = f.sender.lower(), f.recipient.lower() + if s == r or wallet not in (s, r): + continue + out.append( + Observation( + "nft", + "out" if s == wallet else "in", + r if s == wallet else s, + 0, + f.block_number, + f.transaction_index, + f.log_index, + f.transaction_hash, + None, + None, + f.token.lower(), + None, + ) + ) + unique: dict[tuple[str, int], Observation] = {} + for o in out: + unique.setdefault(o.identity, o) + return sorted(unique.values(), key=lambda o: (o.position, o.tx_hash)) + + +@dataclass(frozen=True) +class DiscoveryCandidate: + lookalike: str + imitated: str | None + methods: tuple[str, ...] + kind: Kind + evidence: str # "tx::" + position: tuple[int, int, int] + affix: tuple[int, int] | None + description: str = "suspicious lookalike candidate" + + +@dataclass(frozen=True) +class DiscoveryResult: + version: str + variant: Variant + cutoff: tuple[int, int] # observations strictly before (block, tx index) are used + candidates: list[DiscoveryCandidate] + coverage: dict[str, str] + missing_categories: list[str] + abstain: str | None = None + unattributed_inbound_blocks: list[int] = field(default_factory=list) + + @property + def lookalikes(self) -> set[str]: + return {c.lookalike for c in self.candidates} + + +def _before(o: Observation, cutoff: tuple[int, int]) -> bool: + return (o.block, o.tx_index) < cutoff + + +def _methods(o: Observation, match: tuple[int, int] | None) -> list[str]: + """C0's ``transfer_methods``, applied to any observed class (C1).""" + m: list[str] = [] + if o.succeeded is False: + return m # a reverted transaction moved nothing + if o.direction == "in" and o.value == 0 and o.kind != "nft": + m.append("zero_value_in") + if o.direction == "out" and o.kind == "erc20" and o.wallet_signed is False: + m.append("spoofed_out") + if o.direction == "in" and match is not None: + m.append("lookalike_in") + if o.kind == "erc20" and o.emitter not in TRUSTED_TOKENS: + m.append("untrusted_token_in") + if ( + o.direction == "in" + and o.kind == "erc20" + and o.emitter in STABLECOINS + and 0 < o.value <= DUST_MAX_BASE_UNITS + ): + m.append("dust_in") + return m + + +def _references(obs: Iterable[Observation]) -> dict[str, dict[str, int]]: + """Counterparties the wallet verifiably chose, bucketed by their last MIN_SUFFIX + characters (as C0 does): wallet-signed outgoing events, reverted sends included.""" + chosen: dict[str, dict[str, int]] = {} + for o in obs: + if o.direction == "out" and o.wallet_signed is True: + chosen.setdefault(o.counterparty[-MIN_SUFFIX:], {})[o.counterparty] = o.block + return chosen + + +def _match(party: str, chosen: dict[str, dict[str, int]]) -> tuple[str, tuple[int, int]] | None: + best = None + for k in chosen.get(party[-MIN_SUFFIX:], {}): + m = similar(party, k) + if m is not None and ( + best is None or (sum(m), m[1], k) > (sum(best[1]), best[1][1], best[0]) + ): + best = (k, m) + return best + + +def discover(fixture: Any, *, cutoff: tuple[int, int], variant: Variant = "C1") -> DiscoveryResult: + """Candidates from observations strictly before ``cutoff`` = (block, tx index).""" + cov = coverage_of(fixture) + coverage: dict[str, str] = {k: str(v.status) for k, v in cov.categories.items()} + missing = sorted(k for k, s in coverage.items() if s != "complete") + if variant == "C0": + return _c0(fixture, cutoff, coverage, missing) + obs = [o for o in observations(fixture) if _before(o, cutoff)] + chosen: dict[str, dict[str, int]] = {} + found: list[DiscoveryCandidate] = [] + for o in obs: # chain order: a reference counts only for later events + match = _match(o.counterparty, chosen) if o.direction == "in" else None + methods = _methods(o, match[1] if match else None) + if methods: + found.append( + DiscoveryCandidate( + lookalike=o.counterparty, + imitated=match[0] if match else None, + methods=tuple(methods), + kind=o.kind, + evidence=f"tx:{o.tx_hash.lower()}:{o.log_index}", + position=o.position, + affix=match[1] if match else None, + ) + ) + if o.direction == "out" and o.wallet_signed is True: + chosen.setdefault(o.counterparty[-MIN_SUFFIX:], {})[o.counterparty] = o.block + unattributed = sorted( + u.block_number + for u in getattr(fixture, "unattributed_inbound", None) or [] + if (u.block_number, 0) < cutoff + ) + abstain = None + if variant == "C2": + if not cov.complete(*REFERENCE_CATEGORIES): + abstain = "insufficient history: the wallet's own references are not fully observed" + elif not chosen: + abstain = ( + "no reference observed in the window; history before the window is unobserved, " + "so this is not evidence of no earlier recipients" + ) + return DiscoveryResult( + DISCOVERY_VERSION, variant, cutoff, found, coverage, missing, abstain, unattributed + ) + + +def _c0( + fixture: Any, cutoff: tuple[int, int], coverage: dict[str, str], missing: list[str] +) -> DiscoveryResult: + from cryptoguard.ml import candidates as c0 + + trimmed = fixture.model_copy( + update={ + "transfers": [ + t for t in fixture.transfers if (t.block_number, t.transaction_index) < cutoff + ], + "wallet_transactions": [ + t + for t in fixture.wallet_transactions + if (t.block_number, t.transaction_index) < cutoff + ], + } + ) + found = [ + DiscoveryCandidate( + lookalike=c.event.lookalike, + imitated=c.event.imitated, + methods=c.methods, + kind="erc20", + evidence=f"tx:{c.event.planting_tx}:{c.event.planting_log_index}", + position=( + c.event.planting_block, + c.event.planting_tx_index or 0, + c.event.planting_log_index or 0, + ), + affix=c.best_match, + ) + for c in c0.generate(trimmed) + ] + return DiscoveryResult(DISCOVERY_VERSION, "C0", cutoff, found, coverage, missing) + + +@dataclass(frozen=True) +class PaymentScreen: + recipient: str + flagged: bool | None # None: abstained (references not fully observed) + imitated: str | None + affix: tuple[int, int] | None + recipient_seen_before: bool | None # None when inbound history is not fully observed + reason: str + + +def screen_payment(fixture: Any, *, recipient: str, cutoff: tuple[int, int]) -> PaymentScreen: + """C2's payment-time screen for a payment the wallet is about to sign to ``recipient``: + does the recipient imitate one of the wallet's own earlier references, and has the + wallet ever dealt with it? Uses observations strictly before ``cutoff`` only.""" + recipient = recipient.lower() + cov = coverage_of(fixture) + obs = [o for o in observations(fixture) if _before(o, cutoff)] + chosen = _references(obs) + if not cov.complete(*REFERENCE_CATEGORIES): + return PaymentScreen(recipient, None, None, None, None, "abstain: references incomplete") + if not chosen: + return PaymentScreen( + recipient, None, None, None, None, "abstain: no reference observed in the window" + ) + if recipient in {k for b in chosen.values() for k in b}: + return PaymentScreen(recipient, False, None, None, True, "a reference the wallet chose") + match = _match(recipient, chosen) + seen = any(o.counterparty == recipient for o in obs) + seen_before: bool | None = ( + True if seen else False if cov.complete(*INBOUND_CATEGORIES) else None + ) + if match is None: + return PaymentScreen(recipient, False, None, None, seen_before, "no reference imitated") + return PaymentScreen( + recipient, + True, + match[0], + match[1], + seen_before, + "recipient imitates an earlier reference" + + ("" if seen_before is not None else "; earlier inbound contact not fully observable"), + ) + + +INBOUND_DEPENDENT = ( + "prior_interactions_with_recipient", + "blocks_since_first_interaction", + "blocks_since_last_interaction", + "unsolicited_events_with_recipient", + "lookalike_plantings_observed", +) + + +def scoped_history(fixture: Any, *, recipient: str, block: int, tx_index: int) -> dict[str, Any]: + """``wallet-history/1`` features with category scope: a feature that counts inbound + events is None unless every inbound category was fully observed (``/1`` reports those + as observed counts whenever the ERC-20 scan was complete).""" + from dataclasses import asdict + + from cryptoguard.ml.history import events_from_fixture, history_features + + events, window = events_from_fixture(fixture) + feats = asdict( + history_features( + events, + window, + recipient=recipient, + block=block, + tx_index=tx_index, + boundary="pre_execution", + ) + ) + inbound_ok = coverage_of(fixture).complete(*INBOUND_CATEGORIES) + if not inbound_ok: + feats |= dict.fromkeys(INBOUND_DEPENDENT, None) + feats["feature_version"] = SCOPED_HISTORY_VERSION + feats["inbound_scope_complete"] = inbound_ok + feats["inbound_scope"] = INBOUND_SCOPE if inbound_ok else None + return feats + + +def compare(a: DiscoveryResult, b: DiscoveryResult) -> dict[str, list[str]]: + """Candidate-set differences by lookalike address (protocol 12.4 §6).""" + return { + "added": sorted(b.lookalikes - a.lookalikes), + "removed": sorted(a.lookalikes - b.lookalikes), + "kept": sorted(a.lookalikes & b.lookalikes), + } + + +def signer_links(results: Sequence[tuple[str, Any, DiscoveryResult]]) -> list[tuple[str, str, str]]: + """Cross-wallet links between candidates only through a shared planting *signer* (never + a shared token contract, which anyone can use): (wallet a, wallet b, signer).""" + by_signer: dict[str, set[str]] = {} + for wallet, fixture, res in results: + evidence = {c.evidence for c in res.candidates} + for o in observations(fixture): + ref = f"tx:{o.tx_hash.lower()}:{o.log_index}" + if ref in evidence and o.signer and o.signer != wallet.lower(): + by_signer.setdefault(o.signer, set()).add(wallet.lower()) + return sorted((a, b, s) for s, ws in by_signer.items() for a in ws for b in ws if a < b) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 4529b7d..b747a46 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,11 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + ob = ml.add_parser( + "observation-study", + help="Phase 12.4 observation coverage and candidate discovery (offline, no RPC)", + ) + ob.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.4") ib = ml.add_parser( "incident-benchmark", help="Phase 12.3 independent incident benchmark (offline)" ) @@ -177,6 +182,20 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "observation-study": + import json + + from cryptoguard.ml import observation_study + + result = observation_study.main(ML_DIR / "poisoning", args.out) + summary = { + r["case_id"]: {v: r["variants"][v]["distinct_lookalikes"] for v in ("C0", "C1", "C2")} + | {"screen_flagged": r["payment_screen_unlabelled"]["flagged"]} + for r in result["windows"] + } + print(json.dumps({"windows": summary, "resources": result["resources"]}, indent=1)) + print(f"Wrote {args.out / 'observation-study.json'}") + return 0 if args.ml_command == "poisoning-report": from cryptoguard.ml.poisoning_report import build, write diff --git a/src/cryptoguard/ml/observation_study.py b/src/cryptoguard/ml/observation_study.py new file mode 100644 index 0000000..a47d385 --- /dev/null +++ b/src/cryptoguard/ml/observation_study.py @@ -0,0 +1,280 @@ +"""Phase 12.4 offline study (protocol 12.4): observation coverage and candidate discovery on +the local recorded windows. No RPC, no download; recorded windows that hold a frozen review +item are never computed on (only their coverage metadata is listed). + +Populations: P2 (packaged replay fixtures: excluded, frozen Cohort B), P3 (the two Level I +cases: development cases), P5 (background windows without frozen items: unlabelled). P1 +(synthetic) lives in the test suite with hand-written oracles. +""" + +from __future__ import annotations + +import hashlib +import statistics +import time +import tracemalloc +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.replay.observation import coverage_of + +STUDY_VERSION = "observation-study/1" +PROTOCOL = "protocol-12.4" +DAY = 7_200 + + +def touches_frozen_any(fixture: Any, blind: tuple[frozenset[str], frozenset[str]]) -> bool: + """``recency_validation.touches_frozen`` widened to every observed class: wallet-signed + native recipients, native inbound senders and ERC-721-shaped parties as well.""" + from cryptoguard.ml.recency_validation import touches_frozen + + addrs, txs = blind + if touches_frozen(fixture, blind): + return True + parties = [t.to for t in fixture.wallet_transactions if t.to] + [ + t.transaction_hash for t in fixture.wallet_transactions + ] + parties += [n.sender for n in fixture.native_inbound or []] + parties += [n.transaction_hash for n in fixture.native_inbound or []] + for f in fixture.nft_transfers or []: + parties += [f.sender, f.recipient, f.transaction_hash] + return any(p.lower() in addrs or p.lower() in txs for p in parties) + + +def _payments(fixture: Any, cutoff: tuple[int, int]) -> list[tuple[str, tuple[int, int], str]]: + """Wallet-signed nonzero payments before ``cutoff``: (recipient, position, kind).""" + out: list[tuple[str, tuple[int, int], str]] = [] + for o in cd.observations(fixture): + if ( + o.direction == "out" + and o.wallet_signed is True + and o.value > 0 + and (o.block, o.tx_index) < cutoff + ): + out.append((o.counterparty, (o.block, o.tx_index), o.kind)) + return out + + +def _window(case_id: str, population: str, fixture: Any, cutoff: tuple[int, int]) -> dict[str, Any]: + days = max(1.0, (min(cutoff[0], fixture.to_block + 1) - fixture.from_block) / DAY) + row: dict[str, Any] = { + "case_id": case_id, + "population": population, + "fixture_sha256": fixture.sha256(), + "cutoff": list(cutoff), + "coverage": {k: v.status for k, v in coverage_of(fixture).categories.items()}, + } + variants = {} + for variant in ("C0", "C1", "C2"): + tracemalloc.start() + t0 = time.perf_counter() + res = cd.discover(fixture, cutoff=cutoff, variant=variant) + ms = (time.perf_counter() - t0) * 1000 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + variants[variant] = { + "candidate_events": len(res.candidates), + "distinct_lookalikes": len(res.lookalikes), + "per_wallet_day": round(len(res.candidates) / days, 3), + "with_imitated_reference": sum(c.imitated is not None for c in res.candidates), + "abstain": res.abstain, + "runtime_ms": round(ms, 2), + "peak_traced_kib": round(peak / 1024, 1), + "_result": res, + } + row["c0_vs_c1"] = cd.compare(variants["C0"]["_result"], variants["C1"]["_result"]) + gaps = sorted( + c.position[0] + - next( + ( + o.block + for o in reversed(cd.observations(fixture)) + if o.counterparty == c.imitated + and o.direction == "out" + and o.block <= c.position[0] + ), + c.position[0], + ) + for c in variants["C1"]["_result"].candidates + if c.imitated + ) + row["blocks_reference_to_planting"] = gaps + pays = _payments(fixture, cutoff) + screens = [cd.screen_payment(fixture, recipient=r, cutoff=p) for r, p, _ in pays] + row["payment_screen_unlabelled"] = { + "payments": len(pays), + "flagged": sum(s.flagged is True for s in screens), + "abstained": sum(s.flagged is None for s in screens), + "flagged_recipients": sorted({s.recipient for s in screens if s.flagged}), + } + targets = {c.lookalike for c in variants["C1"]["_result"].candidates} | {r for r, _, _ in pays} + differ = 0 + for r in sorted(targets): + from dataclasses import asdict + + from cryptoguard.ml.history import events_from_fixture, history_features + + events, window = events_from_fixture(fixture) + v1 = asdict( + history_features( + events, + window, + recipient=r, + block=cutoff[0], + tx_index=cutoff[1], + boundary="pre_execution", + ) + ) + v2 = cd.scoped_history(fixture, recipient=r, block=cutoff[0], tx_index=cutoff[1]) + differ += sum(1 for k in cd.INBOUND_DEPENDENT if v1[k] is not None and v2[k] is None) + row["h3_inbound_features_numeric_in_v1_undefined_in_scoped"] = differ + row["h3_feature_rows"] = len(targets) + row["variants"] = { + k: {kk: vv for kk, vv in v.items() if kk != "_result"} for k, v in variants.items() + } + row["_results"] = {k: v["_result"] for k, v in variants.items()} + return row + + +def run(poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.ml.lookalike_ranking import protected_entities + from cryptoguard.ml.recency_validation import touches_frozen + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + + t0 = time.perf_counter() + blind = protected_entities(poisoning_dir) + metadata: list[dict[str, Any]] = [] + rows: list[dict[str, Any]] = [] + for c in load_cases(): # P2 + if c.fixture is not None: + metadata.append( + _meta(c.manifest.case_id, "P2", c.fixture, blind, "excluded: frozen Cohort B") + ) + for c in ib.load_new_cases(): # P3 + if c.fixture is None: + continue + fx = c.fixture + harm = next( + t + for t in fx.transfers + if t.transaction_hash.lower() == c.manifest.harm.transaction_hash.lower() + ) + metadata.append(_meta(c.manifest.case_id, "P3", fx, blind, "development case")) + row = _window(c.manifest.case_id, "P3", fx, (c.manifest.harm.block_number, 0)) + screen = cd.screen_payment( + fx, + recipient=c.manifest.harm.recipient, + cutoff=(harm.block_number, harm.transaction_index), + ) + row["development_payment_screen_on_theft"] = { + "flagged": screen.flagged, + "imitated": screen.imitated, + "affix": screen.affix, + "recipient_seen_before": screen.recipient_seen_before, + "reason": screen.reason, + "label": "development-case regression (motivated-by: P3), not validation", + } + rows.append(row) + for b in load_background(): # P5 + if b.fixture is None: + continue + frozen = touches_frozen(b.fixture, blind) + widened = touches_frozen_any(b.fixture, blind) + metadata.append( + _meta( + b.manifest.case_id, + "P5", + b.fixture, + blind, + "excluded: frozen item" if widened else "unlabelled", + ) + | {"frozen_rule_v1": frozen, "frozen_rule_widened": widened} + ) + if not widened: + rows.append(_window(b.manifest.case_id, "P5", b.fixture, (b.fixture.to_block + 1, 0))) + links = cd.signer_links( + [(r["case_id"], _fixture_of(r["case_id"]), r["_results"]["C1"]) for r in rows] + ) + gaps = [g for r in rows for g in r["blocks_reference_to_planting"]] + peak = peak_rss_bytes() + return { + "study": STUDY_VERSION, + "protocol": PROTOCOL, + "discovery": cd.DISCOVERY_VERSION, + "scoped_history": cd.SCOPED_HISTORY_VERSION, + "git": _git(), + "rpc_requests": 0, + "fixtures": metadata, + "windows": [{k: v for k, v in r.items() if k != "_results"} for r in rows], + "signer_links": links, + "reference_to_planting_blocks": { + "n": len(gaps), + "median": statistics.median(gaps) if gaps else None, + "min": min(gaps, default=None), + "max": max(gaps, default=None), + "label": "descriptive only; P3 (development) and P5 (unlabelled) pooled for this count", + }, + "resources": { + "seconds": round(time.perf_counter() - t0, 2), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + }, + } + + +_FIXTURES: dict[str, Any] = {} + + +def _meta(case_id: str, population: str, fixture: Any, blind: Any, status: str) -> dict[str, Any]: + _FIXTURES[case_id] = fixture + cov = coverage_of(fixture) + return { + "case_id": case_id, + "population": population, + "status": status, + "schema": cov.schema_version, + "fixture_sha256": fixture.sha256(), + "not_complete": sorted(k for k, v in cov.categories.items() if v.status != "complete"), + } + + +def _fixture_of(case_id: str) -> Any: + return _FIXTURES[case_id] + + +def _git() -> str | None: + import subprocess + + try: + return subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + + +def digest(result: dict[str, Any]) -> str: + import json + + return hashlib.sha256(json.dumps(result, sort_keys=True, default=str).encode()).hexdigest() + + +def main(poisoning_dir: Path, out: Path) -> dict[str, Any]: + import json + + result = run(poisoning_dir) + out.mkdir(parents=True, exist_ok=True) + body = json.dumps(result, indent=1, default=str, sort_keys=True) + (out / "observation-study.json").write_text(body + "\n", encoding="utf-8") + return result + + +__all__: Sequence[str] = ("main", "run", "touches_frozen_any") diff --git a/src/cryptoguard/replay/models.py b/src/cryptoguard/replay/models.py index 79e05cd..0120d1a 100644 --- a/src/cryptoguard/replay/models.py +++ b/src/cryptoguard/replay/models.py @@ -18,6 +18,7 @@ from cryptoguard.blockchain.erc20 import TransferEvent from cryptoguard.detectors.poisoning import NativeSend +from cryptoguard.replay.observation import ObservationCoverage CASES_PACKAGE = "cryptoguard.replay.cases" @@ -142,6 +143,58 @@ def from_event(cls, event: TransferEvent) -> RecordedTransfer: ) +class RecordedNativeInbound(BaseModel): + """A top-level transaction another account signed that sent ETH (possibly 0) to the + wallet (``observation/2``). ``succeeded`` is the receipt status; None = not read.""" + + model_config = ConfigDict(extra="forbid") + + transaction_hash: str + block_number: int + transaction_index: int + sender: str + value: str + succeeded: bool | None + + +class UnattributedInbound(BaseModel): + """A balance increase in one block that no successful external transaction to the + wallet explains: an internal transfer, a withdrawal or a fee credit. The sender is + unknown without traces (``observation/2``).""" + + model_config = ConfigDict(extra="forbid") + + block_number: int + value: str + + +class RecordedNftTransfer(BaseModel): + """An ERC-721-shaped Transfer log (4 topics, no data) to or from the wallet.""" + + model_config = ConfigDict(extra="forbid") + + token: str + sender: str + recipient: str + token_id: str + block_number: int + block_hash: str + transaction_hash: str + transaction_index: int + log_index: int + + +# ``observation/2`` additions. A fixture without them serializes exactly as before, so every +# recorded ``observation/1`` fixture keeps its bytes and its hash. +EXTENSION_FIELDS = ( + "observation", + "native_inbound", + "unattributed_inbound", + "nft_transfers", + "discarded_log_counts", +) + + class ReplayFixture(BaseModel): """Chain data recorded once from an RPC provider; the only input replay detectors see.""" @@ -162,9 +215,18 @@ class ReplayFixture(BaseModel): block_timestamps: dict[str, int] transfers: list[RecordedTransfer] wallet_transactions: list[RecordedTransaction] + observation: ObservationCoverage | None = None + native_inbound: list[RecordedNativeInbound] | None = None + unattributed_inbound: list[UnattributedInbound] | None = None + nft_transfers: list[RecordedNftTransfer] | None = None + discarded_log_counts: dict[str, int] | None = None # Transfer-topic logs not decoded def canonical_bytes(self) -> bytes: - return json.dumps(self.model_dump(mode="json"), sort_keys=True, indent=1).encode() + dump = self.model_dump(mode="json") + for key in EXTENSION_FIELDS: + if dump[key] is None: + del dump[key] + return json.dumps(dump, sort_keys=True, indent=1).encode() def sha256(self) -> str: return hashlib.sha256(self.canonical_bytes()).hexdigest() diff --git a/src/cryptoguard/replay/observation.py b/src/cryptoguard/replay/observation.py new file mode 100644 index 0000000..2347066 --- /dev/null +++ b/src/cryptoguard/replay/observation.py @@ -0,0 +1,116 @@ +"""What a recorded window observed, per event category (``observation/2``). + +A complete ERC-20 log scan says nothing about native ETH, a receipt says nothing about +internal value transfers, and a complete window says nothing about history before it. So +completeness is stated per category, and a category that was never collected is +``not_collected`` (or ``unsupported``), never an observed zero. + +Statuses: + +- ``complete``: every event of the category in the window was observed (``count`` of them, + possibly 0: a real zero). +- ``partial`` / ``truncated``: some were observed; how many were missed is unknown. +- ``interrupted`` / ``rejected``: collection stopped on an error or a provider refusal. +- ``not_collected``: the recorder did not look. Absence of records means nothing. +- ``unsupported``: the data source cannot provide the category (e.g. no trace access). +- ``unknown``: completeness cannot be determined. + +Fixtures recorded before ``observation/2`` carry no coverage; ``coverage_of`` derives what +``observation/1`` actually did from the recorder's documented method. +""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict + +OBSERVATION_V1 = "observation/1" +OBSERVATION_V2 = "observation/2" + +Status = Literal[ + "complete", + "partial", + "truncated", + "interrupted", + "rejected", + "not_collected", + "unsupported", + "unknown", +] +CATEGORIES = ( + "erc20_transfer_logs", # Transfer, 3 topics and 32 data bytes, to or from the wallet + "erc20_outgoing_signers", # tx.from of every outgoing ERC-20 transfer's transaction + "erc721_transfer_logs", # Transfer, 4 topics and no data (same topic0 as ERC-20) + "malformed_transfer_logs", # Transfer topic0 in any other shape (counted, not decoded) + "erc1155_transfer_logs", # TransferSingle / TransferBatch (different topic0) + "wallet_signed_transactions", # every transaction the wallet signed (nonce bisection) + "native_inbound_external", # nonzero ETH in top-level transactions to the wallet + "native_inbound_zero_value", # 0-ETH top-level transactions to the wallet + "native_inbound_unattributed", # balance increases no external transaction explains + "internal_value_transfers", # value moved by contract execution (needs traces) +) + + +class CategoryCoverage(BaseModel): + model_config = ConfigDict(extra="forbid") + + status: Status + count: int | None = None # records observed; None when nothing was collected + note: str | None = None + + +class ObservationCoverage(BaseModel): + model_config = ConfigDict(extra="forbid") + + schema_version: str + categories: dict[str, CategoryCoverage] + + def status(self, category: str) -> Status: + c = self.categories.get(category) + return "unknown" if c is None else c.status + + def complete(self, *categories: str) -> bool: + return all(self.status(c) == "complete" for c in categories) + + +_V1_NOT_KEPT = ( + "fetched by the log scan but discarded by observation/1; not even counts were persisted" +) + + +def legacy_coverage(fixture: Any) -> ObservationCoverage: + """What an ``observation/1`` recording observed, from its stored fields and the + recorder's method (see ``replay.record.METHOD``).""" + scan = "complete" if fixture.transfer_scan_complete else "partial" + return ObservationCoverage( + schema_version=OBSERVATION_V1, + categories={ + "erc20_transfer_logs": CategoryCoverage(status=scan, count=len(fixture.transfers)), + "erc20_outgoing_signers": CategoryCoverage( + status="complete" if fixture.sender_lookups_skipped == 0 else "partial", + note=f"{fixture.sender_lookups_skipped} lookups skipped", + ), + "erc721_transfer_logs": CategoryCoverage(status="not_collected", note=_V1_NOT_KEPT), + "malformed_transfer_logs": CategoryCoverage(status="not_collected", note=_V1_NOT_KEPT), + "erc1155_transfer_logs": CategoryCoverage(status="not_collected", note="not queried"), + "wallet_signed_transactions": CategoryCoverage( + status="complete", # the recorder refuses an incomplete nonce bisection + count=len(fixture.wallet_transactions), + ), + "native_inbound_external": CategoryCoverage( + status="not_collected", note="no per-address index for native transfers" + ), + "native_inbound_zero_value": CategoryCoverage(status="not_collected"), + "native_inbound_unattributed": CategoryCoverage(status="not_collected"), + "internal_value_transfers": CategoryCoverage( + status="unsupported", note="the RPC layer has no trace access" + ), + }, + ) + + +def coverage_of(fixture: Any) -> ObservationCoverage: + """The fixture's stated coverage (``observation/2``), else the derived legacy one.""" + stated = getattr(fixture, "observation", None) + return stated if stated is not None else legacy_coverage(fixture) diff --git a/src/cryptoguard/replay/record.py b/src/cryptoguard/replay/record.py index 811e499..4b76833 100644 --- a/src/cryptoguard/replay/record.py +++ b/src/cryptoguard/replay/record.py @@ -40,6 +40,14 @@ "Wallet code at the window start and one block before the harmful block (eth_getCode).", "Timestamps of all referenced blocks (eth_getBlockByNumber).", ] +METHOD_V2 = [ + *METHOD, + "observation/2: ERC-721-shaped Transfer logs from the same scans, kept as records; " + "malformed Transfer-topic logs counted.", + "observation/2: native ETH received, by balance bisection (eth_getBalance) over runs " + "without own transactions, senders read from the increase blocks (eth_getBlockByNumber), " + "unexplained increases kept as unattributed; see services/native_inbound.py.", +] async def record_fixture( @@ -49,6 +57,7 @@ async def record_fixture( chunk_blocks: int = 100, max_log_requests: int = 2_000, max_sender_lookups: int = 500, + observation: int = 1, ) -> ReplayFixture: return await record_window( provider, @@ -60,6 +69,7 @@ async def record_fixture( chunk_blocks=chunk_blocks, max_log_requests=max_log_requests, max_sender_lookups=max_sender_lookups, + observation=observation, ) @@ -76,9 +86,13 @@ async def record_window( max_sender_lookups: int = 500, all_timestamps: bool = True, max_wallet_transactions: int = 10_000, + observation: int = 1, ) -> ReplayFixture: """Record one wallet's observations in ``[start, end]``. With ``all_timestamps=False`` - only the window's first and last block timestamps are read (analyses use block time).""" + only the window's first and last block timestamps are read (analyses use block time). + ``observation=2`` also records native ETH received, ERC-721-shaped transfers and a + per-category coverage (``replay.observation``); 1, the default, records exactly what + every existing fixture holds.""" wallet = to_checksum_address(wallet) await provider.verify_chain() @@ -121,9 +135,19 @@ async def record_window( str(block): "0x" + (await provider.get_code(wallet, block)).hex() for block in (start, end - 1) } + extension = ( + await _observation_v2(provider, wallet, start, end, transfers, transactions, code) + if observation == 2 + else {} + ) + extra_blocks = {r.block_number for r in extension.get("native_inbound") or []} | { + r.block_number for r in extension.get("nft_transfers") or [] + } blocks = sorted( ( - {t.block_number for t in transfers.transfers} | {t.block_number for t in transactions} + {t.block_number for t in transfers.transfers} + | {t.block_number for t in transactions} + | extra_blocks if all_timestamps else set() ) @@ -142,14 +166,122 @@ async def record_window( rpc_requests=provider.client.metrics.requests, transfer_scan_complete=transfers.complete, sender_lookups_skipped=transfers.sender_lookups_skipped, - method=METHOD, + method=METHOD_V2 if observation == 2 else METHOD, wallet_code_hex=code, block_timestamps=timestamps, transfers=[RecordedTransfer.from_event(t) for t in transfers.transfers], wallet_transactions=transactions, + **extension, ) +async def _observation_v2( + provider: RpcEthereumProvider, + wallet: str, + start: int, + end: int, + transfers: Any, + transactions: list[RecordedTransaction], + code: dict[str, str], +) -> dict[str, Any]: + """The ``observation/2`` fields: native ETH received, ERC-721-shaped transfers kept as + records, discarded-log counts, and the coverage of every category.""" + from cryptoguard.core.hexutil import parse_hash32, parse_quantity + from cryptoguard.replay.models import ( + RecordedNativeInbound, + RecordedNftTransfer, + UnattributedInbound, + ) + from cryptoguard.replay.observation import ( + OBSERVATION_V2, + CategoryCoverage, + ObservationCoverage, + Status, + legacy_coverage, + ) + from cryptoguard.services.native_inbound import locate_native_inbound + + plain = all(v == "0x" for v in code.values()) if code else None + found = await locate_native_inbound( + provider, + wallet, + from_block=start, + to_block=end, + own_tx_blocks=[t.block_number for t in transactions], + wallet_is_plain_eoa=plain, + ) + nfts = [] + for log in transfers.erc721_logs: + topics = log["topics"] + nfts.append( + RecordedNftTransfer( + token=to_checksum_address(log["address"]), + sender=to_checksum_address("0x" + topics[1][-40:]), + recipient=to_checksum_address("0x" + topics[2][-40:]), + token_id=str(int(topics[3], 16)), + block_number=parse_quantity(log["blockNumber"]), + block_hash=parse_hash32(log["blockHash"]), + transaction_hash=parse_hash32(log["transactionHash"]), + transaction_index=parse_quantity(log["transactionIndex"]), + log_index=parse_quantity(log["logIndex"]), + ) + ) + scan: Status = "complete" if transfers.complete else "partial" + counts = dict(transfers.log_counts) + nonzero = [x for x in found.inbound if x.value > 0] + zero = [x for x in found.inbound if x.value == 0] + native: Status = found.status # type: ignore[assignment] + unattributed: Status = found.unattributed_status # type: ignore[assignment] + categories = dict(legacy_coverage(_Counts(transfers, transactions)).categories) + categories |= { + "erc721_transfer_logs": CategoryCoverage(status=scan, count=len(nfts)), + "malformed_transfer_logs": CategoryCoverage( + status=scan, count=counts.get("malformed", 0), note="counted, not decoded" + ), + "native_inbound_external": CategoryCoverage( + status=native, count=len(nonzero), note=found.note + ), + "native_inbound_zero_value": CategoryCoverage( + status="unsupported" if native == "unsupported" else "partial", + count=len(zero), + note="moves no balance: seen only in blocks read for other reasons", + ), + "native_inbound_unattributed": CategoryCoverage( + status=unattributed, count=len(found.unattributed), note="sender unknown without traces" + ), + } + return { + "observation": ObservationCoverage(schema_version=OBSERVATION_V2, categories=categories), + "native_inbound": [ + RecordedNativeInbound( + transaction_hash=x.transaction_hash, + block_number=x.block_number, + transaction_index=x.transaction_index, + sender=x.sender, + value=str(x.value), + succeeded=x.succeeded, + ) + for x in found.inbound + ], + "unattributed_inbound": [ + UnattributedInbound(block_number=u.block_number, value=str(u.value)) + for u in found.unattributed + ], + "nft_transfers": nfts, + "discarded_log_counts": {k: v for k, v in counts.items() if k != "erc20"}, + } + + +class _Counts: + """The fields ``legacy_coverage`` reads, from a recording in progress.""" + + def __init__(self, transfers: Any, transactions: list[RecordedTransaction]) -> None: + self.transfer_scan_complete = transfers.complete + self.sender_lookups_skipped = transfers.sender_lookups_skipped + self.transfers = transfers.transfers + self.wallet_transactions = transactions + + async def locate_transaction(provider: RpcEthereumProvider, tx_hash: str) -> dict[str, Any]: """One receipt read: the block, sender, recipient, status and ERC-20 Transfer logs of a publicly reported transaction. Used to fix a pre-registered case's window from its diff --git a/src/cryptoguard/services/native_inbound.py b/src/cryptoguard/services/native_inbound.py new file mode 100644 index 0000000..08afe5a --- /dev/null +++ b/src/cryptoguard/services/native_inbound.py @@ -0,0 +1,219 @@ +"""Locate native ETH a plain-EOA wallet received in a block window, by balance bisection. + +Standard JSON-RPC has no per-address index for native transfers, but it has historical +balances. An externally owned account without code can lose ETH only through transactions +it signs (value plus fee). So between two of its own transactions its balance never falls, +and where it rises, ETH arrived. Bisecting ``eth_getBalance`` over each run of blocks +without an own transaction finds every block whose balance increased; that block's +transaction list then names the external senders (``tx.to == wallet``, nonzero value). + +Exact accounting per increase block: the successful external inbound values must sum to +the increase. Any remainder is **unattributed** (an internal transfer from contract +execution, a validator withdrawal, a fee-recipient credit): its sender is unknown without +traces, and it is recorded as such, never as a transfer from anyone. + +What this cannot see, stated in the coverage: + +- **zero-value native transactions** to the wallet move no balance. They are recorded only + when they happen to sit in a block that was read anyway. +- **blocks holding the wallet's own transactions**: their external inbound transactions + are read from the block, but internal credits there cannot be separated from the fee + without more reads, so ``unattributed`` is partial whenever the window holds own + transactions. +- **wallets with code** (contracts, EIP-7702 delegations): the balance can fall without + a wallet-signed transaction, so the method does not apply (``unsupported``). + +It never uses an outcome address: it is wallet-centric by construction. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field + +from cryptoguard.blockchain.provider import EthereumProvider +from cryptoguard.core.address import to_checksum_address +from cryptoguard.core.errors import InvalidAddressError, RpcError +from cryptoguard.core.hexutil import parse_hash32, parse_quantity + +DEFAULT_MAX_CHANGE_BLOCKS = 200 + + +@dataclass(frozen=True) +class NativeInbound: + transaction_hash: str + block_number: int + transaction_index: int + sender: str + value: int + succeeded: bool | None # receipt status; None when it could not be read + + +@dataclass(frozen=True) +class Unattributed: + block_number: int + value: int + + +@dataclass(frozen=True) +class NativeInboundDiscovery: + inbound: list[NativeInbound] + unattributed: list[Unattributed] + status: str # "complete", "truncated", "partial" or "unsupported" + unattributed_status: str + note: str | None + balance_reads: int + block_reads: int + receipt_reads: int + change_blocks: list[int] = field(default_factory=list) + + +async def locate_native_inbound( + provider: EthereumProvider, + wallet: str, + *, + from_block: int, + to_block: int, + own_tx_blocks: Sequence[int], + wallet_is_plain_eoa: bool | None, + max_change_blocks: int = DEFAULT_MAX_CHANGE_BLOCKS, +) -> NativeInboundDiscovery: + wallet = to_checksum_address(wallet) + if wallet_is_plain_eoa is not True: + return NativeInboundDiscovery( + [], + [], + "unsupported", + "unsupported", + "balance accounting needs a plain EOA (the wallet has code, or it is unknown)", + 0, + 0, + 0, + ) + balances: dict[int, int] = {} + counts = {"balance": 0, "block": 0, "receipt": 0} + + async def balance(block: int) -> int: + if block not in balances: + counts["balance"] += 1 + balances[block] = await provider.get_balance(wallet, block) + return balances[block] + + own = sorted({b for b in own_tx_blocks if from_block <= b <= to_block}) + runs: list[tuple[int, int]] = [] + start = from_block + for b in [*own, to_block + 1]: + if start <= b - 1: + runs.append((start, b - 1)) + start = b + 1 + increases: list[tuple[int, int]] = [] + anomalies: list[str] = [] + truncated = False + + async def bisect(lo: int, hi: int, before: int, after: int) -> None: + nonlocal truncated + if after == before or truncated: + return + if after < before: # impossible for a plain EOA without own transactions + anomalies.append(f"balance fell in blocks {lo}..{hi} without an own transaction") + return + if lo == hi: + if len(increases) >= max_change_blocks: + truncated = True + return + increases.append((lo, after - before)) + return + mid = (lo + hi) // 2 + at_mid = await balance(mid) + await bisect(lo, mid, before, at_mid) + await bisect(mid + 1, hi, at_mid, after) + + for lo, hi in runs: + await bisect(lo, hi, await balance(lo - 1), await balance(hi)) + + inbound: list[NativeInbound] = [] + unattributed: list[Unattributed] = [] + for block, delta in sorted(increases): + txs = await _inbound_txs(provider, wallet, block, counts) + paid = [t for t in txs if t.value > 0] + if sum(t.value for t in paid) != delta: # some may have reverted: read the receipts + paid = [await _with_status(provider, t, counts) for t in paid] + txs = [t for t in txs if t.value == 0] + paid + explained = sum(t.value for t in paid if t.succeeded is not False) + if explained > delta: + anomalies.append(f"block {block}: inbound transactions exceed the balance increase") + elif explained < delta: + unattributed.append(Unattributed(block, delta - explained)) + inbound.extend( + t if t.succeeded is not None or t.value == 0 else _ok(t) for t in txs + ) # an exact sum shows every nonzero one executed + for block in own: # external inbound beside the wallet's own transactions + for t in await _inbound_txs(provider, wallet, block, counts): + inbound.append(await _with_status(provider, t, counts) if t.value else t) + + status = "truncated" if truncated else "partial" if anomalies else "complete" + unattributed_status = status if status != "complete" else "partial" if own else "complete" + notes = anomalies + ( + [f"{len(own)} block(s) with own transactions: internal credits there not separated"] + if own + else [] + ) + return NativeInboundDiscovery( + sorted(inbound, key=lambda t: (t.block_number, t.transaction_index)), + unattributed, + status, + unattributed_status, + "; ".join(notes) or None, + counts["balance"], + counts["block"], + counts["receipt"], + [b for b, _ in sorted(increases)], + ) + + +def _ok(t: NativeInbound) -> NativeInbound: + return NativeInbound( + t.transaction_hash, t.block_number, t.transaction_index, t.sender, t.value, True + ) + + +async def _inbound_txs( + provider: EthereumProvider, wallet: str, block: int, counts: dict[str, int] +) -> list[NativeInbound]: + counts["block"] += 1 + out: list[NativeInbound] = [] + for tx in await provider.get_block_transactions(block): + try: + to, sender = tx.get("to"), tx.get("from") + if not to or str(to).lower() != wallet.lower() or not sender: + continue + if str(sender).lower() == wallet.lower(): + continue # the wallet's own (self-)transaction: not inbound + out.append( + NativeInbound( + transaction_hash=parse_hash32(tx.get("hash")), + block_number=block, + transaction_index=parse_quantity(tx.get("transactionIndex")), + sender=to_checksum_address(sender), + value=parse_quantity(tx.get("value")), + succeeded=None, + ) + ) + except (ValueError, KeyError, InvalidAddressError): + continue # a malformed entry is skipped, never guessed + return out + + +async def _with_status( + provider: EthereumProvider, t: NativeInbound, counts: dict[str, int] +) -> NativeInbound: + counts["receipt"] += 1 + try: + receipt = await provider.get_transaction_receipt(t.transaction_hash) + except RpcError: + return t + status = (receipt or {}).get("status") + ok = True if status == "0x1" else False if status == "0x0" else None + return NativeInbound( + t.transaction_hash, t.block_number, t.transaction_index, t.sender, t.value, ok + ) diff --git a/src/cryptoguard/services/transfers.py b/src/cryptoguard/services/transfers.py index 4081e55..e163b62 100644 --- a/src/cryptoguard/services/transfers.py +++ b/src/cryptoguard/services/transfers.py @@ -34,6 +34,8 @@ class TransferDiscovery: log_counts: dict[str, int] sender_lookups: int sender_lookups_skipped: int + # ERC-721-shaped Transfer logs (4 topics) the scans returned; kept for ``observation/2`` + erc721_logs: list[dict[str, object]] = dataclasses.field(default_factory=list) async def _tx_sender(provider: EthereumProvider, tx_hash: str) -> str | None: @@ -85,6 +87,7 @@ async def discover_transfers( counts = dict.fromkeys((s.value for s in LogShape), 0) seen: set[tuple[str, str]] = set() events: list[TransferEvent] = [] + nft_logs: list[dict[str, object]] = [] for log in [*outgoing.logs, *incoming.logs]: shape, event = classify_transfer_log(log) identity = (str(log.get("blockHash")), str(log.get("logIndex"))) @@ -92,6 +95,8 @@ async def discover_transfers( continue seen.add(identity) counts[shape.value] += 1 + if shape is LogShape.ERC721_SHAPED: + nft_logs.append(log) if event is not None and owner in (event.sender, event.recipient): events.append(event) events.sort(key=lambda e: e.position) @@ -119,4 +124,5 @@ async def discover_transfers( log_counts=counts, sender_lookups=len(looked_up), sender_lookups_skipped=len(outgoing_txs) - len(looked_up), + erc721_logs=nft_logs, ) diff --git a/tests/fakenode.py b/tests/fakenode.py index 723a8d9..50810e0 100644 --- a/tests/fakenode.py +++ b/tests/fakenode.py @@ -94,6 +94,11 @@ def __init__(self, *, chain_id: int = 1, head: int = 20_000_000) -> None: self.created_at: dict[str, int] = {} # contract -> creation block (code absent before) self.created_by_tx: dict[str, str] = {} # creation tx hash -> contract address self.reverted: set[str] = set() # tx hashes whose receipt reports status 0 (no effect) + # Opt-in historical balances: eth_getBalance(address, block) = the set balance plus + # successful native transactions to it, minus those from it, plus ``credits`` + # (internal transfers, withdrawals) up to that block. No gas is charged. + self.balance_history = False + self.credits: list[tuple[int, str, int]] = [] # (block, address, value) def plant( self, signer: str, token: str, transfers: list[tuple[str, str, int]], *, block: int @@ -115,7 +120,9 @@ def deploy(self, deployer: str, contract: str, *, block: int) -> str: self.code.setdefault(contract.lower(), bytes.fromhex("6080604052")) return tx_hash - def send_native(self, sender: str, to: str, value: int, *, block: int) -> str: + def send_native( + self, sender: str, to: str, value: int, *, block: int, tx_index: int = 0 + ) -> str: """Record a transaction signed by ``sender`` (nonces assigned in order).""" sender = sender.lower() nonce = sum(1 for t in self.sent_txs if t["from"] == sender) @@ -129,12 +136,24 @@ def send_native(self, sender: str, to: str, value: int, *, block: int) -> str: "nonce": hex(nonce), "blockNumber": hex(block), "blockHash": block_hash(block, self.fork), - "transactionIndex": "0x0", + "transactionIndex": hex(tx_index), } ) self.tx_senders[tx_hash] = sender return tx_hash + def _balance_at(self, address: str, number: int) -> int: + total = self.balances.get(address, 0) + for tx in self.sent_txs: + if int(tx["blockNumber"], 16) > number or tx["hash"] in self.reverted: + continue + value = int(tx["value"], 16) + if (tx["to"] or "") == address: + total += value + if tx["from"] == address: + total -= value + return total + sum(v for b, a, v in self.credits if a == address and b <= number) + # -- helpers --------------------------------------------------------------------------- def set_account(self, address: str, *, balance: int = 0, code: bytes = b"") -> None: self.balances[address.lower()] = balance @@ -278,6 +297,8 @@ def _dispatch(self, method: str, params: list[Any]) -> Any: ) ) if method == "eth_getBalance": + if self.balance_history and params[1] != "latest": + return hex(self._balance_at(params[0].lower(), int(params[1], 16))) return hex(self.balances.get(params[0].lower(), 0)) if method == "eth_getCode": address = params[0].lower() diff --git a/tests/integration/test_observation_v2.py b/tests/integration/test_observation_v2.py new file mode 100644 index 0000000..6de7af9 --- /dev/null +++ b/tests/integration/test_observation_v2.py @@ -0,0 +1,208 @@ +"""``observation/2`` recording on a mock node (protocol 12.4): native ETH received by +balance bisection, ERC-721-shaped transfers kept, per-category coverage, and an end-to-end +replay comparing the original recorder with the extended one. Mock transports only.""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any + +from cryptoguard.blockchain.abi import TRANSFER_TOPIC, address_topic +from cryptoguard.blockchain.budget import RequestLedger, budgeted_transport +from cryptoguard.blockchain.provider import RpcEthereumProvider +from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy +from cryptoguard.detectors.poisoning import PoisoningConfig +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.replay.engine import Visibility, detector_outputs +from cryptoguard.replay.models import ReplayFixture +from cryptoguard.replay.record import record_window +from cryptoguard.services.native_inbound import locate_native_inbound +from tests.fakenode import FakeNode, block_hash + +WALLET = "0x" + "c" * 40 +REF = "0xabcde" + "1" * 30 + "54321" +DUST = "0xabcde" + "9" * 30 + "54321" # native-dust lookalike of REF +FAKE_LOOK = "0xabcd" + "8" * 32 + "4321" # fake-token lookalike of REF +NFT_LOOK = "0xabc" + "7" * 33 + "4321" # ERC-721 lookalike of REF +STRANGER = "0x" + "5" * 40 +ATTACKER = "0x" + "a1" * 20 +TOKEN = "0x" + "e" * 40 +NFT = "0x" + "d" * 40 +START, END = 1_000, 1_400 + + +async def _no_sleep(_: float) -> None: + return None + + +def _provider(node: FakeNode, tmp: Path) -> tuple[RpcEthereumProvider, RequestLedger]: + ledger = RequestLedger(tmp / "ledger.json", cap=5_000) + client = JsonRpcClient( + "https://rpc.example.invalid", + retry=RetryPolicy(max_retries=0, base_delay=0.0, max_delay=0.0), + transport=budgeted_transport(ledger, node.transport()), + sleep=_no_sleep, + rng=random.Random(0), + ) + provider = RpcEthereumProvider( + client, expected_chain_id=1, endpoint_display="test", max_log_block_range=1000 + ) + return provider, ledger + + +def _nft_log(node: FakeNode, sender: str, recipient: str, token_id: int, block: int) -> None: + tx = "0x" + f"{block:064x}" + node.logs.append( + { + "address": NFT, + "topics": [ + TRANSFER_TOPIC, + address_topic(sender), + address_topic(recipient), + "0x" + f"{token_id:064x}", + ], + "data": "0x", + "blockNumber": hex(block), + "blockHash": block_hash(block), + "transactionHash": tx, + "transactionIndex": "0x2", + "logIndex": "0x0", + "removed": False, + } + ) + node.tx_senders[tx] = ATTACKER + + +def _incident() -> FakeNode: + """A victim pays REF, then is poisoned three ways; the theft is not in the window.""" + node = FakeNode(head=2_000) + node.balance_history = True + node.set_account(WALLET, balance=10**20) + node.add_token(TOKEN) + node.send_native(WALLET, REF, 10**18, block=1_100) # reference use (wallet-signed) + node.send_native(DUST, WALLET, 1_000, block=1_150, tx_index=3) # native dust planting + node.add_transfer_log(TOKEN, FAKE_LOOK, WALLET, 7, block=1_160, signer=ATTACKER) + _nft_log(node, NFT_LOOK, WALLET, 42, block=1_170) + node.credits.append((1_180, WALLET.lower(), 5_000)) # internal credit: no sender + reverted = node.send_native(STRANGER, WALLET, 10**17, block=1_190) + node.reverted.add(reverted) # moved nothing + node.send_native(STRANGER, WALLET, 0, block=1_100, tx_index=4) # 0 ETH beside own tx + node.send_native(STRANGER, WALLET, 0, block=1_250) # 0 ETH alone: invisible to balances + return node + + +async def _record(node: FakeNode, tmp: Path, observation: int) -> tuple[ReplayFixture, int]: + tmp.mkdir(parents=True, exist_ok=True) + provider, ledger = _provider(node, tmp) + try: + fx = await record_window( + provider, + case_id="synthetic-e2e", + chain_id=1, + wallet=WALLET, + start=START, + end=END, + chunk_blocks=100, + observation=observation, + ) + finally: + await provider.aclose() + return fx, ledger.used() + + +async def test_balance_bisection_finds_native_inbound_and_states_its_limits( + tmp_path: Path, +) -> None: + node = _incident() + provider, ledger = _provider(node, tmp_path) + try: + found = await locate_native_inbound( + provider, + WALLET, + from_block=START, + to_block=END, + own_tx_blocks=[1_100], + wallet_is_plain_eoa=True, + ) + finally: + await provider.aclose() + by_block = {(n.block_number, n.sender.lower(), n.value, n.succeeded) for n in found.inbound} + assert by_block == { + (1_150, DUST, 1_000, True), # found by bisection, sender from the block + (1_100, STRANGER, 0, None), # 0 ETH, seen only because the own-tx block was read + } + assert [(u.block_number, u.value) for u in found.unattributed] == [(1_180, 5_000)] + assert found.change_blocks == [1_150, 1_180] # the reverted 0.1 ETH changed nothing + assert (found.status, found.unattributed_status) == ("complete", "partial") + reads = found.balance_reads + found.block_reads + found.receipt_reads + assert reads + 1 == ledger.used() # plus the provider's one chain-id check + + +async def test_balance_bisection_does_not_apply_to_wallets_with_code(tmp_path: Path) -> None: + provider, ledger = _provider(_incident(), tmp_path) + try: + found = await locate_native_inbound( + provider, + WALLET, + from_block=START, + to_block=END, + own_tx_blocks=[], + wallet_is_plain_eoa=False, + ) + finally: + await provider.aclose() + assert (found.status, found.inbound, ledger.used()) == ("unsupported", [], 0) + + +async def test_end_to_end_original_versus_extended_observation(tmp_path: Path) -> None: + node = _incident() + v1, used1 = await _record(node, tmp_path / "a", 1) + v2, used2 = await _record(node, tmp_path / "b", 2) + + # observation/1 is exactly what every existing fixture holds + assert v1.observation is None and v1.native_inbound is None + assert b'"native_inbound"' not in v1.canonical_bytes() + assert used2 > used1 # the extension costs requests, all through the ledger + # observation/2 states what it saw and what it could not + cov = v2.observation + assert cov is not None + assert cov.status("native_inbound_external") == "complete" + assert cov.status("native_inbound_zero_value") == "partial" + assert cov.status("native_inbound_unattributed") == "partial" # own tx in the window + assert cov.status("internal_value_transfers") == "unsupported" + assert cov.status("erc721_transfer_logs") == "complete" + assert [(n.token_id, n.sender.lower()) for n in v2.nft_transfers or []] == [("42", NFT_LOOK)] + assert v2.discarded_log_counts == {"erc721_shaped": 1, "removed": 0, "malformed": 0} + # same inputs to the production detector: its findings do not change + cfg = PoisoningConfig() + full = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS + assert detector_outputs(v1, END, full, cfg) == detector_outputs(v2, END, full, cfg) + + cut = (END + 1, 0) + c0 = cd.discover(v2, cutoff=cut, variant="C0") + c1_old = cd.discover(v1, cutoff=cut, variant="C1") + c1 = cd.discover(v2, cutoff=cut, variant="C1") + expected_c0 = {FAKE_LOOK} # oracle: only the ERC-20 planting is visible to C0 + assert c0.lookalikes == c1_old.lookalikes == expected_c0 + # C1 applies C0's rules unchanged: zero_value_in fires on the 0 ETH stranger seen in the + # own-transaction block, which is not a lookalike (candidate volume, not evidence) + assert c1.lookalikes == {FAKE_LOOK, DUST, NFT_LOOK, STRANGER} + assert cd.compare(c0, c1)["added"] == sorted([DUST, NFT_LOOK, STRANGER]) + by = {c.lookalike: c for c in c1.candidates} + assert (by[STRANGER].methods, by[STRANGER].imitated) == (("zero_value_in",), None) + assert (by[DUST].methods, by[DUST].imitated) == (("lookalike_in",), REF) + assert c1.unattributed_inbound_blocks == [1_180] + # serialization is reproducible: same bytes give the same fixture and hash + again = ReplayFixture.model_validate_json(v2.canonical_bytes()) + assert again.sha256() == v2.sha256() + + +async def test_a_dust_planting_after_the_cutoff_is_not_seen(tmp_path: Path) -> None: + v2, _ = await _record(_incident(), tmp_path, 2) + assert DUST not in cd.discover(v2, cutoff=(1_150, 3), variant="C1").lookalikes + assert DUST in cd.discover(v2, cutoff=(1_150, 4), variant="C1").lookalikes + + +def _unused(*_: Any) -> None: # keep imports explicit for readers + return None diff --git a/tests/test_ml_candidate_discovery.py b/tests/test_ml_candidate_discovery.py new file mode 100644 index 0000000..9c9a41a --- /dev/null +++ b/tests/test_ml_candidate_discovery.py @@ -0,0 +1,387 @@ +"""Protocol 12.4, population P1: synthetic mechanism cases A-L for shadow candidate +discovery. Every expected output is written out by hand from the case's definition, not +computed by the code under test. Synthetic: software correctness only, never a rate.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +import pytest + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.replay.models import ( + RecordedNativeInbound, + RecordedTransaction, + RecordedTransfer, + ReplayFixture, + UnattributedInbound, +) +from cryptoguard.replay.observation import ( + OBSERVATION_V2, + CategoryCoverage, + ObservationCoverage, + legacy_coverage, +) + +VICTIM = "0x" + "c" * 40 +REF = "0xabcde" + "1" * 30 + "54321" # the recipient the victim paid +LOOK_NATIVE = "0xabcde" + "9" * 30 + "54321" # prefix 5 + suffix 5 with REF +LOOK_TOKEN = "0xabcd" + "8" * 32 + "4321" # prefix 4 + suffix 4 with REF +LOOK_2 = "0xabc" + "7" * 33 + "4321" # prefix 3 + suffix 4 +SHORT = "0xab" + "6" * 36 + "21" # prefix 2 + suffix 2: below MIN_AFFIX 6 +ATTACKER = "0x" + "a1" * 20 +OTHER_SIGNER = "0x" + "b2" * 20 +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" # reviewed stablecoin +FAKE_TOKEN = "0x" + "f" * 40 # any unreviewed contract; its symbol is never consulted + + +def _tx(n: int) -> str: + return "0x" + f"{n:064x}" + + +def transfer( + sender: str, + recipient: str, + value: int, + *, + block: int, + signer: str | None, + token: str = USDT, + tx: int = 0, + tx_index: int = 0, + log: int = 0, +) -> RecordedTransfer: + return RecordedTransfer( + token=token, + sender=sender, + recipient=recipient, + value=str(value), + block_number=block, + block_hash=_tx(block), + transaction_hash=_tx(tx or block * 10 + log), + transaction_index=tx_index, + log_index=log, + tx_sender=signer, + ) + + +def native_in( + sender: str, + value: int, + *, + block: int, + succeeded: bool | None = True, + tx_index: int = 0, + tx: int = 0, +) -> RecordedNativeInbound: + return RecordedNativeInbound( + transaction_hash=_tx(tx or block * 10 + 7), + block_number=block, + transaction_index=tx_index, + sender=sender, + value=str(value), + succeeded=succeeded, + ) + + +def full_coverage(**override: str) -> ObservationCoverage: + """observation/2 coverage: every collectable category complete, by construction.""" + cats = { + k: CategoryCoverage(status="complete") + for k in ( + "erc20_transfer_logs", + "erc20_outgoing_signers", + "erc721_transfer_logs", + "malformed_transfer_logs", + "wallet_signed_transactions", + "native_inbound_external", + "native_inbound_unattributed", + ) + } + cats["erc1155_transfer_logs"] = CategoryCoverage(status="not_collected") + cats["native_inbound_zero_value"] = CategoryCoverage(status="partial") + cats["internal_value_transfers"] = CategoryCoverage(status="unsupported") + for k, v in override.items(): + cats[k] = CategoryCoverage(status=v) # type: ignore[arg-type] + return ObservationCoverage(schema_version=OBSERVATION_V2, categories=cats) + + +def fixture( + transfers: list[RecordedTransfer] | None = None, + *, + native: list[RecordedNativeInbound] | None = None, + unattributed: list[UnattributedInbound] | None = None, + v2: bool = True, + reference: bool = True, + complete: bool = True, + wallet: str = VICTIM, + **coverage: str, +) -> ReplayFixture: + ref = [transfer(wallet, REF, 1_000_000, block=1100, signer=wallet, log=1)] if reference else [] + return ReplayFixture( + case_id="synthetic", + chain_id=1, + wallet=wallet, + from_block=1000, + to_block=2000, + recorded_at=datetime(2026, 11, 4, tzinfo=UTC), + recorded_with="synthetic", + rpc_requests=0, + transfer_scan_complete=complete, + sender_lookups_skipped=0, + method=["synthetic"], + wallet_code_hex={"1000": "0x", "1999": "0x"}, + block_timestamps={}, + transfers=ref + (transfers or []), + wallet_transactions=[], + observation=( + full_coverage(**({} if complete else {"erc20_transfer_logs": "partial"}), **coverage) + if v2 + else None + ), + native_inbound=(native or []) if v2 else None, + unattributed_inbound=(unattributed or []) if v2 else None, + nft_transfers=[] if v2 else None, + ) + + +END = (2001, 0) # cutoff after the whole window + + +def found(fx: ReplayFixture, variant: cd.Variant = "C1", cutoff: tuple[int, int] = END) -> Any: + return cd.discover(fx, cutoff=cutoff, variant=variant) + + +# --- Case A: native ETH dust poisoning ----------------------------------------------------- + + +def test_case_a_native_dust_is_invisible_to_c0_and_found_by_c1_only_after_planting() -> None: + fx = fixture(native=[native_in(LOOK_NATIVE, 1_000, block=1200)]) + assert found(fx, "C0").lookalikes == set() + [c] = found(fx).candidates + assert (c.lookalike, c.imitated, c.methods, c.kind) == ( + LOOK_NATIVE, + REF, + ("lookalike_in",), + "native", + ) + assert c.affix == (5, 5) + assert found(fx, cutoff=(1200, 0)).lookalikes == set() # not yet observable + + +# --- Case B: spoofed transferFrom --------------------------------------------------------- + + +def test_case_b_spoofed_transfer_is_flagged_and_never_becomes_a_reference() -> None: + fx = fixture([transfer(VICTIM, LOOK_TOKEN, 0, block=1300, signer=ATTACKER)]) + for variant in ("C0", "C1"): + [c] = found(fx, variant).candidates # type: ignore[arg-type] + assert (c.lookalike, "spoofed_out" in c.methods) == (LOOK_TOKEN, True) + screen = cd.screen_payment(fx, recipient=LOOK_TOKEN, cutoff=END) + assert (screen.flagged, screen.imitated) == (True, REF) # not "a reference the wallet chose" + + +# --- Case C: fake-token planting ---------------------------------------------------------- + + +def test_case_c_fake_token_is_untrusted_by_contract_not_by_symbol() -> None: + fx = fixture( + [transfer(LOOK_TOKEN, VICTIM, 5 * 10**18, block=1300, signer=ATTACKER, token=FAKE_TOKEN)] + ) + [c] = found(fx).candidates + assert c.methods == ("lookalike_in", "untrusted_token_in") + + +# --- Case D: zero-value token transfer ---------------------------------------------------- + + +def test_case_d_zero_value_transfer_from_a_lookalike() -> None: + fx = fixture([transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER)]) + [c0] = found(fx, "C0").candidates + [c1] = found(fx).candidates + assert c0.methods == c1.methods == ("zero_value_in", "lookalike_in") + + +# --- Case E: missing history -------------------------------------------------------------- + + +def test_case_e_missing_history_abstains_instead_of_claiming_no_references() -> None: + fx = fixture( + [transfer(LOOK_TOKEN, VICTIM, 5 * 10**6, block=1300, signer=ATTACKER)], reference=False + ) + res = found(fx, "C2") + assert res.lookalikes == set() + assert res.abstain is not None and "not evidence of no earlier recipients" in res.abstain + assert cd.screen_payment(fx, recipient=LOOK_TOKEN, cutoff=END).flagged is None + partial = fixture(complete=False) + assert found(partial, "C2").abstain is not None + assert "insufficient history" in str(found(partial, "C2").abstain) + assert cd.screen_payment(partial, recipient=LOOK_TOKEN, cutoff=END).flagged is None + + +# --- Case F: multiple lookalikes ---------------------------------------------------------- + + +def test_case_f_competing_lookalikes_keep_their_identity_and_order() -> None: + fx = fixture( + [ + transfer(LOOK_2, VICTIM, 0, block=1250, signer=OTHER_SIGNER), + transfer(LOOK_TOKEN, VICTIM, 0, block=1200, signer=ATTACKER), + ] + ) + res = found(fx) + assert [c.lookalike for c in res.candidates] == [LOOK_TOKEN, LOOK_2] # chain order + assert {c.imitated for c in res.candidates} == {REF} + + +# --- Case G: reverted transaction --------------------------------------------------------- + + +def test_case_g_reverted_native_transfer_is_not_evidence() -> None: + fx = fixture(native=[native_in(LOOK_NATIVE, 1_000, block=1200, succeeded=False)]) + assert found(fx).lookalikes == set() + + +# --- Case H: contract-mediated value ------------------------------------------------------ + + +def test_case_h_unattributed_inbound_is_reported_but_names_no_one() -> None: + fx = fixture(unattributed=[UnattributedInbound(block_number=1400, value="5")]) + res = found(fx) + assert res.candidates == [] + assert res.unattributed_inbound_blocks == [1400] + assert res.coverage["internal_value_transfers"] == "unsupported" + + +# --- Case I: same-block ordering ---------------------------------------------------------- + + +def test_case_i_a_later_transaction_in_the_cutoff_block_is_not_seen() -> None: + fx = fixture( + [ + transfer(LOOK_TOKEN, VICTIM, 0, block=1500, signer=ATTACKER, tx_index=7), + transfer(LOOK_2, VICTIM, 0, block=1500, signer=ATTACKER, tx_index=3, log=2), + ] + ) + assert found(fx, cutoff=(1500, 5)).lookalikes == {LOOK_2} + assert found(fx, cutoff=(1500, 0)).lookalikes == set() + + +# --- Case J: public token contract reuse -------------------------------------------------- + + +def test_case_j_a_shared_token_contract_links_nothing_a_shared_signer_does() -> None: + w2 = "0x" + "d" * 40 + + def one(wallet: str, signer: str) -> tuple[str, ReplayFixture, Any]: + fx = fixture([transfer(LOOK_TOKEN, wallet, 0, block=1300, signer=signer)], wallet=wallet) + return wallet, fx, found(fx) + + assert cd.signer_links([one(VICTIM, ATTACKER), one(w2, OTHER_SIGNER)]) == [] + assert cd.signer_links([one(VICTIM, ATTACKER), one(w2, ATTACKER)]) == [(VICTIM, w2, ATTACKER)] + + +# --- Case K: no poisoning ----------------------------------------------------------------- + + +def test_case_k_a_short_shared_affix_is_not_a_candidate() -> None: + fx = fixture(native=[native_in(SHORT, 5 * 10**18, block=1200)]) + assert found(fx).candidates == [] + assert cd.screen_payment(fx, recipient=SHORT, cutoff=END).flagged is False + + +# --- Case L: duplicate ingestion ---------------------------------------------------------- + + +def test_case_l_the_same_event_from_two_sources_counts_once() -> None: + dup = native_in(LOOK_NATIVE, 1_000, block=1200) + fx = fixture(native=[dup, dup]) + assert len(found(fx).candidates) == 1 + log = transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER) + assert len(cd.observations(fixture([log, log]))) == 2 # the reference and one planting + + +# --- completeness and point-in-time invariants -------------------------------------------- + + +def test_legacy_fixtures_declare_native_and_nft_as_not_collected() -> None: + cov = legacy_coverage(fixture(v2=False)) + assert cov.status("erc20_transfer_logs") == "complete" + assert cov.status("native_inbound_external") == "not_collected" + assert cov.status("erc721_transfer_logs") == "not_collected" + assert cov.status("internal_value_transfers") == "unsupported" + assert cov.status("not a category") == "unknown" + + +def test_scoped_history_never_reports_unobserved_inbound_as_zero() -> None: + legacy = cd.scoped_history(fixture(v2=False), recipient=LOOK_TOKEN, block=1900, tx_index=0) + assert legacy["prior_interactions_with_recipient"] is None # /1 would say 0 + assert legacy["inbound_scope_complete"] is False + assert legacy["distinct_prior_recipients"] == 1 # outgoing scope is complete + v2 = cd.scoped_history(fixture(), recipient=LOOK_TOKEN, block=1900, tx_index=0) + assert v2["prior_interactions_with_recipient"] == 0 # a real zero in the declared scope + assert v2["inbound_scope"] == cd.INBOUND_SCOPE + + +def test_later_events_do_not_change_discovery_at_an_earlier_cutoff() -> None: + base = [transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER)] + later = [ + transfer(LOOK_2, VICTIM, 0, block=1700, signer=ATTACKER), # a later planting + transfer(VICTIM, LOOK_TOKEN, 9 * 10**6, block=1800, signer=VICTIM), # the theft + ] + cut = (1600, 0) + a = found(fixture(base), cutoff=cut) + b = found(fixture(base + later, native=[native_in(LOOK_NATIVE, 5, block=1650)]), cutoff=cut) + assert a.candidates == b.candidates + + +def test_record_order_does_not_change_the_output() -> None: + rows = [ + transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER), + transfer(LOOK_2, VICTIM, 0, block=1250, signer=OTHER_SIGNER), + ] + assert found(fixture(rows)).candidates == found(fixture(rows[::-1])).candidates + + +def test_c1_on_a_legacy_fixture_equals_c0() -> None: + fx = fixture( + [ + transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER), + transfer(VICTIM, LOOK_2, 0, block=1400, signer=ATTACKER), + ], + v2=False, + ) + assert cd.compare(found(fx, "C0"), found(fx, "C1")) == { + "added": [], + "removed": [], + "kept": sorted([LOOK_TOKEN, LOOK_2]), + } + + +@pytest.mark.parametrize("variant", ["C0", "C1", "C2"]) +def test_discovery_takes_no_outcome_input(variant: cd.Variant) -> None: + import inspect + + params = set(inspect.signature(cd.discover).parameters) + assert params == {"fixture", "cutoff", "variant"} # no victim label, no theft recipient + assert found(fixture(), variant).version == cd.DISCOVERY_VERSION + + +def test_a_reverted_own_send_still_counts_as_a_reference() -> None: + fx = fixture(reference=False).model_copy( + update={ + "wallet_transactions": [ + RecordedTransaction( + transaction_hash=_tx(1), + block_number=1100, + transaction_index=0, + nonce=0, + to=REF, + value=str(10**18), + succeeded=False, + ) + ] + } + ) + assert cd.screen_payment(fx, recipient=LOOK_NATIVE, cutoff=END).flagged is True From 53ddd9539eda6efc11fa8f92ff4d0e6b15ba30c2 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 4 Nov 2026 18:06:56 +0300 Subject: [PATCH 61/92] docs(ml): Phase 12.4 report - observation completeness and candidate discovery (no RPC) - ML_OBSERVATION_COMPLETENESS.md: audit of the blockchain-to-warning path; the Stage 2a miss reconstructed (cause not identifiable from local data; 6 event classes unobserved or discarded by observation/1); results of H1-H6 (H5 not evaluated, as pre-declared); queries that would settle the miss (not issued). - observation-study: evaluate the H3 feature comparison at each query's own in-window position (the first run queried past the window, where wallet-history/1 already abstains, and undercounted H3). - Tests: widened frozen-item rule catches native and NFT parties. - 893 passed, 4 deselected; ruff and mypy clean. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 ++ ML_OBSERVATION_COMPLETENESS.md | 288 +++++++++++++++++++++++ README.md | 2 +- src/cryptoguard/ml/observation_study.py | 21 +- tests/integration/test_observation_v2.py | 5 +- tests/test_ml_candidate_discovery.py | 26 +- 6 files changed, 348 insertions(+), 12 deletions(-) create mode 100644 ML_OBSERVATION_COMPLETENESS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 6baeaf8..ed2c4aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,24 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Observation completeness and candidate discovery, Phase 12.4 (no RPC requests) +- **Protocol 12.4** (`docs/ml/protocol-12.4.md`) was frozen before the code and the study. +- **Audit:** `observation/1` never observed inbound native ETH, zero-value native transactions, internal transfers or ERC-1155. It also fetched ERC-721-shaped and malformed `Transfer` logs and discarded them, without keeping their counts. +- **Added `observation/2`** (opt-in: `replay record --observation 2`): + - native ETH received, by balance bisection; + - unattributed credits; + - ERC-721 records and malformed-log counts; + - per-category coverage (`replay/observation.py`). + + Existing fixtures keep their bytes and hashes. +- **Added shadow `poisoning-candidate-discovery/1`** (`ml/candidate_discovery.py`): + - C0 is frozen; + - C1 applies C0's rules to every observed class; + - C2 adds abstention and a payment-time screen; + - `wallet-history/2-scoped` never reports unobserved inbound as zero (109 false zeros under `/1`; no published number used them). +- **Study:** `cryptoguard ml observation-study`. Report: `ML_OBSERVATION_COMPLETENESS.md`. +- **Unchanged:** the production detector and its findings. + ### Incident recording, Stage 2a (1,433 RPC requests of an approved 6,000) - **Case 1, `scamsniffer-763k-2025-02-20`:** - resolved on chain by the frozen rule, recorded, and frozen by test; diff --git a/ML_OBSERVATION_COMPLETENESS.md b/ML_OBSERVATION_COMPLETENESS.md new file mode 100644 index 0000000..ffd7e9e --- /dev/null +++ b/ML_OBSERVATION_COMPLETENESS.md @@ -0,0 +1,288 @@ +# Observation completeness and candidate discovery (Phase 12.4) + +| Item | Value | +|---|---| +| Protocol (frozen before the code and the study) | [`docs/ml/protocol-12.4.md`](docs/ml/protocol-12.4.md), `3a79b74` | +| Implementation (committed before the study ran) | `3917957` | +| Study output (git-ignored) | `data/ml/research/phase12.4/observation-study.json` (`cryptoguard ml observation-study`) | +| New RPC requests / downloads | **0** / none | + +## 1. Executive summary + +**The miss.** The Stage 2a miss (`scamsniffer-763k-2025-02-20`) **cannot be explained from local evidence**. The paid address occurs in no local artifact except the theft records themselves. + +**What the audit confirmed.** The recorder, `observation/1`, does not observe several event classes: +- inbound native ETH; +- zero-value native transactions; +- internal value transfers; +- ERC-1155 events. + +It also fetches ERC-721-shaped and malformed `Transfer` logs, then discards them **without keeping even their counts**. So the miss is compatible with several mechanisms, and native-ETH dust remains one hypothesis among them. Two RPC requests would discriminate between them; see §31. They were not made. + +**What changed:** +- **`observation/2` (opt-in):** it records the following: + - native ETH received, found by balance bisection with exact per-block accounting; + - ERC-721-shaped transfers; + - malformed-log counts; + - completeness for each event category. + + An unobserved category is `not_collected` or `unsupported`, never zero. Every existing fixture keeps its bytes and hash. +- **Shadow discovery (`poisoning-candidate-discovery/1`):** + - **C1** is C0's own rules applied to every observed class. On synthetic cases it recovers native-dust and ERC-721 lookalikes that C0 cannot see. + - **C2** adds abstention and a **payment-time screen**. The screen flags both known thefts. That is a *development-case regression* result, not validation, because those cases motivated it. It flags 0 of 12 screened unlabelled payments in the background windows. +- **A latent defect, fixed in a versioned path.** `wallet-history/1` reports inbound counts as observed zeros, although native inbound and ERC-721 were never collected: 109 values across 29 in-window queries. No published number used those counts. + +**Classification:** confirmed observation improvement, verified on synthetic and mock data only. Also a limited mechanism improvement. For the real miss, the result is data-limited. H5 (ML contribution) was not evaluated, as pre-declared. + +## 2. Repository baseline + +| Item | Value | +|---|---| +| Initial HEAD | `72cfaf3`, clean, equal to `origin/feature/ml-pipeline` | +| CI on `72cfaf3` | 9 of 9 jobs passed | +| Production detector | `address-poisoning` 1.0.0, unchanged | +| Frozen generator (C0) | `candidates/2`, unchanged | + +## 3. Motivating failure, and 4. its exact chronology + +Source: the recorded fixture `67e44177…`. Times are block-header timestamps (UTC, 2025-02-20). + +| Block (tx index) | Time | Event | Signer | Recorded by `/1` | C0 candidate | +|---|---|---|---|---|---| +| 21,890,495 (65) | 22:19:23 | Victim sends token `0x44ff…` to the reference `0x80404f3e…793375` | victim | yes | (reference) | +| 21,890,508 | — | Victim sends 600 ETH to the reference | victim | yes (wallet transaction) | (reference) | +| 21,890,558 (112) | 22:32:23 | Fake-token `0x29f7…` Transfer "from victim" to `0x8045233d…793375` | `0x7730…Ba3f` | yes | yes (`spoofed_out`) | +| 21,890,871 (72) | 23:35:23 | Fake-token `0x6695…` Transfer "from victim" to `0x804041c8…1f3375` | `0x0C0b…2bb9` | yes | yes (`spoofed_out`) | +| 21,890,874 | — | `0x9008d19f…` (a swap settlement contract) credits the victim with 96,517… base units of `0x44ff…` | — | yes | no | +| 21,890,897 (96) | 23:40:35 | **Theft**: victim sends `0x44ff…` to `0x804051b0…793375`. This is the paid address's first appearance. | victim | yes | — | +| after the window | — | 5 further transfers to the same address (from `found.json`) | victim | not in the window | — | + +**Where the paid address appears.** A search of the whole repository and `data/` finds it in exactly two places: +- the theft transfer in the fixture; +- the six theft receipts in `data/ml/research/stage2a/…/found.json`. + +**Classification of the miss: unknown.** Each possible cause, and its status: +- **Confirmed recorder omissions** that could explain it: + - inbound native ETH, nonzero or zero; + - ERC-721 or ERC-1155 plantings; + - internal transfers. +- **Not excluded:** + - an off-wallet channel, such as the reference's own page, another wallet of the victim, or an address book; + - a planting before the window. That is unlikely here, because the reference use itself lies 402 blocks before the theft. +- **Source attribution:** the roles came from Etherscan's filter semantics, and the chain did not contradict them. + +**Counterfactual (synthetic only).** In synthetic case A, a native-dust lookalike planted after a reference payment is invisible to C0 and found by C1. That shows the new support works. It does **not** show that this real case was a dust planting. + +## 5. Observation pipeline audit + +`eth_getLogs` and `scan_logs` (bounded, newest first, chunks split on refusal) +→ `classify_transfer_log` (3 topics plus 32 bytes is ERC-20; 4 topics and no data is ERC-721-*shaped*; anything else is malformed) +→ `discover_transfers` (both directions; outgoing signer by `eth_getTransactionByHash`; dedup by block hash and log index) +→ `locate_wallet_transactions` (nonce bisection, with receipt status for transactions carrying ETH) +→ `ReplayFixture` +→ `detector_outputs` (ERC-20 events plus wallet-signed native sends, at or before the cutoff; no manifest) +→ `detect_poisoning`. + +The research side runs alongside: `ml.history.events_from_fixture` → `history_features` (`wallet-history/1`) and `ml.candidates.generate` (C0) → `warning_rank` (OP1). + +| Defect or limitation | Where | Status | +|---|---|---| +| ERC-721-shaped and malformed logs were fetched, discarded, and their counts not persisted | `discover_transfers`, `record_window` | **fixed** in `observation/2`: records and counts kept | +| No inbound native ETH (no per-address index) | recorder | **fixed** in `observation/2`: balance bisection, for plain EOAs | +| A single window-wide `Coverage.complete` turned unobserved inbound into zeros | `ml/history.py` | **fixed** in the versioned `wallet-history/2-scoped`; `/1` kept, so no result changes | +| `touches_frozen` inspected ERC-20 transfers only | `recency_validation` | widened rule `touches_frozen_any` added. It changes no existing exclusion: P5 is 3/3 excluded and 6/6 admitted under both rules. | +| ERC-1155, zero-value native, internal transfers | — | declared `not_collected` / `partial` / `unsupported` | + +## 6. Ethereum transaction semantics, and 7–9. coverage + +| Class | `/1` | `/2` | Source and semantics | Tests | +|---|---|---|---|---| +| T1 native external out | wallet-signed (nonce bisection) | same | `tx.from`, `to`, `value`, index, status | existing | +| T1 native external in | **not collected** | **complete** (nonzero; plain EOA) | balance bisection; senders from the increase blocks | `test_balance_bisection…` | +| T2 ERC-20 Transfer | complete | complete | the event's `from`/`to` are not the signer | existing; case B | +| T3 zero-value ERC-20 | recorded; `zero_value_in` | same | C0 rule | case D | +| T4 fake token | recorded | same | untrusted by **contract**, never by symbol | case C | +| T5 spoofed `transferFrom` | recorded, signer looked up | same | `spoofed_out`; never a reference | case B | +| T6 internal ETH | **unsupported** | unsupported, with **unattributed** balance credits recorded (no sender) | needs traces | case H; recorder test | +| T7 reverted | outgoing: status kept | inbound: not a transfer (no balance change) | receipt status | case G; recorder test | +| T8 contract-mediated | signer kept; foreign signer means unconfirmed | same | — | existing | +| T9 self-transfer | — | skipped as a counterparty | — | `observations()` | +| T10 duplicates | dedup by block hash and log | dedup by (tx hash, log index or -1) | — | case L | +| ERC-721-shaped | **discarded** | **recorded** | 4 topics, token id kept | recorder test | +| Malformed `Transfer` | **discarded** | **counted** | not decoded | recorder test | +| ERC-1155 | not queried | not queried | `TransferSingle`/`TransferBatch` | declared | +| Zero-value native in | not collected | **partial** (only in blocks read for other reasons) | moves no balance | recorder test | + +## 10. Point-in-time invariants + +- **Cutoff semantics:** discovery uses observations strictly before `(block, tx index)`. +- **Same-block order** is respected (case I). +- **Tests confirm** that a later planting, a later theft or later native inbound does not change discovery at an earlier cutoff, and that record order does not change the output. +- **Finality:** fixtures are recorded at confirmed blocks, as before. No chain monitor was added. + +## 11. Completeness model + +`replay/observation.py` gives each category one of these statuses: `complete`, `partial`, `truncated`, `interrupted`, `rejected`, `not_collected`, `unsupported`, `unknown`. + +- **`coverage_of`** returns the stated coverage of an `observation/2` fixture, or derives an honest `observation/1` coverage from the documented method. +- **Inbound scope.** A complete inbound history means ERC-20, ERC-721-shaped and nonzero native transfers. Zero-value native and internal transfers can never be complete here, and the scope says so. + +## 12. Native ETH support + +**Method.** A plain EOA's balance cannot fall without a transaction it signs. So within each run of blocks without an own transaction, bisecting `eth_getBalance` finds every block where the balance rose. +- That block's transaction list names the external senders. +- When values don't add up, receipts are read. +- Any remainder is **unattributed**: an internal transfer, a withdrawal or a fee credit, with the sender unknown. +- Blocks containing the wallet's own transactions are read directly. Internal credits there can't be separated from the fee, so the unattributed category becomes `partial`. +- Wallets with code (contracts, EIP-7702 delegations) are `unsupported`. +- The method never uses an outcome address. + +**Cost on the mock end-to-end scenario:** + +| Recording | Requests | Recorded | +|---|---|---| +| `observation/1` | 36 | 1 transfer, 1 wallet transaction | +| `observation/2` | 60 (24 more, all reserved in the ledger) | adds 2 native inbound, 1 unattributed, 1 ERC-721 | + +On chain, the extra cost is about 2 × (own-transaction runs + 1) balance reads, plus about log₂(run length) reads and one block read per increase block. + +## 13. Internal transfers + +The RPC layer has no trace method (`trace_*` / `debug_*`), and no local trace artifacts exist. +- **Unattributed balance credits** are the only internal-value evidence, and they name no sender. +- **No internal transfer is fabricated.** +- **Verdict for case 2:** whether an internal transfer was involved is unverifiable without traces. + +## 14. Candidate-generator changes + +- **C0** is frozen. +- **C1** has no new rule. It runs on typed observations (ERC-20, native, NFT) with provenance: signer, emitter, status, identity. +- **C2** adds abstention, for an incomplete reference history or no reference in the window, and `screen_payment`. + - **Production:** neither detector nor production finding changes. A test shows `detector_outputs` is identical on `/1` and `/2` recordings of the same chain. + +## 15. Hypotheses: results + +| ID | Result | Evidence | +|---|---|---| +| H1 | **SUPPORTED** | 6 classes not observed by `/1` (§6). Two were fetched and then discarded. | +| H2 | **SUPPORTED on P1; BLOCKED BY DATA on real windows** | Mock end to end: C1 adds the native-dust lookalike, the ERC-721 lookalike and one non-lookalike `zero_value_in` (a 0-ETH stranger). C0 finds only the fake-token lookalike. No real `/2` window exists, so on P3 and P5, C1 equals C0. | +| H3 | **SUPPORTED** | 109 inbound-dependent values, out of 29 in-window queries × 5 features, are numeric under `/1` and undefined under scope. P3 accounts for 66 and P5 for 43. | +| H4 | **SUPPORTED** | Cases B, C, G, J, K and L match their oracles. | +| H5 | **NOT EVALUATED** (pre-declared) | No labelled population has the new classes. P3 and P5 are described below. | +| H6 | **SUPPORTED** | ≤ 1.3 ms and ≤ 26 KiB traced per window per variant; whole study 0.17 s; peak RSS 68 MiB | + +**Disclosure about oracles.** Two oracles were corrected to the *pre-stated* rule definitions after their first run: +- Case E used a 5-base-unit USDT transfer, which is `dust_in` by C0's documented threshold. The case now uses 5 USDT. +- In the end-to-end test, C1's unchanged `zero_value_in` rule fires on a 0-ETH stranger. + +Neither correction changed code. The second is a real candidate-volume risk (§21). + +## 16. Synthetic mechanism coverage (P1) + +All 12 cases (A–L) and the invariance tests pass: 22 tests in `tests/test_ml_candidate_discovery.py`, plus 4 recorder tests in `tests/integration/test_observation_v2.py`. These are correctness counts, not rates. + +## 17. Temporal features, 18. graph features, 19. unsupervised ML + +- **Temporal (descriptive).** Blocks from the reference's last use to the planting, for C1 candidates with an imitated reference: n = 5, median 20, range 9–60. All five come from the pilot. The Stage 2a plantings are `spoofed_out` and carry no matched reference under C0's rules. +- **Graph.** No planting signer is shared across P3 and P5, so there are 0 cross-wallet links. A shared token contract is never a link (case J). +- **Unsupervised ML.** None was trained. There is no labelled or verified-negative population for the new classes, and fitting an anomaly model on 8 small, mostly empty windows would answer no hypothesis. This is a deliberate negative choice. + +## 20. Candidate recoverability, and 21. volume and ambiguity (real windows) + +| Window | Population | C0 = C1 lookalikes | Per wallet-day | C2 abstains | Unlabelled payments: screened / flagged | +|---|---|---|---|---|---| +| usdt-counterfeit… | P3 | 6 | 3.0 | no | 0 / 0 (1 abstained) | +| scamsniffer-763k… | P3 | 2 | 0.67 | no | 5 / 0 (1 abstained) | +| bg-003, bg-010 | P5 | 0 | 0 | yes, no reference in the window | 0 / 0 | +| bg-005, bg-013, bg-014 | P5 | 0 | 0 | no | 0 / 0 (1 abstained each) | +| bg-011 | P5 | 0 | 0 | no | 7 / 0 (1 abstained) | + +**C1 changes nothing on real windows**, since no `/2` window exists yet. + +**Payment-screen volume:** 0 flagged of 12 screened wallet-signed payments, with 6 abstentions. Those payments are unlabelled, so this is **not** a false-positive rate. The sample is tiny. + +**Risk on future `/2` windows.** C1 applies `zero_value_in` to 0-ETH native transactions. Any third party can send those, so they can inflate the volume of non-lookalike candidates. C1 lists them, unweighted. + +**Development-case payment screen** (motivated by P3; **not validation**): + +| Theft | Flagged | Imitated reference | Affix | Recipient seen before | +|---|---|---|---|---| +| pilot `0x053dc459…` | yes | `0x053dba72…` | 4 + 4 | yes | +| Stage 2a `0x804051b0…` | yes | `0x80404f3e…` | 4 + 6 | unknown (inbound not fully observed) | + +The screen acts at signing time, so its "lead" is zero blocks but before execution. It needs a wallet integration that CryptoGuard's replay does not model. + +## 22. Source selection limitations + +- **P3:** two public, large, firm-noticed thefts, both now development cases. +- **P5:** six unlabelled background windows, which are not benign. +- **P2:** excluded (frozen cohort). +- **P4:** unused (no native or NFT observations). + +## 23. Existing incident regression outcomes + +Both Level I cases reproduce exactly. Their frozen hash-and-result tests pass, and their Phase 12.3 results are unchanged. + +## 24. Production isolation + +- **Unchanged:** the detector, the risk engine, the API and scoring. +- **Defaults:** `record_window` and `replay record` default to `observation/1`. +- **Isolated:** shadow discovery is research-only, behind `cryptoguard ml observation-study`, and is never called by the scanner. + +## 25. Performance, and 28. resources + +| Measure | Value | +|---|---| +| Whole offline study | 0.17 s; peak RSS 68 MiB | +| Discovery per window | ≤ 1.3 ms | +| Disk | a study JSON of a few KB | +| RPC requests / downloads | 0 / none | +| Process control | no other process was touched | + +## 26. Reproducibility + +`observation-study.json` records the git SHA, the protocol, the discovery and scoped-history versions, every fixture's SHA-256 and coverage schema, runtime and peak RSS. Rerunning `cryptoguard ml observation-study` regenerates it offline. + +## 27. Tests and CI + +| Check | Command | Result | +|---|---|---| +| Lint | `uv run ruff check .` | clean | +| Format | `uv run ruff format --check .` | 278 files formatted | +| Types | `uv run mypy src` | clean (149 files) | +| Tests | `uv run pytest -q` | **893 passed**, 4 deselected (`gpu`/`slow`), 0 failed, 0 skipped | + +Of those, 26 tests are new: 22 synthetic and invariance tests, and 4 recorder tests. The CI result is recorded in the PR #1 description. + +## 29. Positive findings + +1. Two event classes were silently discarded, and four were never observed. All six are now explicit. +2. Native inbound ETH can be observed exactly for plain EOAs without traces, with honest limits. +3. Category-scoped completeness removes 109 false zeros. +4. A payment-time lookalike screen would have flagged both known thefts (development cases). + +## 30. Negative findings + +1. The real miss cannot be explained from the data recorded. +2. C1 adds nothing on any existing real window. +3. No ML model is justified by the available data. +4. C1's mirrored `zero_value_in` rule adds non-lookalike candidates. + +## 31. Unresolved questions, and the queries that would answer them (not issued) + +| Query | Requests | What it settles | +|---|---|---| +| Q1 `eth_getTransactionCount(0x804051b0…, 21869296)` and `(…, 21890896)` | **2** | Whether the paid address signed *any* transaction before the theft. If it signed none, a native transfer *sent by it* is ruled out, which leaves contract-emitted logs, NFTs, internal transfers and off-wallet channels. | +| Q2 `observation/2` re-recording of the victim window | about 1,100 (645 measured for `/1`, plus balance bisection and the ERC-721 records) | Native inbound and ERC-721 plantings | +| Q3 `eth_getLogs` for `TransferSingle` / `TransferBatch` with the victim as `to` (topic 3) | 2 × 216 = 432 | ERC-1155 plantings | +| Q4 `trace_filter {toAddress: victim}` over the window | needs a trace-capable provider (a separate approval) | Internal transfers | + +## 32. Next scientific experiment + +**Proposal:** approve **Q1, 2 requests**, then, if its answer leaves the question open, **Q2 (about 1,100)**. + +**Contribution:** it would turn the Stage 2a miss from "unknown" into either an identified observation gap or a confirmed off-wallet channel. + +**Comparison it allows:** a first real `observation/2` window, where C1 can be compared with C0. + +**Limits:** it remains a development case, never validation. Independent validation still needs untouched incidents recorded with `observation/2` from the start. diff --git a/README.md b/README.md index 7f3680b..7e5cf34 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ uv run cryptoguard replay run --write-report EVALUATION.md # Re-record a fixture (needs historical logs + state, e.g. https://eth.drpc.org). Every live # replay command needs a request ledger and an approved cap; retries count, and a run that # reaches the cap writes nothing: -uv run cryptoguard replay record --rpc-url --ledger --cap +uv run cryptoguard replay record --rpc-url --ledger --cap [--observation 2] uv run cryptoguard replay find-transfers --sender [--recipient ] --since --until --rpc-url --ledger --cap # Evaluate the experimental analyses too (incidents + background wallets; analytics extra): uv run --extra analytics cryptoguard replay run --analytics --write-report EVALUATION.md diff --git a/src/cryptoguard/ml/observation_study.py b/src/cryptoguard/ml/observation_study.py index a47d385..9a255dd 100644 --- a/src/cryptoguard/ml/observation_study.py +++ b/src/cryptoguard/ml/observation_study.py @@ -109,25 +109,30 @@ def _window(case_id: str, population: str, fixture: Any, cutoff: tuple[int, int] "abstained": sum(s.flagged is None for s in screens), "flagged_recipients": sorted({s.recipient for s in screens if s.flagged}), } - targets = {c.lookalike for c in variants["C1"]["_result"].candidates} | {r for r, _, _ in pays} + # H3 at each query's own position (in-window): every C1 candidate and every payment + queries = [ + (c.lookalike, (c.position[0], c.position[1])) for c in variants["C1"]["_result"].candidates + ] + queries += [(r, p) for r, p, _ in pays] differ = 0 - for r in sorted(targets): - from dataclasses import asdict + targets = sorted(set(queries)) + from dataclasses import asdict - from cryptoguard.ml.history import events_from_fixture, history_features + from cryptoguard.ml.history import events_from_fixture, history_features - events, window = events_from_fixture(fixture) + events, window = events_from_fixture(fixture) + for r, (block, tx_index) in targets: v1 = asdict( history_features( events, window, recipient=r, - block=cutoff[0], - tx_index=cutoff[1], + block=block, + tx_index=tx_index, boundary="pre_execution", ) ) - v2 = cd.scoped_history(fixture, recipient=r, block=cutoff[0], tx_index=cutoff[1]) + v2 = cd.scoped_history(fixture, recipient=r, block=block, tx_index=tx_index) differ += sum(1 for k in cd.INBOUND_DEPENDENT if v1[k] is not None and v2[k] is None) row["h3_inbound_features_numeric_in_v1_undefined_in_scoped"] = differ row["h3_feature_rows"] = len(targets) diff --git a/tests/integration/test_observation_v2.py b/tests/integration/test_observation_v2.py index 6de7af9..91640a3 100644 --- a/tests/integration/test_observation_v2.py +++ b/tests/integration/test_observation_v2.py @@ -37,6 +37,7 @@ async def _no_sleep(_: float) -> None: def _provider(node: FakeNode, tmp: Path) -> tuple[RpcEthereumProvider, RequestLedger]: + tmp.mkdir(parents=True, exist_ok=True) ledger = RequestLedger(tmp / "ledger.json", cap=5_000) client = JsonRpcClient( "https://rpc.example.invalid", @@ -93,7 +94,6 @@ def _incident() -> FakeNode: async def _record(node: FakeNode, tmp: Path, observation: int) -> tuple[ReplayFixture, int]: - tmp.mkdir(parents=True, exist_ok=True) provider, ledger = _provider(node, tmp) try: fx = await record_window( @@ -161,7 +161,8 @@ async def test_end_to_end_original_versus_extended_observation(tmp_path: Path) - v2, used2 = await _record(node, tmp_path / "b", 2) # observation/1 is exactly what every existing fixture holds - assert v1.observation is None and v1.native_inbound is None + assert v1.observation is None + assert v1.native_inbound is None assert b'"native_inbound"' not in v1.canonical_bytes() assert used2 > used1 # the extension costs requests, all through the ledger # observation/2 states what it saw and what it could not diff --git a/tests/test_ml_candidate_discovery.py b/tests/test_ml_candidate_discovery.py index 9c9a41a..c139aa7 100644 --- a/tests/test_ml_candidate_discovery.py +++ b/tests/test_ml_candidate_discovery.py @@ -212,7 +212,8 @@ def test_case_e_missing_history_abstains_instead_of_claiming_no_references() -> ) res = found(fx, "C2") assert res.lookalikes == set() - assert res.abstain is not None and "not evidence of no earlier recipients" in res.abstain + assert res.abstain is not None + assert "not evidence of no earlier recipients" in res.abstain assert cd.screen_payment(fx, recipient=LOOK_TOKEN, cutoff=END).flagged is None partial = fixture(complete=False) assert found(partial, "C2").abstain is not None @@ -385,3 +386,26 @@ def test_a_reverted_own_send_still_counts_as_a_reference() -> None: } ) assert cd.screen_payment(fx, recipient=LOOK_NATIVE, cutoff=END).flagged is True + + +def test_frozen_items_are_caught_in_every_observed_class() -> None: + from cryptoguard.ml.observation_study import touches_frozen_any + + clean = fixture(native=[native_in(LOOK_NATIVE, 1, block=1200)]) + assert not touches_frozen_any(clean, (frozenset({SHORT}), frozenset())) + assert touches_frozen_any(clean, (frozenset({LOOK_NATIVE}), frozenset())) # native sender + paid = fixture(reference=False).model_copy( + update={ + "wallet_transactions": [ + RecordedTransaction( + transaction_hash=_tx(9), + block_number=1100, + transaction_index=0, + nonce=0, + to=SHORT, + value="1", + ) + ] + } + ) + assert touches_frozen_any(paid, (frozenset({SHORT}), frozenset())) # native recipient From 99f553bc2feb300eb81dc35693c0f08f8e9e7814 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 4 Nov 2026 18:16:32 +0300 Subject: [PATCH 62/92] docs(ml): Phase 12.4 Q1 result (2 approved RPC requests) eth_getTransactionCount of the Stage 2a paid address: 0 at the block before the recorded window, 1 at the block before the theft. It signed exactly one transaction ever before the theft, inside the window, and that transaction emitted no ERC-20 Transfer with the victim. Its content remains unknown (native send, NFT/1155 log, or unrelated); Q1b (about 16 requests) would identify it. Not approved; not issued. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + ML_OBSERVATION_COMPLETENESS.md | 36 +++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed2c4aa..ffa4da3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m - C2 adds abstention and a payment-time screen; - `wallet-history/2-scoped` never reports unobserved inbound as zero (109 false zeros under `/1`; no published number used them). - **Study:** `cryptoguard ml observation-study`. Report: `ML_OBSERVATION_COMPLETENESS.md`. +- **Q1** (2 approved RPC requests): the Stage 2a paid address signed exactly one transaction before the theft, inside the window, and it emitted no ERC-20 Transfer with the victim. Its content is unknown. Q1b (about 16 requests) is proposed. - **Unchanged:** the production detector and its findings. ### Incident recording, Stage 2a (1,433 RPC requests of an approved 6,000) diff --git a/ML_OBSERVATION_COMPLETENESS.md b/ML_OBSERVATION_COMPLETENESS.md index ffd7e9e..a9df812 100644 --- a/ML_OBSERVATION_COMPLETENESS.md +++ b/ML_OBSERVATION_COMPLETENESS.md @@ -5,7 +5,7 @@ | Protocol (frozen before the code and the study) | [`docs/ml/protocol-12.4.md`](docs/ml/protocol-12.4.md), `3a79b74` | | Implementation (committed before the study ran) | `3917957` | | Study output (git-ignored) | `data/ml/research/phase12.4/observation-study.json` (`cryptoguard ml observation-study`) | -| New RPC requests / downloads | **0** / none | +| New RPC requests / downloads | **0** for the phase / none; plus **2** for the approved Q1 (§33) | ## 1. Executive summary @@ -32,6 +32,8 @@ It also fetches ERC-721-shaped and malformed `Transfer` logs, then discards them - **C2** adds abstention and a **payment-time screen**. The screen flags both known thefts. That is a *development-case regression* result, not validation, because those cases motivated it. It flags 0 of 12 screened unlabelled payments in the background windows. - **A latent defect, fixed in a versioned path.** `wallet-history/1` reports inbound counts as observed zeros, although native inbound and ERC-721 were never collected: 109 values across 29 in-window queries. No published number used those counts. +**Q1 (§33, 2 approved requests):** the paid address signed **exactly one transaction ever** before the theft, inside the recorded window. That transaction emitted no ERC-20 Transfer involving the victim. A planting signed by the lookalike itself, through a channel `observation/1` cannot see, is now a concrete possibility. It is not confirmed. + **Classification:** confirmed observation improvement, verified on synthetic and mock data only. Also a limited mechanism improvement. For the real miss, the result is data-limited. H5 (ML contribution) was not evaluated, as pre-declared. ## 2. Repository baseline @@ -286,3 +288,35 @@ Of those, 26 tests are new: 22 synthetic and invariance tests, and 4 recorder te **Comparison it allows:** a first real `observation/2` window, where C1 can be compared with C0. **Limits:** it remains a development case, never validation. Independent validation still needs untouched incidents recorded with `observation/2` from the start. + +## 33. Addendum: Q1 result (2026-11-04, approved; 2 RPC requests) + +**What was asked:** `eth_getTransactionCount(0x804051b0…793375)` at two points: +- block 21,869,296, the block before the recorded window; +- block 21,890,896, the block before the theft. + +**How it ran:** +- **Ledger:** `data/ml/rpc/ledger-q1.json`, with a cap of **2**. The ledger shows 2 requests, with no retry and no chain-id preflight. +- **Endpoint:** `https://eth.drpc.org`. +- **Output:** `data/ml/research/phase12.4/q1-nonce.json`, git-ignored. + +| Block | Nonce (post-state) | +|---|---| +| 21,869,296 (window start − 1) | **0** | +| 21,890,896 (harm block − 1) | **1** | + +**What this establishes.** The paid address had never signed a transaction before the window. It signed **exactly one** in blocks 21,869,297–21,890,896, before the theft. This was February 2025, before EIP-7702, so no authorization tuple could have raised the nonce. The victim's ERC-20 scan of the same window is complete and holds no Transfer naming the address before the theft. So that one transaction emitted no standard ERC-20 Transfer to or from the victim. + +**What remains open.** The transaction's content is unknown. It is consistent with any of three possibilities: +- **(a)** a native ETH send to the victim, nonzero dust or 0 ETH. `observation/1` sees neither. +- **(b)** a contract call that emitted an ERC-721, ERC-1155 or malformed log involving the victim. `observation/1` discarded or never queried these. +- **(c)** a transaction unrelated to the victim, such as funding or a planting on another wallet, with the victim copying the address through another channel. + +**The classification of the miss** moves from *unknown* to **"a self-signed transaction by the lookalike inside the window, of unobserved content"**. A planting through an unobserved channel is now a concrete possibility, but it is still not confirmed. + +**Cheapest next query (Q1b, not issued; needs approval).** Bisect the paid address's nonce over blocks 21,869,297–21,890,896 to find that one transaction's block, then read the block's transactions. About 15 `eth_getTransactionCount` calls plus 1 `eth_getBlockByNumber`, so **about 16 requests**. +- **If** it is a native send to the victim, cause (a) is confirmed. It is then a gap that `observation/2` closes for nonzero values, or only partly for 0 ETH. +- **Otherwise**, one receipt read (1 request) separates (b) from (c). + +**Still a development case.** Whatever Q1b shows, this case remains a development case for any method built since. + From d9ca60c0876d5d1812e5e979ee0b7e3790f9c860 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 4 Nov 2026 18:29:00 +0300 Subject: [PATCH 63/92] docs(ml): Phase 12.4 Q1b result - the Stage 2a miss was a native ETH dust planting (17 approved RPC requests) The paid lookalike's only pre-theft transaction (nonce 0) was a plain native transfer of 1e12 wei to the victim at block 21,890,540, 357 blocks (4,320 s) before the theft and before both fake-token plantings. observation/1 does not record inbound native ETH, so the Phase 12.3 miss is a confirmed recorder omission. In an in-memory reconstruction with that one record, C1 flags the paid address (lookalike_in, affix 4+6 to the reference) 357 blocks early; C0 does not. The record was found by an outcome-directed query: a development-case regression, not validation. The frozen fixture and the Phase 12.3 result are unchanged. Ledger: 1 failed request (outbound connectivity down) + 16 on the one restart; receipt skipped to stay within the cap of 17. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++- ML_OBSERVATION_COMPLETENESS.md | 51 ++++++++++++++++++-- docs/ml/incident-benchmark/stage2a-result.md | 2 + 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffa4da3..2929cad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,11 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m - C2 adds abstention and a payment-time screen; - `wallet-history/2-scoped` never reports unobserved inbound as zero (109 false zeros under `/1`; no published number used them). - **Study:** `cryptoguard ml observation-study`. Report: `ML_OBSERVATION_COMPLETENESS.md`. -- **Q1** (2 approved RPC requests): the Stage 2a paid address signed exactly one transaction before the theft, inside the window, and it emitted no ERC-20 Transfer with the victim. Its content is unknown. Q1b (about 16 requests) is proposed. +- **Q1** (2 approved RPC requests): the Stage 2a paid address signed exactly one transaction before the theft, inside the window. +- **Q1b** (17 approved RPC requests): that transaction was a **native ETH dust transfer, 10¹² wei, to the victim**, 357 blocks before the theft. + - The Stage 2a miss is a confirmed recorder omission, the class `observation/2` adds. + - In a development reconstruction (in memory), C1 flags the paid address 357 blocks early. + - Not validation: the record was found by an outcome-directed query. - **Unchanged:** the production detector and its findings. ### Incident recording, Stage 2a (1,433 RPC requests of an approved 6,000) diff --git a/ML_OBSERVATION_COMPLETENESS.md b/ML_OBSERVATION_COMPLETENESS.md index a9df812..11d4c31 100644 --- a/ML_OBSERVATION_COMPLETENESS.md +++ b/ML_OBSERVATION_COMPLETENESS.md @@ -5,7 +5,7 @@ | Protocol (frozen before the code and the study) | [`docs/ml/protocol-12.4.md`](docs/ml/protocol-12.4.md), `3a79b74` | | Implementation (committed before the study ran) | `3917957` | | Study output (git-ignored) | `data/ml/research/phase12.4/observation-study.json` (`cryptoguard ml observation-study`) | -| New RPC requests / downloads | **0** for the phase / none; plus **2** for the approved Q1 (§33) | +| New RPC requests / downloads | **0** for the phase / none; plus **2** for the approved Q1 (§33) and **17** for the approved Q1b (§34) | ## 1. Executive summary @@ -32,6 +32,8 @@ It also fetches ERC-721-shaped and malformed `Transfer` logs, then discards them - **C2** adds abstention and a **payment-time screen**. The screen flags both known thefts. That is a *development-case regression* result, not validation, because those cases motivated it. It flags 0 of 12 screened unlabelled payments in the background windows. - **A latent defect, fixed in a versioned path.** `wallet-history/1` reports inbound counts as observed zeros, although native inbound and ERC-721 were never collected: 109 values across 29 in-window queries. No published number used those counts. +**Q1b (§34, 17 approved requests) settles the miss.** The paid lookalike's only transaction before the theft was a **native ETH dust transfer of 10¹² wei to the victim**. It came 357 blocks (4,320 s) before the theft, and `observation/1` cannot see it. The miss is therefore a **confirmed recorder omission**. With that one record added in memory, C1 flags the paid address 357 blocks early. That is a development-case reconstruction, not validation. + **Q1 (§33, 2 approved requests):** the paid address signed **exactly one transaction ever** before the theft, inside the recorded window. That transaction emitted no ERC-20 Transfer involving the victim. A planting signed by the lookalike itself, through a channel `observation/1` cannot see, is now a concrete possibility. It is not confirmed. **Classification:** confirmed observation improvement, verified on synthetic and mock data only. Also a limited mechanism improvement. For the real miss, the result is data-limited. H5 (ML contribution) was not evaluated, as pre-declared. @@ -63,7 +65,7 @@ Source: the recorded fixture `67e44177…`. Times are block-header timestamps (U - the theft transfer in the fixture; - the six theft receipts in `data/ml/research/stage2a/…/found.json`. -**Classification of the miss: unknown.** Each possible cause, and its status: +**Classification of the miss, from local data alone: unknown.** It was later settled by Q1b (§34) as a confirmed native-dust omission. Each possible cause, and its status from local data alone: - **Confirmed recorder omissions** that could explain it: - inbound native ETH, nonzero or zero; - ERC-721 or ERC-1155 plantings; @@ -265,7 +267,7 @@ Of those, 26 tests are new: 22 synthetic and invariance tests, and 4 recorder te ## 30. Negative findings -1. The real miss cannot be explained from the data recorded. +1. The real miss cannot be explained from the data recorded. It took 19 targeted requests (§33–34) to explain it. 2. C1 adds nothing on any existing real window. 3. No ML model is justified by the available data. 4. C1's mirrored `zero_value_in` rule adds non-lookalike candidates. @@ -320,3 +322,46 @@ Of those, 26 tests are new: 22 synthetic and invariance tests, and 4 recorder te **Still a development case.** Whatever Q1b shows, this case remains a development case for any method built since. +## 34. Addendum: Q1b result (2026-11-04, approved; 17 RPC requests) + +**How it ran:** +- **Ledger:** `data/ml/rpc/ledger-q1b.json`, with a cap of **17**. +- **First attempt:** 1 request, which failed. The provider could not be reached because outbound connectivity was down: direct TLS failed to every host, while the local HTTPS proxy recovered later. +- **The one permitted restart:** 16 requests. That was 15 nonce probes, bisecting blocks 21,869,297–21,890,896, plus 1 `eth_getBlockByNumber`. +- **Receipt:** skipped, to stay within the cap. +- **Output:** `data/ml/research/phase12.4/q1b-transaction.json`, git-ignored. + +| Field | Value | +|---|---| +| Transaction | `0xf4530315e9248c4a677987a5f32797b0dbc17a12ff713c96421e4e8d9b0b2b83` | +| Block, index, time | 21,890,540, index 150, 2025-02-20 22:28:35 UTC (header timestamp) | +| From → to | `0x804051b0…793375` (the paid lookalike, its nonce 0) → `0xf6b1539c…b6e4` (the victim) | +| Value, input | `0xe8d4a51000` = 1,000,000,000,000 wei (0.000001 ETH), empty input: a plain native transfer | +| Receipt status | **not read**. Two reasons say it executed: the transaction was included, and a plain value transfer to an account without code (the victim's code is `0x` in the fixture; February 2025 is before EIP-7702) cannot revert. Its effect on the victim's balance was not read. | + +**Chronology, completed:** + +| Block | Event | +|---|---| +| 21,890,495 | The reference payment, in token. | +| 21,890,508 | 600 ETH to the reference. | +| **21,890,540** | **Native dust planting from the later-paid lookalike: the earliest planting.** | +| 21,890,558 | The first fake-token lookalike. | +| 21,890,871 | The second fake-token lookalike. | +| 21,890,897 | The theft. | + +**Classification of the Phase 12.3 miss:** a **confirmed recorder omission** (category T1, inbound native ETH, nonzero). The planting is a class that `observation/1` never collects and `observation/2` does. The original Phase 12.3 result, the frozen fixture `67e44177…` and its regression test are unchanged. + +**Development-case reconstruction.** The fixture was taken in memory with this one record added as `native_inbound`, with `succeeded` left unknown, and evaluated at cutoff (21,890,897, 0): +- **C0:** the 2 fake-token lookalikes. The paid address is not seen. +- **C1:** the same 2, **plus the paid address**: + - rule `lookalike_in`, kind native; + - imitates the reference `0x80404f3e…793375`, with affix 4 + 6; + - **357 blocks, 4,320 s, before the theft**. + +**What this does and does not show.** The record was retrieved by a query directed at the outcome address, so this is **not** a blind recording. +- **It shows** that the miss came from observation, not from the rules. C0's own rules, applied to the missing record, recover the address. +- **The wallet-centric path** that would find the same transfer without knowing the outcome is `observation/2` balance bisection. The mock tests verify that path. It has not been run on this real window, which needs Q2, about 1,100 requests, not approved. +- **The case stays a development case.** This is a development-case regression success, not independent validation. +- **The production detector would still not flag it.** It is unchanged and reads no native inbound. Feeding `observation/2` native inbound to the detector is a production change that needs its own approval and evaluation, including the zero-value volume risk in §21. + diff --git a/docs/ml/incident-benchmark/stage2a-result.md b/docs/ml/incident-benchmark/stage2a-result.md index 9a9301d..7dfb62b 100644 --- a/docs/ml/incident-benchmark/stage2a-result.md +++ b/docs/ml/incident-benchmark/stage2a-result.md @@ -123,3 +123,5 @@ wallets using CryptoGuard live. That is a hypothesis for the product, not a meas `cryptoguard ml incident-benchmark verify`, then `run` and `report`, each with `--out data/ml/research/stage2a`. The default manifests are `candidates.json` and `stage2-resolved.json`. + +**Update, 2026-11-04 (forward pointer; the result above is unchanged).** The native-ETH hypothesis in §3 was confirmed by an approved 17-request query. The paid lookalike sent the victim 10¹² wei at block 21,890,540, 357 blocks before the theft, in a class `observation/1` does not record. See `ML_OBSERVATION_COMPLETENESS.md` §34. From 368f652d60ba868044344858247cb404c12daeff Mon Sep 17 00:00:00 2001 From: Rostislav Date: Sun, 8 Nov 2026 22:44:54 +0300 Subject: [PATCH 64/92] feat(ml): final validation of observation/2 before a blind replay (no RPC) - native_inbound: read_receipts; observation/2 now observes the status of every nonzero inbound instead of inferring it from an exact sum (which a reverted inbound plus an equal internal credit would fool). - Adversarial locator tests (12, incl. a seeded randomized oracle). - C2 safeguards: native candidates require a lookalike of the wallet's own reference (zero-value / stranger native transfers alone never become candidates); one candidate per lookalike with an event count. C1 unchanged (coverage measurement). Production detector untouched. - replay record-window: outcome-blind recording from wallet, chain, window and collection settings only; never overwrites; needs a cap. - Pre-register the blind observation/2 replay of the Stage 2a window (verification V1-V5 fixed in advance; cap 2,500 requested, not approved). The frozen fixture and the original C0 miss are unchanged. - 909 passed, 4 deselected; ruff and mypy clean. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + .../preregistration-blind-v2.md | 58 +++++ src/cryptoguard/cli.py | 77 +++++++ src/cryptoguard/ml/candidate_discovery.py | 33 ++- src/cryptoguard/replay/record.py | 1 + src/cryptoguard/services/native_inbound.py | 13 +- .../test_native_inbound_adversarial.py | 199 ++++++++++++++++++ tests/integration/test_observation_v2.py | 39 ++++ tests/integration/test_replay_budget.py | 14 ++ tests/test_ml_candidate_discovery.py | 39 ++++ 10 files changed, 476 insertions(+), 5 deletions(-) create mode 100644 docs/ml/incident-benchmark/preregistration-blind-v2.md create mode 100644 tests/integration/test_native_inbound_adversarial.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2929cad..0ac5f9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,14 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.4 final validation of observation/2 (no RPC requests) +- **Balance-bisection audit:** + - **Fixed:** with matching sums, success was inferred. A reverted inbound plus an internal credit of exactly the same value in the same block would be misattributed. `observation/2` now reads a receipt for every nonzero inbound. + - **Adversarial tests:** several inbound transfers in one block, an inbound followed by an equal spend, an internal credit beside an external inbound, reverted and successful inbound together, a missed own-transaction block, truncation, own transactions at the window edges, a self-transfer, outside-window inbound, the minimum cost, and a seeded randomized oracle. +- **C2, the warning-facing shadow variant:** a native observation is a candidate only when its sender imitates one of the wallet's own references, and there is one candidate per lookalike, with an event count. In a test, 1,000 zero-value strangers produce 0 C2 candidates. C1 stays a coverage measurement. The production detector reads no native inbound. +- **Added `replay record-window`:** outcome-blind recording, taking only the wallet, chain, block window and settings; it never overwrites. +- **Pre-registered:** the outcome-blind replay of the Stage 2a window (`docs/ml/incident-benchmark/preregistration-blind-v2.md`). Cap requested: 2,500. Not approved. + ### Observation completeness and candidate discovery, Phase 12.4 (no RPC requests) - **Protocol 12.4** (`docs/ml/protocol-12.4.md`) was frozen before the code and the study. - **Audit:** `observation/1` never observed inbound native ETH, zero-value native transactions, internal transfers or ERC-1155. It also fetched ERC-721-shaped and malformed `Transfer` logs and discarded them, without keeping their counts. diff --git a/docs/ml/incident-benchmark/preregistration-blind-v2.md b/docs/ml/incident-benchmark/preregistration-blind-v2.md new file mode 100644 index 0000000..9f7771f --- /dev/null +++ b/docs/ml/incident-benchmark/preregistration-blind-v2.md @@ -0,0 +1,58 @@ +# Pre-registration: outcome-blind `observation/2` replay of the Stage 2a window + +**Frozen:** 2026-11-08, in the commit that adds this file. That is before any request for this replay. + +**Status:** **not approved.** It runs only after the user approves a new request cap. Earlier caps are exhausted and do not carry over. + +**Governing rules:** `docs/ml/protocol-12.4.md`, and `ML_OBSERVATION_COMPLETENESS.md` §33–34. + +**Classification:** a **development-case regression**. The case and its planting (Q1b) are known. A success here shows that the wallet-centric path finds the planting blindly. It is not independent validation. + +## 1. Input: the wallet, chain, window and collection settings only + +| Field | Value | +|---|---| +| Wallet | `0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4` (the victim) | +| Chain | 1 | +| Window | blocks 21,869,297–21,890,897: the same window as the frozen fixture (harm block − 21,600 to harm block, the rule fixed in Stage 2a) | +| Collection | `observation/2`, 100-block log chunks, receipts read for every nonzero native inbound transaction | + +The command, `replay record-window`, reads **no manifest**. It never receives the paid address, the planting hash or the harmful hash. The output goes to a new file in the git-ignored research folder. **The frozen fixture `67e44177…` and the original C0 miss stay unchanged.** + +``` +cryptoguard replay record-window --wallet 0xf6b1539cc562c0ca5151825488eb8c3cdaf2b6e4 + --chain-id 1 --from-block 21869297 --to-block 21890897 --observation 2 + --out data/ml/research/phase12.4/blind-v2/fixture.json + --rpc-url https://eth.drpc.org --ledger data/ml/rpc/ledger-blind-v2.json --cap 2500 +``` + +## 2. Request cap requested: 2,500 (cumulative, retries included) + +**Measured basis:** `observation/1` recorded this window in 645 requests. That was 9 transfers and 12 wallet transactions, in 12 distinct blocks. + +| `observation/2` addition | Estimate | +|---|---| +| Balance reads at the edges of 13 runs without own transactions | about 26 | +| Increase blocks, k of them (at least 1: the planting). Each costs about 15 balance reads, 1 block read and 1 receipt. | about 17 × k, so about 340 if k ≈ 20 | +| Block reads for the 12 own-transaction blocks, plus receipts there | about 15 | +| Timestamps of the new blocks | about k | +| **Expected total** | **about 1,050** | + +- **The cap:** 2,500, hard. +- **Retries:** included, through the durable ledger. +- **Stopping at the cap:** a run that hits it is *not evaluable: budget*, and no fixture is written. +- **Restarts:** one restart after a transport error, within the same cap. +- **Endpoint:** no other endpoint and no paid API. +- **Preflight:** the bounded resource check, plus a connectivity check through the local proxy. + +## 3. Verification (fixed now; checked offline after recording) + +| ID | Criterion | +|---|---| +| V1 | `native_inbound` contains transaction `0xf4530315e9248c4a677987a5f32797b0dbc17a12ff713c96421e4e8d9b0b2b83`, with all of these fields: sender `0x804051b0cbc20443943c4f363573ef9bb7793375`, block 21,890,540, transaction index 150, value 1,000,000,000,000 wei, and `succeeded` true **read from the receipt**. | +| V2 | Coverage `native_inbound_external` is `complete`. | +| V3 | The ERC-20 transfers and wallet transactions match the frozen `observation/1` fixture identity for identity. | +| V4 | At cutoff (21,890,897, 0), the same for every variant:
• C0 finds the 2 fake-token lookalikes;
• C1 also contains the paid address, as `lookalike_in`, native;
• C2 keeps the paid address, imitating `0x80404f3e…793375`.
Every other added candidate is reported, along with duplicates, abstentions and coverage. | +| V5 | `detector_outputs` is identical on the `observation/2` fixture and on its `observation/1` projection: production isolation. | + +**If any criterion fails,** the result is reported as a failure of `observation/2` on a real window. Nothing is tuned and nothing is re-run under different settings. diff --git a/src/cryptoguard/cli.py b/src/cryptoguard/cli.py index 9d8dedd..e67e71e 100644 --- a/src/cryptoguard/cli.py +++ b/src/cryptoguard/cli.py @@ -398,6 +398,9 @@ async def run_recording() -> str: return 2 return 0 + if args.replay_command == "record-window": + return _record_window_command(args, settings) + if args.replay_command in ("sample-background", "record-background"): return _background_command(args, settings) @@ -547,6 +550,67 @@ def _utc_day(day: str) -> int: return int(datetime.fromisoformat(day).replace(tzinfo=UTC).timestamp()) +def _record_window_command(args: argparse.Namespace, settings: Settings) -> int: + """Outcome-blind recording: the only inputs are the wallet, the chain, the block window + and the collection settings. No manifest is read, so no victim label, attacker address or + transaction hash can reach the recorder. Fails closed at the cap; never overwrites.""" + from pathlib import Path + + from cryptoguard.blockchain.budget import BudgetExhaustedError, budgeted_transport + from cryptoguard.blockchain.provider import build_rpc_provider + from cryptoguard.core.config import validate_rpc_url + from cryptoguard.replay.record import record_window + + out = Path(args.out) + if out.exists(): + print(f"error: {out} exists; it is never overwritten", file=sys.stderr) + return 1 + if args.from_block > args.to_block: + print("error: --from-block is after --to-block", file=sys.stderr) + return 1 + ledger = _replay_ledger(args) + rpc_settings = settings.model_copy( + update={ + "rpc_url": SecretStr(validate_rpc_url(args.rpc_url)), + "chain_id": args.chain_id, + "rpc_max_concurrency": 2, + } + ) + case_id = f"window-{args.wallet.lower()[:10]}-{args.from_block}-{args.to_block}" + + async def run() -> Any: + provider = build_rpc_provider(rpc_settings, transport=budgeted_transport(ledger)) + before = ledger.used() + try: + return await record_window( + provider, + case_id=case_id, + chain_id=args.chain_id, + wallet=args.wallet, + start=args.from_block, + end=args.to_block, + chunk_blocks=args.chunk_blocks, + observation=args.observation, + ) + finally: + await provider.aclose() + ledger.note(f"replay record-window {case_id}: {ledger.used() - before} reserved") + + try: + fixture = asyncio.run(run()) + except BudgetExhaustedError as exc: + print(f"{case_id}: not evaluable: budget ({exc}); no fixture written", file=sys.stderr) + return 2 + out.parent.mkdir(parents=True, exist_ok=True) + out.write_bytes(fixture.canonical_bytes() + b"\n") + print( + f"Recorded {len(fixture.transfers)} transfers, {len(fixture.wallet_transactions)} wallet " + f"transactions, {len(fixture.native_inbound or [])} native inbound " + f"({fixture.rpc_requests} RPC requests) to {out}" + ) + return 0 + + def _background_command(args: argparse.Namespace, settings: Settings) -> int: from datetime import UTC, datetime @@ -938,6 +1002,19 @@ def main(argv: Sequence[str] | None = None) -> int: p_sample.add_argument("--window-blocks", type=int, default=21_601) p_sample.add_argument("--max-nonce-delta", type=int, default=100) _add_rpc_budget(p_sample, per_run_help="most requests this run may reserve") + p_win = replay_sub.add_parser( + "record-window", + help="record one wallet window, outcome-blind (wallet, chain and blocks only)", + ) + p_win.add_argument("--wallet", required=True) + p_win.add_argument("--chain-id", type=int, default=1) + p_win.add_argument("--from-block", type=int, required=True) + p_win.add_argument("--to-block", type=int, required=True) + p_win.add_argument("--observation", type=int, choices=(1, 2), default=2) + p_win.add_argument("--chunk-blocks", type=int, default=100) + p_win.add_argument("--out", required=True, help="fixture path (never overwritten)") + p_win.add_argument("--rpc-url", required=True) + _add_rpc_budget(p_win, per_run_help="most requests this run may reserve") p_bg = replay_sub.add_parser( "record-background", help="record fixtures for background wallets that have none" ) diff --git a/src/cryptoguard/ml/candidate_discovery.py b/src/cryptoguard/ml/candidate_discovery.py index d86916c..e3f60f8 100644 --- a/src/cryptoguard/ml/candidate_discovery.py +++ b/src/cryptoguard/ml/candidate_discovery.py @@ -8,7 +8,12 @@ ``untrusted_token_in``, ``dust_in``) applied to every class the window actually observed: ERC-20 transfers, and with ``observation/2`` also native ETH received and ERC-721-shaped transfers. No rule is new, so C1 minus C0 is what the extra observations buy. -- **C2**: C1 plus two semantic rules motivated by the Stage 2a miss (``motivated-by: P3``): +- **C2**: the warning-facing variant. C1 plus two safeguards: a native observation becomes a + candidate only when its sender imitates one of the wallet's own references (anyone can + send a wallet 0 ETH, so zero-value or stranger native transfers alone are never a + candidate), and candidates are aggregated to one per lookalike with an event count. C1 + keeps C0's rules unchanged and is a coverage measurement, not a warning list. C2 also adds + two semantic rules motivated by the Stage 2a miss (``motivated-by: P3``): *abstention* (when the wallet's references are not fully observed, say so instead of reporting "no candidate") and a *payment-time screen* (``screen_payment``): at the moment the wallet signs a payment, its recipient is checked against the wallet's own earlier @@ -188,6 +193,7 @@ class DiscoveryCandidate: position: tuple[int, int, int] affix: tuple[int, int] | None description: str = "suspicious lookalike candidate" + events: int = 1 # C2 aggregates one candidate per lookalike; others list each event @dataclass(frozen=True) @@ -288,6 +294,7 @@ def discover(fixture: Any, *, cutoff: tuple[int, int], variant: Variant = "C1") ) abstain = None if variant == "C2": + found = _c2_safeguards(found) if not cov.complete(*REFERENCE_CATEGORIES): abstain = "insufficient history: the wallet's own references are not fully observed" elif not chosen: @@ -300,6 +307,30 @@ def discover(fixture: Any, *, cutoff: tuple[int, int], variant: Variant = "C1") ) +def _c2_safeguards(found: list[DiscoveryCandidate]) -> list[DiscoveryCandidate]: + """Drop native candidates that imitate no reference, then keep one candidate per + lookalike (its earliest evidence, every method seen, and the number of events).""" + kept = [c for c in found if c.kind != "native" or c.imitated is not None] + by_lookalike: dict[str, DiscoveryCandidate] = {} + for c in kept: # chain order: the first occurrence is the earliest evidence + first = by_lookalike.get(c.lookalike) + if first is None: + by_lookalike[c.lookalike] = c + continue + methods = tuple(dict.fromkeys(first.methods + c.methods)) + by_lookalike[c.lookalike] = DiscoveryCandidate( + lookalike=first.lookalike, + imitated=first.imitated or c.imitated, + methods=methods, + kind=first.kind, + evidence=first.evidence, + position=first.position, + affix=first.affix or c.affix, + events=first.events + 1, + ) + return list(by_lookalike.values()) + + def _c0( fixture: Any, cutoff: tuple[int, int], coverage: dict[str, str], missing: list[str] ) -> DiscoveryResult: diff --git a/src/cryptoguard/replay/record.py b/src/cryptoguard/replay/record.py index 4b76833..b291dbb 100644 --- a/src/cryptoguard/replay/record.py +++ b/src/cryptoguard/replay/record.py @@ -209,6 +209,7 @@ async def _observation_v2( to_block=end, own_tx_blocks=[t.block_number for t in transactions], wallet_is_plain_eoa=plain, + read_receipts=True, # success observed, never inferred ) nfts = [] for log in transfers.erc721_logs: diff --git a/src/cryptoguard/services/native_inbound.py b/src/cryptoguard/services/native_inbound.py index 08afe5a..62641ac 100644 --- a/src/cryptoguard/services/native_inbound.py +++ b/src/cryptoguard/services/native_inbound.py @@ -8,9 +8,13 @@ transaction list then names the external senders (``tx.to == wallet``, nonzero value). Exact accounting per increase block: the successful external inbound values must sum to -the increase. Any remainder is **unattributed** (an internal transfer from contract -execution, a validator withdrawal, a fee-recipient credit): its sender is unknown without -traces, and it is recorded as such, never as a transfer from anyone. +the increase. With ``read_receipts`` (what ``observation/2`` uses) every nonzero inbound +transaction's receipt is read, so success is observed, never inferred. Without it, success +is inferred from an exact sum, which a reverted inbound plus an internal credit of exactly +the same value in the same block would fool. Any remainder is **unattributed** (an +internal transfer from contract execution, a validator withdrawal, a fee-recipient credit): +its sender is unknown without traces, and it is recorded as such, never as a transfer from +anyone. What this cannot see, stated in the coverage: @@ -77,6 +81,7 @@ async def locate_native_inbound( own_tx_blocks: Sequence[int], wallet_is_plain_eoa: bool | None, max_change_blocks: int = DEFAULT_MAX_CHANGE_BLOCKS, + read_receipts: bool = False, ) -> NativeInboundDiscovery: wallet = to_checksum_address(wallet) if wallet_is_plain_eoa is not True: @@ -136,7 +141,7 @@ async def bisect(lo: int, hi: int, before: int, after: int) -> None: for block, delta in sorted(increases): txs = await _inbound_txs(provider, wallet, block, counts) paid = [t for t in txs if t.value > 0] - if sum(t.value for t in paid) != delta: # some may have reverted: read the receipts + if read_receipts or sum(t.value for t in paid) != delta: # observe, or resolve a gap paid = [await _with_status(provider, t, counts) for t in paid] txs = [t for t in txs if t.value == 0] + paid explained = sum(t.value for t in paid if t.succeeded is not False) diff --git a/tests/integration/test_native_inbound_adversarial.py b/tests/integration/test_native_inbound_adversarial.py new file mode 100644 index 0000000..ec63d13 --- /dev/null +++ b/tests/integration/test_native_inbound_adversarial.py @@ -0,0 +1,199 @@ +"""Adversarial checks of the balance-bisection native-inbound locator (protocol 12.4 final +validation). Expected outputs are written from each scenario's definition. Mock node only: +it charges no gas, so the wallet's own transactions move exactly their value.""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any + +from cryptoguard.blockchain.provider import RpcEthereumProvider +from cryptoguard.blockchain.rpc import JsonRpcClient, RetryPolicy +from cryptoguard.services.native_inbound import locate_native_inbound +from tests.fakenode import FakeNode + +W = "0x" + "c" * 40 +REF = "0xabcde" + "1" * 30 + "54321" +A, B, C = ("0x" + c * 40 for c in "123") +START, END = 1_000, 1_400 + + +def node() -> FakeNode: + n = FakeNode(head=2_000) + n.balance_history = True + n.set_account(W, balance=10**21) + return n + + +async def _no_sleep(_: float) -> None: + return None + + +async def locate(n: FakeNode, tmp: Path, own: list[int], **kw: Any) -> Any: + """Plain mock transport (no ledger): these tests check results, not budgets.""" + del tmp + client = JsonRpcClient( + "https://rpc.example.invalid", + retry=RetryPolicy(max_retries=0, base_delay=0.0, max_delay=0.0), + transport=n.transport(), + sleep=_no_sleep, + rng=random.Random(0), + ) + provider = RpcEthereumProvider( + client, expected_chain_id=1, endpoint_display="test", max_log_block_range=1000 + ) + try: + return await locate_native_inbound( + provider, + W, + from_block=START, + to_block=END, + own_tx_blocks=own, + wallet_is_plain_eoa=True, + **kw, + ) + finally: + await provider.aclose() + + +def seen(found: Any) -> set[tuple[int, str, int, bool | None]]: + return {(t.block_number, t.sender.lower(), t.value, t.succeeded) for t in found.inbound} + + +async def test_several_inbound_transfers_in_one_block(tmp_path: Path) -> None: + n = node() + n.send_native(A, W, 5, block=1_150, tx_index=1) + n.send_native(B, W, 7, block=1_150, tx_index=2) + f = await locate(n, tmp_path, [], read_receipts=True) + assert seen(f) == {(1_150, A, 5, True), (1_150, B, 7, True)} + assert (f.unattributed, f.status) == ([], "complete") + + +async def test_inbound_then_an_equal_spend_is_still_found(tmp_path: Path) -> None: + n = node() + n.send_native(A, W, 1_000, block=1_150) + n.send_native(W, REF, 1_000, block=1_200) # window endpoints now have equal balances + f = await locate(n, tmp_path, [1_200], read_receipts=True) + assert seen(f) == {(1_150, A, 1_000, True)} + assert f.status == "complete" + + +async def test_internal_credit_beside_an_external_inbound_is_kept_apart(tmp_path: Path) -> None: + n = node() + n.send_native(A, W, 1_000, block=1_150) + n.credits.append((1_150, W, 300)) + f = await locate(n, tmp_path, [], read_receipts=True) + assert seen(f) == {(1_150, A, 1_000, True)} + assert [(u.block_number, u.value) for u in f.unattributed] == [(1_150, 300)] + + +async def test_reverted_and_successful_inbound_in_one_block(tmp_path: Path) -> None: + n = node() + bad = n.send_native(A, W, 10**17, block=1_150, tx_index=1) + n.reverted.add(bad) + n.send_native(B, W, 500, block=1_150, tx_index=2) + f = await locate(n, tmp_path, []) # sums differ, so receipts are read even without the flag + assert seen(f) == {(1_150, A, 10**17, False), (1_150, B, 500, True)} + assert f.unattributed == [] + + +async def test_a_reverted_transfer_masked_by_an_equal_credit(tmp_path: Path) -> None: + """The one case an inferred status gets wrong; observation/2 reads receipts.""" + n = node() + bad = n.send_native(A, W, 777, block=1_150) + n.reverted.add(bad) + n.credits.append((1_150, W, 777)) + observed = await locate(n, tmp_path / "r", [], read_receipts=True) + assert seen(observed) == {(1_150, A, 777, False)} + assert [(u.block_number, u.value) for u in observed.unattributed] == [(1_150, 777)] + inferred = await locate(n, tmp_path / "i", [], read_receipts=False) + assert seen(inferred) == {(1_150, A, 777, True)} # documented limitation of inference + assert inferred.unattributed == [] + + +async def test_a_missed_own_transaction_is_flagged_not_hidden(tmp_path: Path) -> None: + n = node() + n.send_native(W, REF, 5_000, block=1_200) # the caller fails to pass block 1,200 + n.send_native(A, W, 1_000, block=1_300) + f = await locate(n, tmp_path, []) + assert f.status == "partial" + assert f.note is not None + assert "fell" in f.note + + +async def test_too_many_increase_blocks_truncate(tmp_path: Path) -> None: + n = node() + for i, b in enumerate((1_100, 1_200, 1_300)): + n.send_native(A, W, 10 + i, block=b) + f = await locate(n, tmp_path, [], max_change_blocks=2) + assert f.status == "truncated" + assert len(f.change_blocks) == 2 + + +async def test_own_transactions_at_the_window_edges(tmp_path: Path) -> None: + n = node() + n.send_native(W, REF, 1, block=START) + n.send_native(A, W, 900, block=1_200) + n.send_native(W, REF, 1, block=END) + f = await locate(n, tmp_path, [START, END], read_receipts=True) + assert seen(f) == {(1_200, A, 900, True)} + assert f.status == "complete" + + +async def test_a_self_transaction_is_not_inbound(tmp_path: Path) -> None: + n = node() + n.send_native(W, W, 10, block=1_150) + f = await locate(n, tmp_path, [1_150]) + assert f.inbound == [] + + +async def test_inbound_outside_the_window_is_not_reported(tmp_path: Path) -> None: + n = node() + n.send_native(A, W, 5, block=START - 1) + n.send_native(A, W, 6, block=END + 1) + f = await locate(n, tmp_path, []) + assert (f.inbound, f.change_blocks) == ([], []) + + +async def test_a_quiet_window_costs_only_the_run_endpoints(tmp_path: Path) -> None: + n = node() + n.send_native(W, REF, 1, block=1_100) + f = await locate(n, tmp_path, [1_100]) + # runs 1,000..1,099 and 1,101..1,400: balances at 999, 1,099, 1,100 and 1,400 + assert (f.balance_reads, f.block_reads, f.receipt_reads) == (4, 1, 0) + + +async def test_randomized_scenarios_match_an_independent_oracle(tmp_path: Path) -> None: + rng = random.Random(20261108) + for k in range(25): + n = node() + own = sorted(rng.sample(range(START, END + 1), rng.randint(0, 4))) + for b in own: + n.send_native(W, REF, rng.randint(1, 10**6), block=b, tx_index=0) + expect_found: set[tuple[int, str, int, bool | None]] = set() + credits: dict[int, int] = {} + for i in range(rng.randint(0, 6)): + b = rng.randint(START - 20, END + 20) + sender = rng.choice([A, B, C]) + value = rng.choice([0, rng.randint(1, 10**9)]) + tx = n.send_native(sender, W, value, block=b, tx_index=10 + i) + failed = value > 0 and rng.random() < 0.25 + if failed: + n.reverted.add(tx) + if START <= b <= END and value > 0: + expect_found.add((b, sender, value, not failed)) + for _ in range(rng.randint(0, 3)): + b = rng.randint(START, END) + v = rng.randint(1, 10**6) + n.credits.append((b, W, v)) + if b not in own: + credits[b] = credits.get(b, 0) + v + f = await locate(n, tmp_path / str(k), own, read_receipts=True) + nonzero = {s for s in seen(f) if s[2] > 0} + # every nonzero external inbound in the window, success observed, is found; a + # reverted one sitting in a block with no balance increase is (correctly) not seen + assert {s for s in expect_found if s[3]} <= nonzero, k + assert nonzero <= expect_found, k + assert {(u.block_number, u.value) for u in f.unattributed} == set(credits.items()), k + assert f.status == "complete", k diff --git a/tests/integration/test_observation_v2.py b/tests/integration/test_observation_v2.py index 91640a3..8f11cc2 100644 --- a/tests/integration/test_observation_v2.py +++ b/tests/integration/test_observation_v2.py @@ -207,3 +207,42 @@ async def test_a_dust_planting_after_the_cutoff_is_not_seen(tmp_path: Path) -> N def _unused(*_: Any) -> None: # keep imports explicit for readers return None + + +def test_record_window_cli_is_outcome_blind_and_never_overwrites( + tmp_path: Path, monkeypatch: Any +) -> None: + from cryptoguard import cli + from cryptoguard.blockchain import budget as budget_mod + + node = _incident() + monkeypatch.setattr(budget_mod.httpx, "AsyncHTTPTransport", node.transport) + out = tmp_path / "blind" / "fixture.json" + argv = [ + "replay", + "record-window", + "--wallet", + WALLET, + "--chain-id", + "1", + "--from-block", + str(START), + "--to-block", + str(END), + "--out", + str(out), + "--rpc-url", + "https://rpc.example.invalid", + "--ledger", + str(tmp_path / "ledger.json"), + "--cap", + "500", + ] + assert cli.main(argv) == 0 + fx = ReplayFixture.model_validate_json(out.read_text(encoding="utf-8")) + assert fx.observation is not None # observation/2 is the default here + assert DUST in {n.sender.lower() for n in fx.native_inbound or []} + assert RequestLedger(tmp_path / "ledger.json", cap=500).used() == fx.rpc_requests + assert cli.main(argv) == 1 # never overwritten + for flag in ("--case", "--manifest", "--harm", "--attacker", "--cases-dir"): + assert flag not in " ".join(argv) # the command has no outcome input at all diff --git a/tests/integration/test_replay_budget.py b/tests/integration/test_replay_budget.py index a90dd93..915efc0 100644 --- a/tests/integration/test_replay_budget.py +++ b/tests/integration/test_replay_budget.py @@ -146,6 +146,20 @@ async def test_locate_reads_block_parties_and_transfers(tmp_path: Path) -> None: "https://x.invalid", ], ["replay", "record-background", "--rpc-url", "https://x.invalid"], + [ + "replay", + "record-window", + "--wallet", + "0x" + "ab" * 20, + "--from-block", + "1", + "--to-block", + "2", + "--out", + "unused.json", + "--rpc-url", + "https://x.invalid", + ], [ "replay", "sample-background", diff --git a/tests/test_ml_candidate_discovery.py b/tests/test_ml_candidate_discovery.py index c139aa7..e055c82 100644 --- a/tests/test_ml_candidate_discovery.py +++ b/tests/test_ml_candidate_discovery.py @@ -409,3 +409,42 @@ def test_frozen_items_are_caught_in_every_observed_class() -> None: } ) assert touches_frozen_any(paid, (frozenset({SHORT}), frozenset())) # native recipient + + +def test_zero_value_native_floods_cannot_become_unrestricted_warnings() -> None: + """Anyone can send a wallet 0 ETH. C1 (coverage measurement, C0's rules unchanged) + lists each such event; C2 (warning-facing) keeps only native senders that imitate one of + the wallet's own references, one candidate per lookalike; the production detector reads + no native inbound at all.""" + from cryptoguard.detectors.poisoning import PoisoningConfig + from cryptoguard.replay.engine import Visibility, detector_outputs + + strangers = [ + native_in("0x" + f"{i:040x}", 0, block=1200 + i % 700, tx=10_000 + i) for i in range(1000) + ] + lookalike = [native_in(LOOK_NATIVE, 0, block=1300 + i, tx=20_000 + i) for i in range(3)] + fx = fixture(native=strangers + lookalike) + c1 = found(fx, "C1") + assert len(c1.candidates) == 1003 # listed, never weighted: a volume measurement + c2 = found(fx, "C2") + [only] = c2.candidates + assert (only.lookalike, only.imitated, only.events) == (LOOK_NATIVE, REF, 3) + assert only.position == (1300, 0, -1) # the earliest evidence is kept + full = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS + cfg = PoisoningConfig() + legacy = fx.model_copy(update={"native_inbound": None, "observation": None}) + assert detector_outputs(fx, 2000, full, cfg) == detector_outputs(legacy, 2000, full, cfg) + + +def test_c2_keeps_one_candidate_per_lookalike_across_classes() -> None: + fx = fixture( + [ + transfer(LOOK_TOKEN, VICTIM, 0, block=1300, signer=ATTACKER), + transfer(LOOK_TOKEN, VICTIM, 0, block=1310, signer=ATTACKER, log=3), + ], + native=[native_in(LOOK_TOKEN, 0, block=1320)], + ) + assert len(found(fx, "C1").candidates) == 3 + [c] = found(fx, "C2").candidates + assert (c.lookalike, c.events, c.position[0]) == (LOOK_TOKEN, 3, 1300) + assert c.methods == ("zero_value_in", "lookalike_in") From c090814bc489c8d044efdc1d250fb3a39f4c8942 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 00:07:34 +0300 Subject: [PATCH 65/92] docs(ml): blind observation/2 replay passes V1-V5 (1,299 approved RPC requests) replay record-window, given only the victim, chain and block window, recorded the Stage 2a window with observation/2 and independently found the native dust planting (0xf4530315..., block 21,890,540, index 150, 1e12 wei, receipt status read). C0 = the 2 fake-token lookalikes (identical to C0 on the frozen fixture); C1 adds exactly the paid address 357 blocks (4,320 s) before the theft; C2 keeps it; production detector output identical. Development-case regression, not validation. The frozen fixture and original C0 miss are unchanged. Ledger: 596 on a first attempt stopped by a provider rate limit (no fixture written) + 703 on the one permitted restart. Decision (ML_OBSERVATION_COMPLETENESS.md section 35): observation/2 is sufficient for offline research within its scope; production use needs untouched blind incidents, a C2 volume study and an approved detector change. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++- ML_OBSERVATION_COMPLETENESS.md | 64 ++++++++++++++++++- .../preregistration-blind-v2.md | 2 +- 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ac5f9a..a712a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,13 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m - **Adversarial tests:** several inbound transfers in one block, an inbound followed by an equal spend, an internal credit beside an external inbound, reverted and successful inbound together, a missed own-transaction block, truncation, own transactions at the window edges, a self-transfer, outside-window inbound, the minimum cost, and a seeded randomized oracle. - **C2, the warning-facing shadow variant:** a native observation is a candidate only when its sender imitates one of the wallet's own references, and there is one candidate per lookalike, with an event count. In a test, 1,000 zero-value strangers produce 0 C2 candidates. C1 stays a coverage measurement. The production detector reads no native inbound. - **Added `replay record-window`:** outcome-blind recording, taking only the wallet, chain, block window and settings; it never overwrites. -- **Pre-registered:** the outcome-blind replay of the Stage 2a window (`docs/ml/incident-benchmark/preregistration-blind-v2.md`). Cap requested: 2,500. Not approved. +- **Blind replay** (1,299 of an approved 2,500 RPC requests; one rate-limited attempt plus the one restart): `replay record-window` was given only the victim, chain and window. It independently recorded the native dust planting, with its identity, sender, value, block and success read from the receipt. + - **C0:** 2 lookalikes. + - **C1:** adds exactly the paid address, 357 blocks before the theft. + - **Production detector:** unchanged. + - **V1–V5:** all passed. + - **Classification:** a development-case regression, not validation. + - **Decision** (`ML_OBSERVATION_COMPLETENESS.md` §35): `observation/2` is sufficient for offline research within its scope. Production integration needs untouched incidents, a volume study and a separately approved detector change. ### Observation completeness and candidate discovery, Phase 12.4 (no RPC requests) - **Protocol 12.4** (`docs/ml/protocol-12.4.md`) was frozen before the code and the study. diff --git a/ML_OBSERVATION_COMPLETENESS.md b/ML_OBSERVATION_COMPLETENESS.md index 11d4c31..5bf1272 100644 --- a/ML_OBSERVATION_COMPLETENESS.md +++ b/ML_OBSERVATION_COMPLETENESS.md @@ -5,7 +5,7 @@ | Protocol (frozen before the code and the study) | [`docs/ml/protocol-12.4.md`](docs/ml/protocol-12.4.md), `3a79b74` | | Implementation (committed before the study ran) | `3917957` | | Study output (git-ignored) | `data/ml/research/phase12.4/observation-study.json` (`cryptoguard ml observation-study`) | -| New RPC requests / downloads | **0** for the phase / none; plus **2** for the approved Q1 (§33) and **17** for the approved Q1b (§34) | +| New RPC requests / downloads | **0** for the phase / none; plus **2** (Q1, §33), **17** (Q1b, §34) and **1,299** (blind `observation/2` replay, §35), all separately approved | ## 1. Executive summary @@ -365,3 +365,65 @@ Of those, 26 tests are new: 22 synthetic and invariance tests, and 4 recorder te - **The case stays a development case.** This is a development-case regression success, not independent validation. - **The production detector would still not flag it.** It is unchanged and reads no native inbound. Feeding `observation/2` native inbound to the detector is a production change that needs its own approval and evaluation, including the zero-value volume risk in §21. +## 35. Final validation: outcome-blind `observation/2` replay (2026-11-08/09; approved cap 2,500) + +**Pre-registration:** `docs/ml/incident-benchmark/preregistration-blind-v2.md`, frozen in `368f652` before any request. + +**Command:** `replay record-window`. Its only inputs were the victim's address, chain 1, blocks 21,869,297–21,890,897, and `observation/2`. It read no manifest, so the paid address and the hashes never reached the recorder. + +**Ledger:** `data/ml/rpc/ledger-blind-v2.json`, **1,299 of 2,500**. + +| Attempt | Requests | Outcome | +|---|---|---| +| 1 | 596 | Provider rate limit on `eth_getTransactionCount`, after 3 retries. No fixture written (fail closed). | +| The one permitted restart | 703 | Complete. Fixture `data/ml/research/phase12.4/blind-v2/fixture.json`, canonical SHA-256 `19c2cd75…b0fe`. | + +**Preflight.** Before attempt 1, the bounded resource check passed on its 4th try: 2.08 GiB free, CPU 19 %. The disk queue was high, but the recorder writes one small ledger record per request. Before the restart, five checks were made. Three failed, with 0.26–0.88 GiB free, and the 5th passed with 1.63 GiB free and CPU 7 %. No other process was touched. + +**Verification** (criteria fixed in the pre-registration): + +| ID | Result | +|---|---| +| V1 | **PASS.** `native_inbound` holds `0xf4530315…2b83`: sender `0x804051b0…793375`, block 21,890,540, index 150, 1,000,000,000,000 wei, `succeeded` true **read from the receipt**. | +| V2 | **PASS.** `native_inbound_external` is `complete` (2 transfers). | +| V3 | **PASS.** The ERC-20 transfers (9) and wallet transactions (12) match the frozen `observation/1` fixture identity for identity. | +| V4 | **PASS.** At cutoff (21,890,897, 0):
• **C0:** the 2 fake-token lookalikes, identical to C0 on the frozen fixture.
• **C1:** adds **exactly one** candidate, the paid address (`lookalike_in`, native, affix 4 + 6 to `0x80404f3e…`, block 21,890,540: **357 blocks, 4,320 s, before the theft**).
• **C2:** the same 3 lookalikes, one candidate each, with no abstention and the paid address imitating `0x80404f3e…`.
• **Removed:** nothing. **Duplicates:** none. | +| V5 | **PASS.** `detector_outputs` is identical at H − 1 and at H on the `/2` fixture and its `/1` projection. | + +**The other native inbound** was 7.83 ETH from `0x28c6c062…1d60`. It imitates no reference, so it is correctly not a candidate in C1 or C2. + +**The other categories:** +- **Absent:** no unattributed credits, no ERC-721-shaped logs and no malformed logs. The classes `observation/1` discarded were empty in this window. +- **Partial, as designed:** unattributed credits (12 own-transaction blocks) and zero-value native. +- **Unsupported:** internal transfers. +- **Not collected:** ERC-1155. + +**Cost.** The complete attempt took 703 requests. The `/1` recording of the same window, made earlier, took 645. So the `observation/2` additions cost on the order of 60 requests here: 2 increase blocks, plus balance reads at 13 run edges, block reads and receipts. That is well below the pre-registered estimate of about 1,050, which assumed about 20 increase blocks. The failed first attempt shows that the free endpoint's rate limit, not the method, is the main cost risk. + +**What this is.** A **development-case regression success**: the wallet-centric recorder, run blind on the real window, independently found the planting that `observation/1` missed. And C0's own rules, applied to that observation, flag the address that was later paid. It is **not** independent validation, because this case and its planting were known before the run. + +### Decision + +**`observation/2` is sufficiently correct for broader offline research** within its declared scope: nonzero native ETH received by wallets without code, together with ERC-721-shaped records, malformed-log counts and per-category coverage. That conclusion rests on four pieces of evidence: +- the audit, which found and fixed the success-inference weakness; +- 12 adversarial tests, including a randomized oracle; +- the synthetic mechanism suite; +- one real blind window that passed every pre-registered check. + +**Still unverified:** +1. **Zero-value native transactions** (a 0-ETH planting). The method cannot see them, and no real case exercised them. +2. **Internal transfers.** Traces are needed. +3. **ERC-1155** is not queried. +4. **Wallets with code or EIP-7702 delegations.** They are declared `unsupported`, and one delegated and revoked inside a window would go undetected. +5. **Busy wallets:** cost and rate-limit behaviour. This window had 2 increase blocks. +6. **More than one real window.** n = 1, and it is a known case. + +**Needed before any production integration:** +- **(a)** `observation/2` recordings of several **untouched** incidents, recorded blind from the start under a pre-registration; +- **(b)** a volume study of C2 on `observation/2` background windows, as unlabelled alerts per wallet-day, never called a false-positive rate; +- **(c)** a separately pre-registered and approved detector change that reads native inbound as a planting signal. It must require a lookalike and exclude zero-value-only evidence, and it must pass replay regression on every fixture. +- **(d)** a cost and latency profile for live monitoring, where per-block inbound reading is simpler than bisection; +- **(e)** handling for wallets with code. + +Until then the production detector stays unchanged and does not read native inbound. + diff --git a/docs/ml/incident-benchmark/preregistration-blind-v2.md b/docs/ml/incident-benchmark/preregistration-blind-v2.md index 9f7771f..3a19cbb 100644 --- a/docs/ml/incident-benchmark/preregistration-blind-v2.md +++ b/docs/ml/incident-benchmark/preregistration-blind-v2.md @@ -2,7 +2,7 @@ **Frozen:** 2026-11-08, in the commit that adds this file. That is before any request for this replay. -**Status:** **not approved.** It runs only after the user approves a new request cap. Earlier caps are exhausted and do not carry over. +**Status:** run on 2026-11-08/09 under an approved 2,500 cap. It used 1,299 requests: attempt 1 hit a rate limit after 596 and wrote no fixture, and the one restart used 703. **V1–V5 all passed.** See `ML_OBSERVATION_COMPLETENESS.md` §35. This file was not changed before or during the run. **Governing rules:** `docs/ml/protocol-12.4.md`, and `ML_OBSERVATION_COMPLETENESS.md` §33–34. From 16586a515eff723115553a494f31a237e6c8a455 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 00:49:32 +0300 Subject: [PATCH 66/92] docs(ml): freeze protocol 12.5 (candidate discovery and evidence-aware ranking) Frozen before any outcome of the new tasks. Archive ranking questions are answered by citing Phase 12.1 (its test split is used) plus exploratory development-split analyses; the primary ML test is a new self-supervised proxy task (next planting mechanism from the planting prefix) with frequency and Markov baselines, a fixed logistic regression, the 12.1 temporal group split, log loss and a group-bootstrap CI. Wallet-centric work: point-in-time candidate feature schema with value/status pairs, an offline shadow ranking, robustness and cost tests. PU and wallet self-supervised learning are audited, not forced. 0 RPC. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.5.md | 132 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 docs/ml/protocol-12.5.md diff --git a/docs/ml/protocol-12.5.md b/docs/ml/protocol-12.5.md new file mode 100644 index 0000000..7e6d484 --- /dev/null +++ b/docs/ml/protocol-12.5.md @@ -0,0 +1,132 @@ +# Protocol 12.5: ML-driven candidate discovery and evidence-aware ranking + +**Frozen:** 2026-11-09, in the commit that adds this file. That is before any outcome of the new tasks below has been computed. + +**Already seen at freezing:** +- the Phase 12.1–12.4 results; +- the archive episode counts (1,068 eligible episodes, 32,697 plantings); +- the wallet-centric fixtures used in Phase 12.4. + +**RPC:** 0 requests. **Downloads:** none. + +## 1. Position + +Phase 12.1 (`ML_TEMPORAL_GRAPH_RESEARCH.md`) already ran, on the archive's payoff episodes: +- the temporal, semantic and graph ranking features; +- a learned conditional logit, which did not beat recency (T0); +- ablations, strata and controls. + +Its test split has been used. **No archive ranking result in this phase can be confirmatory.** Repeating that study is not a contribution, so archive ranking questions are answered by citing 12.1, plus exploratory analyses on its **development split only**. Wallet-centric data hold 2 known development cases and unlabelled windows, so ranking there is descriptive. + +## 2. Research questions and hypotheses + +| RQ | Hypothesis | Task | Population | Status | +|---|---|---|---|---| +| RQ1 coverage | `observation/2` plus C1 recovers mechanisms invisible to C0. C2 bounds the volume. | T1, T2 | P1 synthetic; P3 dev (v1 and blind v2); P5 | descriptive and controlled | +| RQ2 semantics | The semantic channel of a candidate's latest planting (spoofed-outgoing vs inbound) carries ranking information beyond recency. | T3 | archive development split | **exploratory** | +| RQ3 temporal | **H3a:** a wallet-normalized temporal anomaly score (median/MAD of interarrival) adds nothing to recency within an episode. Predicted analytically: any per-episode monotone transform of the same recency ranks identically. **H3b:** recency is the strongest available temporal ranking signal. | T3 | archive (cited, 12.1); P3 descriptive | analytic, cited | +| RQ4 graph | Graph features add information. | T3 | — | **not re-run.** 12.1 found G1 at random and G2/G3 below it, and the wallet-centric data have 0 cross-wallet signer links. Recorded as blocked. | +| RQ5 missingness | C2 and the feature schema abstain or mark unknowns, and never invent evidence, under controlled information loss. | T5 | P1, P3 | controlled | +| RQ6 cost | Discovery, features and ranking stay bounded under floods. | T5 | P1 | controlled | +| RQ7 generalization | Which findings survive source, mechanism and time shift? | all | stratified | descriptive | +| **RQ8 proxy (new)** | **H8: the mechanism of a victim's next planting is predictable from its planting prefix, better than frequency and Markov baselines.** | T4, a self-supervised event-pattern task | archive episodes | **primary ML test (§4)** | + +## 3. Populations (never pooled) + +| ID | Description | Use | +|---|---|---| +| P1 | Synthetic fixtures with hand-written oracles | correctness, coverage, robustness, cost | +| P2 | The 4 packaged replay fixtures | excluded: frozen Cohort B | +| P3 | 2 Level I development cases. One is recorded twice: `observation/1` (frozen) and the blind `observation/2` replay. | development-case description only; never used for selection | +| P4 | Archive payoff episodes (Tsuchiya, CC BY-NC-ND, local only) | RQ2 exploratory; RQ8 primary | +| P5 | 6 background windows without frozen items (`observation/1`) | unlabelled volume. **Never used to estimate native volume.** | + +**Protected data.** Episodes of the 60 review wallets are already excluded by `load_episodes`. Episodes that share an entity or a linkage group with any frozen item (`lookalike_ranking.protected_overlap`) are also removed. Cohort files must keep their hashes (§8). + +## 4. Primary ML test: RQ8 (next-planting mechanism) + +- **Unit.** One planting event of an eligible archive episode, from the second planting on. +- **Input.** Only plantings in **strictly earlier blocks**. Same-block order is unknown, so same-block predecessors are excluded. +- **Target.** The event's mechanism class: + + | Class | Rule | + |---|---| + | `spoofed_out` | the victim is the sender | + | `counterfeit_in` | otherwise, the counterfeit flag | + | `tiny_in` | otherwise, the tiny flag | + | `zero_in` | otherwise, the zero flag | + | `other` | anything else | + + The flags are the source's own heuristics, and the target is a proxy. **It is not poisoning detection.** +- **Prefix features** (`proxy-features/1`): + - counts and shares of each class in the prefix; + - the last class (one-hot); + - log prefix length; + - log blocks since the previous planting; + - distinct lookalikes in the prefix; + - the last planting's token in a reviewed-stablecoin list or not; + - whether the last two classes are equal. +- **Split.** Phase 12.1's temporal group split (`protocol_groups`, `temporal_split`, test share 0.4): + - train on development episodes; + - evaluate once on test episodes. + + Test episodes were inspected for a different target (12.1 ranking), never for this one. That is disclosed. +- **Baselines** (fit on train only): + 1. the global class frequency; + 2. the victim-prefix frequency (Laplace α = 1, backed off to global); + 3. a first-order Markov transition from the last class (Laplace α = 1). +- **Model.** Multinomial logistic regression (scikit-learn, L2, C = 1, `lbfgs`, standardized features, seed 20261109). **No hyperparameter search.** +- **Primary metric:** test log loss (cross-entropy). +- **Secondary metrics:** macro-F1, and the per-class recall table. +- **Uncertainty:** the paired difference in mean log loss, LR minus the best baseline. Its 95% CI comes from a group bootstrap over episode groups (2,000 draws, seed 20261109). +- **Decision.** **H8 supported** if the LR's log loss is lower than every baseline's and the CI of the difference with the best baseline excludes 0. **Not supported** otherwise. Markov winning is a valid negative result: it would mean simple statistics suffice. + +## 5. RQ2 exploratory (archive development split only) + +- **B5 semantic channel ranking:** candidates whose latest planting is `spoofed_out` rank first, with recency (T0) breaking ties. It is compared with T0 by tie-averaged top-1 on development episodes, with a group bootstrap CI. It is reported as exploratory. **The test split is not used.** +- **H3a** is checked numerically: a median/MAD-normalized recency must produce T0's ranking exactly. + +## 6. Wallet-centric work (T1, T2, T5) + +**Candidate feature schema `poisoning-candidate-features/1`.** Every value is paired with a status: `observed`, `zero_observed`, `unknown` or `not_applicable`. Its families: +- address: affixes, matched references, earlier payment to the reference, blocks since that payment; +- semantics: kind, zero value, signer role, emitter reviewed, receipt status; +- temporal: first and last seen, events, events in the last day, median interarrival; +- graph: in-window signer reuse; +- completeness: the coverage per category. + +The schema uses only observations strictly before the cutoff. Metamorphic tests check that future events, payoffs and signer links change nothing, and that reordering changes nothing. + +**Shadow ranking `poisoning-candidate-ranking/1`** (offline, disabled by default): +- **Input:** C2 candidates. +- **Default order:** B4 (recency of the latest evidence), the only signal with large-sample support. That support is source-conditional, from Phase 12.1. +- **Reported alongside:** B3 (similarity), B5 (semantic channel) and B6 (familiarity) ranks, with feature availability, completeness and evidence references. +- **Never:** a probability, a severity change or a suppression. + +**Robustness (P1, P3):** +- shortened window; +- native observations removed; +- signer unknown; +- no reference history; +- receipts unknown. + +The measures are candidate-set stability, abstention and unsupported rate. + +**Cost (P1):** floods of 10,000 zero-value native transfers and 1,000 lookalikes. The measures are runtime, peak traced memory, and C2 candidates, bounded by distinct lookalikes. + +## 7. Feasibility audits (no forced models) + +- **Self-supervised learning on wallet histories:** blocked if the eligible wallet-centric sequences hold fewer than 1,000 events. At freezing there are about 8 windows with roughly 100 events. +- **PU learning:** + - **Positives:** the paid candidates. Exactly one per episode, chosen by the source's payoff-confirmation rule. + - **Unlabelled:** the rival candidates, all of them plantings. + - **The class prior is fixed by design (1/k)**, and SCAR is violated, so no PU risk is estimated. The ranking formulation (12.1's conditional logit) stays the appropriate one. +- **Graph:** not re-run (§2). + +## 8. Integrity rules + +- **Cohorts and fixtures:** the hashes of Cohort A and B sheets and of the frozen fixtures are checked before and after the phase. +- **Labels and metrics:** no label is invented, and nothing unknown is treated as benign. No false-positive rate, precision or recall is reported. +- **Production:** the detector, its findings and C0 are unchanged, and ML stays out of production. +- **Resources:** one heavy process at a time, under 1 GiB RSS, with no live RPC. The archive episodes are cached once in the git-ignored `data/ml/research/phase12.5/`, and never committed. +- **Gate labels:** PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA, NOT EVALUATED. From 0dd8a2393971e3fc2014a621f8e67170517d8324 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 01:04:29 +0300 Subject: [PATCH 67/92] feat(ml): Phase 12.5 research code - proxy task, candidate features, shadow ranking (no RPC) Committed before the outcome-based run (protocol 12.5, 16586a5). - ml/candidate_research.py: episode cache (protected wallets and every frozen-overlap episode removed; 12.1 groups and temporal split), the primary proxy task planting-mechanism-next/1 (prefix of strictly earlier blocks; global, victim-prefix and Markov baselines; fixed multinomial logistic regression; log loss; group-bootstrap CI), the RQ2 exploratory semantic-channel ranking on the development split, the H3a MAD-recency equivalence, wallet-centric coverage/volume, robustness transforms, development-case ranks and a synthetic flood. - ml/candidate_features.py: poisoning-candidate-features/1 with (value, status) pairs, never zero for unobserved; offline shadow ranking poisoning-candidate-ranking/1 (B4 order; B3/B5/B6 alongside; research CLI only). - CLI: ml candidate-research, ml candidate-ranking. - Tests: 14 with hand-written oracles (proxy rows and same-block rule, baselines, single-class refusal, metrics, bootstrap, tie-averaged top-1, MAD equivalence, end-to-end C0/C1/C2 + features + ranking, point-in-time metamorphic checks, missingness, flood bound, robustness never adds candidates). Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/candidate_features.py | 232 +++++++ src/cryptoguard/ml/candidate_research.py | 834 +++++++++++++++++++++++ src/cryptoguard/ml/cli.py | 32 + tests/test_ml_candidate_research.py | 263 +++++++ 4 files changed, 1361 insertions(+) create mode 100644 src/cryptoguard/ml/candidate_features.py create mode 100644 src/cryptoguard/ml/candidate_research.py create mode 100644 tests/test_ml_candidate_research.py diff --git a/src/cryptoguard/ml/candidate_features.py b/src/cryptoguard/ml/candidate_features.py new file mode 100644 index 0000000..68168da --- /dev/null +++ b/src/cryptoguard/ml/candidate_features.py @@ -0,0 +1,232 @@ +"""Point-in-time candidate features and an offline shadow ranking (protocol 12.5 §6). + +``poisoning-candidate-features/1``: for each C2 candidate of a wallet window, features from +observations strictly before the cutoff, each a ``(value, status)`` pair. ``status`` is one of +``observed``, ``zero_observed`` (a real zero in a fully observed scope), ``unknown`` (the +source did not observe what the feature needs) and ``not_applicable``. A missing +observation is never a zero. + +``poisoning-candidate-ranking/1``: orders C2 candidates by B4 (recency of the latest +evidence), the one signal with large-sample support, which is source-conditional (Phase 12.1, +archive payoff episodes). B3 (similarity), B5 (semantic channel) and B6 (familiarity) ranks +are reported beside it. Research only: disabled by default, called only from the research +CLI, never a probability, a severity, a suppression or a production finding. +""" + +from __future__ import annotations + +import itertools +import statistics +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from typing import Any, Literal + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml.candidates import similar +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.replay.observation import coverage_of + +FEATURE_VERSION = "poisoning-candidate-features/1" +RANKING_VERSION = "poisoning-candidate-ranking/1" +DAY = 7_200 +Status = Literal["observed", "zero_observed", "unknown", "not_applicable"] + + +@dataclass(frozen=True) +class FeatureValue: + value: float | str | None + status: Status + + +def _count(n: int, complete: bool) -> FeatureValue: + if not complete: + return FeatureValue(None, "unknown") + return FeatureValue(float(n), "observed" if n else "zero_observed") + + +def candidate_features( + fixture: Any, candidate: cd.DiscoveryCandidate, cutoff: tuple[int, int] +) -> dict[str, FeatureValue]: + """Features of one candidate from observations strictly before ``cutoff``.""" + cov = coverage_of(fixture) + obs = [o for o in cd.observations(fixture) if (o.block, o.tx_index) < cutoff] + look = candidate.lookalike + mine = [o for o in obs if o.counterparty == look] + refs_complete = cov.complete(*cd.REFERENCE_CATEGORIES) + chosen = [o for o in obs if o.direction == "out" and o.wallet_signed is True] + matched = {o.counterparty for o in chosen if similar(look, o.counterparty)} + first = mine[0] if mine else None + f: dict[str, FeatureValue] = {} + # address + if candidate.affix is None: + f["affix_prefix"] = f["affix_suffix"] = FeatureValue(None, "not_applicable") + else: + f["affix_prefix"] = FeatureValue(float(candidate.affix[0]), "observed") + f["affix_suffix"] = FeatureValue(float(candidate.affix[1]), "observed") + f["matched_references"] = _count(len(matched), refs_complete) + ref_pays = [ + o + for o in chosen + if candidate.imitated and o.counterparty == candidate.imitated and o.succeeded is not False + ] + if candidate.imitated is None: + f["reference_paid_before"] = FeatureValue(None, "not_applicable") + f["blocks_since_reference_payment"] = FeatureValue(None, "not_applicable") + elif not refs_complete: + f["reference_paid_before"] = FeatureValue(None, "unknown") + f["blocks_since_reference_payment"] = FeatureValue(None, "unknown") + else: + f["reference_paid_before"] = FeatureValue(float(bool(ref_pays)), "observed") + f["blocks_since_reference_payment"] = ( + FeatureValue(float(cutoff[0] - ref_pays[-1].block), "observed") + if ref_pays + else FeatureValue(None, "not_applicable") + ) + # semantics (of the earliest evidence) + f["kind"] = FeatureValue(candidate.kind, "observed") + f["channel"] = FeatureValue( + "spoofed_out" if "spoofed_out" in candidate.methods else "inbound", "observed" + ) + if first is None: + f["zero_value"] = FeatureValue(None, "unknown") + f["signer_role"] = FeatureValue(None, "unknown") + else: + f["zero_value"] = FeatureValue(float(first.value == 0), "observed") + role = ( + "lookalike_itself" + if first.kind == "native" and first.direction == "in" + else "unknown" + if first.signer is None + else "wallet" + if first.wallet_signed + else "foreign" + ) + f["signer_role"] = FeatureValue(role, "unknown" if role == "unknown" else "observed") + if candidate.kind == "erc20" and first is not None: + f["emitter_reviewed"] = FeatureValue(float(first.emitter in TRUSTED_TOKENS), "observed") + else: + f["emitter_reviewed"] = FeatureValue(None, "not_applicable") + if candidate.kind == "native" and first is not None: + f["receipt_status"] = ( + FeatureValue(float(first.succeeded), "observed") + if first.succeeded is not None + else FeatureValue(None, "unknown") + ) + else: + f["receipt_status"] = FeatureValue(None, "not_applicable") + # temporal + blocks = [o.block for o in mine] + f["first_seen_block"] = ( + FeatureValue(float(blocks[0]), "observed") if blocks else FeatureValue(None, "unknown") + ) + f["last_seen_block"] = ( + FeatureValue(float(blocks[-1]), "observed") if blocks else FeatureValue(None, "unknown") + ) + f["events"] = FeatureValue(float(len(mine)), "observed") + f["events_last_day"] = FeatureValue( + float(sum(1 for b in blocks if b > cutoff[0] - DAY)), "observed" + ) + gaps = [b - a for a, b in itertools.pairwise(blocks)] + f["median_interarrival"] = ( + FeatureValue(float(statistics.median(gaps)), "observed") + if gaps + else FeatureValue(None, "not_applicable") + ) + # graph (in-window only: no cross-wallet index is available for these windows) + signers = {o.signer for o in mine if o.signer and o.signer != fixture.wallet.lower()} + if not signers: + f["signer_reuse_in_window"] = FeatureValue(None, "unknown") + else: + others = {o.counterparty for o in obs if o.signer in signers and o.counterparty != look} + f["signer_reuse_in_window"] = FeatureValue( + float(len(others)), "observed" if others else "zero_observed" + ) + # completeness (statuses, never risk) + for cat in ("erc20_transfer_logs", "native_inbound_external", "erc20_outgoing_signers"): + f[f"coverage_{cat}"] = FeatureValue(cov.status(cat), "observed") + return f + + +@dataclass(frozen=True) +class RankedCandidate: + lookalike: str + imitated: str | None + methods: tuple[str, ...] + kind: str + evidence: str + cutoff: tuple[int, int] + rank: float # the shadow order (B4), tie-averaged + baseline_ranks: dict[str, float] + features_available: int + features_unknown: int + completeness: dict[str, str] + version: str + explanation: str + + +def _ranks(scores: Mapping[str, tuple[float, ...]]) -> dict[str, float]: + """1 is best; ties share the average rank.""" + order = sorted(scores, key=lambda c: scores[c], reverse=True) + out: dict[str, float] = {} + i = 0 + while i < len(order): + j = i + while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]: + j += 1 + for c in order[i : j + 1]: + out[c] = (i + j) / 2 + 1 + i = j + 1 + return out + + +def rank(fixture: Any, cutoff: tuple[int, int]) -> list[RankedCandidate]: + """The offline shadow ranking of a window's C2 candidates at ``cutoff``.""" + res = cd.discover(fixture, cutoff=cutoff, variant="C2") + feats = {c.lookalike: candidate_features(fixture, c, cutoff) for c in res.candidates} + + def val(c: str, k: str) -> float: + v = feats[c][k].value + return float(v) if isinstance(v, (int, float)) else float("-inf") + + b4 = {c: (val(c, "last_seen_block"),) for c in feats} + b3 = {c: (val(c, "affix_prefix") + val(c, "affix_suffix"),) for c in feats} + b5 = { + c: (float(feats[c]["channel"].value == "spoofed_out"), val(c, "last_seen_block")) + for c in feats + } + b6 = {c: (-val(c, "blocks_since_reference_payment"),) for c in feats} + ranks = {"B4": _ranks(b4), "B3": _ranks(b3), "B5": _ranks(b5), "B6": _ranks(b6)} + out = [] + for c in res.candidates: + f = feats[c.lookalike] + known = sum(1 for v in f.values() if v.status in ("observed", "zero_observed")) + unknown = sum(1 for v in f.values() if v.status == "unknown") + out.append( + RankedCandidate( + lookalike=c.lookalike, + imitated=c.imitated, + methods=c.methods, + kind=c.kind, + evidence=c.evidence, + cutoff=cutoff, + rank=ranks["B4"][c.lookalike], + baseline_ranks={k: v[c.lookalike] for k, v in ranks.items()}, + features_available=known, + features_unknown=unknown, + completeness={ + k.removeprefix("coverage_"): str(v.value) + for k, v in f.items() + if k.startswith("coverage_") + }, + version=RANKING_VERSION, + explanation=( + f"suspicious lookalike candidate ({'+'.join(c.methods)}, {c.kind}); " + f"ordered by recency of its latest evidence; not a probability" + ), + ) + ) + return sorted(out, key=lambda r: (r.rank, r.lookalike)) + + +def serialize(ranked: Sequence[RankedCandidate]) -> list[dict[str, Any]]: + return [asdict(r) for r in ranked] diff --git a/src/cryptoguard/ml/candidate_research.py b/src/cryptoguard/ml/candidate_research.py new file mode 100644 index 0000000..fcec27d --- /dev/null +++ b/src/cryptoguard/ml/candidate_research.py @@ -0,0 +1,834 @@ +"""Phase 12.5 archive research (protocol 12.5 §4 and §5), offline. + +- ``cache_episodes`` / ``load_cache``: the eligible Phase 12.1 payoff episodes (protected + wallets and every episode sharing an entity or linkage group with a frozen review item + removed), with 12.1's group ids and temporal dev/test split, cached once locally. The + source is CC BY-NC-ND: the cache stays in the git-ignored research folder. +- **RQ8, the primary ML test** (``proxy_task``): predict the mechanism class of a victim's + next planting from plantings in strictly earlier blocks. A self-supervised event-pattern + proxy on source-flagged rows, **not** poisoning detection. Baselines: global frequency, + victim-prefix frequency, first-order Markov. Model: a fixed multinomial logistic + regression. Metric: test log loss with a group-bootstrap CI of the paired difference. +- **RQ2, exploratory** (``semantic_channel``): rank candidates by the semantic channel of + their latest planting (``spoofed_out`` first) with recency breaking ties, against recency + alone, on the development split only. +- **H3a** (``mad_recency_equivalence``): a median/MAD-normalized recency ranks exactly as + recency within an episode. +""" + +from __future__ import annotations + +import json +import math +import random +import statistics +from collections import Counter +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +PROXY_TASK = "planting-mechanism-next/1" +PROXY_FEATURES = "proxy-features/1" +CLASSES = ("spoofed_out", "counterfeit_in", "tiny_in", "zero_in", "other") +SEED = 20261109 +STABLECOINS = frozenset( + { + "0xdac17f958d2ee523a2206206994597c13d831ec7", + "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", + "0x6b175474e89094c44da98b954eedeac495271d0f", + } +) + + +@dataclass(frozen=True) +class Planting: + block: int + line: int + token: str + sender: str + receiver: str + flags: int + + +@dataclass(frozen=True) +class CachedEpisode: + victim: str + payoff_block: int + paid: str + group: int + split: str # "dev" or "test" (12.1's temporal group split) + plantings: tuple[Planting, ...] + + def lookalike(self, p: Planting) -> str: + return p.receiver if p.sender == self.victim else p.sender + + @property + def candidates(self) -> tuple[str, ...]: + return tuple(sorted({self.lookalike(p) for p in self.plantings})) + + +def mechanism(p: Planting, victim: str) -> str: + """The protocol's class of one planting (source flags; a proxy, not a verdict).""" + from cryptoguard.ml.tsuchiya_archive import COUNTERFEIT, TINY, ZERO + + if p.sender == victim: + return "spoofed_out" + if p.flags & COUNTERFEIT: + return "counterfeit_in" + if p.flags & TINY: + return "tiny_in" + if p.flags & ZERO: + return "zero_in" + return "other" + + +# --- cache ---------------------------------------------------------------------------------- + + +def cache_episodes(poisoning_dir: Path, out: Path) -> dict[str, Any]: + """Build the episode cache from the local archive subset (about 5 minutes on an HDD).""" + from cryptoguard.ml import lookalike_ranking as lr + + episodes, excluded = lr.load_episodes(poisoning_dir) + addrs, txs = lr.protected_entities(poisoning_dir) + overlap = lr.protected_overlap(episodes, addrs, txs) + kept = [e for e, o in zip(episodes, overlap, strict=True) if not o] + grp, mode = lr.protocol_groups(kept) + split = lr.temporal_split(kept, grp) + out.parent.mkdir(parents=True, exist_ok=True) + with out.open("w", encoding="utf-8") as fh: + for e, g, s in zip(kept, grp, split, strict=True): + fh.write( + json.dumps( + { + "victim": e.victim, + "payoff_block": e.payoff_block, + "paid": e.paid, + "group": g, + "split": s, + "plantings": [ + [r.block, r.line, r.token, r.sender, r.receiver, r.flags] + for r in e.plantings + ], + } + ) + + "\n" + ) + return { + "eligible_episodes": len(episodes), + "excluded_before": excluded, + "excluded_protected_overlap": sum(overlap), + "kept": len(kept), + "group_mode": mode, + "groups": len(set(grp)), + "dev": split.count("dev"), + "test": split.count("test"), + } + + +def load_cache(path: Path) -> list[CachedEpisode]: + out = [] + for line in path.read_text(encoding="utf-8").splitlines(): + d = json.loads(line) + out.append( + CachedEpisode( + d["victim"], + d["payoff_block"], + d["paid"], + d["group"], + d["split"], + tuple(Planting(*p) for p in d["plantings"]), + ) + ) + return out + + +# --- RQ8: next-planting mechanism (self-supervised proxy) ----------------------------------- + + +@dataclass(frozen=True) +class ProxyRow: + group: int + split: str + victim: str + target: str + prefix: tuple[str, ...] # classes of plantings in strictly earlier blocks, in order + features: tuple[float, ...] + + +FEATURE_NAMES = ( + *(f"count_{c}" for c in CLASSES), + *(f"share_{c}" for c in CLASSES), + *(f"last_{c}" for c in CLASSES), + "log_prefix_len", + "log_blocks_since_last", + "distinct_lookalikes", + "last_token_stablecoin", + "last_two_equal", +) + + +def proxy_rows(episodes: Sequence[CachedEpisode]) -> list[ProxyRow]: + """One row per planting that has at least one planting in a strictly earlier block. + Same-block predecessors are never inputs (their order is unknown).""" + rows = [] + for e in episodes: + ordered = sorted(e.plantings, key=lambda p: (p.block, p.line)) + for i, p in enumerate(ordered): + prior = [q for q in ordered[:i] if q.block < p.block] + if not prior: + continue + classes = tuple(mechanism(q, e.victim) for q in prior) + counts = Counter(classes) + n = len(prior) + last = prior[-1] + feats = ( + *(float(counts[c]) for c in CLASSES), + *(counts[c] / n for c in CLASSES), + *(float(classes[-1] == c) for c in CLASSES), + math.log1p(n), + math.log1p(p.block - last.block), + float(len({e.lookalike(q) for q in prior})), + float(last.token.lower() in STABLECOINS), + float(n >= 2 and classes[-1] == classes[-2]), + ) + rows.append( + ProxyRow(e.group, e.split, e.victim, mechanism(p, e.victim), classes, feats) + ) + return rows + + +def _global(train: Sequence[ProxyRow]) -> dict[str, float]: + c = Counter(r.target for r in train) + k = len(CLASSES) + return {cls: (c[cls] + 1) / (len(train) + k) for cls in CLASSES} + + +def baseline_probs( + train: Sequence[ProxyRow], rows: Sequence[ProxyRow] +) -> dict[str, list[dict[str, float]]]: + """Probabilities from the three baselines (fit on ``train`` only).""" + g = _global(train) + trans: dict[str, Counter[str]] = {c: Counter() for c in CLASSES} + for r in train: + trans[r.prefix[-1]][r.target] += 1 + k = len(CLASSES) + out: dict[str, list[dict[str, float]]] = {"global": [], "victim_prefix": [], "markov": []} + for r in rows: + out["global"].append(g) + pc = Counter(r.prefix) + n = len(r.prefix) + out["victim_prefix"].append({c: (pc[c] + g[c]) / (n + 1) for c in CLASSES}) + t = trans[r.prefix[-1]] + tot = sum(t.values()) + out["markov"].append({c: (t[c] + 1) / (tot + k) for c in CLASSES}) + return out + + +def logistic_probs(train: Sequence[ProxyRow], rows: Sequence[ProxyRow]) -> list[dict[str, float]]: + """The protocol's fixed model: standardized features, multinomial L2 logistic regression, + C = 1, lbfgs, seed fixed. No search.""" + import numpy as np + from sklearn.linear_model import LogisticRegression + from sklearn.pipeline import make_pipeline + from sklearn.preprocessing import StandardScaler + + labels = sorted({r.target for r in train}) + if len(labels) < 2: + raise ValueError("single-class training data: the proxy task is undefined") + x = np.array([r.features for r in train], dtype=float) + y = np.array([r.target for r in train]) + model = make_pipeline( + StandardScaler(), LogisticRegression(C=1.0, max_iter=2000, random_state=SEED) + ) + model.fit(x, y) + proba = model.predict_proba(np.array([r.features for r in rows], dtype=float)) + classes = list(model.classes_) + eps = 1e-6 # a class absent from training keeps a small floor, then renormalize + out = [] + for p in proba: + d = {c: eps for c in CLASSES} + for c, v in zip(classes, p, strict=True): + d[c] = float(v) + eps + s = sum(d.values()) + out.append({c: v / s for c, v in d.items()}) + return out + + +def log_losses(probs: Sequence[Mapping[str, float]], rows: Sequence[ProxyRow]) -> list[float]: + return [-math.log(max(p[r.target], 1e-12)) for p, r in zip(probs, rows, strict=True)] + + +def macro_f1(probs: Sequence[Mapping[str, float]], rows: Sequence[ProxyRow]) -> dict[str, Any]: + pred = [max(CLASSES, key=lambda c: (p[c], -CLASSES.index(c))) for p in probs] + true = [r.target for r in rows] + per: dict[str, dict[str, float | int]] = {} + f1s = [] + for c in CLASSES: + tp = sum(1 for a, b in zip(pred, true, strict=True) if a == c and b == c) + fp = sum(1 for a, b in zip(pred, true, strict=True) if a == c and b != c) + fn = sum(1 for a, b in zip(pred, true, strict=True) if a != c and b == c) + support = tp + fn + if support == 0: + continue # macro-F1 over classes present in the evaluation set + prec = tp / (tp + fp) if tp + fp else 0.0 + rec = tp / support + f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0 + per[c] = {"support": support, "recall": round(rec, 4), "f1": round(f1, 4)} + f1s.append(f1) + return {"macro_f1": round(sum(f1s) / len(f1s), 4) if f1s else None, "per_class": per} + + +def group_bootstrap_diff( + a: Sequence[float], b: Sequence[float], groups: Sequence[int], *, draws: int = 2000 +) -> dict[str, float]: + """Mean of a - b (per row), and a 95% percentile CI from resampling groups.""" + by: dict[int, list[float]] = {} + for x, y, g in zip(a, b, groups, strict=True): + by.setdefault(g, []).append(x - y) + keys = sorted(by) + sums = {g: sum(v) for g, v in by.items()} + lens = {g: len(v) for g, v in by.items()} + rng = random.Random(SEED) # noqa: S311 - resampling, not cryptography + stats = [] + for _ in range(draws): + pick = [keys[rng.randrange(len(keys))] for _ in keys] + stats.append(sum(sums[g] for g in pick) / sum(lens[g] for g in pick)) + stats.sort() + point = sum(sums.values()) / sum(lens.values()) + return { + "mean_diff": round(point, 5), + "ci_low": round(stats[int(0.025 * draws)], 5), + "ci_high": round(stats[int(0.975 * draws) - 1], 5), + "groups": len(keys), + } + + +def proxy_task(episodes: Sequence[CachedEpisode]) -> dict[str, Any]: + rows = proxy_rows(episodes) + train = [r for r in rows if r.split == "dev"] + test = [r for r in rows if r.split == "test"] + if not train or not test: + raise ValueError("the proxy task needs both development and test rows") + probs = baseline_probs(train, test) + probs["logistic"] = logistic_probs(train, test) + losses = {k: log_losses(v, test) for k, v in probs.items()} + mean = {k: round(statistics.fmean(v), 5) for k, v in losses.items()} + best = min(("global", "victim_prefix", "markov"), key=lambda k: mean[k]) + diff = group_bootstrap_diff(losses["logistic"], losses[best], [r.group for r in test]) + supported = ( + all(mean["logistic"] < mean[k] for k in ("global", "victim_prefix", "markov")) + and diff["ci_high"] < 0 + ) + return { + "task": PROXY_TASK, + "features": PROXY_FEATURES, + "feature_names": list(FEATURE_NAMES), + "rows": {"train": len(train), "test": len(test)}, + "groups": { + "train": len({r.group for r in train}), + "test": len({r.group for r in test}), + }, + "class_counts": { + "train": dict(Counter(r.target for r in train)), + "test": dict(Counter(r.target for r in test)), + }, + "test_log_loss": mean, + "test_macro_f1": {k: macro_f1(v, test) for k, v in probs.items()}, + "best_baseline": best, + "logistic_minus_best_baseline": diff, + "h8_supported": supported, + "label": "self-supervised proxy on source-flagged plantings; not poisoning detection", + } + + +# --- RQ2 exploratory and H3a --------------------------------------------------------------- + + +def _latest(e: CachedEpisode) -> dict[str, Planting]: + latest: dict[str, Planting] = {} + for p in sorted(e.plantings, key=lambda p: (p.block, p.line)): + latest[e.lookalike(p)] = p + return latest + + +def top1(scores: Mapping[str, tuple[float, ...]], paid: str) -> float: + best = max(scores.values()) + top = [c for c, s in scores.items() if s == best] + return 1.0 / len(top) if paid in top else 0.0 + + +def semantic_channel(episodes: Sequence[CachedEpisode]) -> dict[str, Any]: + """B5 (spoofed-out latest planting first, recency second) against T0 (recency), on the + development split only. Tie-averaged top-1.""" + dev = [e for e in episodes if e.split == "dev"] + t0s, b5s, grp = [], [], [] + paid_spoofed = rival_spoofed = rivals = 0 + for e in dev: + latest = _latest(e) + t0 = {c: (float(p.block),) for c, p in latest.items()} + b5 = { + c: (float(mechanism(p, e.victim) == "spoofed_out"), float(p.block)) + for c, p in latest.items() + } + t0s.append(top1(t0, e.paid)) + b5s.append(top1(b5, e.paid)) + grp.append(e.group) + for c, p in latest.items(): + spoofed = mechanism(p, e.victim) == "spoofed_out" + if c == e.paid: + paid_spoofed += spoofed + else: + rivals += 1 + rival_spoofed += spoofed + return { + "split": "dev", + "episodes": len(dev), + "groups": len(set(grp)), + "T0_top1": round(statistics.fmean(t0s), 4), + "B5_top1": round(statistics.fmean(b5s), 4), + "B5_minus_T0": group_bootstrap_diff(b5s, t0s, grp), + "latest_planting_spoofed_share": { + "paid": round(paid_spoofed / len(dev), 4), + "rivals": round(rival_spoofed / rivals, 4) if rivals else None, + }, + "label": "exploratory (12.1 development split; test split not used)", + } + + +def mad_recency_equivalence(episodes: Sequence[CachedEpisode]) -> dict[str, Any]: + """H3a: z = (latest block - median) / MAD of the episode's planting blocks is a strictly + increasing transform of the latest block, so it must rank candidates exactly as T0.""" + same = differ = undefined = 0 + for e in episodes: + latest = _latest(e) + blocks = [p.block for p in e.plantings] + med = statistics.median(blocks) + mad = statistics.median(abs(b - med) for b in blocks) + if mad == 0: + undefined += 1 + continue + t0 = sorted(latest, key=lambda c: (latest[c].block, c)) + z = sorted(latest, key=lambda c: ((latest[c].block - med) / mad, c)) + if t0 == z: + same += 1 + else: + differ += 1 + return {"episodes_same_order": same, "differ": differ, "mad_zero_undefined": undefined} + + +def inventory(poisoning_dir: Path) -> dict[str, Any]: + """Exact counts of the local research sources (no network).""" + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import load_cases + from cryptoguard.replay.observation import coverage_of + + def window(fx: Any) -> dict[str, Any]: + cov = coverage_of(fx) + return { + "schema": cov.schema_version, + "blocks": fx.to_block - fx.from_block + 1, + "transfers": len(fx.transfers), + "wallet_transactions": len(fx.wallet_transactions), + "native_inbound": None if fx.native_inbound is None else len(fx.native_inbound), + "not_complete": sorted(k for k, v in cov.categories.items() if v.status != "complete"), + } + + out: dict[str, Any] = {"replay_cases": {}, "level_i": {}, "background": {}} + for c in load_cases(): + if c.fixture: + out["replay_cases"][c.manifest.case_id] = window(c.fixture) + for c in ib.load_new_cases(): + if c.fixture: + out["level_i"][c.manifest.case_id] = window(c.fixture) + blind = Path("data/ml/research/phase12.4/blind-v2/fixture.json") + if blind.exists(): + from cryptoguard.replay.models import ReplayFixture + + out["level_i"]["scamsniffer-blind-v2"] = window( + ReplayFixture.model_validate_json(blind.read_text(encoding="utf-8")) + ) + for b in load_background(): + if b.fixture: + out["background"][b.manifest.case_id] = window(b.fixture) + sub = poisoning_dir / "archive_subset.sqlite" + out["archive_subset_bytes"] = sub.stat().st_size if sub.exists() else None + return out + + +# --- wallet-centric experiments (protocol 12.5 §6) ----------------------------------------- + +STABLECOIN_USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +TRANSFORMS = ( + "no_native", + "signer_unknown", + "last_day_only", + "no_reference_history", + "receipts_unknown", +) + + +def _window_variants(fixture: Any, cutoff: tuple[int, int]) -> dict[str, Any]: + import time + import tracemalloc + + from cryptoguard.ml import candidate_discovery as cd + + days = max(1.0, (min(cutoff[0], fixture.to_block + 1) - fixture.from_block) / 7_200) + out: dict[str, Any] = {} + for v in ("C0", "C1", "C2"): + tracemalloc.start() + t0 = time.perf_counter() + res = cd.discover(fixture, cutoff=cutoff, variant=v) + ms = (time.perf_counter() - t0) * 1000 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + by_method: Counter[str] = Counter(m for c in res.candidates for m in c.methods) + out[v] = { + "events": len(res.candidates), + "distinct": len(res.lookalikes), + "per_wallet_day": round(len(res.candidates) / days, 3), + "by_method": dict(sorted(by_method.items())), + "abstain": res.abstain, + "runtime_ms": round(ms, 2), + "peak_kib": round(peak / 1024, 1), + } + out["duplicates_suppressed_by_C2"] = out["C1"]["events"] - out["C2"]["events"] + return out + + +def _drop(fixture: Any, transform: str, cutoff: tuple[int, int]) -> Any: + """Controlled information loss. It never adds anything the source did not observe.""" + from cryptoguard.replay.observation import CategoryCoverage + + if transform == "no_native": + cov = fixture.observation + cats = dict(cov.categories) if cov else {} + cats["native_inbound_external"] = CategoryCoverage(status="not_collected") + return fixture.model_copy( + update={ + "native_inbound": None, + "observation": cov.model_copy(update={"categories": cats}) if cov else None, + } + ) + if transform == "signer_unknown": + return fixture.model_copy( + update={ + "transfers": [t.model_copy(update={"tx_sender": None}) for t in fixture.transfers] + } + ) + if transform == "last_day_only": + lo = cutoff[0] - 7_200 + return fixture.model_copy( + update={ + "from_block": max(fixture.from_block, lo), + "transfers": [t for t in fixture.transfers if t.block_number >= lo], + "wallet_transactions": [ + t for t in fixture.wallet_transactions if t.block_number >= lo + ], + "native_inbound": None + if fixture.native_inbound is None + else [n for n in fixture.native_inbound if n.block_number >= lo], + } + ) + if transform == "no_reference_history": + w = fixture.wallet.lower() + return fixture.model_copy( + update={ + "transfers": [ + t + for t in fixture.transfers + if not (t.sender.lower() == w and (t.tx_sender or "").lower() == w) + ], + "wallet_transactions": [], + } + ) + if transform == "receipts_unknown": + if fixture.native_inbound is None: + return fixture + return fixture.model_copy( + update={ + "native_inbound": [ + n.model_copy(update={"succeeded": None}) for n in fixture.native_inbound + ] + } + ) + raise ValueError(transform) + + +def robustness(fixture: Any, cutoff: tuple[int, int]) -> dict[str, Any]: + from cryptoguard.ml import candidate_discovery as cd + + base = cd.discover(fixture, cutoff=cutoff, variant="C2") + out: dict[str, Any] = {"base": sorted(base.lookalikes)} + for t in TRANSFORMS: + res = cd.discover(_drop(fixture, t, cutoff), cutoff=cutoff, variant="C2") + diff = cd.compare(base, res) + out[t] = { + "kept": len(diff["kept"]), + "removed": len(diff["removed"]), + "added": len(diff["added"]), + "abstain": res.abstain, + "not_complete": sorted(k for k, s in res.coverage.items() if s != "complete"), + } + return out + + +def development_ranks(fixture: Any, cutoff: tuple[int, int], paid: str) -> dict[str, Any]: + """Where each ordering puts the later-paid address among C2 candidates (descriptive).""" + from cryptoguard.ml import candidate_features as cf + + ranked = cf.rank(fixture, cutoff) + hit = next((r for r in ranked if r.lookalike == paid.lower()), None) + return { + "candidates": len(ranked), + "paid_present": hit is not None, + "paid_ranks": None if hit is None else hit.baseline_ranks, + "label": "development case (outcome known); never used for selection", + } + + +def flood_fixture(n_zero: int, n_lookalikes: int) -> Any: + """Synthetic: a wallet flooded with zero-value native transfers from strangers and + 1-wei transfers from many lookalikes of one reference.""" + from datetime import UTC, datetime + + from cryptoguard.replay.models import RecordedNativeInbound, RecordedTransfer, ReplayFixture + from cryptoguard.replay.observation import ( + OBSERVATION_V2, + CategoryCoverage, + ObservationCoverage, + ) + + wallet = "0x" + "c" * 40 + ref = "0xabcde" + "1" * 30 + "54321" + counter = iter(range(1, 10**7)) + + def h() -> str: + return "0x" + f"{next(counter):064x}" + + native = [ + RecordedNativeInbound( + transaction_hash=h(), + block_number=2_000 + i % 5_000, + transaction_index=0, + sender="0x" + f"{i + 1:040x}", + value="0", + succeeded=None, + ) + for i in range(n_zero) + ] + native += [ + RecordedNativeInbound( + transaction_hash=h(), + block_number=2_000 + i % 5_000, + transaction_index=1, + sender="0xabcde" + f"{i:030x}" + "54321", + value="1", + succeeded=True, + ) + for i in range(n_lookalikes) + ] + cats = { + k: CategoryCoverage(status="complete") + for k in ( + "erc20_transfer_logs", + "erc20_outgoing_signers", + "erc721_transfer_logs", + "wallet_signed_transactions", + "native_inbound_external", + ) + } + return ReplayFixture( + case_id="synthetic-flood", + chain_id=1, + wallet=wallet, + from_block=1_000, + to_block=8_000, + recorded_at=datetime(2026, 11, 9, tzinfo=UTC), + recorded_with="synthetic", + rpc_requests=0, + transfer_scan_complete=True, + sender_lookups_skipped=0, + method=["synthetic"], + wallet_code_hex={"1000": "0x"}, + block_timestamps={}, + transfers=[ + RecordedTransfer( + token=STABLECOIN_USDT, + sender=wallet, + recipient=ref, + value="5", + block_number=1_500, + block_hash=h(), + transaction_hash=h(), + transaction_index=0, + log_index=0, + tx_sender=wallet, + ) + ], + wallet_transactions=[], + observation=ObservationCoverage(schema_version=OBSERVATION_V2, categories=cats), + native_inbound=native, + unattributed_inbound=[], + nft_transfers=[], + ) + + +def flood_cost(n_zero: int = 10_000, n_lookalikes: int = 1_000) -> dict[str, Any]: + import time + import tracemalloc + + from cryptoguard.ml import candidate_discovery as cd + from cryptoguard.ml import candidate_features as cf + + fx = flood_fixture(n_zero, n_lookalikes) + cut = (8_001, 0) + out: dict[str, Any] = { + "label": "synthetic", + "zero_value_strangers": n_zero, + "lookalikes": n_lookalikes, + } + runs: dict[str, Callable[[], Sequence[Any]]] = { + "C1": lambda: cd.discover(fx, cutoff=cut, variant="C1").candidates, + "C2": lambda: cd.discover(fx, cutoff=cut, variant="C2").candidates, + "ranking": lambda: cf.rank(fx, cut), + } + for name, fn in runs.items(): + tracemalloc.start() + t0 = time.perf_counter() + n = len(fn()) + sec = time.perf_counter() - t0 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + out[name] = {"items": n, "seconds": round(sec, 2), "peak_mib": round(peak / 2**20, 1)} + return out + + +def wallet_experiments(poisoning_dir: Path) -> dict[str, Any]: + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.ml.lookalike_ranking import protected_entities + from cryptoguard.ml.observation_study import touches_frozen_any + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import ReplayFixture + + blind = protected_entities(poisoning_dir) + windows: dict[str, Any] = {} + dev: dict[str, Any] = {} + robust: dict[str, Any] = {} + for c in ib.load_new_cases(): + if c.fixture is None: + continue + cut = (c.manifest.harm.block_number, 0) + windows[c.manifest.case_id] = {"population": "P3", **_window_variants(c.fixture, cut)} + dev[c.manifest.case_id] = development_ranks(c.fixture, cut, c.manifest.harm.recipient) + robust[c.manifest.case_id] = robustness(c.fixture, cut) + path = Path("data/ml/research/phase12.4/blind-v2/fixture.json") + if path.exists(): + fx = ReplayFixture.model_validate_json(path.read_text(encoding="utf-8")) + cut = (21_890_897, 0) + paid = "0x804051b0cbc20443943c4f363573ef9bb7793375" + windows["scamsniffer-blind-v2"] = {"population": "P3", **_window_variants(fx, cut)} + dev["scamsniffer-blind-v2"] = development_ranks(fx, cut, paid) + robust["scamsniffer-blind-v2"] = robustness(fx, cut) + for b in load_background(): + if b.fixture is None or touches_frozen_any(b.fixture, blind): + continue + cut = (b.fixture.to_block + 1, 0) + windows[b.manifest.case_id] = {"population": "P5", **_window_variants(b.fixture, cut)} + return { + "windows": windows, + "development_ranks": dev, + "robustness": robust, + "flood": flood_cost(), + } + + +# --- entry point ---------------------------------------------------------------------------- + + +def _git() -> str | None: + import subprocess + + try: + return subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + + +def main(poisoning_dir: Path, out: Path, rebuild_cache: bool = False) -> dict[str, Any]: + """Run every Phase 12.5 experiment from local artifacts; write one JSON.""" + import hashlib + import time + + from cryptoguard.ml import candidate_features as cf + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + t0 = time.perf_counter() + cache = out / "episodes.jsonl" + cache_info = None + if rebuild_cache or not cache.exists(): + cache_info = cache_episodes(poisoning_dir, cache) + episodes = load_cache(cache) + timings: dict[str, float] = {} + + def timed(name: str, fn: Callable[[], Any]) -> Any: + s = time.perf_counter() + value = fn() + timings[name] = round(time.perf_counter() - s, 2) + return value + + proxy = timed("proxy_task", lambda: proxy_task(episodes)) + semantic = timed("semantic_channel", lambda: semantic_channel(episodes)) + mad = timed("mad_recency", lambda: mad_recency_equivalence(episodes)) + wallet = timed("wallet_experiments", lambda: wallet_experiments(poisoning_dir)) + inv = timed("inventory", lambda: inventory(poisoning_dir)) + peak = peak_rss_bytes() + result: dict[str, Any] = { + "protocol": "protocol-12.5", + "git": _git(), + "versions": { + "proxy_task": PROXY_TASK, + "proxy_features": PROXY_FEATURES, + "candidate_features": cf.FEATURE_VERSION, + "ranking": cf.RANKING_VERSION, + }, + "seed": SEED, + "inputs": { + "episode_cache_sha256": hashlib.sha256(cache.read_bytes()).hexdigest(), + "episodes": len(episodes), + "cache_built_now": cache_info, + }, + "rpc_requests": 0, + "proxy_task": proxy, + "semantic_channel": semantic, + "mad_recency_equivalence": mad, + "wallet": wallet, + "inventory": inv, + "resources": { + "seconds": round(time.perf_counter() - t0, 2), + "steps": timings, + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + }, + } + result["summary"] = { + "proxy_test_log_loss": proxy["test_log_loss"], + "h8_supported": proxy["h8_supported"], + "logistic_minus_best": proxy["logistic_minus_best_baseline"], + "semantic_B5_minus_T0_dev": semantic["B5_minus_T0"], + "mad_equivalence": mad, + "resources": result["resources"], + } + out.mkdir(parents=True, exist_ok=True) + (out / "candidate-research.json").write_text( + json.dumps(result, indent=1, default=str, sort_keys=True) + "\n", encoding="utf-8" + ) + return result diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index b747a46..9ae7d7a 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,19 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + cr = ml.add_parser( + "candidate-research", + help="Phase 12.5 candidate discovery and ranking research (offline, no RPC)", + ) + cr.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.5") + cr.add_argument("--rebuild-cache", action="store_true", help="re-read the archive subset") + rk = ml.add_parser( + "candidate-ranking", + help="offline shadow ranking of one recorded window (research only, no RPC)", + ) + rk.add_argument("--fixture", type=Path, required=True) + rk.add_argument("--cutoff-block", type=int, required=True) + rk.add_argument("--cutoff-index", type=int, default=0) ob = ml.add_parser( "observation-study", help="Phase 12.4 observation coverage and candidate discovery (offline, no RPC)", @@ -182,6 +195,25 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "candidate-research": + import json + + from cryptoguard.ml import candidate_research + + result = candidate_research.main(ML_DIR / "poisoning", args.out, args.rebuild_cache) + print(json.dumps(result["summary"], indent=1, default=str)) + print(f"Wrote {args.out / 'candidate-research.json'}") + return 0 + if args.ml_command == "candidate-ranking": + import json + + from cryptoguard.ml import candidate_features + from cryptoguard.replay.models import ReplayFixture + + fixture = ReplayFixture.model_validate_json(args.fixture.read_text(encoding="utf-8")) + ranked = candidate_features.rank(fixture, (args.cutoff_block, args.cutoff_index)) + print(json.dumps(candidate_features.serialize(ranked), indent=1, default=str)) + return 0 if args.ml_command == "observation-study": import json diff --git a/tests/test_ml_candidate_research.py b/tests/test_ml_candidate_research.py new file mode 100644 index 0000000..f616cb5 --- /dev/null +++ b/tests/test_ml_candidate_research.py @@ -0,0 +1,263 @@ +"""Protocol 12.5: proxy task, exploratory ranking, candidate features and the shadow ranking. +Expected values are written from each case's definition. Synthetic data only.""" + +from __future__ import annotations + +import json +import math + +import pytest + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_features as cf +from cryptoguard.ml import candidate_research as cr +from tests.test_ml_candidate_discovery import ( + ATTACKER, + END, + FAKE_TOKEN, + LOOK_2, + LOOK_NATIVE, + LOOK_TOKEN, + SHORT, + VICTIM, + fixture, + native_in, + transfer, +) + +V = "0x" + "1" * 40 +L1, L2, L3 = ("0x" + c * 40 for c in "abc") +ZERO, TINY, COUNTERFEIT = 1 << 1, 1 << 2, 1 << 3 + + +def ep( + plantings: list[tuple[int, int, str, str, int]], + *, + paid: str = L1, + split: str = "dev", + group: int = 0, +) -> cr.CachedEpisode: + return cr.CachedEpisode( + V, + 10_000, + paid, + group, + split, + tuple(cr.Planting(b, line, "0xt", s, r, f) for b, line, s, r, f in plantings), + ) + + +# --- RQ8 proxy rows ------------------------------------------------------------------------ + + +def test_proxy_rows_use_only_strictly_earlier_blocks() -> None: + e = ep( + [ + (100, 1, V, L1, ZERO), # spoofed_out + (100, 2, L2, V, ZERO), # zero_in, same block: never an input to block 100 + (110, 1, L3, V, TINY), # tiny_in + (110, 2, L2, V, COUNTERFEIT), # counterfeit_in + (120, 1, L1, V, ZERO), # zero_in + ] + ) + rows = cr.proxy_rows([e]) + assert [(r.target, r.prefix) for r in rows] == [ + ("tiny_in", ("spoofed_out", "zero_in")), + ("counterfeit_in", ("spoofed_out", "zero_in")), # same prefix: 110 order unknown + ("zero_in", ("spoofed_out", "zero_in", "tiny_in", "counterfeit_in")), + ] + f = dict(zip(cr.FEATURE_NAMES, rows[0].features, strict=True)) + assert (f["count_spoofed_out"], f["last_zero_in"], f["distinct_lookalikes"]) == (1, 1, 2) + assert f["log_blocks_since_last"] == pytest.approx(math.log1p(10)) + + +def test_baselines_are_normalized_and_markov_follows_transitions() -> None: + train = cr.proxy_rows( + [ep([(1, 1, V, L1, ZERO), (2, 1, V, L1, ZERO), (3, 1, V, L1, ZERO)], group=1)] + ) + probs = cr.baseline_probs(train, train) + for name in ("global", "victim_prefix", "markov"): + for p in probs[name]: + assert sum(p.values()) == pytest.approx(1.0) + # both training rows go spoofed_out -> spoofed_out: (2 + 1) / (2 + 5) + assert probs["markov"][0]["spoofed_out"] == pytest.approx(3 / 7) + + +def test_logistic_refuses_single_class_and_is_deterministic() -> None: + one = cr.proxy_rows([ep([(1, 1, V, L1, ZERO), (2, 1, V, L1, ZERO)])]) + with pytest.raises(ValueError, match="single-class"): + cr.logistic_probs(one, one) + mixed = cr.proxy_rows( + [ep([(1, 1, V, L1, ZERO), (2, 1, L2, V, TINY), (3, 1, V, L1, ZERO), (4, 1, L2, V, TINY)])] + ) + assert cr.logistic_probs(mixed, mixed) == cr.logistic_probs(mixed, mixed) + + +def test_log_loss_macro_f1_and_bootstrap() -> None: + rows = cr.proxy_rows([ep([(1, 1, V, L1, ZERO), (2, 1, L2, V, TINY), (3, 1, V, L1, ZERO)])]) + assert [r.target for r in rows] == ["tiny_in", "spoofed_out"] + certain = [{c: float(c == r.target) for c in cr.CLASSES} for r in rows] + assert cr.log_losses(certain, rows) == [0.0, 0.0] + assert cr.macro_f1(certain, rows)["macro_f1"] == 1.0 + b = cr.group_bootstrap_diff([1.0, 3.0], [0.0, 1.0], [0, 1], draws=200) + assert b["mean_diff"] == 1.5 + assert b["ci_low"] <= 1.5 <= b["ci_high"] + assert cr.group_bootstrap_diff([1.0, 3.0], [0.0, 1.0], [0, 1], draws=200) == b + + +def test_proxy_task_needs_both_splits() -> None: + with pytest.raises(ValueError, match="development and test"): + cr.proxy_task([ep([(1, 1, V, L1, ZERO), (2, 1, L2, V, TINY)], split="dev")]) + + +# --- RQ2 and H3a --------------------------------------------------------------------------- + + +def test_top1_averages_ties() -> None: + assert cr.top1({"a": (1.0,), "b": (1.0,), "c": (0.0,)}, "a") == 0.5 + assert cr.top1({"a": (1.0,), "b": (2.0,)}, "a") == 0.0 + + +def test_semantic_channel_on_a_constructed_dev_set() -> None: + # recency favours L2 (inbound, latest); the channel rule favours L1 (spoofed, paid) + e = ep([(10, 1, V, L1, ZERO), (20, 1, L2, V, TINY)], paid=L1) + held_out = ep([(10, 1, V, L1, ZERO), (20, 1, L2, V, TINY)], paid=L1, split="test", group=9) + res = cr.semantic_channel([e, held_out]) + assert (res["episodes"], res["T0_top1"], res["B5_top1"]) == (1, 0.0, 1.0) + assert res["latest_planting_spoofed_share"] == {"paid": 1.0, "rivals": 0.0} + + +def test_mad_normalized_recency_ranks_exactly_like_recency() -> None: + e = ep([(10, 1, V, L1, ZERO), (15, 1, L2, V, TINY), (40, 1, L3, V, ZERO)]) + flat = ep([(10, 1, V, L1, ZERO), (10, 2, L2, V, TINY)]) + assert cr.mad_recency_equivalence([e, flat]) == { + "episodes_same_order": 1, + "differ": 0, + "mad_zero_undefined": 1, + } + + +# --- candidate features and the shadow ranking ---------------------------------------------- + + +def scenario(**kw: object) -> object: + """Legitimate reference (REF at 1100), native dust from LOOK_NATIVE (1200), a fake-token + lookalike LOOK_TOKEN (1300), an ordinary unrelated 5 ETH payment in from SHORT (1250).""" + return fixture( + [transfer(LOOK_TOKEN, VICTIM, 10**18, block=1300, signer=ATTACKER, token=FAKE_TOKEN)], + native=[ + native_in(LOOK_NATIVE, 10**12, block=1200), + native_in(SHORT, 5 * 10**18, block=1250), + ], + **kw, # type: ignore[arg-type] + ) + + +def test_end_to_end_original_and_extended_pathways() -> None: + fx = scenario() + c0 = cd.discover(fx, cutoff=END, variant="C0") + c1 = cd.discover(fx, cutoff=END, variant="C1") + c2 = cd.discover(fx, cutoff=END, variant="C2") + assert c0.lookalikes == {LOOK_TOKEN} # the native channel is invisible to C0 + assert c1.lookalikes == c2.lookalikes == {LOOK_TOKEN, LOOK_NATIVE} # SHORT: no lookalike + assert c2.abstain is None + ranked = cf.rank(fx, END) + assert [r.lookalike for r in ranked] == [LOOK_TOKEN, LOOK_NATIVE] # B4: latest first + assert ranked[0].baseline_ranks["B3"] == 2.0 # LOOK_TOKEN affix 4+4 < LOOK_NATIVE 5+5 + assert all("not a probability" in r.explanation for r in ranked) + native = next(c for c in c2.candidates if c.lookalike == LOOK_NATIVE) + f = cf.candidate_features(fx, native, END) + assert f["signer_role"] == cf.FeatureValue("lookalike_itself", "observed") + assert f["receipt_status"] == cf.FeatureValue(1.0, "observed") + assert f["emitter_reviewed"].status == "not_applicable" + assert f["reference_paid_before"] == cf.FeatureValue(1.0, "observed") + blob = json.dumps(cf.serialize(ranked), default=str) + assert json.loads(blob)[0]["version"] == cf.RANKING_VERSION + partial = scenario(complete=False) + assert "insufficient history" in str(cd.discover(partial, cutoff=END, variant="C2").abstain) + pf = cf.candidate_features(partial, native, END) + assert pf["matched_references"].status == "unknown" # not a zero + + +def test_missing_observations_are_unknown_never_zero() -> None: + fx = scenario() + tok = next(c for c in cd.discover(fx, cutoff=END, variant="C2").candidates if c.kind == "erc20") + f = cf.candidate_features(fx, tok, END) + assert f["signer_reuse_in_window"].status == "zero_observed" # signer known, no reuse + unknown_signer = fx.model_copy( # type: ignore[attr-defined] + update={"transfers": [t.model_copy(update={"tx_sender": None}) for t in fx.transfers]} # type: ignore[attr-defined] + ) + g = cf.candidate_features(unknown_signer, tok, END) + assert g["signer_reuse_in_window"] == cf.FeatureValue(None, "unknown") + + +def test_features_are_point_in_time() -> None: + fx = scenario() + cut = (1350, 0) + later = fixture( + [ + transfer(LOOK_TOKEN, VICTIM, 10**18, block=1300, signer=ATTACKER, token=FAKE_TOKEN), + transfer(LOOK_2, VICTIM, 0, block=1500, signer=ATTACKER), # a later planting + transfer(VICTIM, LOOK_NATIVE, 9 * 10**6, block=1600, signer=VICTIM), # the payoff + transfer(LOOK_TOKEN, VICTIM, 0, block=1700, signer=ATTACKER, log=4), # signer link + ], + native=[ + native_in(LOOK_NATIVE, 10**12, block=1200), + native_in(SHORT, 5 * 10**18, block=1250), + native_in(LOOK_NATIVE, 7, block=1800), + ], + ) + a = {c.lookalike: c for c in cd.discover(fx, cutoff=cut, variant="C2").candidates} + b = {c.lookalike: c for c in cd.discover(later, cutoff=cut, variant="C2").candidates} + assert a == b + for look, cand in a.items(): + assert cf.candidate_features(fx, cand, cut) == cf.candidate_features(later, b[look], cut) + assert cf.serialize(cf.rank(fx, cut)) == cf.serialize(cf.rank(later, cut)) + + +def test_feature_schema_is_stable() -> None: + fx = scenario() + c = cd.discover(fx, cutoff=END, variant="C2").candidates[0] + assert sorted(cf.candidate_features(fx, c, END)) == sorted( + [ + "affix_prefix", + "affix_suffix", + "matched_references", + "reference_paid_before", + "blocks_since_reference_payment", + "kind", + "channel", + "zero_value", + "signer_role", + "emitter_reviewed", + "receipt_status", + "first_seen_block", + "last_seen_block", + "events", + "events_last_day", + "median_interarrival", + "signer_reuse_in_window", + "coverage_erc20_transfer_logs", + "coverage_native_inbound_external", + "coverage_erc20_outgoing_signers", + ] + ) + + +def test_flood_is_bounded_by_distinct_lookalikes() -> None: + fx = cr.flood_fixture(2_000, 100) + cut = (8_001, 0) + assert len(cd.discover(fx, cutoff=cut, variant="C1").candidates) == 2_100 + assert len(cd.discover(fx, cutoff=cut, variant="C2").candidates) == 100 + assert len(cf.rank(fx, cut)) == 100 + + +def test_robustness_transforms_never_add_candidates() -> None: + fx = scenario() + res = cr.robustness(fx, END) + assert res["base"] == sorted([LOOK_TOKEN, LOOK_NATIVE]) + for t in cr.TRANSFORMS: + assert res[t]["added"] == 0, t + assert res["no_native"]["removed"] == 1 # LOOK_NATIVE is no longer observable + assert "native_inbound_external" in res["no_native"]["not_complete"] + assert res["no_reference_history"]["abstain"] is not None From 8fbc3a103ae123224c4dfc3c2ac96f716191297c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 01:52:50 +0300 Subject: [PATCH 68/92] perf(ml): build candidate observations once per ranking (quadratic scan fixed) The Phase 12.5 study found candidate_features rebuilding every observation per candidate: 424 s to rank 1,000 flood candidates over 11,000 observations. A per-window context (observations, party and signer indexes, references) is now built once. Outputs are identical on both Level I cases, the blind observation/2 recording and a 2,200-event flood; the full flood now ranks in 0.27 s. Regression test counts the observation builds. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/candidate_features.py | 40 +++++++++++++++++++----- tests/test_ml_candidate_research.py | 17 ++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/src/cryptoguard/ml/candidate_features.py b/src/cryptoguard/ml/candidate_features.py index 68168da..5aa4c24 100644 --- a/src/cryptoguard/ml/candidate_features.py +++ b/src/cryptoguard/ml/candidate_features.py @@ -44,16 +44,41 @@ def _count(n: int, complete: bool) -> FeatureValue: return FeatureValue(float(n), "observed" if n else "zero_observed") +@dataclass(frozen=True) +class _Context: + """One window's observations before the cutoff, indexed once (no per-candidate scan).""" + + cov: Any + by_party: dict[str, list[cd.Observation]] + chosen: list[cd.Observation] + by_signer: dict[str, set[str]] + + @classmethod + def build(cls, fixture: Any, cutoff: tuple[int, int]) -> _Context: + obs = [o for o in cd.observations(fixture) if (o.block, o.tx_index) < cutoff] + by_party: dict[str, list[cd.Observation]] = {} + by_signer: dict[str, set[str]] = {} + for o in obs: + by_party.setdefault(o.counterparty, []).append(o) + if o.signer: + by_signer.setdefault(o.signer, set()).add(o.counterparty) + chosen = [o for o in obs if o.direction == "out" and o.wallet_signed is True] + return cls(coverage_of(fixture), by_party, chosen, by_signer) + + def candidate_features( - fixture: Any, candidate: cd.DiscoveryCandidate, cutoff: tuple[int, int] + fixture: Any, + candidate: cd.DiscoveryCandidate, + cutoff: tuple[int, int], + context: _Context | None = None, ) -> dict[str, FeatureValue]: """Features of one candidate from observations strictly before ``cutoff``.""" - cov = coverage_of(fixture) - obs = [o for o in cd.observations(fixture) if (o.block, o.tx_index) < cutoff] + ctx = context or _Context.build(fixture, cutoff) + cov = ctx.cov look = candidate.lookalike - mine = [o for o in obs if o.counterparty == look] + mine = ctx.by_party.get(look, []) refs_complete = cov.complete(*cd.REFERENCE_CATEGORIES) - chosen = [o for o in obs if o.direction == "out" and o.wallet_signed is True] + chosen = ctx.chosen matched = {o.counterparty for o in chosen if similar(look, o.counterparty)} first = mine[0] if mine else None f: dict[str, FeatureValue] = {} @@ -137,7 +162,7 @@ def candidate_features( if not signers: f["signer_reuse_in_window"] = FeatureValue(None, "unknown") else: - others = {o.counterparty for o in obs if o.signer in signers and o.counterparty != look} + others = {p for s in signers for p in ctx.by_signer.get(s, set())} - {look} f["signer_reuse_in_window"] = FeatureValue( float(len(others)), "observed" if others else "zero_observed" ) @@ -182,7 +207,8 @@ def _ranks(scores: Mapping[str, tuple[float, ...]]) -> dict[str, float]: def rank(fixture: Any, cutoff: tuple[int, int]) -> list[RankedCandidate]: """The offline shadow ranking of a window's C2 candidates at ``cutoff``.""" res = cd.discover(fixture, cutoff=cutoff, variant="C2") - feats = {c.lookalike: candidate_features(fixture, c, cutoff) for c in res.candidates} + ctx = _Context.build(fixture, cutoff) + feats = {c.lookalike: candidate_features(fixture, c, cutoff, ctx) for c in res.candidates} def val(c: str, k: str) -> float: v = feats[c][k].value diff --git a/tests/test_ml_candidate_research.py b/tests/test_ml_candidate_research.py index f616cb5..eed1075 100644 --- a/tests/test_ml_candidate_research.py +++ b/tests/test_ml_candidate_research.py @@ -261,3 +261,20 @@ def test_robustness_transforms_never_add_candidates() -> None: assert res["no_native"]["removed"] == 1 # LOOK_NATIVE is no longer observable assert "native_inbound_external" in res["no_native"]["not_complete"] assert res["no_reference_history"]["abstain"] is not None + + +def test_ranking_builds_observations_once_not_per_candidate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Regression for the quadratic scan (424 s for 1,000 flood candidates before the fix).""" + calls = {"n": 0} + real = cd.observations + + def counting(fx: object) -> list[cd.Observation]: + calls["n"] += 1 + return real(fx) + + monkeypatch.setattr(cd, "observations", counting) + ranked = cf.rank(cr.flood_fixture(500, 50), (8_001, 0)) + assert len(ranked) == 50 + assert calls["n"] == 2 # once for C2 discovery, once for the feature context From 82d54a32e52affba4399f549f8d349d7c2d3fc49 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 02:06:21 +0300 Subject: [PATCH 69/92] docs(ml): Phase 12.5 report - candidate discovery and ranking research (no RPC) ML_CANDIDATE_DISCOVERY_RESEARCH.md: data audit (P1-P5, never pooled), protected exclusions, C0/C1/C2 coverage and volume, the pre-registered proxy test (H8 not supported: logistic log loss 1.945 vs 0.200 for victim-prefix frequency under strong temporal covariate shift; post-hoc diagnostic), RQ2 semantic channel (no gain, -0.009 [-0.022, 0.005]), H3a analytic equivalence, robustness (signer loss removes all spoofed candidates), cost, PU and self-supervised feasibility, decision gates, and the next experiment. 924 passed, 4 deselected. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + ML_CANDIDATE_DISCOVERY_RESEARCH.md | 341 +++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+) create mode 100644 ML_CANDIDATE_DISCOVERY_RESEARCH.md diff --git a/CHANGELOG.md b/CHANGELOG.md index a712a97..4e0c39d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,18 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.5: ML-driven candidate discovery and evidence-aware ranking (no RPC requests) +- **Protocol 12.5** (`docs/ml/protocol-12.5.md`) was frozen before any new outcome. The code was committed before the outcome run. +- **Primary pre-registered ML test** (`planting-mechanism-next/1`, a self-supervised proxy on 1,067 archive episodes): **not supported.** + - The fixed logistic regression's test log loss is 1.945, against 0.200 for victim-prefix frequency, because of strong temporal covariate shift. + - Its macro-F1 is higher (0.323 against 0.284). +- **Semantic channel** (exploratory, development split): no gain over recency, at −0.009 [−0.022, +0.005]. +- **MAD temporal anomaly:** analytically equivalent to recency (1,056 of 1,056 episodes). +- **Development cases:** recency and similarity disagree; descriptive only. +- **Added:** `poisoning-candidate-features/1` (value/status pairs, never zero for unobserved), and an offline shadow ranking `poisoning-candidate-ranking/1` (research CLI only). +- **Fixed:** a quadratic scan in candidate features. Ranking 1,000 flood candidates went from 424 s to about 2 s, with identical outputs. +- **Report:** `ML_CANDIDATE_DISCOVERY_RESEARCH.md`. + ### Phase 12.4 final validation of observation/2 (no RPC requests) - **Balance-bisection audit:** - **Fixed:** with matching sums, success was inferred. A reverted inbound plus an internal credit of exactly the same value in the same block would be misattributed. `observation/2` now reads a receipt for every nonzero inbound. diff --git a/ML_CANDIDATE_DISCOVERY_RESEARCH.md b/ML_CANDIDATE_DISCOVERY_RESEARCH.md new file mode 100644 index 0000000..c390ecf --- /dev/null +++ b/ML_CANDIDATE_DISCOVERY_RESEARCH.md @@ -0,0 +1,341 @@ +# ML-driven candidate discovery and evidence-aware ranking (Phase 12.5) + +| Item | Value | +|---|---| +| Protocol (frozen before any new outcome) | [`docs/ml/protocol-12.5.md`](docs/ml/protocol-12.5.md), `16586a5` | +| Code (committed before the outcome run) | `0dd8a23`; performance fix `8fbc3a1` (outputs identical) | +| Study output (git-ignored) | `data/ml/research/phase12.5/candidate-research.json` (`cryptoguard ml candidate-research`) | +| RPC requests / downloads | **0** / none | + +## 1. Executive summary + +**Does machine learning add information beyond complete observations and transparent deterministic rules? On the data available, no.** The results: +- **Primary pre-registered ML test (RQ8): not supported.** It predicts a victim's next planting mechanism from their planting history, on 1,067 archive episodes, as a self-supervised proxy task. + - A fixed logistic regression is far worse than simple baselines on test log loss: **1.945** against **0.200** for the victim-prefix frequency. + - The reason is temporal covariate shift. Later campaigns plant far more intensively: the 90th-percentile planting history is 2,481 in test against 163 in training, and the model's count features extrapolate. + - Its macro-F1 is higher (0.323 against 0.284), so some minority-class structure is learnable, but it is not calibrated under shift. +- **Exploratory semantics (RQ2): no gain.** Ranking by the semantic channel of the latest planting changes top-1 by **−0.009** [−0.022, +0.005] against recency, on 640 development episodes in 632 groups. Recency reproduces Phase 12.1's development score exactly (0.730). +- **Temporal anomaly (H3a): analytically null, as predicted.** A median/MAD-normalized recency orders candidates identically to recency in 1,056 of 1,056 definable episodes. +- **The two development cases disagree.** Recency puts the later-paid address 2nd of 6 in the pilot and **3rd of 3** in the native-dust case. Similarity puts it 1st there but 5.5th of 6 in the pilot. No ordering is consistent on n = 2. This is descriptive, not evidence. +- **Engineering.** The feature schema and an offline shadow ranking exist. A **quadratic-scan defect** was found and fixed: ranking 1,000 flood candidates went from 424 s to 0.27–2.2 s, with identical outputs. +- **Robustness.** Losing transaction-signer information removes every spoofed-transfer candidate. Signer lookups are a critical observation, not an optional feature. + +**Classification:** +- a negative ML finding (RQ8, RQ2, H3a); +- a source-dependent result (recency); +- a confirmed candidate-discovery improvement on controlled tasks (C1/C2, re-verified); +- blocked by data for wallet-centric ML: there are no labels and only 3 real recordings. + +## 2. Research hypotheses + +Defined in the protocol (§2): RQ1–RQ8. + +- **Primary test:** H8 (§4 of the protocol). +- **Exploratory:** RQ2 and H3a. +- **Not re-run:** archive ranking (Phase 12.1 answered it, and its test split is used) and graph models (12.1 null). + +## 3. Data audit, and 4. research populations + +| Population | Source | Size | Labels | Use | +|---|---|---|---|---| +| P1 | synthetic fixtures | tests | oracle, by construction | correctness, coverage, robustness, cost | +| P2 | 4 packaged incident fixtures | 4 windows | known outcome | **excluded** (frozen Cohort B overlap) | +| P3 | 2 Level I cases: `observation/1` ×2, plus the blind `observation/2` replay of one | 3 recordings, 2 wallets | known outcome | development description only | +| P4 | Tsuchiya archive subset (`archive_subset.sqlite`, 146 MB; CC BY-NC-ND, local only) | 1,068 payoff episodes → **1,067** after protected-overlap removal; 1,058 linkage groups; development 640 / test 427 (12.1 split) | the source's payoff confirmation, plus mechanism flags (source heuristics) | RQ8 primary; RQ2 exploratory | +| P5 | background windows, `observation/1` | 9; **6 eligible** (3 hold frozen items) | none (unlabelled) | volume | +| Reference only | Poison-Hunter ground truth | 5,890 addresses | — | overlap checks | + +**These populations are never pooled.** P4 is source-selected: every candidate is a source-flagged planting toward a victim who later paid. P5 and P3 are wallet-centric recordings. P5 has no native observations, so it cannot estimate native volume. + +## 5. Observation completeness + +| Recording | Schema | Native inbound | ERC-721 | Internal | +|---|---|---|---|---| +| 6 P5 + 2 P3 (`observation/1`) | `observation/1` | not collected | not collected | unsupported | +| blind replay (P3) | `observation/2` | complete (2 transfers) | complete (0) | unsupported | + +Only **one** real `observation/2` window exists. + +## 6. Protected data exclusions + +- **Cohorts:** the Cohort A and B sheet and key hashes are unchanged: `a0ec4b6e…`, `407b412f…`, `121c112d…`, `f333386d…`, with files untouched since 2026-11-02. +- **Archive:** episodes of the 60 review wallets are removed, plus **1 more** that shares an entity or linkage group with a frozen item. +- **Background:** 3 P5 windows are excluded (`touches_frozen_any`). +- **Cohort data:** no cohort file or answer key was read. + +## 7. Candidate-generation baselines + +| Variant | Definition | +|---|---| +| C0 | the frozen `candidates/2` rules | +| C1 | the same rules on every observed class | +| C2 | lookalike-gated native candidates, one per lookalike, plus abstention | + +| Baseline | Definition | Phase 12.1 equivalent | +|---|---|---| +| B3 | similarity | B0 | +| B4 | recency | T0 | +| B5 | semantic channel | — | +| B6 | familiarity, i.e. recency of the reference payment | B3 | +| B7 | MAD temporal anomaly | ≡ B4 (H3a) | +| B8 | graph | G1–G3, null | + +## 8. Feature definitions (`poisoning-candidate-features/1`) + +Every feature is a `(value, status)` pair, with status `observed`, `zero_observed`, `unknown` or `not_applicable`. Unobserved never means zero. + +| Family | Features | +|---|---| +| Address | `affix_prefix`, `affix_suffix`, `matched_references`, `reference_paid_before`, `blocks_since_reference_payment` | +| Semantics | `kind`, `channel`, `zero_value`, `signer_role` (wallet / foreign / lookalike itself / unknown), `emitter_reviewed`, `receipt_status` | +| Temporal | `first_seen_block`, `last_seen_block`, `events`, `events_last_day`, `median_interarrival` | +| Graph | `signer_reuse_in_window` (in-window only: no cross-wallet index exists for these windows) | +| Completeness | coverage of ERC-20 logs, native inbound and signers (status, never risk) | + +The proxy task uses `proxy-features/1` (protocol §4). + +## 9. Temporal features + +- **Recency (B4/T0):** the only temporal signal with large-sample support. It is source-conditional: 12.1 test top-1 0.618 against B0's 0.300, and 0.730 on development, reproduced here. +- **H3a:** a wallet-normalized MAD score is a strictly increasing transform of recency within an episode, so it adds nothing. The check found 1,056 identical orders, 0 differing, and 11 undefined (MAD = 0). +- **The 12.1 burst, count and decay features** (T1–T4) added little beyond recency. +- **The proxy task** shows that planting *intensity* drifts strongly over time (§19). + +## 10. Transaction semantics + +- **Paid lookalikes:** the latest planting is `spoofed_out` for **97.0 %** (development). +- **Rivals:** the same share is **92.9 %**. +- **Result:** the channel barely separates them, and B5 adds nothing to top-1 (§20). +- **Where semantics do matter:** for **validity**. Without the signer, spoofed transfers can't be told apart from wallet payments (§23). + +## 11. Graph features + +Not re-run: +- Phase 12.1 found G1 at random and G2/G3 slightly below it. +- Its token negative control was anti-informative. +- Graph features cost about 1 h 47 min of HDD lookups. +- The wallet-centric data have **0** cross-wallet signer links. + +**Status: blocked by data.** No new hypothesis justifies a graph model. + +## 12. Unsupervised methods, 13. self-supervised feasibility, 14. PU feasibility + +- **Unsupervised anomaly detection (M1):** an Isolation Forest or similar on wallet windows would score about 11 real candidates, with no labels. That answers no hypothesis, so **none was trained**. The one temporal anomaly with a defined role (MAD) is analytically equivalent to recency (H3a). +- **Self-supervised learning on wallet histories:** **blocked by data.** The eligible wallet-centric recordings hold about 100 events across 9 windows, against the protocol's threshold of 1,000. Instead, the self-supervised task ran on **attacker planting sequences** (P4: 12,803 training and 18,710 test events), which is legitimate for an event-pattern question (§19). +- **PU learning: not viable.** + - Positives are the paid candidates, exactly one per episode, chosen by the source's payoff-confirmation rule. + - The unlabelled set is the rival plantings. + - The class prior is fixed by construction (1/k), not a population prior, and SCAR is violated, because labelling depends on the victim's later payment. + - No PU risk or calibrated probability can be identified. A within-episode ranking, such as 12.1's conditional logit, is the right formulation. It did not beat recency. + +## 15. Training design, and 16. evaluation protocol + +**RQ8** (protocol §4): +- **Unit:** one planting with at least one planting in a strictly earlier block. Same-block predecessors are never inputs. +- **Target:** five mechanism classes. +- **Split:** 12.1's temporal group split. +- **Baselines:** global, victim-prefix and Markov, fit on training only. +- **Model:** a fixed multinomial logistic regression (standardized, C = 1, seed 20261109). No search. +- **Primary metric:** test log loss. +- **Secondary metric:** macro-F1. +- **Uncertainty:** a 95 % group-bootstrap CI over 426 test groups (2,000 draws). + +## 17. Candidate coverage, and 18. candidate volume + +| Window (population) | C0 events / distinct | C1 | C2 | C2 dedup | Per wallet-day (C2) | +|---|---|---|---|---|---| +| pilot (P3, `/1`) | 9 / 6 | 9 / 6 | 6 / 6 | 3 | 2.0 | +| Scam Sniffer (P3, `/1`, frozen) | 2 / 2 | 2 / 2 | 2 / 2 | 0 | 0.67 | +| Scam Sniffer blind (P3, `/2`) | 2 / 2 | **3 / 3** | 3 / 3 | 0 | 1.0 | +| 6 × P5 (`/1`) | 0 | 0 | 0 | 0 | 0 (2 windows abstain: no reference) | + +**Synthetic (P1):** +- C1 recovers native-dust and ERC-721 lookalikes that C0 can't see. +- A flood of 10,000 zero-value strangers plus 1,000 lookalikes gives C1 11,000 events and **C2 1,000** (one per lookalike). + +**Native volume on unlabelled wallets is unknown:** P5 is `observation/1`. These counts are not a false-positive rate. + +## 19. Temporal experiments: RQ8 results (primary, pre-registered) + +Test split: 18,710 events, 426 groups. Training: 12,803 events, 631 groups. + +| Method | Test log loss | Macro-F1 | Recall: spoofed / tiny / counterfeit / zero | +|---|---|---|---| +| Global frequency | 0.2146 | 0.245 | 1.00 / 0 / 0 / 0 | +| Victim-prefix frequency | **0.1997** | 0.284 | 0.999 / 0 / 0.108 / 0 | +| Markov (last class) | 0.2005 | 0.245 | 1.00 / 0 / 0 / 0 | +| Logistic regression | **1.9451** | **0.323** | 0.796 / 0.446 / 0.118 / 0 | + +- **LR minus the best baseline:** **+1.745** [−0.021, +3.837]. That is far worse on the point estimate. The decision rule requires a lower loss than every baseline, with the CI excluding 0. **H8 is not supported.** +- **Class balance:** `spoofed_out` is 96 % of events (17,931 of 18,710 in test). + +**Post-hoc diagnostic** (exploratory; it does not change the decision): +- **Median LR loss:** 0.021. +- **The tail:** 3,242 test rows with loss above 5 carry **91 %** of the total loss, and 3,084 of them are `spoofed_out` predicted as a minority class. +- **Covariate shift:** prefix length at p50 / p90 / p99 is 28 / 163 / 320 in training against **60 / 2,481 / 4,165** in test. 4,207 test rows exceed the longest training prefix. +- **Interpretation:** planting intensity grew sharply over time, and unbounded count features extrapolate. Robust frequency statistics are the better choice under this shift. + +## 20. Semantic experiments: RQ2 (exploratory, development split only) + +| | Top-1 (640 episodes, 632 groups) | +|---|---| +| T0 recency | 0.730 (identical to 12.1's development figure) | +| B5 channel, then recency | 0.720 | +| B5 − T0 | **−0.009** [−0.022, +0.005] | + +The semantic channel adds no ranking information beyond recency. + +## 21. Graph experiments + +None. See §11. + +## 22. Model comparisons + +The only trained model is RQ8's logistic regression. It loses to the victim-prefix frequency baseline on the primary metric, and wins only on macro-F1. + +**Phase 12.1's conditional logit** did not beat recency either. No learned ranking is justified on the available labels. + +**Development-case ranks** (C2 candidates; descriptive, outcome known): + +| Case | Candidates | B3 similarity | B4 recency | B5 channel | B6 familiarity | +|---|---|---|---|---|---| +| pilot (`/1`) | 6 | 5.5 | **2** | 2 | 1.5 | +| Scam Sniffer blind (`/2`) | 3 | **1** | 3 | 3 | 3 | +| Scam Sniffer frozen (`/1`) | 2 | paid not observable | — | — | — | + +## 23. Robustness (C2; controlled information loss) + +Each cell shows candidates kept / removed / added. + +| Transform | pilot (6) | Scam Sniffer `/1` (2) | Scam Sniffer blind `/2` (3) | +|---|---|---|---| +| no native | 6/0/0 | 2/0/0 | 2/**1**/0 (the paid lookalike is lost) | +| signer unknown | 4/**2**/0, abstains | 0/**2**/0 | 1/**2**/0 | +| last day only | 6/0/0 | 2/0/0 | 3/0/0 | +| no reference history | 6/0/0, abstains | 2/0/0, abstains | 2/1/0, abstains | +| receipts unknown | 6/0/0 | 2/0/0 | 3/0/0 | + +**No transform ever adds a candidate:** no evidence is invented. Without references, C2 abstains, and it says history before the window is unobserved. **Signer loss is the most damaging gap.** + +## 24. Source-shift diagnostics, and 25. negative controls + +- **Within P4:** + - mechanism shares are stable (96 % spoofed in both splits); + - planting intensity shifts strongly across time; + - recency holds across years in 12.1's strata. +- **Across populations:** wallet-centric candidates number 11, so no feature-distribution test is meaningful. +- **12.1's negative controls** still apply: the within-episode G1 shuffle sits at random, and the token control is anti-informative. +- **The public-token-reuse control:** a shared token contract never links wallets. The synthetic case J test passes. + +## 26. Ablations + +- **Proxy model:** ablations are meaningless here. It already loses to frequency baselines, and dropping features can't make it valid. +- **Ranking ablations:** 12.1's apply. Removing any non-temporal component improved its hybrid. +- **The informative ablation here is observational:** removing native observations or signers removes candidates (§23). + +## 27. Operational cost + +| Step | Wall | Peak | +|---|---|---| +| Archive episode cache, built once | 279 s | 86 MiB RSS (disk-bound) | +| Full study rerun (cache present) | **27 s** | 336 MiB RSS | +| Proxy task (training plus evaluation) | 20 s | — | +| Flood: C1 / C2 / ranking, 11,000 observations | 0.73 / 0.64 / 2.2 s | ≤ 12 MiB traced | +| Shadow ranking before the fix | 424 s | — | + +## 28. Statistical uncertainty + +- **RQ8:** a group bootstrap over 426 test groups. +- **RQ2:** a group bootstrap over 632 development groups. +- **Development cases:** n = 2, exact ranks only, and no inference. +- **Multiple comparisons:** there is one primary test, H8. Everything else is labelled exploratory. + +## 29. Production isolation + +**Unchanged:** the detector, the risk engine and C0. Detector output is byte-identical (tests). + +**The shadow ranking `poisoning-candidate-ranking/1`:** +- runs only through `cryptoguard ml candidate-ranking`, a research CLI; +- is never called by the scanner; +- carries no probability, severity, suppression or deletion. + +## 30. Reproducibility + +`cryptoguard ml candidate-research [--rebuild-cache]` regenerates everything from local artifacts. Its output records: +- the git SHA, the protocol and the seed; +- the episode-cache SHA-256 (`c0fa1f6f…`); +- the versions of every component; +- the step timings and peak RSS. + +**Required local inputs:** `data/ml/poisoning/archive_subset.sqlite` and `archive_targets.json` (CC BY-NC-ND, never committed), the review sheets, which are used only to exclude entities, and the fixtures. If any is absent, the command fails and names it. There are no downloads and no RPC. + +## 31. Tests and CI + +| Check | Command | Result | +|---|---|---| +| Lint | `uv run ruff check .` | clean | +| Format | `uv run ruff format --check .` | 286 files formatted | +| Types | `uv run mypy src` | clean (151 files) | +| Tests | `uv run pytest -q` | **924 passed**, 4 deselected (`gpu`/`slow`), 0 failed, 0 skipped | + +There are 15 new tests in `tests/test_ml_candidate_research.py`. The CI run is recorded in the PR #1 description. + +## 32. Positive findings + +1. The C1/C2 coverage gains and C2's volume bound hold on controlled cases, and on the one real `observation/2` window. +2. The features never turn unobserved data into zeros, and they are point-in-time correct under metamorphic tests. +3. The quadratic-scan defect is fixed, about 200× faster with identical outputs. +4. Recency's development score reproduces exactly (0.730). + +## 33. Negative findings + +1. H8 is not supported: the learned model is far worse than frequency baselines under temporal shift. +2. The semantic channel adds no ranking information. +3. The temporal anomaly is equivalent to recency. +4. No learned ranker is justified. +5. Recency, the strongest archive signal, fails on the one native-dust development case. + +## 34. Unsupported claims (none made) + +**Not claimed:** +- any precision, recall, false-positive rate or theft-prevention rate; +- any calibrated probability; +- ML superiority over production; +- generalization of recency to wallet-centric `observation/2` data. + +## 35. Remaining data requirements + +1. **Untouched incidents**, recorded blind with `observation/2` from the start: at least 10, with harm-transaction hashes from public write-ups. +2. **`observation/2` background windows**, for unlabelled native volume under C2. +3. **Independent labels** for rival candidates, which would require human review of the frozen cohorts. None has been submitted. + +## 36. Recommended next experiment + +**Question:** on untouched `observation/2` incident windows, does recency (B4) put the later-paid lookalike first more often than similarity (B3)? + +| Element | Specification | +|---|---| +| Data | At least 10 untouched incidents, user-sourced, each with a harm-transaction hash, recorded with `replay record-window --observation 2` | +| Labels | The paid address, taken from the harm transaction and used only to score | +| Cost | About 700–1,300 RPC requests per window (measured 703, plus rate-limit retries). A cap of about 15,000 for 10 windows. Offline analysis takes seconds. | +| Pre-registration | Before any recording. A cluster-level sign test (amendment 12.3-A1). | +| Falsification | B3 better than B4 in more planting-signer clusters than worse. Under the pre-registered rule, B4 not better in at least 6 untied clusters. | + +Phase 12.6 is not started. + +## Decision gates + +| Gate | Status | Evidence | +|---|---|---| +| A. Data quality | PASS WITH LIMITATIONS | Exact inventory (§3). P4 is source-selected, P5 has no native data, and P3 is n = 2. | +| B. Observation correctness | PASS WITH LIMITATIONS | Phase 12.4 audit and tests, plus 1 real blind `observation/2` window | +| C. Candidate coverage | PASS WITH LIMITATIONS | Synthetic mechanisms, plus 1 real development case: C1 recovers the native-dust lookalike | +| D. Candidate-volume control | PASS WITH LIMITATIONS | Synthetic flood bounded by distinct lookalikes (§18). Real native volume unknown. | +| E. Temporal research | PASS WITH LIMITATIONS | Recency is informative, but source-conditional (12.1). No new temporal method adds information (H3a; RQ8). | +| F. Semantic research | FAIL (ranking) | B5 − T0 = −0.009 [−0.022, +0.005]. Semantics are needed for candidate validity (signer), not for ranking. | +| G. Graph research | BLOCKED BY DATA | 12.1 null; 0 wallet-centric links | +| H. ML validity | PASS | RQ8 is a properly specified proxy with a temporal group split, fixed model and baselines. The result is negative. | +| I. Missingness robustness | PASS | Transforms never add candidates. Abstentions and unknown statuses, never zeros (§23, §8). | +| J. Generalization | FAIL | The proxy model breaks under temporal shift, and recency fails on the native-dust development case | +| K. Production isolation | PASS | Detector and C0 unchanged. Shadow ranking reachable only through the research CLI. | +| L. Reproducibility | PASS | One command from local artifacts, with hashes, seed and versions (§30) | From c060ccc6a89c666ed0ae558446d63b62876879b8 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 02:40:07 +0300 Subject: [PATCH 70/92] docs(ml): freeze protocol 12.6 (candidate reliability and signer provenance) Frozen before the evidence model exists and before any H2-H7 measurement. Records the development audit (outgoing signer coverage 18/18 on eligible recordings; the 12.5 signer-loss result came from masking) and the deterministic recovery rule R-SIG (an outgoing event whose transaction is absent from the wallet's complete signed set was not signed by a code-less wallet; 18/18 consistent with looked-up signers). Hypotheses H1-H7, evidence levels, the ordering and summary contract. No learned ranking model: no valid labels. 0 RPC. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.6.md | 86 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 docs/ml/protocol-12.6.md diff --git a/docs/ml/protocol-12.6.md b/docs/ml/protocol-12.6.md new file mode 100644 index 0000000..c6491d5 --- /dev/null +++ b/docs/ml/protocol-12.6.md @@ -0,0 +1,86 @@ +# Protocol 12.6: candidate reliability, signer provenance and evidence-aware presentation + +**Frozen:** 2026-11-09, in the commit that adds this file. That is before the evidence model exists and before any H2–H7 measurement. + +**Development analyses already done:** +- the signer-coverage audit (§1); +- the recovery-rule consistency check (§2). + +**RPC:** 0. **Downloads:** none. + +## 1. Audit finding (development analysis) + +On the 9 eligible wallet-centric recordings (P3 and P5, frozen-overlap windows excluded): +- every outgoing ERC-20 transfer has a looked-up signer (18 of 18), and 0 lookups were skipped; +- 8 of them are foreign-signed spoofs; +- incoming transfers' signers are never looked up, by design. + +**So the Phase 12.5 finding is not a recovery defect.** "Signer loss removes every spoofed candidate" came from synthetic masking. A spoof is defined by the victim *not* having signed, so it needs signer evidence. + +**The realistic failure** is a busy wallet. The recorder looks up at most 500 outgoing transactions, and the overflow becomes an unknown signer. Such an event is silently neither a reference nor a spoof. + +## 2. Deterministic local recovery (rule R-SIG) + +Nonce bisection records **every** transaction a wallet signed in the window: `wallet_signed_transactions`, complete by construction. For an outgoing ERC-20 event whose signer was not looked up: + +| Condition | Signer status | +|---|---| +| Its transaction is in the wallet's signed set | **`wallet` (verified)** | +| The signed set is complete, the wallet has no code at the cutoff, and the transaction is not in the set | **`foreign_identity_unknown` (verified by absence)**. The signer's address stays unknown and is never guessed. | +| Otherwise | **`unknown`** | + +**Exclusions:** +- **A wallet with code** (a contract wallet or EIP-7702 delegation) **never gets the absence inference.** Others can execute its transfers. + +**Consistency on real data** (development): the rule matches the looked-up signer in 18 of 18 eligible outgoing transfers, including 8 of 8 foreign-signed ones. + +## 3. Hypotheses + +| ID | Hypothesis | Population | Measure | Fails if | +|---|---|---|---|---| +| H1 provenance | The evidence model never substitutes the event sender for the signer, the token for the attacker, or an association for signing evidence. R-SIG recovers spoof status without inventing identities. | P1 synthetic, P2/P3 real (consistency) | oracle agreement; R-SIG agreement on real data | any disagreement | +| H2 deduplication | Grouping by (chain, victim, lookalike) reduces output while every distinct evidence record stays linked | P1, P3 | raw events, groups, evidence records kept | any evidence record lost, or any merge across victims or chains | +| H3 presentation | A bounded top-k summary discloses the total and the truncation, is deterministic, and never drops the strongest-evidence candidate under spam | P1, 12 adversarial scenarios | presence of the designated high-evidence candidate in top-k; disclosure fields; determinism | the candidate is dropped, or truncation is not disclosed | +| H4 missingness | Under masking (S0–S5), no claim is made that needs the masked information; unknowns lower *support*, never raise *suspicion* | P1, P3 | unsafe inferences by C1 (baseline) and by the evidence model; candidates kept, recovered or abstained | the evidence model makes any unsafe inference | +| H5 ranking | The evidence-aware order is more stable under cheap spam than recency-only or similarity-only orders | P1; a P3 copy with injected synthetic spam (in memory) | top-k retention of the real candidates; Kendall τ of their relative order | the evidence-aware order retains fewer real candidates than a baseline | +| H6 ML | Robust proxy features (shares, log counts) reduce shift sensitivity on the RQ8 proxy | P4 **development split only**, an internal temporal sub-split (earliest 70 % of groups train, latest 30 % validate) | log loss, macro-F1, top-class ECE (10 bins) against raw-feature LR and the frequency baselines | **exploratory.** The 12.5 test split is never used. No confirmatory claim. | +| H7 cost | Grouping, ranking and summary scale near-linearly | P1 at 10 / 100 / 1,000 / 10,000 candidates | wall, peak traced memory, evidence records, output bytes, throughput | super-linear growth or unbounded memory | + +**No learned ranking model (M4).** No valid ranking labels exist beyond 2 development cases and the used 12.1 test split. + +## 4. Evidence levels (non-probabilistic) + +| Level | Definition | +|---|---| +| `directly_verified` | A planting whose mechanism is established by the transaction's own provenance: an outgoing event "from" the victim whose signer is verified not to be the wallet (known foreign, or R-SIG absence), or a native transfer from the lookalike whose receipt reads success | +| `supported` | A lookalike planting whose execution is implied but not read, such as a token log from the lookalike, or native with unread status | +| `partially_supported` | An outgoing event to a lookalike of a verified reference with an **unknown** signer, which is not asserted as a spoof. Also any non-lookalike rule (`zero_value_in`, `dust_in`). | +| `insufficient` | The wallet's references are not fully observed | +| `unsupported_source` | Coverage-level only: classes not collected | + +## 5. Ordering and summary (research only) + +**Suspicion, support and availability are separate dimensions.** The order of groups is: +1. evidence level; +2. affix strength (prefix + suffix to the imitated reference). Vanity cost grows about 16× per character, so cheap spam has short affixes. +3. latest planting position; +4. lookalike address (deterministic). + +**Missingness only ever lowers the support level.** It never raises suspicion. + +**Summary contract:** +- top-k (default 10); +- the totals of groups, raw events and evidence records; +- the number shown and a `truncated` flag; +- the identities of the hidden groups; +- counts per level and per mechanism; +- a note that hidden candidates are not assessed as safe. + +**A display budget is not an evidence budget.** All groups and records stay in the result. The production detector is never consulted or changed. + +## 6. Integrity + +- **Unchanged:** C0, C1 and C2 and their published outputs. The new model is a separate module (`candidate-evidence/1`). +- **Data:** no cohort file is read beyond the entity exclusion. Frozen-overlap windows are excluded. +- **Claims:** no labels, no probabilities, no false-positive rate. +- **Resources:** one process, under 1 GiB. From 8e59c9d67b6305c2ba11617feddd337b6c8bf832 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 02:47:09 +0300 Subject: [PATCH 71/92] feat(ml): evidence-preserving candidate groups, signer recovery (R-SIG), bounded summary Committed before the Phase 12.6 measurements (protocol c060ccc). Research only; C0/C1/C2 and their published outputs are unchanged. - ml/candidate_evidence.py (candidate-evidence/1): one group per (chain, victim, lookalike) keeping every distinct evidence record in chain order with typed provenance (signer status, event sender and recipient, emitter, receipt). Rule R-SIG: an outgoing event whose transaction is in the wallet's complete signed set was signed by the wallet; absent from it (code-less wallet) it was not - the signer's address is never guessed. Non-probabilistic levels (directly verified, supported, partially supported); unknowns lower support and are listed, never raise suspicion; unknown token identity is never "untrusted"; unknown-signer outgoing lookalikes are kept as partially supported, never called spoofs. Order: level, affix strength (costly to forge), latest planting, address. Bounded summary discloses totals, truncation and hidden identities; nothing is deleted. - ml/reliability_study.py + `ml reliability-study`: R-SIG consistency, S1-S5 masking with unsafe-inference counts (C1 vs evidence model), deduplication, 12 adversarial scenarios, spam stability of orderings, development-split robust proxy features, 10-10,000 scaling. - Tests: 27 with hand-written oracles. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/candidate_evidence.py | 400 ++++++++++++++ src/cryptoguard/ml/cli.py | 21 + src/cryptoguard/ml/reliability_study.py | 671 +++++++++++++++++++++++ tests/test_ml_candidate_evidence.py | 220 ++++++++ 4 files changed, 1312 insertions(+) create mode 100644 src/cryptoguard/ml/candidate_evidence.py create mode 100644 src/cryptoguard/ml/reliability_study.py create mode 100644 tests/test_ml_candidate_evidence.py diff --git a/src/cryptoguard/ml/candidate_evidence.py b/src/cryptoguard/ml/candidate_evidence.py new file mode 100644 index 0000000..f6de26e --- /dev/null +++ b/src/cryptoguard/ml/candidate_evidence.py @@ -0,0 +1,400 @@ +"""Evidence-preserving candidate groups and a bounded summary (``candidate-evidence/1``), +research only (protocol 12.6). + +Every candidate is a group identified by (chain, victim, lookalike) that keeps **every** +distinct evidence record that caused it, in chain order, each with typed provenance: + +- ``signer_status``: ``wallet``, ``foreign_known`` (looked-up signer, not the wallet), + ``foreign_identity_unknown`` (rule R-SIG: the transaction is absent from the wallet's + complete signed set and the wallet has no code, so the wallet did not sign it, but who did + is unknown), ``lookalike_itself`` (a native transfer the lookalike sent) or ``unknown``. + The event's ``from`` field is never taken as the signer. +- ``event_sender`` / ``event_recipient``: what the log or transaction reports. +- ``emitter``: the token contract (``None`` when unknown); never an attacker identity. +- ``receipt``: ``succeeded``, ``reverted``, ``implied_by_log`` (a log exists only for an + executed transaction) or ``unknown``. + +Evidence levels are categories, not probabilities: ``directly_verified``, ``supported``, +``partially_supported`` (see ``LEVELS``). Missing information lowers the support level and +is listed in ``missing``; it never raises suspicion. The summary shows a bounded top-k +with the totals, a truncation flag and the hidden identities: a display budget is not an +evidence budget, and hidden candidates are not assessed as safe. The production detector +is never consulted or changed. +""" + +from __future__ import annotations + +import json +from collections.abc import Iterable, Sequence +from dataclasses import asdict, dataclass, replace +from typing import Any, Literal + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml.candidates import DUST_MAX_BASE_UNITS, MIN_SUFFIX, STABLECOINS, similar +from cryptoguard.ml.payments import TRUSTED_TOKENS +from cryptoguard.replay.observation import coverage_of + +EVIDENCE_VERSION = "candidate-evidence/1" +LEVELS = ("directly_verified", "supported", "partially_supported") +SignerStatus = Literal[ + "wallet", "foreign_known", "foreign_identity_unknown", "lookalike_itself", "unknown" +] +Receipt = Literal["succeeded", "reverted", "implied_by_log", "unknown"] +HIDDEN_NOTE = "hidden candidates are not assessed as safe; all evidence remains in the result" + + +@dataclass(frozen=True) +class EvidenceRecord: + identity: str # "tx::", -1 for a transaction's own value + kind: str + direction: str + block: int + tx_index: int + log_index: int + mechanisms: tuple[str, ...] + level: str + signer_status: SignerStatus + signer: str | None # only a looked-up or self-evident address, never inferred + event_sender: str + event_recipient: str + emitter: str | None + receipt: Receipt + value_zero: bool + missing: tuple[str, ...] + + +@dataclass(frozen=True) +class CandidateGroup: + identity: str # "::" + chain_id: int + victim: str + lookalike: str + references: tuple[tuple[str, int, int], ...] # (imitated reference, prefix, suffix) + mechanisms: tuple[str, ...] + kinds: tuple[str, ...] + level: str + affix: int | None # best prefix + suffix to an imitated reference + first_position: tuple[int, int, int] + last_position: tuple[int, int, int] + evidence: tuple[EvidenceRecord, ...] + missing: tuple[str, ...] + + +@dataclass(frozen=True) +class EvidenceResult: + version: str + chain_id: int + victim: str + cutoff: tuple[int, int] + groups: tuple[CandidateGroup, ...] # in the research order + raw_events: int # observation records before deduplication + evidence_records: int # distinct records linked to groups + signers_recovered: int # unknown signers resolved by R-SIG + unattributable_events: int # records that could not be placed relative to the wallet + abstain: str | None + coverage: dict[str, str] + + +def _plain_eoa(fixture: Any, cutoff_block: int) -> bool: + known = {int(b): c for b, c in fixture.wallet_code_hex.items() if int(b) <= cutoff_block} + return bool(known) and known[max(known)] == "0x" + + +def raw_event_count(fixture: Any) -> int: + """Wallet observation records before deduplication (what an ingestion produced).""" + w = fixture.wallet.lower() + n = sum( + 1 + for t in fixture.transfers + if w in (t.sender.lower(), t.recipient.lower()) and t.sender.lower() != t.recipient.lower() + ) + n += sum(1 for t in fixture.wallet_transactions if t.to and int(t.value)) + n += sum(1 for x in fixture.native_inbound or [] if x.sender.lower() != w) + n += sum(1 for x in fixture.nft_transfers or [] if w in (x.sender.lower(), x.recipient.lower())) + return n + + +def build( + fixture: Any, + *, + cutoff: tuple[int, int], + observations: Sequence[cd.Observation] | None = None, + signed: Iterable[str] | None = None, + wallet_tx_complete: bool | None = None, +) -> EvidenceResult: + """Evidence groups from observations strictly before ``cutoff``. ``observations``, + ``signed`` and ``wallet_tx_complete`` can be supplied (masking experiments); by default + they come from the fixture.""" + cov = coverage_of(fixture) + wallet = fixture.wallet.lower() + obs = [ + o + for o in (observations if observations is not None else cd.observations(fixture)) + if (o.block, o.tx_index) < cutoff + ] + signed_set = { + h.lower() + for h in ( + signed + if signed is not None + else (t.transaction_hash for t in fixture.wallet_transactions) + ) + } + complete = ( + cov.status("wallet_signed_transactions") == "complete" + if wallet_tx_complete is None + else wallet_tx_complete + ) + plain = _plain_eoa(fixture, cutoff[0]) + refs_complete = complete and cov.complete("erc20_transfer_logs") + chosen: dict[str, dict[str, int]] = {} + records: dict[str, list[tuple[EvidenceRecord, list[tuple[str, int, int]]]]] = {} + recovered = 0 + for o in obs: + status, signer, rec = _signer(o, wallet, signed_set, complete and plain) + recovered += rec + match = _match(o.counterparty, chosen) if o.counterparty else None + mechanisms, level, missing = _assess(o, status, match) + if o.direction == "out" and status == "wallet": + chosen.setdefault(o.counterparty[-MIN_SUFFIX:], {})[o.counterparty] = o.block + if not mechanisms: + continue + receipt: Receipt = ( + "implied_by_log" + if o.kind != "native" + else "succeeded" + if o.succeeded is True + else "reverted" + if o.succeeded is False + else "unknown" + ) + r = EvidenceRecord( + identity=f"tx:{o.tx_hash.lower()}:{o.log_index}", + kind=o.kind, + direction=o.direction, + block=o.block, + tx_index=o.tx_index, + log_index=o.log_index, + mechanisms=mechanisms, + level=level, + signer_status=status, + signer=signer, + event_sender=wallet if o.direction == "out" else o.counterparty, + event_recipient=o.counterparty if o.direction == "out" else wallet, + emitter=o.emitter, + receipt=receipt, + value_zero=o.value == 0, + missing=missing, + ) + refs = [(match[0], match[1][0], match[1][1])] if match else [] + records.setdefault(o.counterparty, []).append((r, refs)) + groups = [ + _group(fixture.chain_id, wallet, look, items, refs_complete) + for look, items in records.items() + ] + groups.sort(key=order_key) + abstain = None + if not refs_complete: + abstain = "insufficient history: the wallet's own references are not fully observed" + elif not chosen: + abstain = ( + "no reference observed in the window; history before the window is unobserved, so " + "this is not evidence of no earlier recipients" + ) + return EvidenceResult( + version=EVIDENCE_VERSION, + chain_id=fixture.chain_id, + victim=wallet, + cutoff=cutoff, + groups=tuple(groups), + raw_events=raw_event_count(fixture), + evidence_records=sum(len(g.evidence) for g in groups), + signers_recovered=recovered, + unattributable_events=0, + abstain=abstain, + coverage={k: str(v.status) for k, v in cov.categories.items()}, + ) + + +def _signer( + o: cd.Observation, wallet: str, signed: set[str], absence_ok: bool +) -> tuple[SignerStatus, str | None, int]: + """(status, address, recovered?) for one observation. R-SIG: membership in the wallet's + signed set proves the wallet signed; absence from a complete set of a code-less wallet + proves it did not. The signer's address is never guessed.""" + if o.kind == "native" and o.direction == "in": + return "lookalike_itself", o.counterparty, 0 + if o.kind == "native" and o.direction == "out": + return "wallet", wallet, 0 + if o.direction != "out" or o.kind != "erc20": + return "unknown", None, 0 + if o.signer is not None: + return ("wallet", wallet, 0) if o.signer == wallet else ("foreign_known", o.signer, 0) + if o.tx_hash.lower() in signed: + return "wallet", wallet, 1 + if absence_ok: + return "foreign_identity_unknown", None, 1 + return "unknown", None, 0 + + +def _match(party: str, chosen: dict[str, dict[str, int]]) -> tuple[str, tuple[int, int]] | None: + best = None + for k in chosen.get(party[-MIN_SUFFIX:], {}): + m = similar(party, k) + if m is not None and ( + best is None or (sum(m), m[1], k) > (sum(best[1]), best[1][1], best[0]) + ): + best = (k, m) + return best + + +def _assess( + o: cd.Observation, status: SignerStatus, match: tuple[str, tuple[int, int]] | None +) -> tuple[tuple[str, ...], str, tuple[str, ...]]: + """(mechanisms, level, missing) for one observation; empty mechanisms: not evidence.""" + missing: list[str] = [] + if o.succeeded is False: + return (), "", () + if o.direction == "out": + if o.kind != "erc20" or status == "wallet": + return (), "", () + if status in ("foreign_known", "foreign_identity_unknown"): + if status == "foreign_identity_unknown": + missing.append("signer_identity") + return ("spoofed_out",), "directly_verified", tuple(missing) + if match is not None: # unknown signer: never asserted as a spoof + return ("unverified_out_lookalike",), "partially_supported", ("signer",) + return (), "", () + m: list[str] = [] + if o.kind == "native": + if match is None: + return (), "", () # anyone can send ETH: native evidence needs a lookalike + if o.succeeded is None: + missing.append("receipt") + return ( + ("lookalike_in",), + "directly_verified" if o.succeeded is True else "supported", + tuple(missing), + ) + if o.value == 0 and o.kind != "nft": + m.append("zero_value_in") + if match is not None: + m.append("lookalike_in") + if o.kind == "erc20": + if o.emitter is None: + missing.append("token_identity") # unknown token: no "untrusted" claim + elif o.emitter not in TRUSTED_TOKENS: + m.append("untrusted_token_in") + if o.kind == "erc20" and o.emitter in STABLECOINS and 0 < o.value <= DUST_MAX_BASE_UNITS: + m.append("dust_in") + if not m: + return (), "", () + level = "supported" if match is not None else "partially_supported" + return tuple(m), level, tuple(missing) + + +def _group( + chain_id: int, + wallet: str, + look: str, + items: list[tuple[EvidenceRecord, list[tuple[str, int, int]]]], + refs_complete: bool, +) -> CandidateGroup: + evidence = tuple(r for r, _ in items) + refs = sorted({ref for _, rs in items for ref in rs}) + level = min((r.level for r in evidence), key=LEVELS.index) + missing = sorted( + {m for r in evidence for m in r.missing} + | (set() if refs_complete else {"reference_history"}) + ) + positions = [(r.block, r.tx_index, r.log_index) for r in evidence] + return CandidateGroup( + identity=f"{chain_id}:{wallet}:{look}", + chain_id=chain_id, + victim=wallet, + lookalike=look, + references=tuple(refs), + mechanisms=tuple(sorted({m for r in evidence for m in r.mechanisms})), + kinds=tuple(sorted({r.kind for r in evidence})), + level=level, + affix=max((p + s for _, p, s in refs), default=None), + first_position=min(positions), + last_position=max(positions), + evidence=evidence, + missing=tuple(missing), + ) + + +def order_key(g: CandidateGroup) -> tuple[int, int, tuple[int, int, int], str]: + """Support level first, then affix strength (costly to forge), then the latest + planting, then the address. Missing information never moves a group up.""" + neg = (-g.last_position[0], -g.last_position[1], -g.last_position[2]) + return (LEVELS.index(g.level), -(g.affix or 0), neg, g.lookalike) + + +def summarize(result: EvidenceResult, k: int = 10) -> dict[str, Any]: + """The bounded research summary. It discloses the totals and the truncation; it never + deletes a group or a record.""" + shown = result.groups[:k] + hidden = result.groups[k:] + by_level: dict[str, int] = {} + by_mechanism: dict[str, int] = {} + for g in result.groups: + by_level[g.level] = by_level.get(g.level, 0) + 1 + for m in g.mechanisms: + by_mechanism[m] = by_mechanism.get(m, 0) + 1 + return { + "version": result.version, + "cutoff": list(result.cutoff), + "total_groups": len(result.groups), + "raw_events": result.raw_events, + "evidence_records": result.evidence_records, + "shown": len(shown), + "truncated": bool(hidden), + "hidden_identities": [g.identity for g in hidden], + "by_level": dict(sorted(by_level.items(), key=lambda kv: LEVELS.index(kv[0]))), + "by_mechanism": dict(sorted(by_mechanism.items())), + "abstain": result.abstain, + "note": HIDDEN_NOTE, + "top": [ + { + "identity": g.identity, + "level": g.level, + "mechanisms": list(g.mechanisms), + "kinds": list(g.kinds), + "references": [list(r) for r in g.references], + "affix": g.affix, + "first_block": g.first_position[0], + "last_block": g.last_position[0], + "evidence_count": len(g.evidence), + "missing": list(g.missing), + "explanation": explain(g), + } + for g in shown + ], + } + + +def explain(g: CandidateGroup) -> str: + """Three separate dimensions: suspicion, support, and what is missing.""" + ref = f" imitating {g.references[0][0]} (affix {g.affix})" if g.references else "" + gaps = f"; missing: {', '.join(g.missing)}" if g.missing else "" + return ( + f"suspicion: {'+'.join(g.mechanisms)}{ref}; support: {g.level} " + f"({len(g.evidence)} record(s)){gaps}; not a probability" + ) + + +def to_json(result: EvidenceResult) -> str: + return json.dumps(asdict(result), sort_keys=True, default=list) + + +def mask(observations: Sequence[cd.Observation], what: str) -> list[cd.Observation]: + """Controlled information loss for the S1-S5 experiments (never adds information).""" + if what == "signer": + return [replace(o, signer=None, wallet_signed=None) for o in observations] + if what == "receipt": + return [replace(o, succeeded=None) if o.kind == "native" else o for o in observations] + if what == "token": + return [replace(o, emitter=None) if o.kind == "erc20" else o for o in observations] + raise ValueError(what) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 9ae7d7a..5f226c6 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,17 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + rs = ml.add_parser( + "reliability-study", + help="Phase 12.6 signer provenance, evidence groups and spam resilience (offline)", + ) + rs.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.6") + rs.add_argument( + "--episode-cache", + type=Path, + default=ML_DIR / "research" / "phase12.5" / "episodes.jsonl", + help="the Phase 12.5 archive episode cache (development split used only)", + ) cr = ml.add_parser( "candidate-research", help="Phase 12.5 candidate discovery and ranking research (offline, no RPC)", @@ -195,6 +206,16 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "reliability-study": + import json + + from cryptoguard.ml import reliability_study + + result = reliability_study.main(ML_DIR / "poisoning", args.out, args.episode_cache) + brief = {k: result[k] for k in ("rsig_consistency", "resources")} + print(json.dumps(brief, indent=1, default=str)) + print(f"Wrote {args.out / 'reliability-study.json'}") + return 0 if args.ml_command == "candidate-research": import json diff --git a/src/cryptoguard/ml/reliability_study.py b/src/cryptoguard/ml/reliability_study.py new file mode 100644 index 0000000..5a81ec4 --- /dev/null +++ b/src/cryptoguard/ml/reliability_study.py @@ -0,0 +1,671 @@ +"""Phase 12.6 offline study (protocol 12.6): signer provenance, evidence groups, bounded +summaries, spam resilience, robust proxy features and cost. No RPC; frozen-overlap windows +are never computed on; the 12.5 proxy test split is never used. +""" + +from __future__ import annotations + +import json +import time +import tracemalloc +from collections.abc import Callable, Sequence +from dataclasses import replace +from datetime import UTC, datetime +from functools import partial +from pathlib import Path +from typing import Any + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_evidence as ce + +STUDY_VERSION = "reliability-study/1" +USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" +FAKE = "0x" + "f" * 40 +WALLET = "0x" + "c" * 40 +REF = "0xabcde" + "1" * 30 + "54321" + + +def lookalike(i: int, *, prefix: int = 3, suffix: int = 3, ref: str = REF) -> str: + """A deterministic lookalike of ``ref`` sharing exactly ``prefix`` and ``suffix`` hex.""" + body = ref[2:] + mid_len = 40 - prefix - suffix + # the first and last differing characters are fixed (so the shared affix is exact) and + # the index fills the middle (so different indexes give different addresses) + first = "f" if body[prefix] != "f" else "e" + last = "f" if body[39 - suffix] != "f" else "e" + middle = f"{i:0{mid_len - 2}x}" + if len(middle) > mid_len - 2: + raise ValueError("index too large for this affix") + return "0x" + body[:prefix] + first + middle + last + body[40 - suffix :] + + +def wallet_fixture( + *, + transfers: Sequence[tuple[str, str, int, int, str | None, str, int]] = (), + native: Sequence[tuple[str, int, int, bool | None]] = (), + wallet_txs: Sequence[tuple[str, int, int]] = (), + ref_block: int = 1_100, + refs_complete: bool = True, + code: str = "0x", +) -> Any: + """Synthetic window. The wallet pays REF (wallet-signed, in its signed set) at + ``ref_block``. ``transfers``: (sender, recipient, value, block, signer, token, tx_index); + ``native``: (sender, value, block, succeeded); ``wallet_txs``: (to, value, block).""" + import hashlib + + from cryptoguard.replay.models import ( + RecordedNativeInbound, + RecordedTransaction, + RecordedTransfer, + ReplayFixture, + ) + from cryptoguard.replay.observation import ( + OBSERVATION_V2, + CategoryCoverage, + ObservationCoverage, + ) + + def h(*parts: object) -> str: + """A content-derived hash: the same record gets the same hash in any fixture.""" + return "0x" + hashlib.sha256(repr(parts).encode()).hexdigest() + + ref_tx = h("ref", ref_block) + rows = [ + RecordedTransfer( + token=USDT, + sender=WALLET, + recipient=REF, + value="1000000", + block_number=ref_block, + block_hash=h("block", ref_block), + transaction_hash=ref_tx, + transaction_index=0, + log_index=0, + tx_sender=WALLET, + ) + ] + for i, (s, r, v, b, signer, token, idx) in enumerate(transfers): + rows.append( + RecordedTransfer( + token=token, + sender=s, + recipient=r, + value=str(v), + block_number=b, + block_hash=h("block", b), + transaction_hash=h("transfer", s, r, v, b, signer, token, idx), + transaction_index=idx, + log_index=i + 1, + tx_sender=signer, + ) + ) + txs = [ + RecordedTransaction( + transaction_hash=ref_tx, + block_number=ref_block, + transaction_index=0, + nonce=0, + to=USDT, + value="0", + ) + ] + for n, (to, v, b) in enumerate(wallet_txs, start=1): + txs.append( + RecordedTransaction( + transaction_hash=h("wallet-tx", to, v, b, n), + block_number=b, + transaction_index=0, + nonce=n, + to=to, + value=str(v), + succeeded=True, + ) + ) + nat = [ + RecordedNativeInbound( + transaction_hash=h("native", s, v, b, ok), + block_number=b, + transaction_index=1, + sender=s, + value=str(v), + succeeded=ok, + ) + for s, v, b, ok in native + ] + status = "complete" if refs_complete else "partial" + cats = { + k: CategoryCoverage(status="complete") + for k in ( + "erc20_transfer_logs", + "erc20_outgoing_signers", + "erc721_transfer_logs", + "native_inbound_external", + "malformed_transfer_logs", + ) + } + cats["wallet_signed_transactions"] = CategoryCoverage(status=status) + return ReplayFixture( + case_id="synthetic", + chain_id=1, + wallet=WALLET, + from_block=1_000, + to_block=9_000, + recorded_at=datetime(2026, 11, 9, tzinfo=UTC), + recorded_with="synthetic", + rpc_requests=0, + transfer_scan_complete=True, + sender_lookups_skipped=0, + method=["synthetic"], + wallet_code_hex={"1000": code}, + block_timestamps={}, + transfers=rows, + wallet_transactions=txs, + observation=ObservationCoverage(schema_version=OBSERVATION_V2, categories=cats), + native_inbound=nat, + unattributed_inbound=[], + nft_transfers=[], + ) + + +END = (9_001, 0) + + +# --- adversarial scenarios (protocol 12.6 H3) ---------------------------------------------- + + +def scenarios() -> dict[str, tuple[Any, str | None]]: + """name -> (fixture, the designated high-evidence lookalike or None).""" + strong = lookalike(0, prefix=5, suffix=5) + weak = [lookalike(i + 1) for i in range(1_000)] + refs = [lookalike(i, prefix=0, suffix=0, ref="0x" + f"{i + 7:040x}") for i in range(50)] + out: dict[str, tuple[Any, str | None]] = { + "1_zero_value_strangers": ( + wallet_fixture( + native=[("0x" + f"{i + 1:040x}", 0, 2_000 + i, None) for i in range(1_000)] + ), + None, + ), + "2_distinct_lookalikes": ( + wallet_fixture(native=[(w, 1, 2_000 + i, True) for i, w in enumerate(weak)]), + None, + ), + "3_repeated_dust_one_lookalike": ( + wallet_fixture(native=[(weak[0], 1, 2_000 + i, True) for i in range(500)]), + weak[0], + ), + "4_many_lookalikes_one_reference_with_one_strong": ( + wallet_fixture( + native=[(w, 1, 3_000 + i, True) for i, w in enumerate(weak)] + + [(strong, 1, 2_000, True)] + ), + strong, + ), + "5_multiple_references": ( + wallet_fixture( + wallet_txs=[(r, 10**15, 1_200 + i) for i, r in enumerate(refs)], + native=[(lookalike(i, ref=r), 1, 3_000 + i, True) for i, r in enumerate(refs)], + ), + None, + ), + "6_fake_token_spam": ( + wallet_fixture( + transfers=[ + (w, WALLET, 10**18, 2_000 + i, None, FAKE, 0) for i, w in enumerate(weak) + ] + ), + None, + ), + "7_same_block_repeats": ( + wallet_fixture(native=[(w, 1, 2_000, True) for w in weak[:100]]), + None, + ), + "8_unknown_signer_with_complete_signed_set": ( + wallet_fixture(transfers=[(WALLET, strong, 0, 2_000, None, USDT, 0)]), + strong, + ), + "9_missing_receipt": (wallet_fixture(native=[(strong, 1, 2_000, None)]), strong), + "10_partial_history": ( + wallet_fixture( + transfers=[(WALLET, strong, 0, 2_000, None, USDT, 0)], refs_complete=False + ), + None, + ), + "11_one_strong_among_weak": ( + wallet_fixture( + transfers=[(WALLET, strong, 0, 2_000, "0x" + "a1" * 20, USDT, 0)] + + [ + ("0x" + f"{i + 1:040x}", WALLET, 5, 3_000 + i, None, USDT, 0) + for i in range(1_000) + ], + native=[(w, 1, 4_000 + i, None) for i, w in enumerate(weak)], + ), + strong, + ), + "12_public_token_reuse": ( + wallet_fixture( + transfers=[ + (w, WALLET, 0, 2_000 + i, None, USDT, 0) for i, w in enumerate(weak[:200]) + ] + ), + None, + ), + } + return out + + +def _measure(fn: Callable[[], Any]) -> tuple[Any, float, float]: + tracemalloc.start() + t0 = time.perf_counter() + value = fn() + sec = time.perf_counter() - t0 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + return value, round(sec, 3), round(peak / 2**20, 2) + + +def run_scenarios(k: int = 10) -> dict[str, Any]: + out: dict[str, Any] = {} + for name, (fx, strong) in scenarios().items(): + res, sec, mib = _measure(partial(ce.build, fx, cutoff=END)) + summary = ce.summarize(res, k) + again = ce.summarize(ce.build(fx, cutoff=END), k) + c1 = cd.discover(fx, cutoff=END, variant="C1") + top = [t["identity"].split(":")[-1] for t in summary["top"]] + out[name] = { + "raw_events": res.raw_events, + "c1_events": len(c1.candidates), + "groups": len(res.groups), + "evidence_records": res.evidence_records, + "summary_shown": summary["shown"], + "truncated": summary["truncated"], + "hidden": len(summary["hidden_identities"]), + "by_level": summary["by_level"], + "strong_rank": None + if strong is None + else next((i + 1 for i, g in enumerate(res.groups) if g.lookalike == strong), None), + "strong_in_top_k": None if strong is None else strong in top, + "abstain": res.abstain, + "deterministic": summary == again, + "seconds": sec, + "peak_mib": mib, + "summary_bytes": len(json.dumps(summary)), + } + return out + + +# --- signer-provenance and masking experiments (H1, H4) ------------------------------------- + + +def rsig_consistency(fixtures: Sequence[tuple[str, Any]]) -> dict[str, Any]: + agree = disagree = foreign = 0 + for _, f in fixtures: + w = f.wallet.lower() + signed = {t.transaction_hash.lower() for t in f.wallet_transactions} + for t in f.transfers: + if t.sender.lower() != w or t.tx_sender is None: + continue + truth = t.tx_sender.lower() == w + agree += truth == (t.transaction_hash.lower() in signed) + disagree += truth != (t.transaction_hash.lower() in signed) + foreign += not truth + return { + "outgoing_with_known_signer": agree + disagree, + "agree": agree, + "disagree": disagree, + "foreign": foreign, + "windows": len(fixtures), + } + + +def _c1_unsafe( + obs: Sequence[cd.Observation], fixture: Any, cutoff: tuple[int, int], masked: str +) -> int: + """Claims C1's rules make that need the masked information.""" + n = 0 + chosen: dict[str, dict[str, int]] = {} + for o in obs: + if (o.block, o.tx_index) >= cutoff: + continue + match = cd._match(o.counterparty, chosen) if o.direction == "in" else None + methods = cd._methods(o, match[1] if match else None) + if masked == "token" and "untrusted_token_in" in methods and o.emitter is None: + n += 1 + if o.direction == "out" and o.wallet_signed is True: + chosen.setdefault(o.counterparty[-3:], {})[o.counterparty] = o.block + del fixture + return n + + +def masking(fixture: Any, cutoff: tuple[int, int]) -> dict[str, Any]: + """S0 complete; S1 signer; S2 event sender (outgoing events unattributable); + S3 receipt; S4 token identity; S5 partial history (signed set incomplete, early half + of the window lost).""" + base_obs = cd.observations(fixture) + s0 = ce.build(fixture, cutoff=cutoff) + base = {g.lookalike: g.level for g in s0.groups} + conditions: dict[str, Any] = { + "S1_signer": (ce.mask(base_obs, "signer"), None, None), + "S2_event_sender": ([o for o in base_obs if o.direction != "out"], None, None), + "S3_receipt": (ce.mask(base_obs, "receipt"), None, None), + "S4_token": (ce.mask(base_obs, "token"), None, None), + } + mid = (fixture.from_block + cutoff[0]) // 2 + conditions["S5_partial_history"] = ([o for o in base_obs if o.block >= mid], None, False) + out: dict[str, Any] = {"S0": {"groups": len(base), "levels": _levels(s0)}} + for name, (obs, signed, complete) in conditions.items(): + res = ce.build( + fixture, cutoff=cutoff, observations=obs, signed=signed, wallet_tx_complete=complete + ) + now = {g.lookalike: g.level for g in res.groups} + out[name] = { + "kept": len(base.keys() & now.keys()), + "lost": len(base.keys() - now.keys()), + "added": len(now.keys() - base.keys()), + "level_lowered": sum( + 1 + for k in base.keys() & now.keys() + if ce.LEVELS.index(now[k]) > ce.LEVELS.index(base[k]) + ), + "level_raised": sum( + 1 + for k in base.keys() & now.keys() + if ce.LEVELS.index(now[k]) < ce.LEVELS.index(base[k]) + ), + "signers_recovered": res.signers_recovered, + "abstain": res.abstain is not None, + "unattributable_events": len(base_obs) - len(obs) if name == "S2_event_sender" else 0, + "c1_unsafe_inferences": _c1_unsafe(obs, fixture, cutoff, name.split("_")[1]), + "evidence_unsafe_inferences": _evidence_unsafe(res, name), + "c1_candidates": len( + { + o.counterparty + for o in obs + if (o.block, o.tx_index) < cutoff and cd._methods(o, None) + } + ), + } + return out + + +def _levels(res: ce.EvidenceResult) -> dict[str, int]: + c: dict[str, int] = {} + for g in res.groups: + c[g.level] = c.get(g.level, 0) + 1 + return c + + +def _evidence_unsafe(res: ce.EvidenceResult, condition: str) -> int: + """A claim the evidence model makes although its required information was masked.""" + n = 0 + for g in res.groups: + for r in g.evidence: + if ( + condition == "S4_token" + and "untrusted_token_in" in r.mechanisms + and r.emitter is None + ): + n += 1 + if "spoofed_out" in r.mechanisms and r.signer_status == "unknown": + n += 1 + if r.level == "directly_verified" and r.kind == "native" and r.receipt == "unknown": + n += 1 + return n + + +# --- spam stability of orderings (H5) ------------------------------------------------------- + + +def spam_stability( + fixture: Any, cutoff: tuple[int, int], *, n: int = 1_000, k: int = 10 +) -> dict[str, Any]: + """Inject ``n`` cheap native-dust lookalikes (affix 3+3, latest in the window) into a + copy of a real window (in memory) and check which orderings keep the real candidates + in the top-k.""" + from cryptoguard.replay.models import RecordedNativeInbound + + base = ce.build(fixture, cutoff=cutoff) + real = [g.lookalike for g in base.groups if g.references] + if not real: + return {"real_candidates": 0} + ref = base.groups[0].references[0][0] if base.groups[0].references else real[0] + last = cutoff[0] - 1 + spam = [ + RecordedNativeInbound( + transaction_hash="0x" + f"{0xEE00000000 + i:064x}", + block_number=last - (i % 50), + transaction_index=0, + sender=lookalike(i + 1, ref=ref), + value="1", + succeeded=True, + ) + for i in range(n) + ] + spammed = fixture.model_copy( + update={"native_inbound": list(fixture.native_inbound or []) + spam} + ) + res = ce.build(spammed, cutoff=cutoff) + groups = list(res.groups) + orders = { + "evidence_aware": [g.lookalike for g in groups], + "recency_only": [ + g.lookalike + for g in sorted(groups, key=lambda g: (tuple(-x for x in g.last_position), g.lookalike)) + ], + "similarity_only": [ + g.lookalike for g in sorted(groups, key=lambda g: (-(g.affix or 0), g.lookalike)) + ], + } + before = [g.lookalike for g in base.groups if g.lookalike in real] + out: dict[str, Any] = {"real_candidates": len(real), "spam": n, "k": k} + for name, order in orders.items(): + kept = [x for x in order[:k] if x in real] + rel = [x for x in order if x in real] + out[name] = {"real_in_top_k": len(kept), "kendall_tau_vs_unspammed": _tau(before, rel)} + return out + + +def _tau(a: Sequence[str], b: Sequence[str]) -> float | None: + pos = {x: i for i, x in enumerate(b)} + items = [x for x in a if x in pos] + if len(items) < 2: + return None + conc = disc = 0 + for i in range(len(items)): + for j in range(i + 1, len(items)): + same = (pos[items[i]] - pos[items[j]]) * (i - j) + conc += same > 0 + disc += same < 0 + return round((conc - disc) / (conc + disc), 4) if conc + disc else None + + +# --- robust proxy features (H6, exploratory, development split only) ------------------------ + + +def robust_proxy_dev(cache: Path) -> dict[str, Any]: + import math + + from cryptoguard.ml import candidate_research as cr + + episodes = [e for e in cr.load_cache(cache) if e.split == "dev"] # never the test split + start: dict[int, int] = {} + for e in episodes: + start[e.group] = min(start.get(e.group, e.payoff_block), e.payoff_block) + ordered = sorted(start, key=lambda g: (start[g], g)) + cut = int(0.7 * len(ordered)) + inner_train = set(ordered[:cut]) + rows = cr.proxy_rows(episodes) + train = [replace(r, split="dev") for r in rows if r.group in inner_train] + val = [replace(r, split="test") for r in rows if r.group not in inner_train] + names = cr.FEATURE_NAMES + + def robust(r: cr.ProxyRow) -> cr.ProxyRow: + f = list(r.features) + for i, name in enumerate(names): + if name.startswith("count_") or name == "distinct_lookalikes": + f[i] = math.log1p(f[i]) + return replace(r, features=tuple(f)) + + probs = cr.baseline_probs(train, val) + probs["logistic_raw"] = cr.logistic_probs(train, val) + probs["logistic_robust"] = cr.logistic_probs( + [robust(r) for r in train], [robust(r) for r in val] + ) + losses = {k: cr.log_losses(v, val) for k, v in probs.items()} + + def quant(xs: list[int]) -> list[int]: + s = sorted(xs) + return [s[int(q * (len(s) - 1))] for q in (0.5, 0.9, 0.99)] + + return { + "label": "exploratory: 12.1 development split only, internal temporal sub-split", + "rows": {"inner_train": len(train), "inner_validation": len(val)}, + "groups": {"inner_train": len(inner_train), "inner_validation": len(ordered) - cut}, + "prefix_len_p50_p90_p99": { + "inner_train": quant([len(r.prefix) for r in train]), + "inner_validation": quant([len(r.prefix) for r in val]), + }, + "log_loss": {k: round(sum(v) / len(v), 5) for k, v in losses.items()}, + "macro_f1": {k: cr.macro_f1(v, val)["macro_f1"] for k, v in probs.items()}, + "top_class_ece": {k: _ece(v, val) for k, v in probs.items()}, + "robust_minus_raw": cr.group_bootstrap_diff( + losses["logistic_robust"], losses["logistic_raw"], [r.group for r in val] + ), + } + + +def _ece(probs: Sequence[dict[str, float]], rows: Sequence[Any], bins: int = 10) -> float: + b: list[list[tuple[float, bool]]] = [[] for _ in range(bins)] + for p, r in zip(probs, rows, strict=True): + c = max(p, key=lambda x: p[x]) + conf = p[c] + b[min(bins - 1, int(conf * bins))].append((conf, c == r.target)) + n = len(rows) + return round( + sum( + abs(sum(x for x, _ in xs) / len(xs) - sum(y for _, y in xs) / len(xs)) * len(xs) / n + for xs in b + if xs + ), + 5, + ) + + +# --- cost (H7) ------------------------------------------------------------------------------ + + +def scaling(sizes: Sequence[int] = (10, 100, 1_000, 10_000)) -> list[dict[str, Any]]: + out = [] + for n in sizes: + fx = wallet_fixture( + native=[(lookalike(i + 1), 1, 2_000 + i % 6_000, True) for i in range(n)] + ) + res, sec, mib = _measure(partial(ce.build, fx, cutoff=END)) + summary, s_sec, _ = _measure(partial(ce.summarize, res, 10)) + out.append( + { + "candidates": n, + "groups": len(res.groups), + "evidence_records": res.evidence_records, + "build_seconds": sec, + "summary_seconds": s_sec, + "peak_mib": mib, + "summary_bytes": len(json.dumps(summary)), + "full_result_bytes": len(ce.to_json(res)), + "groups_per_second": round(len(res.groups) / sec) if sec else None, + } + ) + return out + + +# --- entry point ---------------------------------------------------------------------------- + + +def eligible_windows(poisoning_dir: Path) -> list[tuple[str, Any, tuple[int, int]]]: + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.ml.lookalike_ranking import protected_entities + from cryptoguard.ml.observation_study import touches_frozen_any + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import ReplayFixture + + blind = protected_entities(poisoning_dir) + out = [ + (c.manifest.case_id, c.fixture, (c.manifest.harm.block_number, 0)) + for c in ib.load_new_cases() + if c.fixture is not None + ] + path = Path("data/ml/research/phase12.4/blind-v2/fixture.json") + if path.exists(): + out.append( + ( + "scamsniffer-blind-v2", + ReplayFixture.model_validate_json(path.read_text(encoding="utf-8")), + (21_890_897, 0), + ) + ) + for b in load_background(): + if b.fixture is not None and not touches_frozen_any(b.fixture, blind): + out.append((b.manifest.case_id, b.fixture, (b.fixture.to_block + 1, 0))) + return out + + +def main(poisoning_dir: Path, out: Path, cache: Path) -> dict[str, Any]: + import subprocess + + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + t0 = time.perf_counter() + windows = eligible_windows(poisoning_dir) + dedup = {} + masks = {} + for name, fx, cut in windows: + res = ce.build(fx, cutoff=cut) + dedup[name] = { + "raw_events": res.raw_events, + "c1_events": len(cd.discover(fx, cutoff=cut, variant="C1").candidates), + "c2_candidates": len(cd.discover(fx, cutoff=cut, variant="C2").candidates), + "groups": len(res.groups), + "evidence_records": res.evidence_records, + "levels": _levels(res), + "abstain": res.abstain, + } + if res.groups: + masks[name] = masking(fx, cut) + spam = { + n: spam_stability(fx, cut) + for n, fx, cut in windows + if n.startswith(("usdt", "scamsniffer-blind")) + } + try: + git = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + git = None + result: dict[str, Any] = { + "study": STUDY_VERSION, + "protocol": "protocol-12.6", + "evidence_version": ce.EVIDENCE_VERSION, + "git": git, + "rpc_requests": 0, + "rsig_consistency": rsig_consistency([(n, fx) for n, fx, _ in windows]), + "deduplication": dedup, + "masking": masks, + "scenarios": run_scenarios(), + "spam_stability": spam, + "robust_proxy_dev": robust_proxy_dev(cache) if cache.exists() else "episode cache missing", + "scaling": scaling(), + } + peak = peak_rss_bytes() + result["resources"] = { + "seconds": round(time.perf_counter() - t0, 2), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + } + out.mkdir(parents=True, exist_ok=True) + (out / "reliability-study.json").write_text( + json.dumps(result, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" + ) + return result diff --git a/tests/test_ml_candidate_evidence.py b/tests/test_ml_candidate_evidence.py new file mode 100644 index 0000000..5874715 --- /dev/null +++ b/tests/test_ml_candidate_evidence.py @@ -0,0 +1,220 @@ +"""Protocol 12.6: evidence-preserving candidate groups, signer provenance (rule R-SIG), the +bounded summary and spam resilience. Synthetic only; every expectation is written from the +scenario's definition.""" + +from __future__ import annotations + +import json + +import pytest + +from cryptoguard.detectors.poisoning import PoisoningConfig +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_evidence as ce +from cryptoguard.ml import reliability_study as rs +from cryptoguard.replay.engine import Visibility, detector_outputs + +W, REF, USDT, FAKE, END = rs.WALLET, rs.REF, rs.USDT, rs.FAKE, rs.END +ATTACKER = "0x" + "a1" * 20 +STRONG = rs.lookalike(0, prefix=5, suffix=5) +WEAK = rs.lookalike(1) + + +def by_look(res: ce.EvidenceResult) -> dict[str, ce.CandidateGroup]: + return {g.lookalike: g for g in res.groups} + + +def test_lookalike_helper_shares_exactly_the_requested_affix() -> None: + from cryptoguard.detectors.poisoning import affix_match + + assert affix_match(STRONG, REF) == (5, 5) + assert affix_match(WEAK, REF) == (3, 3) + + +# --- provenance ---------------------------------------------------------------------------- + + +def test_event_sender_is_never_taken_as_the_signer() -> None: + fx = rs.wallet_fixture(transfers=[(W, STRONG, 0, 2_000, ATTACKER, USDT, 0)]) + [r] = by_look(ce.build(fx, cutoff=END))[STRONG].evidence + assert (r.event_sender, r.signer, r.signer_status) == (W, ATTACKER, "foreign_known") + assert r.mechanisms == ("spoofed_out",) + assert r.level == "directly_verified" + + +def test_rsig_recovers_an_unknown_signer_both_ways() -> None: + fx = rs.wallet_fixture(transfers=[(W, STRONG, 0, 2_000, None, USDT, 0)]) + res = ce.build(fx, cutoff=END) + [r] = by_look(res)[STRONG].evidence + assert (r.signer_status, r.signer) == ("foreign_identity_unknown", None) # never guessed + assert r.mechanisms == ("spoofed_out",) + assert "signer_identity" in r.missing + # the reference payment had a looked-up signer; masking it, R-SIG finds it in the set + masked = ce.build(fx, cutoff=END, observations=ce.mask(cd.observations(fx), "signer")) + assert masked.signers_recovered == 2 # the reference (wallet) and the spoof (absence) + assert by_look(masked)[STRONG].evidence[0].signer_status == "foreign_identity_unknown" + + +def test_no_absence_inference_for_a_wallet_with_code_or_an_incomplete_signed_set() -> None: + for kw in ({"code": "0x6080"}, {"refs_complete": False}): + fx = rs.wallet_fixture(transfers=[(W, STRONG, 0, 2_000, None, USDT, 0)], **kw) # type: ignore[arg-type] + g = by_look(ce.build(fx, cutoff=END)).get(STRONG) + if g is not None: # a lookalike of a verified reference: kept, never called a spoof + [r] = g.evidence + assert (r.signer_status, r.mechanisms) == ("unknown", ("unverified_out_lookalike",)) + assert r.level == "partially_supported" + + +def test_native_sender_is_the_lookalike_and_receipts_set_the_level() -> None: + ok = by_look(ce.build(rs.wallet_fixture(native=[(STRONG, 1, 2_000, True)]), cutoff=END)) + unread = by_look(ce.build(rs.wallet_fixture(native=[(STRONG, 1, 2_000, None)]), cutoff=END)) + reverted = by_look(ce.build(rs.wallet_fixture(native=[(STRONG, 1, 2_000, False)]), cutoff=END)) + assert ok[STRONG].evidence[0].signer_status == "lookalike_itself" + assert (ok[STRONG].level, unread[STRONG].level) == ("directly_verified", "supported") + assert unread[STRONG].missing == ("receipt",) + assert STRONG not in reverted # a reverted transfer is not evidence + + +def test_unknown_token_identity_never_becomes_untrusted() -> None: + fx = rs.wallet_fixture(transfers=[(STRONG, W, 10**18, 2_000, None, FAKE, 0)]) + obs = ce.mask(cd.observations(fx), "token") + [r] = by_look(ce.build(fx, cutoff=END, observations=obs))[STRONG].evidence + assert "untrusted_token_in" not in r.mechanisms + assert "token_identity" in r.missing + [known] = by_look(ce.build(fx, cutoff=END))[STRONG].evidence + assert known.mechanisms == ("lookalike_in", "untrusted_token_in") + + +# --- identity and grouping ----------------------------------------------------------------- + + +def test_one_group_per_lookalike_keeps_every_record_in_order() -> None: + fx = rs.wallet_fixture( + native=[(STRONG, 1, 2_100, True), (STRONG, 1, 2_000, True)], + transfers=[(STRONG, W, 0, 2_050, None, USDT, 0), (W, STRONG, 0, 2_200, ATTACKER, USDT, 0)], + ) + g = by_look(ce.build(fx, cutoff=END))[STRONG] + assert [r.block for r in g.evidence] == [2_000, 2_050, 2_100, 2_200] + assert g.mechanisms == ("lookalike_in", "spoofed_out", "zero_value_in") + assert g.kinds == ("erc20", "native") + assert g.identity == f"1:{W}:{STRONG}" + assert g.references == ((REF, 5, 5),) + + +def test_duplicate_ingestion_does_not_inflate_records() -> None: + fx = rs.wallet_fixture(native=[(STRONG, 1, 2_000, True)]) + dup = fx.model_copy(update={"native_inbound": fx.native_inbound * 2}) + assert ce.build(dup, cutoff=END).evidence_records == 1 + assert ce.build(dup, cutoff=END).raw_events == ce.build(fx, cutoff=END).raw_events + 1 + + +def test_identity_separates_victims_and_chains() -> None: + fx = rs.wallet_fixture(native=[(STRONG, 1, 2_000, True)]) + other = fx.model_copy(update={"chain_id": 10}) + a = ce.build(fx, cutoff=END).groups[0].identity + b = ce.build(other, cutoff=END).groups[0].identity + assert a != b + assert a.split(":")[2] == b.split(":")[2] == STRONG + + +def test_future_events_do_not_change_groups_at_an_earlier_cutoff() -> None: + base = rs.wallet_fixture(native=[(STRONG, 1, 2_000, True)]) + later = rs.wallet_fixture( + native=[(STRONG, 1, 2_000, True), (WEAK, 1, 5_000, True), (STRONG, 1, 6_000, True)], + transfers=[(W, STRONG, 10**6, 7_000, W, USDT, 0)], + ) + cut = (3_000, 0) + a, b = ce.build(base, cutoff=cut), ce.build(later, cutoff=cut) + assert [(g.identity, g.evidence) for g in a.groups] == [ + (g.identity, g.evidence) for g in b.groups + ] + + +# --- summary and spam ---------------------------------------------------------------------- + + +def test_summary_discloses_truncation_and_keeps_everything() -> None: + fx = rs.wallet_fixture(native=[(rs.lookalike(i + 1), 1, 2_000 + i, True) for i in range(25)]) + res = ce.build(fx, cutoff=END) + s = ce.summarize(res, 10) + assert (s["total_groups"], s["shown"], s["truncated"]) == (25, 10, True) + assert len(s["hidden_identities"]) == 15 + assert "not assessed as safe" in s["note"] + assert len(res.groups) == 25 # the display budget deletes nothing + assert ce.summarize(ce.build(fx, cutoff=END), 10) == s # deterministic + + +@pytest.mark.parametrize("name", sorted(rs.scenarios())) +def test_adversarial_scenarios(name: str) -> None: + fx, strong = rs.scenarios()[name] + res = ce.build(fx, cutoff=END) + expected_groups = { + "1_zero_value_strangers": 0, # anyone can send 0 ETH: never a candidate alone + "2_distinct_lookalikes": 1_000, + "3_repeated_dust_one_lookalike": 1, + "4_many_lookalikes_one_reference_with_one_strong": 1_001, + "5_multiple_references": 50, + "6_fake_token_spam": 1_000, + "7_same_block_repeats": 100, + "8_unknown_signer_with_complete_signed_set": 1, + "9_missing_receipt": 1, + "10_partial_history": 1, + "11_one_strong_among_weak": 2_001, # 1,000 dust strangers + 1,000 lookalikes + strong + "12_public_token_reuse": 200, + }[name] + assert len(res.groups) == expected_groups + if strong is not None: + assert res.groups[0].lookalike == strong # never buried under weaker events + if name == "3_repeated_dust_one_lookalike": + assert res.evidence_records == 500 + if name == "10_partial_history": + assert res.abstain is not None + assert res.groups[0].level == "partially_supported" + + +def test_spam_stability_prefers_costly_affixes_over_recency() -> None: + fx = rs.wallet_fixture( + transfers=[(W, STRONG, 0, 2_000, ATTACKER, USDT, 0)], + native=[(rs.lookalike(0, prefix=4, suffix=4), 1, 2_100, True)], + ) + out = rs.spam_stability(fx, END, n=300, k=10) + assert out["real_candidates"] == 2 + assert out["evidence_aware"]["real_in_top_k"] == 2 + assert out["recency_only"]["real_in_top_k"] == 0 # cheap recent spam buries them + assert out["similarity_only"]["real_in_top_k"] == 2 + + +# --- isolation and determinism ------------------------------------------------------------- + + +def test_production_detector_is_untouched() -> None: + fx, _ = rs.scenarios()["11_one_strong_among_weak"] + full = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS + before = detector_outputs(fx, 9_000, full, PoisoningConfig()) + ce.summarize(ce.build(fx, cutoff=END)) + assert detector_outputs(fx, 9_000, full, PoisoningConfig()) == before + + +def test_result_serializes_deterministically() -> None: + fx, _ = rs.scenarios()["4_many_lookalikes_one_reference_with_one_strong"] + a, b = ce.to_json(ce.build(fx, cutoff=END)), ce.to_json(ce.build(fx, cutoff=END)) + assert a == b + assert json.loads(a)["version"] == ce.EVIDENCE_VERSION + + +def test_masking_never_produces_unsafe_claims() -> None: + fx = rs.wallet_fixture( + transfers=[ + (W, STRONG, 0, 2_000, ATTACKER, USDT, 0), + (WEAK, W, 10**18, 2_100, None, FAKE, 0), + ], + native=[(rs.lookalike(0, prefix=4, suffix=4), 1, 2_200, True)], + ) + out = rs.masking(fx, END) + for cond in ("S1_signer", "S2_event_sender", "S3_receipt", "S4_token", "S5_partial_history"): + assert out[cond]["evidence_unsafe_inferences"] == 0, cond + assert out[cond]["added"] == 0, cond + assert out[cond]["level_raised"] == 0, cond + assert out["S4_token"]["c1_unsafe_inferences"] == 1 # C1 calls an unknown token untrusted + assert out["S1_signer"]["lost"] == 0 # R-SIG recovers the spoof + assert out["S3_receipt"]["level_lowered"] == 1 # verified native drops to supported From f4caf5ac5a20cc9c40354b29602e07f3fe34eb9c Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 03:12:43 +0300 Subject: [PATCH 72/92] docs(ml): Phase 12.6 report - candidate reliability and signer provenance (no RPC) ML_CANDIDATE_RELIABILITY.md: signer-provenance audit (outgoing signer coverage 18/18; the 12.5 result came from masking), R-SIG recovery (18/18 consistent; 0 candidates lost with all signers masked), confirmed defects (C2 dropped evidence records; no signer recovery; C1 calls an unknown token untrusted), evidence groups, S1-S5 masking (0 unsafe inferences vs 5 for C1), 12 adversarial scenarios, H5 negative (support first loses to similarity under cheap verified spam), exploratory robust proxy features, linear scaling, production-readiness decisions. 950 passed, 1 failed (load-sensitive lease test; passes 3/3 alone). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 ++ ML_CANDIDATE_RELIABILITY.md | 331 ++++++++++++++++++++++++++++++++++++ 2 files changed, 346 insertions(+) create mode 100644 ML_CANDIDATE_RELIABILITY.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e0c39d..03913f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,21 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.6: candidate reliability and signer provenance (no RPC requests) +- **Protocol 12.6** (`docs/ml/protocol-12.6.md`) was frozen first. The code was committed before the measured run. +- **Audit:** real recordings have complete outgoing-signer coverage (18 of 18). The Phase 12.5 "signer loss" result came from masking. +- **Signer recovery (R-SIG):** an outgoing event absent from a code-less wallet's complete signed set was not signed by the wallet. The signer's address is never guessed. It matches the looked-up signer in 18 of 18 cases. With all signers masked, the real windows lose 0 candidates. +- **`candidate-evidence/1`:** + - one group per (chain, victim, lookalike), keeping every record (the pilot's 9, where C2 kept 6); + - typed provenance; + - non-probabilistic levels; + - 0 unsafe inferences under masking (C1 makes 5 with token identity unknown); + - a bounded summary that discloses totals and truncation. +- **12 adversarial scenarios:** zero-value floods produce 0 groups, and a strong candidate stays rank 1 among 2,001. Cost is linear: 10,000 groups in 1.8 s. +- **H5 failed:** under cheap verified dust spam, a support-first order is beaten by similarity. +- **Exploratory:** log-scaled proxy features beat raw ones on a development sub-split. +- **Report:** `ML_CANDIDATE_RELIABILITY.md`. + ### Phase 12.5: ML-driven candidate discovery and evidence-aware ranking (no RPC requests) - **Protocol 12.5** (`docs/ml/protocol-12.5.md`) was frozen before any new outcome. The code was committed before the outcome run. - **Primary pre-registered ML test** (`planting-mechanism-next/1`, a self-supervised proxy on 1,067 archive episodes): **not supported.** diff --git a/ML_CANDIDATE_RELIABILITY.md b/ML_CANDIDATE_RELIABILITY.md new file mode 100644 index 0000000..c9a0153 --- /dev/null +++ b/ML_CANDIDATE_RELIABILITY.md @@ -0,0 +1,331 @@ +# Candidate reliability, signer provenance and evidence-aware presentation (Phase 12.6) + +| Item | Value | +|---|---| +| Protocol (frozen first) | [`docs/ml/protocol-12.6.md`](docs/ml/protocol-12.6.md), `c060ccc` | +| Code (committed before the measured run) | `8e59c9d` | +| Study output (git-ignored) | `data/ml/research/phase12.6/reliability-study.json` (`cryptoguard ml reliability-study`) | +| RPC requests / downloads | **0** / none | + +## 1. Executive summary + +**Is signer loss a defect?** No. The real recordings have complete outgoing-signer coverage: 18 of 18 on the eligible windows, with 0 lookups skipped. The Phase 12.5 result, "signer loss removes every spoofed candidate", came from masking. A spoof is defined by the victim *not* signing, so it needs signer evidence. The realistic gap is the recorder's 500-lookup cap on busy wallets. + +**Deterministic recovery, R-SIG.** Nonce bisection records every transaction a wallet signed. +- An outgoing event whose transaction is in that set was signed by the wallet. +- One absent from a complete set, for a wallet without code, was **not** signed by it. The signer's address is never guessed. +- **Result:** the rule matches the looked-up signer in **18 of 18** real cases, including 8 of 8 spoofs. +- **With every signer masked,** the real windows lose **0** candidates and recover 4–5 signers each. Phase 12.5 lost them all. + +**Evidence model, `candidate-evidence/1`.** +- **One group per (chain, victim, lookalike)**, keeping **every** record. The pilot's 9 events become 6 groups with all 9 records; C2 had kept only one per group. +- **Typed provenance:** the event sender is never taken as the signer, and an unknown token is never called untrusted. With token identity masked, C1 makes 5 such unsupported claims on the pilot; the evidence model makes **0** under every masking condition. + +**Spam resilience.** +- 1,000 zero-value strangers produce **0** groups (C1 lists 1,000). +- One strong candidate stays **rank 1** among 2,001. +- The bounded summary discloses totals and truncation, and deletes nothing. +- It scales linearly: 10,000 groups in 1.77 s. + +**H5 fails against similarity (pre-registered).** The support-first order keeps only 3 of 6 real pilot candidates in the top 10 under cheap dust spam, while similarity-only keeps 6 of 6. A dust receipt verifies execution, which is cheap for an attacker. **Support is not suspicion.** Recency keeps 0. + +**H6 (exploratory).** Log-scaled proxy features beat raw ones on a development sub-split. That sub-split has mild shift, so this does **not** show the Phase 12.5 failure is fixed. + +**No learned ranking model.** There are no valid labels. + +**Classification:** +- a confirmed provenance improvement (R-SIG); +- confirmed evidence preservation and spam resilience on controlled tasks; +- a negative ranking finding (H5); +- an exploratory feature-robustness signal (H6). + +## 2. Baseline repository state + +| Item | Value | +|---|---| +| HEAD | `82d54a3`, clean, equal to `origin/feature/ml-pipeline` | +| CI | 9 of 9 jobs passed | +| Cohort sheet hashes | Cohort A `a0ec4b6e…` and Cohort B `121c112d…`, unchanged | +| Detector | `address-poisoning` 1.0.0 | +| Generators | C0 `candidates/2`, plus C1 and C2 (`poisoning-candidate-discovery/1`), unchanged | + +## 3. Signer-provenance audit + +| Field | Source | Historical availability | Trust | Missingness | Failure mode | Correction | +|---|---|---|---|---|---|---| +| Transaction signer (outgoing ERC-20) | `eth_getTransactionByHash` `from`, newest 500 | complete in real windows (18 of 18) | verified | skipped beyond 500 (`sender_lookups_skipped`) | unknown signer: neither reference nor spoof | **R-SIG** recovery from the signed set | +| Transaction signer (incoming ERC-20) | not looked up | never | — | always unknown | none for current rules (inbound evidence is the event's own `from`) | stated as `unknown` | +| Event sender / recipient | log topics | complete | as reported by the emitting contract (a fake token can report anything) | — | taken as the signer | **never substituted**: `event_sender` is kept separate | +| Emitting contract | log address | complete | an identity, not a legitimacy | — | treated as attacker | never an attacker identity | +| Native sender | the transaction's `from` (balance bisection) | `observation/2` only | verified (the sender signed it) | not collected in `/1` | — | `lookalike_itself` | +| Wallet's own transactions | nonce bisection | complete by construction | verified | — | — | basis of R-SIG | +| Receipt status | receipts (native, `/2`); logs imply execution | native `/2`: read | verified | unread: `unknown` | inferred success (fixed in 12.4) | `succeeded` / `reverted` / `implied_by_log` / `unknown` | +| Token legitimacy | reviewed list | static | list-based | unknown when masked | C1 calls an unknown token untrusted | no claim; `token_identity` listed as missing | + +## 4. Confirmed defects + +1. **C2 aggregation dropped evidence.** It kept the first record per lookalike: the pilot had 9 records in 6 candidates, and 3 records were dropped. Fixed in `candidate-evidence/1`. C2 itself is unchanged, for reproducibility. +2. **There was no signer recovery** even though the wallet's complete signed set is local. Fixed by R-SIG, at the research layer. +3. **C1 asserts `untrusted_token_in` when token identity is unknown.** That is 5 unsafe claims on the pilot under masking. Real logs always carry the token, so in practice this is a latent defect. The evidence model makes no such claim. C1 is unchanged. + +## 5. Unsupported hypotheses + +- **"Real recordings lose signer information":** not observed (18 of 18, 0 skipped). +- **"Missing signer could support a spoof claim":** rejected by design. Without R-SIG evidence, an outgoing lookalike is kept as `unverified_out_lookalike` (partially supported) and never called a spoof. + +## 6. Evidence representation + +`EvidenceRecord` holds: +- identity: `tx::`; +- kind and direction; +- position: block, transaction index, log index; +- mechanisms and level; +- signer status and signer; +- event sender and recipient; +- emitter and receipt; +- the zero-value flag; +- `missing`. + +`CandidateGroup` holds: +- identity and lookalike; +- the references, with affixes; +- mechanisms and kinds; +- the best level and best affix; +- the first and last positions; +- every record, in order; +- `missing`. + +**Levels** (non-probabilistic): + +| Level | Definition | +|---|---| +| `directly_verified` | a foreign-signed or R-SIG-absent spoof; a native lookalike transfer whose receipt reads success | +| `supported` | a token lookalike planting; a native transfer with an unread receipt | +| `partially_supported` | an unknown-signer outgoing lookalike; a non-lookalike rule | + +## 7. Candidate identity rules + +- **Identity:** `::`. +- **Separate identities:** different victims or chains never share one (tested). +- **Not identity:** a shared token contract is never part of identity or of linkage (scenario 12). +- **Duplicates:** source duplicates collapse on `(tx hash, log index)`. + +## 8. Deduplication results (real windows, eligible only) + +| Window | Raw records | C1 events | C2 candidates | Groups | Records kept | +|---|---|---|---|---|---| +| pilot | 12 | 9 | 6 | 6 | **9** (C2 kept 6) | +| Scam Sniffer `/1` | 13 | 2 | 2 | 2 | 2 | +| Scam Sniffer blind `/2` | 15 | 3 | 3 | 3 | 3 | +| 6 × P5 | 0–9 | 0 | 0 | 0 | 0 (2 abstain: no reference) | + +## 9. Candidate presentation, and 14. operational candidate budget + +**The summary holds:** +- `total_groups`, `raw_events`, `evidence_records`; +- `shown` (k = 10) and `truncated`; +- `hidden_identities`; +- counts by level and by mechanism; +- `abstain`; +- the note that hidden candidates are not assessed as safe; +- for each shown group: references, affix, blocks, evidence count, missing, and an explanation along three separate dimensions (suspicion, support, missing). + +**Order:** +1. level; +2. affix; +3. latest planting; +4. address, which keeps it deterministic (tested). + +**A display budget is not an evidence budget.** All groups and records stay in the result. + +**Measured cost of disclosure:** the hidden-identity list makes the summary O(n). It is 95.6 KB at 1,000 groups and 915 KB at 10,000 (§21). A UI may prefer counts plus a digest. The list is kept because the protocol requires it. + +## 10. Adversarial spam results (synthetic, 12 scenarios; all deterministic) + +| Scenario | Raw | C1 events | Groups | Records | Shown / hidden | Strong rank | Time | +|---|---|---|---|---|---|---|---| +| 1. 1,000 zero-value strangers | 1,001 | 1,000 | **0** | 0 | 0 / 0 | — | 0.02 s | +| 2. 1,000 distinct lookalikes | 1,001 | 1,000 | 1,000 | 1,000 | 10 / 990 | — | 0.19 s | +| 3. 500 dust transfers from one lookalike | 501 | 500 | **1** | **500** | 1 / 0 | 1 | 0.04 s | +| 4. 1,000 weak + 1 strong (one reference) | 1,002 | 1,001 | 1,001 | 1,001 | 10 / 991 | **1** | 0.23 s | +| 5. 50 references, a lookalike of each | 101 | 50 | 50 | 50 | 10 / 40 | — | 0.01 s | +| 6. 1,000 fake-token events | 1,001 | 1,000 | 1,000 | 1,000 | 10 / 990 | — | 0.14 s | +| 7. 100 in one block | 101 | 100 | 100 | 100 | 10 / 90 | — | 0.01 s | +| 8. Unknown signer, complete signed set | 2 | **0** | **1** (spoof by R-SIG) | 1 | 1 / 0 | 1 | <0.01 s | +| 9. Missing receipt | 2 | 1 | 1 (supported) | 1 | 1 / 0 | 1 | <0.01 s | +| 10. Partial history | 2 | 0 | 1 (partial), abstains | 1 | 1 / 0 | — | <0.01 s | +| 11. Strong spoof among 2,000 weak | 2,002 | 2,001 | 2,001 | 2,001 | 10 / 1,991 | **1** | 0.31 s | +| 12. 200 plantings via public USDT | 201 | 200 | 200 | 200 | 10 / 190 | — | 0.03 s | + +Peak traced memory is at most 3.1 MiB for any scenario. + +## 11. Historical correctness + +- **Cutoff:** strictly before `(block, tx index)`. +- **Tested:** later plantings, payoffs and lookalikes leave groups and records at an earlier cutoff unchanged, and record order changes nothing. +- **Hashes** in the synthetic builder are content-derived, so a record has the same identity in any fixture. + +## 12. Missingness handling (S0–S5, real windows) + +Each cell shows kept / lost / added, then the change in level. + +| Condition | pilot (6) | Scam Sniffer `/1` (2) | Scam Sniffer blind `/2` (3) | C1 unsafe | Evidence unsafe | +|---|---|---|---|---|---| +| S1 signer | 6/0/0; 5 recovered | 2/0/0; 4 recovered | 3/0/0; 4 recovered | 0 | **0** | +| S2 event sender | 4/2/0; 4 lowered, abstains | 0/2/0, abstains | 0/3/0, abstains | 0 | **0** | +| S3 receipt | 6/0/0 | 2/0/0 | 3/0/0; 1 lowered (verified → supported) | 0 | **0** | +| S4 token identity | 6/0/0 | 2/0/0 | 3/0/0 | **5** | **0** | +| S5 partial history | 6/0/0, abstains | 2/0/0, abstains | 3/0/0, abstains | 0 | **0** | + +**No condition ever adds a candidate or raises a level.** Missing information only lowers support or causes abstention. + +## 13. ML research protocol + +Protocol 12.6 sets out H1–H7. No learned ranking model (M4) was trained: no valid ranking labels exist beyond 2 development cases and Phase 12.1's used test split. + +## 15. Ranking methods, and baseline comparisons (H5) + +| Ordering | Definition | +|---|---| +| **Evidence-aware** | level, then affix, then latest planting | +| Recency-only | latest planting | +| Similarity-only | affix | + +**Test:** 1,000 cheap native-dust lookalikes (affix 3 + 3, receipt success, planted latest) are injected into copies of the two real windows, in memory. + +| Window (real candidates) | Evidence-aware: real in top 10 / τ | Recency-only | Similarity-only | +|---|---|---|---| +| Scam Sniffer blind (3) | **3** / 1.00 | 0 / −0.33 | 3 / 1.00 | +| pilot (6) | **3** / 1.00 | 0 / 0.47 | **6** / 0.47 | + +**H5 is not supported.** The evidence-aware order retains fewer real candidates than similarity-only on the pilot. +- **Cause:** cheap dust spam earns `directly_verified`, because its receipt is real. So it outranks the pilot's `supported` lookalikes, whose affixes are stronger. +- **Lesson:** the support level measures how certain the *interpretation* is, and that certainty is cheap for an attacker to produce. It must not lead the order. +- **Not tested here:** ordering by affix first, then level. It is proposed for the next pre-registered test and not claimed. +- **Recency is the most spam-fragile order.** + +## 16. Learned-model feasibility, and 17. feature robustness (H6, exploratory) + +**Setup:** Phase 12.1's development split only. The 12.5 test split is never used. An internal temporal sub-split: 442 training groups (7,766 rows) and 190 validation groups (5,037 rows). + +| Method | Log loss | Macro-F1 | Top-class ECE | +|---|---|---|---| +| Global | 0.2804 | 0.243 | 0.0023 | +| Victim prefix | 0.2621 | 0.297 | 0.0206 | +| Markov | 0.2713 | 0.243 | 0.0108 | +| LR, raw counts (12.5 features) | 0.2708 | 0.350 | 0.0284 | +| **LR, log-scaled counts** | **0.2384** | **0.393** | 0.0133 | + +- **Robust minus raw:** −0.032 [−0.068, −0.006] over 190 groups. +- **Shift within this sub-split:** prefix p90 154 → 177, which is mild. +- **Not shown:** that the 12.5 failure, with p90 163 → 2,481, is fixed. That would need an untouched later population. +- **Status:** exploratory. The Phase 12.5 conclusion stands. + +## 18. Evaluation populations + +| Population | Description | +|---|---| +| P1 | synthetic | +| P2 | the 2 Level I development cases | +| P3 | 9 eligible wallet recordings | +| P4/P5 | the archive episode cache, development split only | + +They are never pooled. Background windows are not negatives. + +## 19. Candidate-volume analysis + +| Population | Volume | +|---|---| +| Real (P3) | 0–6 groups per window; at most 2 groups per wallet-day | +| Synthetic | bounded by distinct lookalikes, never by raw events | + +Native volume on unlabelled wallets is still unmeasured, because P5 is `observation/1`. + +## 20. Statistical limitations + +- **Real windows:** n = 3, two of them development cases. +- **Spam tests:** synthetic, testing robustness, not detection. +- **H6:** exploratory, on development data that was seen before. +- **Not reported:** any precision, recall, false-positive rate or probability. + +## 21. Operational performance (synthetic, linear) + +| Candidates | Build | Summary | Peak traced | Result JSON | Summary JSON | Groups / s | +|---|---|---|---|---|---|---| +| 10 | 0.002 s | <0.001 s | 0.01 MiB | 10.8 KB | 5.5 KB | 5,000 | +| 100 | 0.011 s | <0.001 s | 0.12 MiB | 103 KB | 13.7 KB | 9,091 | +| 1,000 | 0.169 s | 0.004 s | 1.44 MiB | 1.03 MB | 95.6 KB | 5,917 | +| 10,000 | 1.771 s | 0.028 s | 16.6 MiB | 10.3 MB | 915 KB | 5,647 | + +**The whole study:** 90 s, peak RSS 235 MiB, one process. + +**The Phase 12.5 optimization is preserved:** observations are built once per window. + +## 22. Production isolation + +- **Detector:** unchanged. `detector_outputs` is identical before and after building evidence (tested). +- **Research code:** reachable only through `cryptoguard ml reliability-study`. +- **Dependencies:** no new production dependency. scikit-learn is used only in the exploratory proxy, as before. + +## 23. Tests, and 24. CI + +| Check | Command | Result | +|---|---|---| +| Lint | `uv run ruff check .` | clean | +| Format | `uv run ruff format --check .` | 291 files formatted | +| Types | `uv run mypy src` | clean (153 files) | +| Tests | `uv run pytest -q` | **950 passed, 1 failed**, 4 deselected (an 18-minute run on a heavily loaded machine) | + +**About the failure.** It was `tests/integration/test_leases.py::test_lease_of_a_crashed_process_is_recovered_after_expiry`, a timing-sensitive lease-expiry test whose own comment records load flakiness. It passed **3 of 3** reruns in isolation. Phase 12.6 changed no lease code: its only source changes are `ml/cli.py` and two new research modules. + +There are 27 new tests in `tests/test_ml_candidate_evidence.py`. + +**Frozen artifacts:** the Cohort A and B sheet and key hashes are unchanged after the run (`a0ec4b6e…`, `407b412f…`, `121c112d…`, `f333386d…`). The frozen Level I fixtures are pinned by their regression tests, which passed. + +CI is recorded in the PR #1 description. + +## 25. Resource usage + +- 0 RPC requests, 0 downloads. +- The study took 90 s at 235 MiB peak. +- It reused the Phase 12.5 episode cache, with no archive re-read. + +## 26. Positive findings + +1. R-SIG recovers spoof status without inventing identities, matching the real signer in 18 of 18 cases. +2. Evidence is fully preserved and grouped. +3. No unsafe inference occurs under any masking. +4. Spam can't bury a strong candidate whose support is also high, and zero-value floods produce nothing. +5. Cost scales linearly. + +## 27. Negative findings + +1. H5: a support-first order is beaten by similarity under cheap verified spam. +2. Recency is the most spam-fragile order. +3. The summary's hidden-identity list is O(n). +4. There is no valid task for a learned ranker. + +## 28. Production-readiness decisions + +| Change | Category | Decision | Risk and evidence | +|---|---|---|---| +| R-SIG signer recovery | A/B, provenance | **Eligible for a separately approved production change.** Not integrated here: it would silently change production spoof signals for busy wallets. | 18 of 18 consistency; contract and EIP-7702 wallets excluded | +| Evidence model and levels | B | research (shadow); integrate after a migration review | levels are not probabilities | +| Unknown-signer outgoing lookalikes kept as partially supported | C | research only | never a spoof claim | +| Bounded summary contract | E | research output; never suppresses production warnings | O(n) disclosure list | +| Support-first ordering | D | **do not adopt**; H5 failed | spam outranks real candidates | +| Robust proxy features | D | exploratory | mild-shift development sub-split only | + +## 29. Recommended next experiment + +**Question:** on untouched `observation/2` incident windows, does an affix-first order, then support, then recency, keep the later-paid lookalike in the top 10 under cheap spam more often than recency? + +| Element | Specification | +|---|---| +| Observations | At least 10 untouched incidents, recorded blind with `observation/2`. User-sourced harm-transaction hashes. | +| Labels | The paid address, from the harm transaction, used only to score | +| Contribution | The first prospective-style test of spam-robust ordering on real data | +| Cost | About 700–1,300 RPC requests per window, so about 15,000 in total. Analysis takes seconds. | +| Failure | The affix-first order does not keep the paid lookalike in the top 10 in more untied clusters than recency, under amendment A1's cluster sign test | + +Phase 12.7 is not started. From 5a5e876741af602a6f049176576eb2b2cdb459f9 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 12:34:51 +0300 Subject: [PATCH 73/92] feat(ml): signer-recovery guards, authorization, bounded pages; deterministic lease test candidate-evidence/2 (research only, detector unchanged): - absence_guard: R-SIG infers "not signed by the wallet" only for a complete, count-consistent, nonce-contiguous signed set of an account whose code is 0x at every sample up to the cutoff (no EIP-7702 designator, no contract code); legacy fixtures must document the nonce bisection. Otherwise the signer stays unknown. - A looked-up signer that contradicts the signed set is "conflicting": never a reference, never a spoof. - Not signed is not unauthorized: a value-moving foreign-signed transfer is foreign_initiated_out with authorization unknown (allowance, permit, delegation or fabricated log); only zero-value ones are spoofed_out. - Presentation order reads no support level (affix, recency, address); the pre-registered support-first order is kept as evidence_order_key for H5. - Bounded summary (no hidden-identity list), digest-checked page() and group_records() offset/limit access. reliability-study/2: signer guard matrix, real-window authorization audit, separation checks, 10,000-event adversarial suite, summary scaling to 100,000. Lease test: distinct child exit codes, explicit-clock expiry probes instead of a conditional wall-clock check, a bounded join that kills a hung child, and a new expiry-boundary test (no instant with two owners). Amendment: docs/ml/amendment-12.6.1.md. Co-Authored-By: Claude Opus 5.5 --- docs/ml/amendment-12.6.1.md | 79 ++++ src/cryptoguard/ml/candidate_evidence.py | 348 +++++++++++++---- src/cryptoguard/ml/cli.py | 2 +- src/cryptoguard/ml/reliability_study.py | 454 ++++++++++++++++++++++- tests/integration/test_leases.py | 52 ++- tests/test_ml_candidate_evidence.py | 2 +- tests/test_ml_signer_guards.py | 350 +++++++++++++++++ 7 files changed, 1191 insertions(+), 96 deletions(-) create mode 100644 docs/ml/amendment-12.6.1.md create mode 100644 tests/test_ml_signer_guards.py diff --git a/docs/ml/amendment-12.6.1.md b/docs/ml/amendment-12.6.1.md new file mode 100644 index 0000000..6d7c2d9 --- /dev/null +++ b/docs/ml/amendment-12.6.1.md @@ -0,0 +1,79 @@ +# Amendment 12.6.1: signer-recovery guards, authorization, bounded pages, presentation order + +**Written:** 2026-11-09, with the code it describes. Phase 12.6.1 is a correctness and +operations phase, not a new hypothesis test, so nothing here is pre-registered. Every number in +`ML_CANDIDATE_RELIABILITY.md` §30–§39 comes from a study run on the commit that adds this file +(the run records its git SHA). + +**Amends:** `protocol-12.6.md`, the R-SIG rule, the presentation order and the summary +contract. **Unchanged:** H1–H7, their pre-registered results (H5 still fails), the evidence +levels, the group identity, C0/C1/C2, the production detector and every frozen fixture. + +**Code:** `ml/candidate_evidence.py` (`candidate-evidence/2`), `ml/reliability_study.py` +(`reliability-study/2`). Research only: nothing is wired into the detector or a warning. + +## A1. R-SIG proves non-signing only, and only when the guard allows it + +Absence from the wallet's signed set proves that the wallet did not **directly** sign a +transaction only when `absence_guard` finds all of the following: + +1. The signed set is stated `complete`, with the stated count equal to the records held. +2. A legacy (`observation/1`) fixture documents the nonce bisection that its completeness + claim rests on. +3. Recorded nonces are unique and consecutive. A gap means a nonce was consumed without a + recorded transaction: a missing page, or an EIP-7702 authorization. +4. Every recorded transaction lies inside the window. +5. The account's code is known at the window start, and it is `0x` at every sample up to the + cutoff. That rules out an EIP-7702 delegation designator and contract or smart-wallet code. + Samples after the cutoff are ignored. + +Otherwise the signer stays `unknown`, and an outgoing lookalike stays +`unverified_out_lookalike` (partially supported). A looked-up signer that contradicts the +signed set is `conflicting`. It is never treated as a reference and never as a spoof. + +The recorder's 500-lookup cap (`max_sender_lookups`) limits signer **lookups**. It does not +limit the signed set, so R-SIG still applies to busy wallets. + +## A2. Not signed is not unauthorized + +A wallet can authorize a pull without signing the transaction that performs it, through an +ERC-20 allowance, a permit, or an EIP-7702 delegation. A fabricated log needs no authorization +at all. So every outgoing ERC-20 record now carries `authorization`: + +- **Zero value, foreign signer:** `spoofed_out`, `authorization = not_required`. Nothing moved. +- **Nonzero value, foreign signer (looked up or by R-SIG):** `foreign_initiated_out`, plus + `untrusted_token_out` when the emitter is known and not trusted. The record has + `authorization = unknown`, and `authorization` is listed as missing. It is not called a spoof. + +The evidence level is unchanged. It still describes the observed facts. + +## A3. Presentation order reads no support level + +Groups are presented by affix strength, then by the latest planting, then by address +(`presentation_key`). The support level and the missing list are never read. This follows +from the 12.6 separation of support from suspicion: + +- a verified receipt cannot move a candidate up; +- a missing fact cannot move a candidate up or down. + +The pre-registered support-first order is kept as `evidence_order_key`, only to reproduce H5. + +**This is not validated.** The pilot and the ScamSniffer window are development data; they +informed the choice and cannot confirm it. Whether the order helps on new incidents is the +next experiment (§29 of the report). It is not claimed here. + +## A4. Bounded summary and page access + +`summarize(result, k)` returns: +- at most `k` items (1 ≤ k ≤ 1,000); +- the totals and `hidden_count`; +- a `truncated` flag and `next_offset`; +- a `result_digest` of the full result. + +It no longer lists hidden identities, so its size no longer grows with the number of +candidates. The full evidence is reached through two functions: +- `page(result, offset, limit, expect_digest)`, which follows the project's + `items`/`total`/`limit`/`offset` page convention and refuses a stale digest; +- `group_records(result, identity, offset, limit)`, which pages one group's records. + +Nothing is deleted, and hidden candidates are still "not assessed as safe". diff --git a/src/cryptoguard/ml/candidate_evidence.py b/src/cryptoguard/ml/candidate_evidence.py index f6de26e..d8c0630 100644 --- a/src/cryptoguard/ml/candidate_evidence.py +++ b/src/cryptoguard/ml/candidate_evidence.py @@ -1,31 +1,47 @@ -"""Evidence-preserving candidate groups and a bounded summary (``candidate-evidence/1``), -research only (protocol 12.6). +"""Evidence-preserving candidate groups and a bounded summary (``candidate-evidence/2``), +research only (protocols 12.6 and 12.6.1). Every candidate is a group identified by (chain, victim, lookalike) that keeps **every** distinct evidence record that caused it, in chain order, each with typed provenance: - ``signer_status``: ``wallet``, ``foreign_known`` (looked-up signer, not the wallet), ``foreign_identity_unknown`` (rule R-SIG: the transaction is absent from the wallet's - complete signed set and the wallet has no code, so the wallet did not sign it, but who did - is unknown), ``lookalike_itself`` (a native transfer the lookalike sent) or ``unknown``. - The event's ``from`` field is never taken as the signer. + complete signed set, so the wallet did not *directly* sign it; who did is unknown), + ``lookalike_itself`` (a native transfer the lookalike sent), ``conflicting`` (the looked-up + signer and the signed set disagree) or ``unknown``. The event's ``from`` field is never + taken as the signer. +- ``authorization``: whether the wallet authorized the value movement. ``direct_signature`` + (the wallet signed the transaction), ``not_required`` (a zero-value transfer moves nothing), + ``unknown`` (the wallet did not sign the transaction, but an ERC-20 allowance, a permit or + an EIP-7702 delegation can still authorize a pull, and a fabricated log needs none) or + ``not_applicable`` (incoming records). R-SIG never proves an absence of authorization. - ``event_sender`` / ``event_recipient``: what the log or transaction reports. - ``emitter``: the token contract (``None`` when unknown); never an attacker identity. - ``receipt``: ``succeeded``, ``reverted``, ``implied_by_log`` (a log exists only for an executed transaction) or ``unknown``. +R-SIG's absence inference runs only when ``absence_guard`` finds the signed set provably +complete for a plain externally owned account up to the cutoff (see its docstring). + Evidence levels are categories, not probabilities: ``directly_verified``, ``supported``, -``partially_supported`` (see ``LEVELS``). Missing information lowers the support level and -is listed in ``missing``; it never raises suspicion. The summary shows a bounded top-k -with the totals, a truncation flag and the hidden identities: a display budget is not an -evidence budget, and hidden candidates are not assessed as safe. The production detector -is never consulted or changed. +``partially_supported`` (see ``LEVELS``). They describe how well the *observed facts* are +established, not how suspicious a candidate is, so they never move a candidate up or down +the presentation order (``presentation_key``: similarity, then recency, then address). +Missing information lowers the support level and is listed in ``missing``; it never raises +suspicion. Legitimacy is never assessed. + +The summary is bounded by ``k``: it reports the totals, the hidden count, a truncation flag +and a digest of the full result; ``page`` and ``group_records`` give offset/limit access to +every group and every record. A display budget is not an evidence budget, and hidden +candidates are not assessed as safe. The production detector is never consulted or changed. """ from __future__ import annotations +import hashlib +import itertools import json -from collections.abc import Iterable, Sequence +from collections.abc import Callable, Iterable, Sequence from dataclasses import asdict, dataclass, replace from typing import Any, Literal @@ -34,13 +50,27 @@ from cryptoguard.ml.payments import TRUSTED_TOKENS from cryptoguard.replay.observation import coverage_of -EVIDENCE_VERSION = "candidate-evidence/1" +EVIDENCE_VERSION = "candidate-evidence/2" # /2: signer guards, authorization, bounded pages LEVELS = ("directly_verified", "supported", "partially_supported") SignerStatus = Literal[ - "wallet", "foreign_known", "foreign_identity_unknown", "lookalike_itself", "unknown" + "wallet", + "foreign_known", + "foreign_identity_unknown", + "lookalike_itself", + "conflicting", + "unknown", ] +Authorization = Literal["direct_signature", "not_required", "unknown", "not_applicable"] Receipt = Literal["succeeded", "reverted", "implied_by_log", "unknown"] HIDDEN_NOTE = "hidden candidates are not assessed as safe; all evidence remains in the result" +ORDER_NOTE = ( + "a deterministic presentation order (address similarity, then recency, then address); " + "not a risk score or a probability; the support level is reported separately and never " + "moves a candidate up or down" +) +MAX_PAGE = 1_000 # largest page a caller can request +MAX_REFERENCES_SHOWN = 3 # per summary item; the full list is in the result +DELEGATION_PREFIX = "0xef0100" # EIP-7702 delegation designator @dataclass(frozen=True) @@ -55,6 +85,7 @@ class EvidenceRecord: level: str signer_status: SignerStatus signer: str | None # only a looked-up or self-evident address, never inferred + authorization: Authorization event_sender: str event_recipient: str emitter: str | None @@ -72,7 +103,7 @@ class CandidateGroup: references: tuple[tuple[str, int, int], ...] # (imitated reference, prefix, suffix) mechanisms: tuple[str, ...] kinds: tuple[str, ...] - level: str + level: str # support for the observed facts, not suspicion affix: int | None # best prefix + suffix to an imitated reference first_position: tuple[int, int, int] last_position: tuple[int, int, int] @@ -86,18 +117,76 @@ class EvidenceResult: chain_id: int victim: str cutoff: tuple[int, int] - groups: tuple[CandidateGroup, ...] # in the research order + groups: tuple[CandidateGroup, ...] # in the presentation order raw_events: int # observation records before deduplication evidence_records: int # distinct records linked to groups signers_recovered: int # unknown signers resolved by R-SIG unattributable_events: int # records that could not be placed relative to the wallet abstain: str | None coverage: dict[str, str] - - -def _plain_eoa(fixture: Any, cutoff_block: int) -> bool: - known = {int(b): c for b, c in fixture.wallet_code_hex.items() if int(b) <= cutoff_block} - return bool(known) and known[max(known)] == "0x" + absence_inference: bool # whether R-SIG could infer "not signed by the wallet" + absence_blocked_by: tuple[str, ...] # why not (empty when allowed) + + +def absence_guard( + fixture: Any, cutoff_block: int, *, signed_complete: bool | None = None +) -> tuple[str, ...]: + """Why absence from the wallet's signed set does **not** prove that the wallet did not + directly sign a transaction before ``cutoff_block``; empty when it does. + + Absence proves non-signing only if the set is every transaction the account signed in + the window and the account could not act otherwise. So all of these must hold: + + 1. the signed set is stated ``complete`` (a ``partial`` / ``truncated`` / ``unknown`` set + proves nothing), with the stated count equal to the records held; + 2. a legacy (``observation/1``) fixture documents the nonce bisection its completeness + claim rests on; + 3. the recorded nonces are unique and consecutive: a gap is a nonce the account used + without a recorded transaction (a missing page, or an EIP-7702 authorization, which + increments the authority's nonce inside someone else's transaction); + 4. every recorded transaction lies inside the window; + 5. the account's code is known at the window start and is empty (``0x``) at every sample + up to the cutoff: an EIP-7702 delegation (``0xef0100...``) lets other senders execute + code as the account, and a contract or smart wallet never signs at all. Samples after + the cutoff are not used (no future information). + + Code between samples is not observed; condition 3 is what rules out a delegation set and + cleared inside the window (both need an authorization, which uses a nonce). A complete + signed set never says whether the wallet *authorized* a pull (allowance, permit): see + ``Authorization``. + """ + reasons: list[str] = [] + cov = coverage_of(fixture) + entry = cov.categories.get("wallet_signed_transactions") + status = cov.status("wallet_signed_transactions") + complete = status == "complete" if signed_complete is None else signed_complete + txs = list(fixture.wallet_transactions) + if not complete: + reasons.append( + f"signed set not complete ({status if signed_complete is None else 'masked'})" + ) + if entry is not None and entry.count is not None and entry.count != len(txs): + reasons.append(f"signed-set count mismatch (stated {entry.count}, held {len(txs)})") + if getattr(fixture, "observation", None) is None and not any( + "nonce bisection" in m for m in getattr(fixture, "method", None) or [] + ): + reasons.append("legacy fixture without a documented nonce bisection") + nonces = sorted(t.nonce for t in txs) + if len(set(nonces)) != len(nonces) or any(b - a != 1 for a, b in itertools.pairwise(nonces)): + reasons.append("nonce gap or duplicate (missing page or EIP-7702 authorization)") + if any(not fixture.from_block <= t.block_number <= fixture.to_block for t in txs): + reasons.append("signed transaction outside the window") + samples = {int(b): c.lower() for b, c in fixture.wallet_code_hex.items()} + if not any(b <= fixture.from_block for b in samples): + reasons.append("account code unknown at the window start") + for b in sorted(samples): + if b > cutoff_block: + break + if samples[b].startswith(DELEGATION_PREFIX): + reasons.append(f"EIP-7702 delegation designator at block {b}") + elif samples[b] != "0x": + reasons.append(f"account has code at block {b} (contract or smart wallet)") + return tuple(dict.fromkeys(reasons)) def raw_event_count(fixture: Any) -> int: @@ -124,7 +213,7 @@ def build( ) -> EvidenceResult: """Evidence groups from observations strictly before ``cutoff``. ``observations``, ``signed`` and ``wallet_tx_complete`` can be supplied (masking experiments); by default - they come from the fixture.""" + they come from the fixture. Observations must be in chain order.""" cov = coverage_of(fixture) wallet = fixture.wallet.lower() obs = [ @@ -140,21 +229,21 @@ def build( else (t.transaction_hash for t in fixture.wallet_transactions) ) } + blocked = absence_guard(fixture, cutoff[0], signed_complete=wallet_tx_complete) complete = ( cov.status("wallet_signed_transactions") == "complete" if wallet_tx_complete is None else wallet_tx_complete ) - plain = _plain_eoa(fixture, cutoff[0]) refs_complete = complete and cov.complete("erc20_transfer_logs") chosen: dict[str, dict[str, int]] = {} records: dict[str, list[tuple[EvidenceRecord, list[tuple[str, int, int]]]]] = {} recovered = 0 for o in obs: - status, signer, rec = _signer(o, wallet, signed_set, complete and plain) + status, signer, rec = _signer(o, wallet, signed_set, not blocked) recovered += rec match = _match(o.counterparty, chosen) if o.counterparty else None - mechanisms, level, missing = _assess(o, status, match) + mechanisms, level, missing, auth = _assess(o, status, match) if o.direction == "out" and status == "wallet": chosen.setdefault(o.counterparty[-MIN_SUFFIX:], {})[o.counterparty] = o.block if not mechanisms: @@ -179,6 +268,7 @@ def build( level=level, signer_status=status, signer=signer, + authorization=auth, event_sender=wallet if o.direction == "out" else o.counterparty, event_recipient=o.counterparty if o.direction == "out" else wallet, emitter=o.emitter, @@ -192,7 +282,7 @@ def build( _group(fixture.chain_id, wallet, look, items, refs_complete) for look, items in records.items() ] - groups.sort(key=order_key) + groups.sort(key=presentation_key) abstain = None if not refs_complete: abstain = "insufficient history: the wallet's own references are not fully observed" @@ -213,6 +303,8 @@ def build( unattributable_events=0, abstain=abstain, coverage={k: str(v.status) for k, v in cov.categories.items()}, + absence_inference=not blocked, + absence_blocked_by=blocked, ) @@ -220,17 +312,21 @@ def _signer( o: cd.Observation, wallet: str, signed: set[str], absence_ok: bool ) -> tuple[SignerStatus, str | None, int]: """(status, address, recovered?) for one observation. R-SIG: membership in the wallet's - signed set proves the wallet signed; absence from a complete set of a code-less wallet - proves it did not. The signer's address is never guessed.""" + signed set proves the wallet signed; absence, only when ``absence_guard`` allows it, + proves it did not *directly* sign. A looked-up signer that contradicts the set is + ``conflicting``. The signer's address is never guessed.""" if o.kind == "native" and o.direction == "in": return "lookalike_itself", o.counterparty, 0 if o.kind == "native" and o.direction == "out": return "wallet", wallet, 0 if o.direction != "out" or o.kind != "erc20": return "unknown", None, 0 + in_set = o.tx_hash.lower() in signed if o.signer is not None: - return ("wallet", wallet, 0) if o.signer == wallet else ("foreign_known", o.signer, 0) - if o.tx_hash.lower() in signed: + if o.signer == wallet: + return ("conflicting", None, 0) if absence_ok and not in_set else ("wallet", wallet, 0) + return ("conflicting", None, 0) if in_set else ("foreign_known", o.signer, 0) + if in_set: return "wallet", wallet, 1 if absence_ok: return "foreign_identity_unknown", None, 1 @@ -250,31 +346,44 @@ def _match(party: str, chosen: dict[str, dict[str, int]]) -> tuple[str, tuple[in def _assess( o: cd.Observation, status: SignerStatus, match: tuple[str, tuple[int, int]] | None -) -> tuple[tuple[str, ...], str, tuple[str, ...]]: - """(mechanisms, level, missing) for one observation; empty mechanisms: not evidence.""" +) -> tuple[tuple[str, ...], str, tuple[str, ...], Authorization]: + """(mechanisms, level, missing, authorization) for one observation; empty mechanisms: + not evidence.""" missing: list[str] = [] if o.succeeded is False: - return (), "", () + return (), "", (), "not_applicable" if o.direction == "out": if o.kind != "erc20" or status == "wallet": - return (), "", () + return (), "", (), "direct_signature" if status in ("foreign_known", "foreign_identity_unknown"): if status == "foreign_identity_unknown": missing.append("signer_identity") - return ("spoofed_out",), "directly_verified", tuple(missing) - if match is not None: # unknown signer: never asserted as a spoof - return ("unverified_out_lookalike",), "partially_supported", ("signer",) - return (), "", () + if o.value == 0: # nothing moved: no authorization question, a display spoof + return ("spoofed_out",), "directly_verified", tuple(missing), "not_required" + # value moved without the wallet's signature: an allowance, a permit, a delegation + # or a fabricated log; which one is not observed, so this is not called a spoof + mech = ["foreign_initiated_out"] + if o.emitter is None: + missing.append("token_identity") + elif o.emitter not in TRUSTED_TOKENS: + mech.append("untrusted_token_out") + missing.append("authorization") + return tuple(mech), "directly_verified", tuple(missing), "unknown" + if match is not None: # unknown or conflicting signer: never asserted as a spoof + gap = "signer_conflict" if status == "conflicting" else "signer" + return ("unverified_out_lookalike",), "partially_supported", (gap,), "unknown" + return (), "", (), "unknown" m: list[str] = [] if o.kind == "native": if match is None: - return (), "", () # anyone can send ETH: native evidence needs a lookalike + return (), "", (), "not_applicable" # anyone can send ETH: needs a lookalike if o.succeeded is None: missing.append("receipt") return ( ("lookalike_in",), "directly_verified" if o.succeeded is True else "supported", tuple(missing), + "not_applicable", ) if o.value == 0 and o.kind != "nft": m.append("zero_value_in") @@ -288,9 +397,9 @@ def _assess( if o.kind == "erc20" and o.emitter in STABLECOINS and 0 < o.value <= DUST_MAX_BASE_UNITS: m.append("dust_in") if not m: - return (), "", () + return (), "", (), "not_applicable" level = "supported" if match is not None else "partially_supported" - return tuple(m), level, tuple(missing) + return tuple(m), level, tuple(missing), "not_applicable" def _group( @@ -325,63 +434,168 @@ def _group( ) -def order_key(g: CandidateGroup) -> tuple[int, int, tuple[int, int, int], str]: - """Support level first, then affix strength (costly to forge), then the latest - planting, then the address. Missing information never moves a group up.""" +# --- orders --------------------------------------------------------------------------------- + + +def presentation_key(g: CandidateGroup) -> tuple[int, tuple[int, int, int], str]: + """The presentation order: affix strength (costly to forge), then the latest planting, + then the address. It reads only suspicion indicators: the support level and the missing + list are never consulted, so verifying a fact cannot move a candidate up, and missing a + fact cannot move it up or down.""" + neg = (-g.last_position[0], -g.last_position[1], -g.last_position[2]) + return (-(g.affix or 0), neg, g.lookalike) + + +def evidence_order_key(g: CandidateGroup) -> tuple[int, int, tuple[int, int, int], str]: + """The pre-registered protocol 12.6 order (support level first). It failed H5: cheap + verified dust outranks costly lookalikes. Kept only to reproduce that result.""" neg = (-g.last_position[0], -g.last_position[1], -g.last_position[2]) return (LEVELS.index(g.level), -(g.affix or 0), neg, g.lookalike) +ORDERS: dict[str, Callable[[CandidateGroup], Any]] = { + "affix_then_recency": presentation_key, + "evidence_then_affix": evidence_order_key, # H5 reproduction only +} + + +# --- bounded access ------------------------------------------------------------------------- + + +def digest(result: EvidenceResult) -> str: + """A content digest of the full result (every group and record identity, in order), so a + page can be checked against the result it was cut from.""" + h = hashlib.sha256(f"{result.version}|{result.victim}|{result.cutoff}".encode()) + for g in result.groups: + h.update(g.identity.encode()) + h.update(g.level.encode()) + for r in g.evidence: + h.update(r.identity.encode()) + return h.hexdigest() + + +def _bounded(n: int, name: str) -> int: + if not 1 <= n <= MAX_PAGE: + raise ValueError(f"{name} must be between 1 and {MAX_PAGE}") + return n + + +def _item(g: CandidateGroup, rank: int) -> dict[str, Any]: + return { + "rank": rank, + "identity": g.identity, + "level": g.level, + "mechanisms": list(g.mechanisms), + "kinds": list(g.kinds), + "references": [list(r) for r in g.references[:MAX_REFERENCES_SHOWN]], + "references_total": len(g.references), + "affix": g.affix, + "first_block": g.first_position[0], + "last_block": g.last_position[0], + "evidence_count": len(g.evidence), + "missing": list(g.missing), + "legitimacy": "not_assessed", + "explanation": explain(g), + } + + def summarize(result: EvidenceResult, k: int = 10) -> dict[str, Any]: - """The bounded research summary. It discloses the totals and the truncation; it never - deletes a group or a record.""" + """The bounded research summary: at most ``k`` groups, the totals, the hidden count, the + truncation flag, the offset of the next page and the result digest. Its size does not + grow with the number of groups or records; it never deletes a group or a record.""" + k = _bounded(k, "k") shown = result.groups[:k] - hidden = result.groups[k:] by_level: dict[str, int] = {} by_mechanism: dict[str, int] = {} for g in result.groups: by_level[g.level] = by_level.get(g.level, 0) + 1 for m in g.mechanisms: by_mechanism[m] = by_mechanism.get(m, 0) + 1 + hidden = len(result.groups) - len(shown) return { "version": result.version, "cutoff": list(result.cutoff), + "order": "affix_then_recency", + "order_note": ORDER_NOTE, + "result_digest": digest(result), "total_groups": len(result.groups), "raw_events": result.raw_events, "evidence_records": result.evidence_records, "shown": len(shown), - "truncated": bool(hidden), - "hidden_identities": [g.identity for g in hidden], + "hidden_count": hidden, + "truncated": hidden > 0, + "next_offset": len(shown) if hidden else None, "by_level": dict(sorted(by_level.items(), key=lambda kv: LEVELS.index(kv[0]))), "by_mechanism": dict(sorted(by_mechanism.items())), + "absence_inference": result.absence_inference, + "absence_blocked_by": list(result.absence_blocked_by), "abstain": result.abstain, "note": HIDDEN_NOTE, - "top": [ - { - "identity": g.identity, - "level": g.level, - "mechanisms": list(g.mechanisms), - "kinds": list(g.kinds), - "references": [list(r) for r in g.references], - "affix": g.affix, - "first_block": g.first_position[0], - "last_block": g.last_position[0], - "evidence_count": len(g.evidence), - "missing": list(g.missing), - "explanation": explain(g), - } - for g in shown - ], + "top": [_item(g, i + 1) for i, g in enumerate(shown)], } +class StaleResultError(ValueError): + """The page was requested against a different result than the caller's digest.""" + + +def page( + result: EvidenceResult, *, offset: int = 0, limit: int = 10, expect_digest: str | None = None +) -> dict[str, Any]: + """Groups ``[offset, offset + limit)`` in the presentation order (``items`` / ``total`` / + ``limit`` / ``offset``, the project's page convention). With ``expect_digest`` the page + is refused if the result changed since the summary was made.""" + limit = _bounded(limit, "limit") + if offset < 0: + raise ValueError("offset must be >= 0") + d = digest(result) + if expect_digest is not None and expect_digest != d: + raise StaleResultError("the result changed since this digest was issued") + items = result.groups[offset : offset + limit] + end = offset + len(items) + return { + "items": [_item(g, offset + i + 1) for i, g in enumerate(items)], + "total": len(result.groups), + "limit": limit, + "offset": offset, + "next_offset": end if end < len(result.groups) else None, + "result_digest": d, + } + + +def group_records( + result: EvidenceResult, identity: str, *, offset: int = 0, limit: int = 100 +) -> dict[str, Any]: + """Every record of one group, by reference (its identity), one bounded page at a time.""" + limit = _bounded(limit, "limit") + for g in result.groups: + if g.identity == identity: + items = g.evidence[offset : offset + limit] + end = offset + len(items) + return { + "identity": identity, + "items": [asdict(r) for r in items], + "total": len(g.evidence), + "limit": limit, + "offset": offset, + "next_offset": end if end < len(g.evidence) else None, + } + raise KeyError(identity) + + +def rank_of(result: EvidenceResult, lookalike: str) -> int | None: + """1-based position of a lookalike in the presentation order (None: not a candidate).""" + look = lookalike.lower() + return next((i + 1 for i, g in enumerate(result.groups) if g.lookalike == look), None) + + def explain(g: CandidateGroup) -> str: - """Three separate dimensions: suspicion, support, and what is missing.""" + """Three separate dimensions: suspicion indicators, support, and what is missing.""" ref = f" imitating {g.references[0][0]} (affix {g.affix})" if g.references else "" gaps = f"; missing: {', '.join(g.missing)}" if g.missing else "" return ( - f"suspicion: {'+'.join(g.mechanisms)}{ref}; support: {g.level} " - f"({len(g.evidence)} record(s)){gaps}; not a probability" + f"indicators: {'+'.join(g.mechanisms)}{ref}; support: {g.level} " + f"({len(g.evidence)} record(s)){gaps}; not a probability; legitimacy not assessed" ) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 5f226c6..6692446 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -133,7 +133,7 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None "reliability-study", help="Phase 12.6 signer provenance, evidence groups and spam resilience (offline)", ) - rs.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.6") + rs.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.6.1") rs.add_argument( "--episode-cache", type=Path, diff --git a/src/cryptoguard/ml/reliability_study.py b/src/cryptoguard/ml/reliability_study.py index 5a81ec4..04acbb1 100644 --- a/src/cryptoguard/ml/reliability_study.py +++ b/src/cryptoguard/ml/reliability_study.py @@ -1,6 +1,8 @@ -"""Phase 12.6 offline study (protocol 12.6): signer provenance, evidence groups, bounded -summaries, spam resilience, robust proxy features and cost. No RPC; frozen-overlap windows -are never computed on; the 12.5 proxy test split is never used. +"""Phase 12.6 / 12.6.1 offline study (protocol 12.6): signer provenance, evidence groups, +bounded summaries, spam resilience, robust proxy features and cost; 12.6.1 adds the signer +guard matrix, the authorization audit, reliability/suspicion separation, the 10,000-candidate +adversarial suite and bounded-summary scaling to 100,000. No RPC; frozen-overlap windows are +never computed on; the 12.5 proxy test split is never used. """ from __future__ import annotations @@ -18,7 +20,7 @@ from cryptoguard.ml import candidate_discovery as cd from cryptoguard.ml import candidate_evidence as ce -STUDY_VERSION = "reliability-study/1" +STUDY_VERSION = "reliability-study/2" USDT = "0xdac17f958d2ee523a2206206994597c13d831ec7" FAKE = "0x" + "f" * 40 WALLET = "0x" + "c" * 40 @@ -46,7 +48,7 @@ def wallet_fixture( wallet_txs: Sequence[tuple[str, int, int]] = (), ref_block: int = 1_100, refs_complete: bool = True, - code: str = "0x", + code: str | dict[str, str] = "0x", ) -> Any: """Synthetic window. The wallet pays REF (wallet-signed, in its signed set) at ``ref_block``. ``transfers``: (sender, recipient, value, block, signer, token, tx_index); @@ -123,14 +125,15 @@ def h(*parts: object) -> str: ) nat = [ RecordedNativeInbound( - transaction_hash=h("native", s, v, b, ok), + # the occurrence index keeps repeated identical transfers distinct transactions + transaction_hash=h("native", s, v, b, ok, j), block_number=b, transaction_index=1, sender=s, value=str(v), succeeded=ok, ) - for s, v, b, ok in native + for j, (s, v, b, ok) in enumerate(native) ] status = "complete" if refs_complete else "partial" cats = { @@ -156,7 +159,7 @@ def h(*parts: object) -> str: transfer_scan_complete=True, sender_lookups_skipped=0, method=["synthetic"], - wallet_code_hex={"1000": code}, + wallet_code_hex={"1000": code} if isinstance(code, str) else dict(code), block_timestamps={}, transfers=rows, wallet_transactions=txs, @@ -278,11 +281,9 @@ def run_scenarios(k: int = 10) -> dict[str, Any]: "evidence_records": res.evidence_records, "summary_shown": summary["shown"], "truncated": summary["truncated"], - "hidden": len(summary["hidden_identities"]), + "hidden": summary["hidden_count"], "by_level": summary["by_level"], - "strong_rank": None - if strong is None - else next((i + 1 for i, g in enumerate(res.groups) if g.lookalike == strong), None), + "strong_rank": None if strong is None else ce.rank_of(res, strong), "strong_in_top_k": None if strong is None else strong in top, "abstain": res.abstain, "deterministic": summary == again, @@ -405,8 +406,10 @@ def _evidence_unsafe(res: ce.EvidenceResult, condition: str) -> int: and r.emitter is None ): n += 1 - if "spoofed_out" in r.mechanisms and r.signer_status == "unknown": + if "spoofed_out" in r.mechanisms and r.signer_status in ("unknown", "conflicting"): n += 1 + if "spoofed_out" in r.mechanisms and not r.value_zero: + n += 1 # value moved: whether the wallet authorized it is not observed if r.level == "directly_verified" and r.kind == "native" and r.receipt == "unknown": n += 1 return n @@ -446,7 +449,8 @@ def spam_stability( res = ce.build(spammed, cutoff=cutoff) groups = list(res.groups) orders = { - "evidence_aware": [g.lookalike for g in groups], + "evidence_aware": [g.lookalike for g in sorted(groups, key=ce.evidence_order_key)], + "presentation": [g.lookalike for g in groups], "recency_only": [ g.lookalike for g in sorted(groups, key=lambda g: (tuple(-x for x in g.last_position), g.lookalike)) @@ -455,7 +459,9 @@ def spam_stability( g.lookalike for g in sorted(groups, key=lambda g: (-(g.affix or 0), g.lookalike)) ], } - before = [g.lookalike for g in base.groups if g.lookalike in real] + before = [ + g.lookalike for g in sorted(base.groups, key=ce.evidence_order_key) if g.lookalike in real + ] out: dict[str, Any] = {"real_candidates": len(real), "spam": n, "k": k} for name, order in orders.items(): kept = [x for x in order[:k] if x in real] @@ -577,6 +583,416 @@ def scaling(sizes: Sequence[int] = (10, 100, 1_000, 10_000)) -> list[dict[str, A return out +# --- 12.6.1: signer guard matrix and authorization audit ------------------------------------ + +ATTACKER = "0x" + "a1" * 20 +STRONG = lookalike(0, prefix=5, suffix=5) + + +def _with(fx: Any, **update: Any) -> Any: + return fx.model_copy(update=update) + + +def _signed_status(fx: Any, status: str, count: int | None = None) -> Any: + from cryptoguard.replay.observation import CategoryCoverage + + cov = fx.observation.model_copy(deep=True) + cov.categories["wallet_signed_transactions"] = CategoryCoverage( + status=status, + count=count, + ) + return _with(fx, observation=cov) + + +def _probe( + fx: Any, cutoff: tuple[int, int], party: str, tx_hash: str | None = None +) -> dict[str, Any]: + """What the evidence model says about the wallet's outgoing event(s) to ``party``.""" + res = ce.build(fx, cutoff=cutoff) + out: dict[str, Any] = { + "absence_inference": res.absence_inference, + "blocked_by": list(res.absence_blocked_by), + "observed_before_cutoff": False, + } + group = next((g for g in res.groups if g.lookalike == party.lower()), None) + recs = [ + r + for r in (group.evidence if group else ()) + if r.direction == "out" and (tx_hash is None or r.identity.startswith(f"tx:{tx_hash}")) + ] + if recs: + r = recs[-1] + out |= { + "observed_before_cutoff": True, + "evidence": True, + "signer_status": r.signer_status, + "mechanisms": list(r.mechanisms), + "authorization": r.authorization, + "level": r.level, + "missing": list(r.missing), + } + return out + signed = {t.transaction_hash.lower() for t in fx.wallet_transactions} + for o in cd.observations(fx): + if ( + o.direction == "out" + and o.counterparty == party.lower() + and (o.block, o.tx_index) < cutoff + ): + if tx_hash is not None and o.tx_hash.lower() != tx_hash: + continue + status, _, _ = ce._signer(o, fx.wallet.lower(), signed, res.absence_inference) + out |= {"observed_before_cutoff": True, "evidence": False, "signer_status": status} + return out + + +def signer_matrix() -> dict[str, dict[str, Any]]: + """Each condition of the 12.6.1 audit on a synthetic window: whether R-SIG may infer + "not signed by the wallet", what it says about the probe event, and why.""" + from cryptoguard.replay.models import RecordedTransaction + + spoof = (WALLET, STRONG, 0, 2_000, None, USDT, 0) + pull = (WALLET, STRONG, 10**6, 2_000, None, USDT, 0) + base = wallet_fixture(transfers=[spoof]) + rows: dict[str, dict[str, Any]] = {} + rows["complete_history_zero_value"] = _probe(base, END, STRONG) + rows["complete_history_value_moved_trusted_token"] = _probe( + wallet_fixture(transfers=[pull]), END, STRONG + ) + rows["complete_history_value_moved_untrusted_token"] = _probe( + wallet_fixture(transfers=[(WALLET, STRONG, 10**6, 2_000, None, FAKE, 0)]), END, STRONG + ) + capped = _with(base, sender_lookups_skipped=600) + rows["signer_lookups_capped_at_500"] = _probe(capped, END, STRONG) + rows["signed_set_truncated"] = _probe(_signed_status(base, "truncated"), END, STRONG) + rows["signed_set_partial_recording"] = _probe(_signed_status(base, "partial"), END, STRONG) + rows["signed_set_count_mismatch"] = _probe(_signed_status(base, "complete", 5), END, STRONG) + gap = wallet_fixture(transfers=[spoof], wallet_txs=[(REF, 10**15, 1_200), (REF, 10**15, 1_300)]) + txs = list(gap.wallet_transactions) + txs[-1] = txs[-1].model_copy(update={"nonce": txs[-1].nonce + 1}) + rows["missing_page_or_7702_authorization_nonce_gap"] = _probe( + _with(gap, wallet_transactions=txs), END, STRONG + ) + rows["legacy_fixture_without_documented_bisection"] = _probe( + _with(base, observation=None), END, STRONG + ) + rows["code_deployed_inside_window_before_cutoff"] = _probe( + _with(base, wallet_code_hex={"1000": "0x", "1500": "0x6080"}), END, STRONG + ) + rows["code_only_after_cutoff_not_used"] = _probe( + _with(base, wallet_code_hex={"1000": "0x", "9500": "0x6080"}), END, STRONG + ) + rows["code_unknown_at_window_start"] = _probe( + _with(base, wallet_code_hex={"1500": "0x"}), END, STRONG + ) + rows["eip7702_delegation_at_window_start"] = _probe( + _with(base, wallet_code_hex={"1000": "0xef0100" + "ab" * 20}), END, STRONG + ) + rows["smart_wallet"] = _probe(_with(base, wallet_code_hex={"1000": "0x6080"}), END, STRONG) + # the wallet signs a call to a router, which pulls the tokens with transferFrom + router = wallet_fixture(transfers=[pull]) + pulled = router.transfers[-1] + call = RecordedTransaction( + transaction_hash=pulled.transaction_hash, + block_number=pulled.block_number, + transaction_index=pulled.transaction_index, + nonce=1, + to="0x" + "7a" * 20, + value="0", + ) + rows["contract_interaction_wallet_signed"] = _probe( + _with(router, wallet_transactions=[*router.wallet_transactions, call]), END, STRONG + ) + # same block: the wallet's own transaction and a foreign spoof, either side of a cutoff + same = wallet_fixture( + transfers=[ + (WALLET, STRONG, 0, 2_000, None, USDT, 0), + (WALLET, REF, 5, 2_000, None, USDT, 2), + ] + ) + own = same.transfers[-1] + same = _with( + same, + wallet_transactions=[ + *same.wallet_transactions, + RecordedTransaction( + transaction_hash=own.transaction_hash, + block_number=2_000, + transaction_index=2, + nonce=1, + to=USDT, + value="0", + ), + ], + ) + rows["same_block_spoof_before_own_tx"] = _probe(same, (2_000, 1), STRONG) + own_hash = own.transaction_hash.lower() + rows["same_block_own_tx_after_cutoff_excluded"] = _probe(same, (2_000, 1), REF, own_hash) + rows["same_block_own_tx_included"] = _probe(same, END, REF, own_hash) + unknown_receipt = _with( + router, + wallet_transactions=[ + *router.wallet_transactions, + call.model_copy(update={"value": "1", "succeeded": None}), + ], + ) + rows["wallet_signed_with_unknown_receipt"] = _probe(unknown_receipt, END, STRONG) + conflict = wallet_fixture(transfers=[(WALLET, STRONG, 0, 2_000, ATTACKER, USDT, 0)]) + hit = conflict.transfers[-1] + rows["looked_up_signer_contradicts_signed_set"] = _probe( + _with( + conflict, + wallet_transactions=[ + *conflict.wallet_transactions, + call.model_copy(update={"transaction_hash": hit.transaction_hash}), + ], + ), + END, + STRONG, + ) + return rows + + +def signer_audit(windows: Sequence[tuple[str, Any, tuple[int, int]]]) -> dict[str, Any]: + """Real windows: is the absence inference allowed, and how many foreign-signed outgoing + events moved value (the authorization question).""" + per: dict[str, Any] = {} + totals = {"foreign_zero_value": 0, "foreign_value_trusted": 0, "foreign_value_untrusted": 0} + c1_overclaims = 0 + from cryptoguard.ml.payments import TRUSTED_TOKENS + + for name, fx, cut in windows: + res = ce.build(fx, cutoff=cut) + w = fx.wallet.lower() + signed = {t.transaction_hash.lower() for t in fx.wallet_transactions} + counts = dict.fromkeys(totals, 0) + for t in fx.transfers: + if t.sender.lower() != w or (t.block_number, t.transaction_index) >= cut: + continue + foreign = (t.tx_sender is not None and t.tx_sender.lower() != w) or ( + t.tx_sender is None + and res.absence_inference + and t.transaction_hash.lower() not in signed + ) + if not foreign: + continue + if int(t.value) == 0: + counts["foreign_zero_value"] += 1 + elif t.token.lower() in TRUSTED_TOKENS: + counts["foreign_value_trusted"] += 1 + else: + counts["foreign_value_untrusted"] += 1 + c1 = cd.discover(fx, cutoff=cut, variant="C1") + over = sum( + 1 + for c in c1.candidates + if "spoofed_out" in c.methods + and any( + t.transaction_hash.lower() == c.evidence.split(":")[1] and int(t.value) > 0 + for t in fx.transfers + ) + ) + c1_overclaims += over + for k in totals: + totals[k] += counts[k] + per[name] = { + "absence_inference": res.absence_inference, + "blocked_by": list(res.absence_blocked_by), + **counts, + "c1_spoof_claims_on_value_moved": over, + "evidence_spoof_claims_on_value_moved": sum( + 1 + for g in res.groups + for r in g.evidence + if "spoofed_out" in r.mechanisms and not r.value_zero + ), + } + return {"windows": per, "totals": totals, "c1_spoof_claims_on_value_moved": c1_overclaims} + + +# --- 12.6.1: reliability is not suspicion --------------------------------------------------- + + +def separation(fixture: Any, cutoff: tuple[int, int]) -> dict[str, Any]: + """Does removing information (receipts, token identity, signers) move any kept candidate + in the presentation order? It must not: the order reads no support level.""" + base = ce.build(fixture, cutoff=cutoff) + order = [g.lookalike for g in base.groups] + obs = cd.observations(fixture) + out: dict[str, Any] = {} + for what in ("receipt", "token", "signer"): + res = ce.build(fixture, cutoff=cutoff, observations=ce.mask(obs, what)) + now = [g.lookalike for g in res.groups] + kept = [x for x in order if x in set(now)] + out[what] = { + "kept": len(kept), + "relative_order_unchanged": kept == [x for x in now if x in set(kept)], + "levels_changed": sum( + 1 + for a, b in zip( + sorted(base.groups, key=lambda g: g.lookalike), + sorted(res.groups, key=lambda g: g.lookalike), + strict=False, + ) + if a.lookalike == b.lookalike and a.level != b.level + ), + } + return out + + +# --- 12.6.1: adversarial suite at 10,000 and bounded-summary scaling ------------------------- + + +def adversarial_fixtures(n: int = 10_000) -> dict[str, tuple[Any, str]]: + """name -> (fixture, the high-relevance lookalike). Every flood is ``n`` events.""" + cheap = [lookalike(i + 1) for i in range(n)] + spoof = (WALLET, STRONG, 0, 2_000, ATTACKER, USDT, 0) + unsigned = (WALLET, STRONG, 0, 2_000, None, USDT, 0) + dust = [(w, 1, 3_000 + i % 5_000, True) for i, w in enumerate(cheap)] + refs = [lookalike(i, prefix=0, suffix=0, ref="0x" + f"{i + 7:040x}") for i in range(50)] + per_ref = n // len(refs) + return { + "cheap_lookalikes": (wallet_fixture(transfers=[spoof], native=dust), STRONG), + "repeated_dust_one_lookalike": ( + wallet_fixture( + transfers=[spoof], native=[(cheap[0], 1, 3_000 + i % 5_000, True) for i in range(n)] + ), + STRONG, + ), + "fake_token_flood": ( + wallet_fixture( + transfers=[spoof] + + [ + (w, WALLET, 10**18, 3_000 + i % 5_000, None, FAKE, 0) + for i, w in enumerate(cheap) + ] + ), + STRONG, + ), + "missing_signer_information": (wallet_fixture(transfers=[unsigned], native=dust), STRONG), + "partial_historical_coverage": ( + wallet_fixture(transfers=[unsigned], native=dust, refs_complete=False), + STRONG, + ), + "multiple_reference_recipients": ( + wallet_fixture( + transfers=[spoof], + wallet_txs=[(r, 10**15, 1_200 + i) for i, r in enumerate(refs)], + native=[ + (lookalike(j + 1, ref=r), 1, 3_000 + (i * per_ref + j) % 5_000, True) + for i, r in enumerate(refs) + for j in range(per_ref) + ], + ), + STRONG, + ), + "multiple_candidate_mechanisms": ( + wallet_fixture( + transfers=[spoof, (STRONG, WALLET, 0, 2_050, None, USDT, 0)], + native=[(STRONG, 1, 2_100, True), *dust], + ), + STRONG, + ), + "identical_similarity_ties": ( + wallet_fixture( + transfers=[spoof], + native=[ + (lookalike(i + 1, prefix=5, suffix=5), 1, 3_000 + i % 50, True) + for i in range(n) + ], + ), + STRONG, + ), + "recency_manipulation": ( + wallet_fixture(transfers=[spoof], native=[(w, 1, 9_000, True) for w in cheap]), + STRONG, + ), + } + + +def adversarial(n: int = 10_000, k: int = 10) -> dict[str, Any]: + out: dict[str, Any] = {} + for name, (fx, strong) in adversarial_fixtures(n).items(): + res, sec, mib = _measure(partial(ce.build, fx, cutoff=END)) + again = ce.build(fx, cutoff=END) + rank = ce.rank_of(res, strong) + summary = ce.summarize(res, k) + found = None + if rank is not None: # reach it through the bounded page interface only + pg = ce.page(res, offset=rank - 1, limit=1, expect_digest=summary["result_digest"]) + found = pg["items"][0]["identity"].endswith(strong) + g = next(g for g in res.groups if g.lookalike == strong) if rank else None + out[name] = { + "flood_events": n, + "groups": len(res.groups), + "evidence_records": res.evidence_records, + "strong_rank": rank, + "strong_rank_evidence_order": None + if rank is None + else 1 + sorted(res.groups, key=ce.evidence_order_key).index(g), + "strong_in_top_k": rank is not None and rank <= k, + "strong_reachable_by_page": found, + "strong_level": None if g is None else g.level, + "strong_mechanisms": None if g is None else list(g.mechanisms), + "strong_records": None if g is None else len(g.evidence), + "deterministic": ce.digest(res) == ce.digest(again), + "build_seconds": sec, + "peak_traced_mib": mib, + "summary_bytes": len(json.dumps(summary)), + "abstain": res.abstain is not None, + } + return out + + +def summary_scaling(sizes: Sequence[int] = (1_000, 10_000, 100_000)) -> list[dict[str, Any]]: + """Bounded output at growing candidate counts. Observations are generated directly (one + small dataclass per event, no fixture models), so 100,000 candidates stay small.""" + base_fx = wallet_fixture() + base = cd.observations(base_fx) + out = [] + for n in sizes: + obs = base + [ + cd.Observation( + "native", + "in", + lookalike(i + 1), + 1, + 2_000 + i // 20, + i % 20, + -1, + "0x" + f"{0xA0000000 + i:064x}", + lookalike(i + 1), + False, + None, + True, + ) + for i in range(n) + ] + res, sec, mib = _measure(partial(ce.build, base_fx, cutoff=END, observations=obs)) + summary, s_sec, _ = _measure(partial(ce.summarize, res, 10)) + mid = ce.page(res, offset=n // 2, limit=10) + recs = ce.group_records(res, res.groups[0].identity) + t0 = time.perf_counter() + ce.digest(res) + out.append( + { + "candidates": n, + "groups": len(res.groups), + "build_seconds": sec, + "build_peak_traced_mib": mib, + "summary_seconds": s_sec, + "digest_seconds": round(time.perf_counter() - t0, 3), + "summary_bytes": len(json.dumps(summary)), + "page_bytes": len(json.dumps(mid)), + "group_records_bytes": len(json.dumps(recs)), + "hidden_count": summary["hidden_count"], + "truncated": summary["truncated"], + } + ) + del obs, res, summary, mid, recs + return out + + # --- entry point ---------------------------------------------------------------------------- @@ -647,7 +1063,7 @@ def main(poisoning_dir: Path, out: Path, cache: Path) -> dict[str, Any]: git = None result: dict[str, Any] = { "study": STUDY_VERSION, - "protocol": "protocol-12.6", + "protocol": "protocol-12.6 (+ 12.6.1 amendment)", "evidence_version": ce.EVIDENCE_VERSION, "git": git, "rpc_requests": 0, @@ -658,6 +1074,12 @@ def main(poisoning_dir: Path, out: Path, cache: Path) -> dict[str, Any]: "spam_stability": spam, "robust_proxy_dev": robust_proxy_dev(cache) if cache.exists() else "episode cache missing", "scaling": scaling(), + # 12.6.1 + "signer_matrix": signer_matrix(), + "signer_audit": signer_audit(windows), + "separation": {n: separation(fx, cut) for n, fx, cut in windows if n in masks}, + "adversarial_10k": adversarial(), + "summary_scaling": summary_scaling(), } peak = peak_rss_bytes() result["resources"] = { diff --git a/tests/integration/test_leases.py b/tests/integration/test_leases.py index ed348cd..c3b917b 100644 --- a/tests/integration/test_leases.py +++ b/tests/integration/test_leases.py @@ -40,12 +40,16 @@ def _contend(url: str, start: float, results: mp.Queue) -> None: # runs in a ch results.put(("error", f"{type(exc).__name__}: {exc}")) -CRASH_TTL = 8.0 # generous: process teardown on a loaded machine can take seconds +CRASH_TTL = 3_600.0 # expiry is probed with explicit clock values, so no real wait depends on it +CRASHED_HOLDING = 17 # the child took the lease and died without releasing it +CHILD_GOT_NONE = 3 # the child could not take the lease (a test-setup failure) +# An exception in the child exits with code 1: distinct from both, so a child failure is never +# mistaken for the crash under test. def _crash_holding_lease(url: str) -> None: # child: take the lease, then die without release - LeaseStore(_repo(url)).acquire(KEY, CRASH_TTL) - os._exit(1) + lease = LeaseStore(_repo(url)).acquire(KEY, CRASH_TTL) + os._exit(CRASHED_HOLDING if lease is not None else CHILD_GOT_NONE) @pytest.fixture @@ -106,19 +110,45 @@ def test_lease_of_a_crashed_process_is_recovered_after_expiry(db_url: str) -> No ctx = mp.get_context("spawn") p = ctx.Process(target=_crash_holding_lease, args=(db_url,)) p.start() - p.join(timeout=60) - assert p.exitcode == 1 + p.join(timeout=180) # spawn start-up alone took up to 11 s under CPU contention + if p.is_alive(): + p.kill() + pytest.fail("the child did not finish within 180 s") + assert p.exitcode == CRASHED_HOLDING, f"child exit code {p.exitcode} (1: it raised)" store = LeaseStore(_repo(db_url)) held = store.holder(KEY) assert held is not None # the dead owner never released it - # Judge "still held" against the lease's own expiry, not against how fast the OS tore the - # child down (a 1 s lease made this flaky under load: it expired before the check). - if datetime.now(UTC) < held.expires_at - timedelta(seconds=1): - assert store.acquire(KEY, 30) is None - time.sleep(max(0.0, (held.expires_at - datetime.now(UTC)).total_seconds()) + 0.3) - recovered = store.acquire(KEY, 30) + # Expiry is judged with explicit clock values, so these assertions always run and cannot + # race the scheduler (the earlier version skipped "still held" when the check came late). + tick = timedelta(microseconds=1) + assert store.acquire(KEY, 30, now=datetime.now(UTC)) is None # held, by real time too + assert store.acquire(KEY, 30, now=held.expires_at - tick) is None # held until expiry + assert store.acquire(KEY, 30, now=held.expires_at) is None # not yet free at the instant + assert store.holder(KEY) == held # failed attempts changed nothing + recovered = store.acquire(KEY, 30, now=held.expires_at + tick) assert recovered is not None assert recovered.generation == 2 + assert recovered.owner != held.owner + + +def test_expiry_boundary_never_has_two_owners(db_url: str) -> None: + """At the expiry instant the old owner is already fenced out and nobody can take over yet; + one microsecond later the takeover succeeds. No instant has two valid owners.""" + repo = _repo(db_url) + store = LeaseStore(repo) + tick = timedelta(microseconds=1) + first = store.acquire(KEY, 10, now=datetime(2026, 1, 1, tzinfo=UTC)) + assert first is not None + exp = first.expires_at + with repo._sessions() as session, session.begin(): + LeaseStore.check(session, first, now=exp - tick) # still valid just before + for at in (exp, exp + tick): + with repo._sessions() as session, session.begin(), pytest.raises(LeaseLostError): + LeaseStore.check(session, first, now=at) + assert store.acquire(KEY, 10, now=exp) is None + second = store.acquire(KEY, 10, now=exp + tick) + assert second is not None + assert second.generation == 2 def test_stale_worker_is_fenced_out_and_cannot_release_the_new_lease(db_url: str) -> None: diff --git a/tests/test_ml_candidate_evidence.py b/tests/test_ml_candidate_evidence.py index 5874715..d13cf30 100644 --- a/tests/test_ml_candidate_evidence.py +++ b/tests/test_ml_candidate_evidence.py @@ -138,7 +138,7 @@ def test_summary_discloses_truncation_and_keeps_everything() -> None: res = ce.build(fx, cutoff=END) s = ce.summarize(res, 10) assert (s["total_groups"], s["shown"], s["truncated"]) == (25, 10, True) - assert len(s["hidden_identities"]) == 15 + assert (s["hidden_count"], s["next_offset"]) == (15, 10) assert "not assessed as safe" in s["note"] assert len(res.groups) == 25 # the display budget deletes nothing assert ce.summarize(ce.build(fx, cutoff=END), 10) == s # deterministic diff --git a/tests/test_ml_signer_guards.py b/tests/test_ml_signer_guards.py new file mode 100644 index 0000000..974864b --- /dev/null +++ b/tests/test_ml_signer_guards.py @@ -0,0 +1,350 @@ +"""Phase 12.6.1: when absence from the signed set proves "not signed by the wallet", what it +never proves (authorization), bounded summaries with page access, and the separation of +evidence support from suspicion. Synthetic only; every expectation follows from the +scenario's definition.""" + +from __future__ import annotations + +import json +from dataclasses import replace + +import pytest + +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_evidence as ce +from cryptoguard.ml import reliability_study as rs + +W, REF, USDT, FAKE, END = rs.WALLET, rs.REF, rs.USDT, rs.FAKE, rs.END +STRONG = rs.STRONG + + +# --- the signer guard matrix ---------------------------------------------------------------- + +ALLOWED_SPOOF = (True, "foreign_identity_unknown", ["spoofed_out"]) +BLOCKED = (False, "unknown", ["unverified_out_lookalike"]) +EXPECTED = { + "complete_history_zero_value": ALLOWED_SPOOF, + "complete_history_value_moved_trusted_token": ( + True, + "foreign_identity_unknown", + ["foreign_initiated_out"], + ), + "complete_history_value_moved_untrusted_token": ( + True, + "foreign_identity_unknown", + ["foreign_initiated_out", "untrusted_token_out"], + ), + "signer_lookups_capped_at_500": ALLOWED_SPOOF, # the cap limits lookups, not the set + "signed_set_truncated": BLOCKED, + "signed_set_partial_recording": BLOCKED, + "signed_set_count_mismatch": BLOCKED, + "missing_page_or_7702_authorization_nonce_gap": BLOCKED, + "legacy_fixture_without_documented_bisection": BLOCKED, + "code_deployed_inside_window_before_cutoff": BLOCKED, + "code_only_after_cutoff_not_used": ALLOWED_SPOOF, + "code_unknown_at_window_start": BLOCKED, + "eip7702_delegation_at_window_start": BLOCKED, + "smart_wallet": BLOCKED, + "contract_interaction_wallet_signed": (True, "wallet", None), + "same_block_spoof_before_own_tx": ALLOWED_SPOOF, + "same_block_own_tx_included": (True, "wallet", None), + "wallet_signed_with_unknown_receipt": (True, "wallet", None), + "looked_up_signer_contradicts_signed_set": ( + True, + "conflicting", + ["unverified_out_lookalike"], + ), +} + + +@pytest.fixture(scope="module") +def matrix() -> dict[str, dict]: + return rs.signer_matrix() + + +@pytest.mark.parametrize("case", sorted(EXPECTED)) +def test_signer_guard_matrix(matrix: dict[str, dict], case: str) -> None: + row = matrix[case] + allowed, status, mechanisms = EXPECTED[case] + assert row["absence_inference"] is allowed, row + assert bool(row["blocked_by"]) is not allowed + assert row["signer_status"] == status + if mechanisms is None: + assert row["evidence"] is False # the wallet's own action is never evidence + else: + assert row["mechanisms"] == mechanisms + if not allowed: # never a negative signer claim from an incomplete source + assert row["signer_status"] not in ("foreign_identity_unknown", "foreign_known") + assert row["level"] == "partially_supported" + + +def test_matrix_covers_every_case(matrix: dict[str, dict]) -> None: + assert set(matrix) == set(EXPECTED) | {"same_block_own_tx_after_cutoff_excluded"} + assert matrix["same_block_own_tx_after_cutoff_excluded"]["observed_before_cutoff"] is False + + +def test_absence_never_proves_authorization() -> None: + pulled = rs.wallet_fixture(transfers=[(W, STRONG, 10**6, 2_000, None, USDT, 0)]) + [r] = ce.build(pulled, cutoff=END).groups[0].evidence + assert "spoofed_out" not in r.mechanisms # an allowance or a permit can authorize a pull + assert (r.authorization, "authorization" in r.missing) == ("unknown", True) + spoof = rs.wallet_fixture(transfers=[(W, STRONG, 0, 2_000, None, USDT, 0)]) + [s] = ce.build(spoof, cutoff=END).groups[0].evidence + assert (s.mechanisms, s.authorization) == (("spoofed_out",), "not_required") + + +def test_a_known_foreign_signer_does_not_prove_authorization_either() -> None: + fx = rs.wallet_fixture(transfers=[(W, STRONG, 10**6, 2_000, rs.ATTACKER, USDT, 0)]) + [r] = ce.build(fx, cutoff=END).groups[0].evidence + assert (r.signer_status, r.signer) == ("foreign_known", rs.ATTACKER) + assert r.mechanisms == ("foreign_initiated_out",) + assert r.authorization == "unknown" + + +def test_conflicting_signer_never_becomes_a_reference() -> None: + """A looked-up wallet signer whose transaction is absent from a complete signed set is a + conflict: the counterparty is not treated as a recipient the wallet chose.""" + other = "0x1234500000000000000000000000000000067890" # unrelated to REF + late = rs.lookalike(1, prefix=4, suffix=4, ref=other) + claimed = rs.wallet_fixture( + transfers=[(W, other, 5, 2_000, W, USDT, 0)], native=[(late, 1, 3_000, True)] + ) + res = ce.build(claimed, cutoff=END) + assert res.absence_inference + # had ``other`` become a reference, its lookalike would be a candidate + assert late not in {g.lookalike for g in res.groups} + # control: the same payment, present in the signed set, does make it a reference + pay = claimed.transfers[-1] + from cryptoguard.replay.models import RecordedTransaction + + signed = claimed.model_copy( + update={ + "wallet_transactions": [ + *claimed.wallet_transactions, + RecordedTransaction( + transaction_hash=pay.transaction_hash, + block_number=2_000, + transaction_index=0, + nonce=1, + to=USDT, + value="0", + ), + ] + } + ) + assert late in {g.lookalike for g in ce.build(signed, cutoff=END).groups} + + +def test_duplicate_nonce_blocks_the_absence_inference() -> None: + fx = rs.wallet_fixture( + transfers=[(W, STRONG, 0, 2_000, None, USDT, 0)], wallet_txs=[(REF, 10**15, 1_200)] + ) + txs = [t.model_copy(update={"nonce": 0}) for t in fx.wallet_transactions] + blocked = ce.absence_guard(fx.model_copy(update={"wallet_transactions": txs}), END[0]) + assert any("nonce" in b for b in blocked) + + +def test_guard_uses_no_information_after_the_cutoff() -> None: + early = rs.wallet_fixture(transfers=[(W, STRONG, 0, 2_000, None, USDT, 0)]) + with_future_code = early.model_copy( + update={"wallet_code_hex": {"1000": "0x", "5000": "0xef0100" + "ab" * 20}} + ) + cut = (3_000, 0) + assert ce.absence_guard(with_future_code, cut[0]) == () + a, b = ce.build(early, cutoff=cut), ce.build(with_future_code, cutoff=cut) + assert ce.digest(a) == ce.digest(b) + assert ce.absence_guard(with_future_code, 6_000) # once the cutoff passes it, it counts + + +def test_real_recorder_method_documents_the_bisection() -> None: + from cryptoguard.replay.record import METHOD + + assert any("nonce bisection" in m for m in METHOD) + + +# --- bounded summary and page access -------------------------------------------------------- + + +def _many(n: int) -> ce.EvidenceResult: + fx = rs.wallet_fixture( + native=[(rs.lookalike(i + 1), 1, 2_000 + i % 5_000, True) for i in range(n)] + ) + return ce.build(fx, cutoff=END) + + +def test_summary_size_does_not_grow_with_the_number_of_candidates() -> None: + small, big = ce.summarize(_many(20), 10), ce.summarize(_many(3_000), 10) + assert big["hidden_count"] == 2_990 + assert big["truncated"] + assert abs(len(json.dumps(big)) - len(json.dumps(small))) < 64 # digits only + assert "hidden_identities" not in big + + +def test_pages_cover_every_group_exactly_once_in_order() -> None: + res = _many(57) + s = ce.summarize(res, 10) + seen, offset = [i["identity"] for i in s["top"]], s["next_offset"] + while offset is not None: + pg = ce.page(res, offset=offset, limit=10, expect_digest=s["result_digest"]) + seen += [i["identity"] for i in pg["items"]] + offset = pg["next_offset"] + assert seen == [g.identity for g in res.groups] + assert [i["rank"] for i in ce.page(res, offset=50, limit=10)["items"]] == list(range(51, 58)) + + +def test_stale_page_and_unbounded_requests_are_refused() -> None: + res = _many(12) + with pytest.raises(ce.StaleResultError): + ce.page(res, offset=10, expect_digest=ce.digest(_many(13))) + for bad in (0, ce.MAX_PAGE + 1): + with pytest.raises(ValueError, match="k must be between"): + ce.summarize(res, bad) + with pytest.raises(ValueError, match="limit must be between"): + ce.page(res, limit=bad) + with pytest.raises(ValueError, match="offset must be"): + ce.page(res, offset=-1) + + +def test_group_records_pages_every_record() -> None: + weak = rs.lookalike(1) + fx = rs.wallet_fixture(native=[(weak, 1, 2_000 + i, True) for i in range(250)]) + res = ce.build(fx, cutoff=END) + ident = res.groups[0].identity + got, offset = [], 0 + while offset is not None: + pg = ce.group_records(res, ident, offset=offset, limit=100) + got += [r["identity"] for r in pg["items"]] + offset = pg["next_offset"] + assert got == [r.identity for r in res.groups[0].evidence] + assert len(got) == 250 + with pytest.raises(KeyError): + ce.group_records(res, "1:nobody:nothing") + + +def test_summary_items_are_bounded_and_carry_no_probability() -> None: + res = _many(15) + s = ce.summarize(res, 10) + + def floats(x: object) -> int: + if isinstance(x, float): + return 1 + if isinstance(x, dict): + return sum(floats(v) for v in x.values()) + if isinstance(x, list): + return sum(floats(v) for v in x) + return 0 + + assert floats(s) == 0 + assert all(i["legitimacy"] == "not_assessed" for i in s["top"]) + assert all(len(i["references"]) <= ce.MAX_REFERENCES_SHOWN for i in s["top"]) + assert "not a risk score" in s["order_note"] + + +# --- support is not suspicion --------------------------------------------------------------- + + +def test_presentation_order_never_reads_the_support_level() -> None: + res = _many(30) + for g in res.groups: + for level in ce.LEVELS: + assert ce.presentation_key(replace(g, level=level)) == ce.presentation_key(g) + assert ce.presentation_key(replace(g, missing=("receipt",))) == ce.presentation_key(g) + + +def test_a_verified_receipt_does_not_move_a_candidate_up() -> None: + a, b = rs.lookalike(1), rs.lookalike(2) # same affix + fx = rs.wallet_fixture(native=[(a, 1, 2_000, True), (b, 1, 3_000, None)]) + res = ce.build(fx, cutoff=END) + assert [g.lookalike for g in res.groups] == [b, a] # newer first; support not consulted + assert [g.level for g in res.groups] == ["supported", "directly_verified"] + # the pre-registered (H5-failed) evidence order would have put the verified one first + assert sorted(res.groups, key=ce.evidence_order_key)[0].lookalike == a + + +def test_missing_evidence_never_changes_the_order() -> None: + fx = rs.wallet_fixture( + transfers=[ + (W, STRONG, 0, 2_000, rs.ATTACKER, USDT, 0), + (rs.lookalike(1), W, 10**18, 2_100, None, FAKE, 0), + ], + native=[(rs.lookalike(0, prefix=4, suffix=4), 1, 2_200, True)], + ) + out = rs.separation(fx, END) + for what in ("receipt", "token", "signer"): + assert out[what]["relative_order_unchanged"], what + assert out[what]["kept"] == 3, what + + +def test_h5_reproduction_is_preserved() -> None: + """The pre-registered order still loses to similarity under cheap verified dust; the + presentation order is reported beside it, never in its place.""" + fx = rs.wallet_fixture( + transfers=[(W, STRONG, 0, 2_000, rs.ATTACKER, USDT, 0)], + native=[ + (rs.lookalike(0, prefix=4, suffix=4), 1, 2_100, None), # unread receipt: supported + ], + ) + out = rs.spam_stability(fx, END, n=300, k=10) + assert out["evidence_aware"]["real_in_top_k"] == 1 # verified spam buries the unread one + assert out["presentation"]["real_in_top_k"] == 2 + assert out["similarity_only"]["real_in_top_k"] == 2 + assert out["recency_only"]["real_in_top_k"] == 0 + + +# --- adversarial floods (2,000 events here; 10,000 in the study) ---------------------------- + + +@pytest.fixture(scope="module") +def floods() -> dict[str, dict]: + return rs.adversarial(n=2_000) + + +@pytest.mark.parametrize("name", sorted(rs.adversarial_fixtures(n=10))) +def test_high_relevance_candidate_stays_reachable(floods: dict[str, dict], name: str) -> None: + row = floods[name] + assert row["deterministic"] + assert row["strong_reachable_by_page"] is True # never deleted, always reachable + if name == "identical_similarity_ties": + # 2,000 newer lookalikes with the same affix: recency decides, disclosed, reachable + assert row["strong_rank"] == 2_001 + else: + assert row["strong_rank"] == 1, row + assert row["strong_in_top_k"] + + +def test_flood_record_counts(floods: dict[str, dict]) -> None: + assert floods["repeated_dust_one_lookalike"]["groups"] == 2 + assert floods["repeated_dust_one_lookalike"]["evidence_records"] == 2_001 # none merged + assert floods["multiple_candidate_mechanisms"]["strong_mechanisms"] == [ + "lookalike_in", + "spoofed_out", + "zero_value_in", + ] + assert floods["missing_signer_information"]["strong_level"] == "directly_verified" + assert floods["partial_historical_coverage"]["strong_level"] == "partially_supported" + assert floods["partial_historical_coverage"]["abstain"] + assert floods["fake_token_flood"]["groups"] == 2_001 + + +def test_masking_still_makes_no_unsafe_claims_with_value_moving_spoofs() -> None: + fx = rs.wallet_fixture( + transfers=[ + (W, STRONG, 0, 2_000, rs.ATTACKER, USDT, 0), + (W, rs.lookalike(1), 10**6, 2_050, None, FAKE, 0), + ], + ) + out = rs.masking(fx, END) + for cond in ("S1_signer", "S3_receipt", "S4_token", "S5_partial_history"): + assert out[cond]["evidence_unsafe_inferences"] == 0, cond + assert out[cond]["added"] == 0, cond + assert out[cond]["level_raised"] == 0, cond + obs = cd.observations(fx) + assert any(o.value and o.direction == "out" for o in obs) + + +def test_identical_repeated_transfers_stay_distinct_records() -> None: + """The synthetic builder gives each event its own transaction: two identical dust sends + in one block are two records, not one (a 12.6.1 study-harness fix).""" + weak = rs.lookalike(1) + fx = rs.wallet_fixture(native=[(weak, 1, 2_000, True), (weak, 1, 2_000, True)]) + assert ce.build(fx, cutoff=END).evidence_records == 2 From 5e37788d6dd273f18b7675f30761a0912692b231 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 12:53:54 +0300 Subject: [PATCH 74/92] docs(ml): Phase 12.6.1 report - signer guards, authorization, bounded pages, lease test (no RPC) ML_CANDIDATE_RELIABILITY.md sections 30-39 with the measured run on 5a5e876 (reliability-study/2, 92 s, 623 MiB peak, 0 RPC): 20-condition signer guard matrix, real-window authorization audit (6 value-moving foreign events no longer called spoofs; R-SIG 18/18), bounded summary 6.8 KB at 1k/10k/100k, separation of support from order, H5 preserved, 10,000-event adversarial suite, lease-test investigation. In-place notes mark the 12.6 statements this corrects. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ ML_CANDIDATE_RELIABILITY.md | 307 +++++++++++++++++++++++++++++++++++- 2 files changed, 312 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03913f6..1bdf212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,15 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.6.1: signer-recovery safety, bounded summaries, research reliability (no RPC requests) +- **Correction:** R-SIG proves only that the wallet did not directly sign a transaction, never that it did not authorize the movement (an allowance, a permit or an EIP-7702 delegation). A value-moving foreign-signed transfer is now `foreign_initiated_out` with `authorization = unknown`; only zero-value ones are `spoofed_out`. On the real windows, 6 value-moving untrusted-token events are relabelled, the groups and levels are unchanged, and C1 still makes 6 such spoof claims. +- **`absence_guard`:** the absence inference requires a complete, count-consistent, nonce-contiguous signed set, and code `0x` at every sample up to the cutoff (no EIP-7702 designator or contract code). Otherwise the signer stays unknown. 20 conditions are tested. The rule still agrees 18 of 18 on the real windows. +- **Bounded summary:** 6.8 KB at 1,000, 10,000 and 100,000 candidates, where the hidden-identity list made it 915 KB at 10,000. Digest-checked `page()` and `group_records()` give offset/limit access to all evidence. +- **Presentation order** (affix, recency, address) reads no support level. H5 is reproduced unchanged. The order is not validated. +- **Adversarial suite with 10,000-event floods:** the strong candidate is rank 1 in 8 of 9 scenarios, and reachable by page in all 9. Equal-affix ties fall back to recency. +- **Lease test:** distinct child exit codes, a bounded join, expiry probes with explicit clock values, and a new boundary test. It passed 15 of 15 runs under CPU contention. +- **Docs:** `docs/ml/amendment-12.6.1.md`; report `ML_CANDIDATE_RELIABILITY.md` §30–§39. + ### Phase 12.6: candidate reliability and signer provenance (no RPC requests) - **Protocol 12.6** (`docs/ml/protocol-12.6.md`) was frozen first. The code was committed before the measured run. - **Audit:** real recordings have complete outgoing-signer coverage (18 of 18). The Phase 12.5 "signer loss" result came from masking. diff --git a/ML_CANDIDATE_RELIABILITY.md b/ML_CANDIDATE_RELIABILITY.md index c9a0153..16035f2 100644 --- a/ML_CANDIDATE_RELIABILITY.md +++ b/ML_CANDIDATE_RELIABILITY.md @@ -6,6 +6,7 @@ | Code (committed before the measured run) | `8e59c9d` | | Study output (git-ignored) | `data/ml/research/phase12.6/reliability-study.json` (`cryptoguard ml reliability-study`) | | RPC requests / downloads | **0** / none | +| Phase 12.6.1 addendum | §30–§39 (signer guards, authorization, bounded pages, lease test) | ## 1. Executive summary @@ -16,6 +17,7 @@ - One absent from a complete set, for a wallet without code, was **not** signed by it. The signer's address is never guessed. - **Result:** the rule matches the looked-up signer in **18 of 18** real cases, including 8 of 8 spoofs. - **With every signer masked,** the real windows lose **0** candidates and recover 4–5 signers each. Phase 12.5 lost them all. +- **12.6.1 correction:** R-SIG proves only that the wallet did not *directly sign*, never that it did not *authorize* (allowance, permit, delegation), and it now runs only under `absence_guard` (§30–§31). **Evidence model, `candidate-evidence/1`.** - **One group per (chain, victim, lookalike)**, keeping **every** record. The pilot's 9 events become 6 groups with all 9 records; C2 had kept only one per group. @@ -124,7 +126,7 @@ **The summary holds:** - `total_groups`, `raw_events`, `evidence_records`; - `shown` (k = 10) and `truncated`; -- `hidden_identities`; +- `hidden_identities` (replaced in 12.6.1 by `hidden_count`, `next_offset`, a digest and page access, §32); - counts by level and by mechanism; - `abstain`; - the note that hidden candidates are not assessed as safe; @@ -138,7 +140,7 @@ **A display budget is not an evidence budget.** All groups and records stay in the result. -**Measured cost of disclosure:** the hidden-identity list makes the summary O(n). It is 95.6 KB at 1,000 groups and 915 KB at 10,000 (§21). A UI may prefer counts plus a digest. The list is kept because the protocol requires it. +**Measured cost of disclosure:** the hidden-identity list makes the summary O(n). It is 95.6 KB at 1,000 groups and 915 KB at 10,000 (§21). A UI may prefer counts plus a digest. The list is kept because the protocol requires it. **12.6.1:** removed; the summary is now 6.8 KB at any size (§32). ## 10. Adversarial spam results (synthetic, 12 scenarios; all deterministic) @@ -276,7 +278,7 @@ Native volume on unlabelled wallets is still unmeasured, because P5 is `observat | Types | `uv run mypy src` | clean (153 files) | | Tests | `uv run pytest -q` | **950 passed, 1 failed**, 4 deselected (an 18-minute run on a heavily loaded machine) | -**About the failure.** It was `tests/integration/test_leases.py::test_lease_of_a_crashed_process_is_recovered_after_expiry`, a timing-sensitive lease-expiry test whose own comment records load flakiness. It passed **3 of 3** reruns in isolation. Phase 12.6 changed no lease code: its only source changes are `ml/cli.py` and two new research modules. +**About the failure.** It was `tests/integration/test_leases.py::test_lease_of_a_crashed_process_is_recovered_after_expiry`, a timing-sensitive lease-expiry test whose own comment records load flakiness. It passed **3 of 3** reruns in isolation. Phase 12.6 changed no lease code: its only source changes are `ml/cli.py` and two new research modules. **12.6.1:** investigated and fixed in the test (§37). There are 27 new tests in `tests/test_ml_candidate_evidence.py`. @@ -309,7 +311,7 @@ CI is recorded in the PR #1 description. | Change | Category | Decision | Risk and evidence | |---|---|---|---| -| R-SIG signer recovery | A/B, provenance | **Eligible for a separately approved production change.** Not integrated here: it would silently change production spoof signals for busy wallets. | 18 of 18 consistency; contract and EIP-7702 wallets excluded | +| R-SIG signer recovery (see §39 for the 12.6.1 decision) | A/B, provenance | **Eligible for a separately approved production change.** Not integrated here: it would silently change production spoof signals for busy wallets. | 18 of 18 consistency; contract and EIP-7702 wallets excluded | | Evidence model and levels | B | research (shadow); integrate after a migration review | levels are not probabilities | | Unknown-signer outgoing lookalikes kept as partially supported | C | research only | never a spoof claim | | Bounded summary contract | E | research output; never suppresses production warnings | O(n) disclosure list | @@ -329,3 +331,300 @@ CI is recorded in the PR #1 description. | Failure | The affix-first order does not keep the paid lookalike in the top 10 in more untied clusters than recency, under amendment A1's cluster sign test | Phase 12.7 is not started. + +--- + +# Phase 12.6.1 addendum: signer-recovery safety, bounded summaries, research reliability + +| Item | Value | +|---|---| +| Amendment | [`docs/ml/amendment-12.6.1.md`](docs/ml/amendment-12.6.1.md), written with the code | +| Code | `5a5e876` (`candidate-evidence/2`, `reliability-study/2`) | +| Study output (git-ignored) | `data/ml/research/phase12.6.1/reliability-study.json`, run on `5a5e876` | +| RPC requests / downloads | **0** / none | + +Sections 1–29 above are the Phase 12.6 record and stay as written. Where 12.6.1 corrects +them, the correction is stated here and marked in place. + +## 30. Executive summary (12.6.1) + +**Correction to 12.6:** R-SIG had been used as if "not signed by the wallet" meant "not +authorized by the wallet". It doesn't. An ERC-20 allowance, a permit or an EIP-7702 delegation +lets someone else's transaction move the wallet's tokens, and a fabricated log needs no +authorization at all. +- **Now:** only a **zero-value** foreign-signed transfer is `spoofed_out` (nothing moved, so + no authorization question arises). +- **Value moved:** the transfer is `foreign_initiated_out`, with `authorization = unknown`. +- **Effect on the real windows:** + - All 8 real foreign-signed events are still evidence, in the same groups and at the same + levels. + - The 6 that moved value were called spoofs by C1/C0 and by `candidate-evidence/1`. All 6 + came from untrusted token contracts and are now labelled `foreign_initiated_out` + + `untrusted_token_out`. + - None moved a trusted token. + +**Signer recovery is now guarded.** The absence inference runs only if the signed set is: +- complete; +- count-consistent; +- nonce-contiguous; +- inside the window; +- from an account whose code is `0x` at every sample up to the cutoff. + +Otherwise the signer stays unknown. 20 conditions are tested (§31). The guard allows the +inference on all 9 eligible real windows, and R-SIG still agrees with the looked-up signer +in **18 of 18** cases. + +**The summary is bounded.** It is 6.8 KB at 1,000, 10,000 and 100,000 candidates. Under +12.6, the hidden-identity list made it 915 KB at 10,000. Every group and record stays +reachable through digest-checked offset/limit pages. + +**Support no longer orders candidates.** The presentation order is affix, then recency, +then address. Masking receipts, token identity or signers changed the relative order of +**0** kept candidates on the 3 real windows with candidates. H5's negative result is +reproduced unchanged (§34). + +**Adversarial suite at 10,000 events per scenario:** +- the high-relevance candidate is rank 1 in 8 of 9 scenarios; +- in the ninth, 10,000 equally similar lookalikes planted later outrank it by recency (rank + 10,001); +- it stays reachable through the page interface in all 9; +- output is deterministic everywhere; +- each build takes about 2 s at about 17 MiB traced; +- the whole study ran in 92 s at a 623 MiB RSS peak, mostly from the 100,000-candidate step. + +**Lease test:** the cause of the single 12.6 failure could not be attributed: only the +failing test's name was kept, not its assertion. The test had three defects, all now fixed +(§37): an ambiguous child exit code, an unbounded wait for the child, and lease checks tied +to the wall clock. The rewritten test passed 15 of 15 runs under CPU contention. + +## 31. Signer-recovery audit (synthetic matrix) + +The probe is an outgoing USDT transfer from the wallet to a lookalike, whose signer was not +looked up. + +| Condition | Absence inference | Probe result | Why | +|---|---|---|---| +| Complete history, zero value | allowed | `foreign_identity_unknown`, `spoofed_out`, authorization `not_required` | — | +| Complete history, value moved, trusted token | allowed | `foreign_initiated_out`, authorization `unknown` | allowance, permit or delegation possible | +| Complete history, value moved, untrusted token | allowed | `foreign_initiated_out` + `untrusted_token_out`, authorization `unknown` | — | +| Signer lookups capped (600 skipped) | allowed | spoof recovered | the 500 cap limits lookups, not the signed set | +| Signed set `truncated` | **blocked** | `unknown`, `unverified_out_lookalike` | incomplete source | +| Signed set `partial` (partial recording) | **blocked** | same | incomplete source | +| Stated count ≠ held (5 vs 1) | **blocked** | same | inconsistent source | +| Nonce gap (missing page or EIP-7702 authorization) | **blocked** | same | a nonce was used with no recorded transaction | +| Legacy fixture without documented nonce bisection | **blocked** | same | completeness claim unsupported | +| Code deployed inside the window, before the cutoff | **blocked** | same | contract code | +| Code only after the cutoff | allowed | spoof recovered | future samples are not used | +| No code sample at the window start | **blocked** | same | code unknown | +| EIP-7702 delegation designator at the window start | **blocked** | same | delegated execution | +| Smart wallet (code) | **blocked** | same | never signs itself | +| Wallet calls a router that pulls with `transferFrom` | allowed | `wallet`, not evidence | the outer transaction is in the signed set | +| Same block: spoof before the wallet's own transaction | allowed | spoof recovered | identity is by hash, not order | +| Same block: own transaction after the cutoff | allowed | not observed | the cutoff is `(block, tx index)` | +| Same block: own transaction before the cutoff | allowed | `wallet`, not evidence | — | +| Wallet-signed transaction with unknown receipt | allowed | `wallet`, not evidence | membership does not depend on the receipt | +| Looked-up foreign signer, but the hash is in the signed set | allowed | `conflicting`, `unverified_out_lookalike` | never a spoof and never a reference | + +**Why these conditions suffice for recorder output.** The recorder (`replay/record.py`) +refuses an incomplete nonce bisection. And an EIP-7702 authorization included in someone +else's transaction increments the wallet's nonce with no wallet-signed transaction in that +block, so `_read_transaction` raises and no fixture is written. The guard re-checks both +from the stored data, so a fixture produced any other way is held to the same standard. + +**Limitation.** A signed set truncated at either end while still claiming `complete`, with a +matching count, is not detectable from the fixture, because the boundary nonces are not +stored. The guard relies on the recorder's guarantee there. + +**Real windows (`signer_audit`):** +- Absence inference is allowed on 9 of 9 eligible windows; nonces are contiguous and code is + `0x` at every sample. +- Foreign-signed outgoing events: 2 zero-value (pilot), 6 value-moving through untrusted + tokens (2 per development window), 0 value-moving through trusted tokens. +- C1 spoof claims on value-moving transfers: **6**. `candidate-evidence/2`: **0**. + +## 32. Bounded summary and page access + +| Candidates | Build | Build peak (traced) | Summary | Summary JSON | Page of 10 | Group records page | Digest | +|---|---|---|---|---|---|---|---| +| 1,000 | 0.14 s | 1.1 MiB | 0.009 s | 6,807 B | 6,209 B | 743 B | 0.001 s | +| 10,000 | 1.60 s | 13.2 MiB | 0.093 s | 6,812 B | 6,222 B | 743 B | 0.012 s | +| 100,000 | 17.8 s | 137 MiB | 0.81 s | 6,817 B | 6,235 B | 743 B | 0.13 s | + +**Generation:** observations are generated directly, one small dataclass per event, with no +fixture models. + +**What the summary contains:** +- the top `k` (1 ≤ k ≤ 1,000); +- `total_groups`, `hidden_count`, `truncated` and `next_offset`; +- `result_digest`; +- counts by level and by mechanism (fixed vocabularies); +- `absence_inference` and its blockers; +- at most 3 references per item, with `references_total`. + +**Access:** +- `page(offset, limit, expect_digest)` follows the project's `items`/`total`/`limit`/`offset` + convention and refuses a stale digest; +- `group_records(identity, offset, limit)` pages a single group's records. + +**Tests:** +- pages cover every group exactly once, in order; +- out-of-range `k`/`limit`/`offset` are refused; +- the summary carries no floats; +- every item says `legitimacy: not_assessed`. + +## 33. Evidence reliability versus suspiciousness + +| Requirement | How it holds | Test | +|---|---|---| +| A verified receipt does not raise suspicion | `presentation_key` never reads `level`; a verified older lookalike ranks below an unread newer one with the same affix | `test_a_verified_receipt_does_not_move_a_candidate_up` | +| High evidence quality does not imply attack probability | levels stay categories; `explain` separates indicators, support and missing | `test_presentation_order_never_reads_the_support_level` | +| Missing evidence is not suspicious | masking receipts, tokens or signers keeps the relative order (synthetic and real) | `test_missing_evidence_never_changes_the_order`; real windows below | +| Similarity and time are separate from provenance | the order uses affix and recency; level is reported beside them | same | +| Unknown legitimacy stays unknown | `legitimacy: not_assessed` on every item | `test_summary_items_are_bounded_and_carry_no_probability` | +| No calibrated-probability claims | no float field in the summary; `order_note` says "not a risk score or a probability" | same | + +**Real windows:** + +| Window | Mask | Kept | Relative order unchanged | Levels changed | +|---|---|---|---|---| +| pilot | receipt / token / signer | 6 / 6 / 6 | yes / yes / yes | 0 / 0 / 0 | +| ScamSniffer `/1` | receipt / token / signer | 2 / 2 / 2 | yes / yes / yes | 0 / 0 / 0 | +| ScamSniffer blind `/2` | receipt / token / signer | 3 / 3 / 3 | yes / yes / yes | 1 / 0 / 0 | + +The one level change is a lowering (verified → supported) and moved nothing. + +## 34. H5 preserved; the presentation order is not validated + +The H5 injection was repeated unchanged: 1,000 verified dust lookalikes (affix 3 + 3). + +| Window (real candidates) | Evidence-first (pre-registered) | Presentation (affix, recency) | Similarity-only | Recency-only | +|---|---|---|---|---| +| ScamSniffer blind (3) | 3 | 3 | 3 | 0 | +| pilot (6) | **3** | 6 | 6 | 0 | + +- **H5 stays negative.** +- **The presentation order's 6 of 6 on the pilot is development data.** The pilot informed + the choice, so it is not independent validation and is not claimed as one. The order was + adopted because support must not act as suspicion (§33), not because of this table. +- **Partial-history case:** under the evidence-first order, a strong but partially supported + candidate ranks 10,001st of 10,001 (§35). Missing evidence became burial there. The + presentation order keeps it at rank 1. + +## 35. Adversarial suite (synthetic, 10,000 flood events per scenario) + +| Scenario | Groups | Records | Strong rank (presentation) | Strong rank (evidence-first) | Reachable by page | Strong support | Build | Peak traced | Summary | +|---|---|---|---|---|---|---|---|---|---| +| 10,000 cheap lookalikes (3 + 3 dust) | 10,001 | 10,001 | **1** | 1 | yes | directly verified | 2.08 s | 16.6 MiB | 6.8 KB | +| Repeated dust from one lookalike | 2 | 10,001 | **1** | 1 | yes | directly verified | 0.98 s | 9.0 MiB | 2.0 KB | +| Fake-token flood | 10,001 | 10,001 | **1** | 1 | yes | directly verified | 1.86 s | 17.7 MiB | 7.1 KB | +| Missing signer (R-SIG) | 10,001 | 10,001 | **1** | 1 | yes | directly verified | 2.07 s | 16.5 MiB | 6.9 KB | +| Partial historical coverage | 10,001 | 10,001 | **1** | 10,001 | yes | partially supported, abstains | 2.19 s | 17.0 MiB | 7.5 KB | +| 50 references × 200 lookalikes | 10,001 | 10,001 | **1** | 1 | yes | directly verified | 2.23 s | 16.6 MiB | 6.8 KB | +| Multiple mechanisms (spoof + zero-value in + native) | 10,001 | 10,003 | **1** (3 mechanisms, 3 records) | 1 | yes | directly verified | 1.87 s | 16.5 MiB | 6.9 KB | +| 10,000 identical-similarity ties (5 + 5), later | 10,001 | 10,001 | 10,001 | 10,001 | **yes** | directly verified | 2.26 s | 16.6 MiB | 6.9 KB | +| Recency manipulation (all spam in the last block) | 10,001 | 10,001 | **1** | 1 | yes | directly verified | 2.28 s | 16.6 MiB | 6.8 KB | + +**Determinism:** all 9 builds produce identical digests when repeated. + +**Remaining weakness: ties.** +- With equal affixes, recency decides. An attacker who plants k or more later lookalikes, + each as similar as the real one, pushes it off the first page. +- At 5 + 5 hex characters, each such lookalike costs about 2⁴⁰ address-generation + attempts. +- The candidate is still listed, counted in `hidden_count` and reachable by page. + +**Harness fix found by this suite:** the synthetic builder had given identical dust sends +in the same block the same transaction hash, which merged them. It now adds the event index +to the hash (tested). The evidence model was not involved. + +## 36. Historical correctness + +- The guard reads only code samples at or before the cutoff. A later EIP-7702 designator + leaves an earlier result byte-identical (by digest) and blocks the inference only once the + cutoff passes it (tested). +- The signed set may contain later transactions. Membership is tested only for events before + the cutoff, and completeness covers the whole window. + +## 37. The lease test + +**Investigation:** the full-suite failure kept only the test's name, so the failing assertion +is unknown. + +**Measurements on the unchanged test:** +- 20 of 20 passed, with 4 CPU burners competing for the 4 cores. +- Each run took 14–21 s, against 3 s idle. Nearly all of it was spawn start-up before the + lease was taken (6–11 s). +- From the child taking the lease to the parent's check: 0.28–0.72 s. +- Lease time remaining at the check: about 7.3–7.7 s of the 8 s TTL. +- The conditional "still held" assertion ran in 15 of 15 instrumented runs. + +So scheduling delay before the check doesn't explain a failure. + +**Defects in the test that could explain it:** +1. **Ambiguous exit code.** A child that raises also exits with code 1, so a child failure + passed `exitcode == 1` and then failed later at `held is not None` with no diagnosis. +2. **Unbounded wait.** A join that timed out left a live child and failed with an unclear + assertion. +3. **Wall-clock coupling.** The "still held" assertion was conditional, and it was a + check-then-act on the real clock: a pause over 1 s between the check and `acquire`'s own + clock read fails it even though the lease logic is correct. + +**Fix, with no assertion weakened:** +- distinct exit codes (17: crashed holding; 3: no lease; 1: raised); +- a 180 s bounded join that kills a hung child; +- expiry probed with explicit clock values: held at expiry − 1 µs, still held at the expiry + instant, recovered with generation 2 at + 1 µs. These checks always run; before, they could + be skipped. +- A new deterministic test: at the expiry instant the old owner is already fenced out and + nobody can take over yet, so no instant has two owners. + +**Result:** the rewritten test passed 15 of 15 runs under the same 4-burner contention, with +no wall-clock waits. + +**Production code:** unchanged. One observation: `acquire` reads the clock before waiting on +a busy database, so the new lease expires early by the wait time. That is safe, because +fencing rejects late writes, and it is noted rather than changed. + +## 38. Validation (12.6.1) + +| Check | Result | +|---|---| +| `ruff check` / `ruff format --check` / `mypy src` | clean / formatted / clean (153 files) | +| New tests | `tests/test_ml_signer_guards.py`: 47; `tests/integration/test_leases.py`: 1 new, 1 rewritten | +| Full suite | **999 passed, 0 failed**, 4 deselected, in 14 min 22 s at about 1.6 GiB free RAM; the rewritten lease test passed within it | +| Package | `uv build --offline` wheel and sdist; `scripts/inspect_dist.py` OK (wheel 190 files, sdist 398) | +| Frozen artifacts | cohort sheet and key hashes unchanged; original incident fixtures untouched (no data file modified) | +| CI | recorded in the PR #1 description | + +## 39. Readiness, limitations and decisions (12.6.1) + +| Change | Decision | +|---|---| +| R-SIG with `absence_guard`, as a non-signing proof | **Reliable for offline research.** Production integration still needs a separately approved change. It would alter production spoof signals for busy wallets, and the production detector's own `spoofed_out` definition would first need the authorization split (A2). | +| Authorization split (`foreign_initiated_out`) | research; C0/C1 and the detector unchanged, so earlier results stay reproducible | +| Presentation order (affix, recency, address) | offline research default; **not validated** (§34) | +| Bounded summary and pages | research interface, ready for a UI prototype; never suppresses production warnings | +| Lease test | fixed; no production change | + +**Is the candidate-evidence pipeline reliable enough for broader offline research?** Yes, +for offline research on recorded windows: +- signer claims are guarded and never negative from an incomplete source; +- authorization is never assumed; +- evidence is preserved and paged with bounded output; +- missing evidence moves nothing; +- outputs are deterministic and cost is linear (100,000 candidates in 18 s). + +**What blocks production integration:** +1. **No independent validation.** The presentation order and the indicators are tested only + on synthetic data and 2 development incidents. +2. **Authorization is unobserved.** Distinguishing an approved pull from a fabricated log + needs allowance and permit history, which no recording collects yet. +3. **Legitimate intent-based settlements** (solver-signed `transferFrom` pulls) become + `foreign_initiated_out` groups whenever value moves. That is a false-positive source + with unmeasured volume. +4. **The production detector's spoof rule** would need the authorization split and a + migration review before R-SIG feeds warnings. +5. **Equal-affix ties** fall back to recency (§35). +6. **The signed set's end boundaries** rest on the recorder's guarantee (§31). + +The next experiment is unchanged (§29). Phase 12.7 is not started. From 9263dba72e19cbf5501d6bce92cfd55c2a0aaa71 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 14:45:20 +0300 Subject: [PATCH 75/92] docs(ml): freeze protocol 12.7 (adversarial candidate exposure, robust top-K, LTR) Threat model with an explicit work-factor model (2^(4(p+s)) key trials per reference), identifiability limits L1-L4, baselines B0-B7, the proposed work-weighted group-discounted selector P1 (lambda = 4 bits fixed a priori), ablations, negative controls, a 16-family synthetic grid (m in 0..10,000, K in 1..50, 10 seeds), hypotheses H1-H6 with decision criteria, and a learning-to-rank study confined to the 12.1 development split. Frozen before any selector, benchmark or LTR code exists. RPC budget 0. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.7.md | 318 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 docs/ml/protocol-12.7.md diff --git a/docs/ml/protocol-12.7.md b/docs/ml/protocol-12.7.md new file mode 100644 index 0000000..ac9e3ad --- /dev/null +++ b/docs/ml/protocol-12.7.md @@ -0,0 +1,318 @@ +# Protocol 12.7: adversarial candidate exposure, robust top-K selection, learning-to-rank + +**Frozen:** 2026-11-09, in the commit that adds this file. That is before any code for the +proposed selector, the benchmark or the learning-to-rank study exists, and before any result +is computed. + +**Base:** `5e37788` (`candidate-evidence/2`). + +**RPC budget:** 0. + +**Already known before freezing.** These are development facts, and nothing here counts them +as new evidence: +- the Phase 12.6.1 adversarial suite (rank 1 in 8 of 9 scenarios; rank 10,001 under 10,000 + later equal-affix decoys); +- the H5 result (support-first order loses); +- Phase 12.1's finding that recency (`T0`) best predicts which lookalike a victim paid, on its + test split. That split is never used again here. + +## 1. Problem + +The current pipeline has five separate stages: + +| Stage | What it is | Where it lives | +|---|---|---| +| Generation | evidence groups | `candidate_evidence.build` | +| Scoring | a per-group priority | new | +| Ranking | the full order | new | +| Exposure | the first K of that order | `summarize` | +| Preservation | every group and record reachable | `page`, `group_records` | + +Phase 12.7 changes only scoring and ranking, and adds metadata to exposure. Generation and +preservation are unchanged. + +## 2. Threat model + +**The attacker controls:** +- the lookalike addresses they generate, and their similarity to a victim reference, within + a compute budget; +- planting time (any block before the cutoff, earlier or later than any other planting); +- repetitions, values and mechanisms: native dust, fake-token logs, zero-value + `transferFrom` and other foreign-signed transfers; +- how many addresses and transactions they use; +- the distribution of that activity across accounts. + +**The attacker does not control:** +- the victim's genuine payments, and so the set of references, whose size G_R is fixed by the + victim's history; +- the victim's signatures; +- finalized chain order; +- provenance that is already observed. + +Unknown information (signer, receipt, token identity, history) stays unknown. It is never +trusted, and it is never ranked. + +**Work-factor model (illustrative, not a universal cost).** Take one specific reference R. A +uniformly random address matches its first p and last s hex characters with probability +16^−(p+s). The expected number of key trials is therefore 16^(p+s) = 2^(4(p+s)). +- **Bits of an affix:** `bits = 4(p+s)`. +- **Matching any of R references** costs about 2^(4(p+s)) / R, so the per-reference budget is + what matters. +- **Other similarity definitions** (case-sensitive checksums, fuzzy or edit distance) have + other work factors and are not modelled. +- **Event spam** (repeating events from an existing address) costs gas only. Illustrative + amounts: native transfer 21,000 gas; zero-value `transferFrom` about 40,000; fake-token + log about 35,000 to 50,000. +- **Reporting:** in key trials and gas units, never in USD. + +## 3. Identifiability limits, stated before any experiment + +**L1.** Suppose m+1 candidates are equal under every feature an ordering may read, with +m ≥ K. Then for any deterministic ordering whose tie rule is known to the attacker, the +attacker can place the m decoys ahead of the target, so Exposure@K = 0 in the worst case. +- **Recency:** the attacker chooses planting time. +- **Address order:** the attacker grinds addresses. +- **A public-seed hash:** the attacker grinds addresses against it. + +**L2.** A keyed hash with a seed the attacker does not know makes the order of equals +uniformly random from the attacker's point of view. The expected exposure of the target +among m+1 equals, with K' slots available to them, is min(1, K'/(m+1)). This tends to 0 as m +grows. It is a probability, not a guarantee. In this study the seed is fixed and public, for +reproducibility, so L2 is measured over 10 seeds as a model of a secret seed. + +**L3, group exposure.** Group candidates by the reference they imitate. The number of +reference groups is at most the victim's reference count plus a fixed number of +mechanism buckets for unreferenced candidates, and the attacker cannot increase it. A +selector that reserves exposure per group can therefore bound when the target's *group* +appears, independently of m, while candidate-level exposure inside a flooded group stays +under L1/L2. + +**L4. Pagination** always preserves every candidate. It is not exposure. + +## 4. Methods (identical candidate sets: the groups of one `build`) + +**Features read, all available before the cutoff:** +- `bits` = 4 · affix, or 0 without a reference; +- the best reference, the one with the highest affix, ties going to the lexicographically + smallest; +- last and first position; +- mechanisms. + +Support level, `missing` and receipt status are never read (12.6.1 A3). The oracle target is +never read. + +**Bucket:** the best reference. A candidate with no reference goes to the bucket of its +mechanism signature, `mech:`. + +**Keyed hash:** `h = sha256(f"{seed}:{lookalike}")`. + +| Id | Order | +|---|---| +| B0 | similarity first: bits ↓, last position ↓ (recency), address (the 12.6.1 presentation order) | +| B1 | recency first: last position ↓, bits ↓, address | +| B2 | evidence level first (negative reference only; H5 failed) | +| B3 | mechanism round-robin: buckets by mechanism signature, ordered by their best B0 member; B0 order within; take one per bucket per round | +| B4 | reference round-robin (λ = ∞): buckets ordered by best bits ↓ then bucket key; B0 order within; one per bucket per round | +| B5 | cover then fill: the B0-best member of every bucket first (in B0 order), then everything else in B0 order | +| B6 | B0 with keyed-hash ties: bits ↓, h, address | +| B7 | temporal anomaly: equivalent to B1 (Phase 12.5 showed MAD ≡ recency on 1,056 of 1,056). Not re-implemented; B1 stands in for it. No graph features exist for these windows. | +| **P1** | **work-weighted, group-discounted selection (WGS)**, below | + +**P1 (proposed).** +- **Within each bucket,** order the members by bits ↓, then h, then address. Member j + (0-based) gets priority `π = bits − λ·j`, with **λ = 4 bits**. +- **Globally,** order by π ↓, then the bucket's best bits ↓, then h, then address. +- **Reading λ = 4:** the j-th lookalike of the same reference must be one hex character + more similar than a lookalike of another reference to be shown before it. +- **λ is fixed a priori by the work-factor model.** Values 0, 2, 8 and ∞ are sensitivity + analyses only, and the primary result uses λ = 4. +- **Recency is not read by P1.** +- **Cost:** O(n log n), with no pairwise structure. + +**P1's provable properties, each tested:** +1. It is a permutation of the input groups, so nothing is added, removed or duplicated. +2. It is deterministic for fixed input and seed, and invariant to input order. +3. It reads no oracle, no support level and no time. +4. **Bounded group displacement.** Let the target's bucket have best bits b, and let every + other bucket contain only members with bits ≤ b_A. Then the first member of the target's + bucket sits at position ≤ 1 + Σ_{other buckets} min(n_g, ⌊(b_A − b)/λ⌋ + 1) when + b_A ≥ b, and ≤ 1 + (number of other buckets whose best bits are > b, plus ties) when + b_A < b. Either way the bound does not depend on the number of decoys m. B0's + displacement grows with the count of decoys with bits ≥ b. + +**Ablations of P1:** + +| Id | Change | +|---|---| +| A-nosim | bits := 0 (pure bucket rotation in hash order) | +| A-rec | ties within a bucket broken by recency instead of h | +| A-λ0 | λ = 0, which equals B6, i.e. no reference grouping | +| A-λ2, A-λ8 | λ = 2, λ = 8 | +| A-λ∞ | λ = ∞ (round-robin with hash ties) | +| A-nomech | all unreferenced candidates in one bucket | + +**Not ablated:** +- **coverage metadata:** reported, never ranked, so the ablation is identical by + construction; +- **graph context:** none exists for these windows, so NOT EVALUATED. + +**Negative controls:** + +| Id | Control | Expected | +|---|---|---| +| NC-random | seeded random permutation | Exposure@K ≈ K/n | +| NC-revrec | oldest first | — | +| NC-time | P1 with planting blocks randomly permuted among candidates | identical order (P1 reads no time) | +| NC-mech | P1 with mechanism labels shuffled among referenced candidates | identical | +| NC-serial | every method on shuffled input order | identical | +| NC-signer | add foreign-signed outgoing transfers to non-lookalikes | target rank unchanged | +| NC-public-token | zero-value USDT from many unrelated strangers | at most unreferenced buckets; target exposure unchanged | + +## 5. Synthetic benchmark (controlled adversarial robustness; not real-world recall) + +**Base window:** the `reliability_study.wallet_fixture` builder, with a victim that has 5 +genuine references R1–R5 (wallet-signed payments, blocks 1,100–1,500) and a cutoff of +(9,001, 0). The target(s) are defined by construction (oracle) and never encoded in features. +- **Decoy count m:** {0, 10, 100, 1,000, 10,000}. +- **K:** {1, 3, 5, 10, 20, 50}. +- **Seeds for hash methods:** 0–9. +- **Unless stated:** the target is a zero-value foreign-signed `transferFrom` to a 4+4 + (32-bit) lookalike of R1 at block 2,000, and decoys are newer (blocks ≥ 3,000), assigned to + references round-robin. + +| Family | Target(s) | Decoys (m) | +|---|---|---| +| F1 native dust flood | default | native dust, 3+3, R1–R5 | +| F2 fake-token flood | default | incoming fake-token logs, 3+3, R1–R5 | +| F3 zero-value flood | default | incoming zero-value USDT, 3+3, R1–R5 | +| F4 repetition | default | m native dust repeats from **one** 5+5 lookalike of R2 | +| F5 distinct equal lookalikes | default | native dust, 4+4, R1–R5 | +| F6 equal similarity, same reference | default | native dust, 4+4, **R1 only** (identifiability family) | +| F7 recent decoys, other references | default | native dust, 4+4, R2–R5 | +| F8 reference overlap | default; R2 shares a 3-character prefix and suffix with R1 | native dust, 4+4 of R2 | +| F9 mixed mechanisms | one 4+4 lookalike of R1 with a spoof, native dust and zero-value USDT in (3 records) | 4+4, R2–R5, cycling native / fake token / zero value | +| F10 unknown signer | spoof with an unknown signer (R-SIG) | native dust, 4+4, R2–R5 | +| F11 missing receipt | native dust from a 4+4 lookalike of R1, receipt unknown | verified native dust, 4+4, R2–R5 | +| F12 partial history | spoof with an unknown signer, signed set `partial` (unverified) | native dust, 4+4, R2–R5 | +| F13 contract-mediated | value-moving foreign-signed USDT pull to a 4+4 lookalike of R1 (`foreign_initiated_out`) | native dust, 4+4, R2–R5 | +| F14 one campaign, several relevant | 3 spoofs, 5+5 lookalikes of R1 | native dust, 4+4, R2–R5 | +| F15 one among unrelated | spoof, 3+3 of R1 | m unrelated: half native from non-lookalike strangers, half zero-value USDT from strangers | +| F16 several relevant compete | spoof 4+4 of R1; native 4+4 of R2; zero-value USDT in 3+3 of R3 (blocks 2,000–2,200) | native dust, 4+4, **R1 only** | + +## 6. Metrics + +- **Exposure@K:** 1 if a relevant candidate's rank ≤ K. Averaged over the relevant candidates + of a cell, and over seeds for hash methods. +- **Exposure rank and rank displacement:** rank(m) − rank(0). +- **Attack cost to displacement:** the smallest m in the grid with rank > K (∞ if none), + translated by the cost model into decoy-address work (m · 2^bits_decoy trials, divided by + the references used) and gas. +- **Target-group coverage@K (TGC@K):** whether any member of the target's best-reference + bucket is within the top K. Group coverage is not threat coverage. +- **Preservation:** whether the ordering is a permutation of `build`'s groups; checked + exactly. +- **Determinism:** digest equality on a repeated run. +- **Runtime and memory:** wall time, tracemalloc peak and process peak RSS. + +Synthetic Exposure@K is not real-world recall. + +## 7. Hypotheses and decision criteria + +The benchmark is deterministic: differences are exact, not samples, so no p-values are +computed for it. + +- **H1 (primary).** Over all 16 families × 5 m × 6 K, P1's mean Exposure@K exceeds B0's. P1 + is ≥ B0 (family mean over m and K) in at least 12 of 16 families, and no family is worse by + more than 0.10. + - **Supported** if all three hold. + - **Partially supported** if only the first holds. + - **Failure:** otherwise. +- **H2.** P1's TGC@K ≥ B0's in every cell. The bound of §4 property 4 holds in every cell + where its premise holds. +- **H3 (recency attacks).** In F1–F3 (decoy bits < target bits), B0 and P1 keep the target at + rank 1 for every m, while B1's Exposure@K is 0 whenever m ≥ K. +- **H4 (identifiability, F6).** B0's Exposure@K is 0 for m ≥ K, because the target is the + oldest of its equals. P1 and B6's mean exposure over 10 seeds is within ±0.10 of + min(1, K/(m+1)) at every m ≥ K. No method guarantees exposure. +- **H5 (diversity cost, F14).** Reported as the trade-off. P1 is not adopted as the research + default if its F14 mean Exposure@K is below B0's by more than 0.10. +- **H6 (ablations).** Report which component carries any H1 gain. If A-nosim or A-λ∞ alone + matches P1 within 0.01 overall, the simpler method is preferred. + +## 8. Learning to rank + +**Feasibility rule.** Train only on a population with at least 100 independent queries, each +with at least 2 candidates and a real outcome label, a temporal split, no protected overlap +and no future features. Otherwise report "not trained". + +**Population.** The archive's lookalike-prioritization episodes (`lookalike-prioritization/1`, +real source-confirmed payoffs: which lookalike was paid): +- **12.1 development split only** (640 episodes, 632 groups). The 12.1 test split is not + used, not even for feature computation. +- **Protected wallets and transactions** are excluded exactly as in 12.1. +- **Features** without the graph, 12.1 definitions: S = `B0` (affix vs. the victim's own + recipients), R = `T0` (age of the last planting), N = `T1` (distinct planting + transactions). +- **Internal temporal split:** dev groups ordered by earliest payoff. The earliest 70 % of + episodes are used to fit, the latest 30 % to evaluate. + +**Models:** +- **M-LTR:** a pairwise conditional logit (12.1's `learned` construction: L2 logistic + regression on standardized paid-minus-rival differences) on (S, R, N). +- **M-LTR-noR:** the same on (S, N), excluding the attacker-cheap feature. + +**Baselines on the same episodes, tie-averaged:** +- similarity S; +- recency R; +- lexicographic S-then-R (which is B0); +- random. + +**Source-conditional metrics:** top-1 and MRR, with paired group bootstrap and group +sign-flip p-values against B0, as in 12.1. + +**Adversarial transfer.** The fitted M-LTR and M-LTR-noR scorers are applied to the synthetic +benchmark, with the same feature definitions computed from evidence groups. Exposure@K is +reported beside B0 and P1. + +**Gate G (ML contribution) passes only if both hold:** +1. M-LTR beats B0 on the internal validation split by at least 0.05 top-1, with a CI + excluding 0; +2. M-LTR's mean benchmark Exposure@K is no more than 0.05 below B0's. + +Otherwise ML adds no robust value. The archive is source-conditional: attackers there were +not gaming this ranker, and recency is attacker-controlled. + +**Source shift.** Compare the fit and validation feature distributions (quantiles of S, R, N +and candidate counts), and report validation metrics by candidate-count bin and by the +paid planting's mechanism. On the benchmark, report results by family, decoy count and +completeness. + +## 9. Development cases (development-case analysis, not independent validation) + +The pilot, ScamSniffer `/1` and ScamSniffer blind `/2`, at the existing cutoffs. + +**Reported:** the paid lookalike's rank under B0, B1, B2, B6 and P1 (with M-LTR where its +features exist), plus C2's own candidate list order (a different candidate set, labelled as +such), and missingness. No method is tuned on these cases. + +## 10. Integration, cost, reproducibility + +- `select(result, method, config)` returns the same groups reordered, with the method id and a + config hash. `summarize` / `page` report both, and each item reports its reference bucket + size. Nothing else in the summary contract changes. +- **Performance:** P1 on 100, 1,000, 10,000 and 100,000 groups. The study runs in one process + with a bounded resource preflight. +- **Outputs:** `cryptoguard ml adversarial-ranking` writes + `data/ml/research/phase12.7/adversarial-ranking.json` (git-ignored), with its git SHA, + config and seeds. +- **Research-only:** the production detector, its findings and the warning severities are + unchanged. + +## 11. Gates + +- **Statuses:** PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA, NOT EVALUATED. +- **Gates:** historical correctness, preservation, exposure (H1), similarity attacks (F5–F8), + recency attacks (H3), diversity trade-off (H5), ML (gate G), missingness, cost, production + isolation, reproducibility. +- **Independent validation** is **BLOCKED BY DATA**. Neither synthetic data nor the two known + incidents can pass it. From 7ac195fbfa8794fb9b2daf67dce7ff11432ce2b3 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 14:54:00 +0300 Subject: [PATCH 76/92] feat(ml): adversarial-selection/1 research selectors and the 12.7 benchmark - adversarial_ranking: baselines B0-B6 and negative controls, and the proposed work-weighted group-discounted selector P1 (priority = 4*affix - lambda*j per reference bucket, keyed-hash ties, no time, no support level, no oracle) with its ablations and a provable displacement bound independent of decoy count. select() returns a labelled permutation (method id + config hash). - candidate_evidence: EvidenceResult carries its order and config hash; the digest covers them; summary/page report them and each item's reference bucket and bucket size. The default order and contract are otherwise unchanged. - adversarial_benchmark: the 16 pre-registered families (m 0..10,000, K 1..50, 10 seeds), Exposure@K, TGC@K, displacement, attack cost, H1-H4 checks, negative controls, the 12.1 development-split LTR study (test split dropped before features), development cases, performance, resource preflight. - CLI: cryptoguard ml adversarial-ranking. Committed before the measured run (protocol 12.7). 0 RPC. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/adversarial_benchmark.py | 997 ++++++++++++++++++++ src/cryptoguard/ml/adversarial_ranking.py | 237 +++++ src/cryptoguard/ml/candidate_evidence.py | 45 +- src/cryptoguard/ml/cli.py | 21 + tests/test_ml_adversarial_ranking.py | 276 ++++++ 5 files changed, 1570 insertions(+), 6 deletions(-) create mode 100644 src/cryptoguard/ml/adversarial_benchmark.py create mode 100644 src/cryptoguard/ml/adversarial_ranking.py create mode 100644 tests/test_ml_adversarial_ranking.py diff --git a/src/cryptoguard/ml/adversarial_benchmark.py b/src/cryptoguard/ml/adversarial_benchmark.py new file mode 100644 index 0000000..beecb96 --- /dev/null +++ b/src/cryptoguard/ml/adversarial_benchmark.py @@ -0,0 +1,997 @@ +"""Phase 12.7 offline study (protocol 12.7): adversarial candidate exposure. + +Populations are kept apart and labelled in the output: + +- ``synthetic``: the 16 pre-registered scenario families (controlled adversarial + robustness; synthetic Exposure@K is not real-world recall); +- ``archive_dev``: the 12.1 lookalike-prioritization development split (source-conditional + development evaluation; its test split is never used); +- ``development_cases``: the pilot and the ScamSniffer windows (development-case analysis, + not independent validation). + +No RPC requests. Protected wallets are excluded exactly as in 12.1, and the frozen cohort +files are never opened for writing. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import random +import time +import tracemalloc +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any + +from cryptoguard.ml import adversarial_ranking as ar +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_evidence as ce +from cryptoguard.ml import reliability_study as rs + +STUDY_VERSION = "adversarial-ranking-study/1" +W, USDT, FAKE, END = rs.WALLET, rs.USDT, rs.FAKE, rs.END +ATTACKER = rs.ATTACKER +M_GRID = (0, 10, 100, 1_000, 10_000) +K_GRID = (1, 3, 5, 10, 20, 50) +SEEDS = tuple(range(10)) +GAS = {"native": 21_000, "zero_value_erc20": 40_000, "fake_token": 45_000} # illustrative + + +# --- references and families ---------------------------------------------------------------- + + +def references(*, overlap: bool = False) -> list[str]: + """R1 (the builder's USDT payment) and R2-R5 (wallet-signed native payments). With + ``overlap``, R2 shares exactly a 3-character prefix and suffix with R1.""" + refs = [rs.REF] + [ + "0x" + hashlib.sha256(f"cg127-ref-{i}".encode()).hexdigest()[:40] for i in range(2, 6) + ] + if overlap: + r1 = rs.REF[2:] + body = hashlib.sha256(b"cg127-overlap").hexdigest() + fourth = "0" if r1[3] != "0" else "1" + before_suffix = "0" if r1[-4] != "0" else "1" + refs[1] = "0x" + r1[:3] + fourth + body[:32] + before_suffix + r1[-3:] + return refs + + +def _fixture( + refs: Sequence[str], + *, + transfers: Sequence[Any] = (), + native: Sequence[Any] = (), + refs_complete: bool = True, +) -> Any: + return rs.wallet_fixture( + transfers=list(transfers), + native=list(native), + wallet_txs=[(r, 10**15, 1_100 + 100 * i) for i, r in enumerate(refs[1:], start=1)], + refs_complete=refs_complete, + ) + + +@dataclass(frozen=True) +class Scenario: + family: str + m: int + fixture: Any + relevant: tuple[str, ...] # the oracle targets: scoring only, never a feature + target_ref: str # the reference the (first) target imitates + + +def _decoys(m: int, p: int, s: int, refs: Sequence[str], start: int = 1_000) -> list[str]: + return [rs.lookalike(start + i, prefix=p, suffix=s, ref=refs[i % len(refs)]) for i in range(m)] + + +def _block(i: int) -> int: + return 3_000 + i % 5_000 # decoys are newer than every target (blocks 2,000-2,200) + + +def scenario(family: str, m: int) -> Scenario: + refs = references(overlap=family == "F8_reference_overlap") + r1 = refs[0] + t = rs.lookalike(0, prefix=4, suffix=4, ref=r1) + spoof = (W, t, 0, 2_000, ATTACKER, USDT, 0) + + def native_dust(ds: Sequence[str]) -> list[Any]: + return [(d, 1, _block(i), True) for i, d in enumerate(ds)] + + others = refs[1:] + rel: tuple[str, ...] = (t,) + tr: list[Any] = [spoof] + nat: list[Any] = [] + complete = True + if family == "F1_native_dust_flood": + nat = native_dust(_decoys(m, 3, 3, refs)) + elif family == "F2_fake_token_flood": + tr += [ + (d, W, 10**18, _block(i), None, FAKE, 0) for i, d in enumerate(_decoys(m, 3, 3, refs)) + ] + elif family == "F3_zero_value_flood": + tr += [(d, W, 0, _block(i), None, USDT, 0) for i, d in enumerate(_decoys(m, 3, 3, refs))] + elif family == "F4_repetition_one_address": + strong = rs.lookalike(999, prefix=5, suffix=5, ref=refs[1]) + nat = [(strong, 1, _block(i), True) for i in range(m)] + elif family == "F5_distinct_equal_lookalikes": + nat = native_dust(_decoys(m, 4, 4, refs)) + elif family == "F6_equal_similarity_same_reference": + nat = native_dust(_decoys(m, 4, 4, [r1])) + elif family in ("F7_recent_decoys_other_references", "F10_unknown_signer"): + nat = native_dust(_decoys(m, 4, 4, others)) + if family == "F10_unknown_signer": + tr = [(W, t, 0, 2_000, None, USDT, 0)] + elif family == "F8_reference_overlap": + nat = native_dust(_decoys(m, 4, 4, [refs[1]])) + elif family == "F9_mixed_mechanisms": + tr += [(t, W, 0, 2_100, None, USDT, 0)] + nat = [(t, 1, 2_050, True)] + for i, d in enumerate(_decoys(m, 4, 4, others)): + kind = i % 3 + if kind == 0: + nat.append((d, 1, _block(i), True)) + elif kind == 1: + tr.append((d, W, 10**18, _block(i), None, FAKE, 0)) + else: + tr.append((d, W, 0, _block(i), None, USDT, 0)) + elif family == "F11_missing_receipt": + tr = [] + nat = [(t, 1, 2_000, None), *native_dust(_decoys(m, 4, 4, others))] + elif family == "F12_partial_history": + tr = [(W, t, 0, 2_000, None, USDT, 0)] + nat = native_dust(_decoys(m, 4, 4, others)) + complete = False + elif family == "F13_contract_mediated": + tr = [(W, t, 10**6, 2_000, ATTACKER, USDT, 0)] + nat = native_dust(_decoys(m, 4, 4, others)) + elif family == "F14_one_campaign_several_relevant": + ts = [rs.lookalike(j, prefix=5, suffix=5, ref=r1) for j in range(3)] + rel = tuple(ts) + tr = [(W, x, 0, 2_000 + 10 * j, ATTACKER, USDT, j) for j, x in enumerate(ts)] + nat = native_dust(_decoys(m, 4, 4, others)) + elif family == "F15_one_among_unrelated": + t = rs.lookalike(0, prefix=3, suffix=3, ref=r1) + rel = (t,) + tr = [(W, t, 0, 2_000, ATTACKER, USDT, 0)] + strangers = ["0x" + f"{0x5000000 + i:040x}" for i in range(m)] + half = m // 2 + nat = [(s, 1, _block(i), True) for i, s in enumerate(strangers[:half])] + tr += [(s, W, 0, _block(i), None, USDT, 0) for i, s in enumerate(strangers[half:])] + elif family == "F16_several_relevant_compete": + t2 = rs.lookalike(0, prefix=4, suffix=4, ref=refs[1]) + t3 = rs.lookalike(0, prefix=3, suffix=3, ref=refs[2]) + rel = (t, t2, t3) + tr = [spoof, (t3, W, 0, 2_200, None, USDT, 0)] + nat = [(t2, 1, 2_100, True), *native_dust(_decoys(m, 4, 4, [r1]))] + else: + raise ValueError(family) + fx = _fixture(refs, transfers=tr, native=nat, refs_complete=complete) + return Scenario(family, m, fx, tuple(x.lower() for x in rel), r1.lower()) + + +FAMILIES = ( + "F1_native_dust_flood", + "F2_fake_token_flood", + "F3_zero_value_flood", + "F4_repetition_one_address", + "F5_distinct_equal_lookalikes", + "F6_equal_similarity_same_reference", + "F7_recent_decoys_other_references", + "F8_reference_overlap", + "F9_mixed_mechanisms", + "F10_unknown_signer", + "F11_missing_receipt", + "F12_partial_history", + "F13_contract_mediated", + "F14_one_campaign_several_relevant", + "F15_one_among_unrelated", + "F16_several_relevant_compete", +) + +# decoy cost per family: (decoy bits, references used, gas kind); None: no decoys / strangers +DECOY_COST: dict[str, tuple[int, int, str] | None] = { + "F1_native_dust_flood": (24, 5, "native"), + "F2_fake_token_flood": (24, 5, "fake_token"), + "F3_zero_value_flood": (24, 5, "zero_value_erc20"), + "F4_repetition_one_address": (40, 1, "native"), # one address, m repeats + "F5_distinct_equal_lookalikes": (32, 5, "native"), + "F6_equal_similarity_same_reference": (32, 1, "native"), + "F7_recent_decoys_other_references": (32, 4, "native"), + "F8_reference_overlap": (32, 1, "native"), + "F9_mixed_mechanisms": (32, 4, "native"), + "F10_unknown_signer": (32, 4, "native"), + "F11_missing_receipt": (32, 4, "native"), + "F12_partial_history": (32, 4, "native"), + "F13_contract_mediated": (32, 4, "native"), + "F14_one_campaign_several_relevant": (32, 4, "native"), + "F15_one_among_unrelated": None, + "F16_several_relevant_compete": (32, 1, "native"), +} + + +def attack_cost(family: str, m: int) -> dict[str, Any] | None: + """Illustrative cost of m decoys: expected key trials (log2) and gas units.""" + c = DECOY_COST[family] + if c is None or m == 0: + return None + b, _refs, kind = c + addresses = 1 if family == "F4_repetition_one_address" else m + trials = addresses * 2.0**b + return { + "decoy_bits": b, + "addresses": addresses, + "log2_key_trials": round(math.log2(trials), 2), + "gas": m * GAS[kind], + } + + +# --- methods ---------------------------------------------------------------------------------- + + +def selectors(seed: int) -> dict[str, ar.Selector]: + s = ar.Selector + return { + "B0": s("B0"), + "B1": s("B1"), + "B2": s("B2"), + "B3": s("B3"), + "B4": s("B4"), + "B5": s("B5"), + "B6": s("B6", seed=seed), + "P1": s("P1", seed=seed), + "A-nosim": s("P1", seed=seed, nosim=True), + "A-rec": s("P1", seed=seed, tie="recency"), + "A-lam2": s("P1", seed=seed, lam=2.0), + "A-lam8": s("P1", seed=seed, lam=8.0), + "A-laminf": s("P1", seed=seed, lam=math.inf), + "A-nomech": s("P1", seed=seed, nomech=True), + "NC-random": s("random", seed=seed), + "NC-revrec": s("revrec"), + } + + +SEEDED = frozenset( + {"B6", "P1", "A-nosim", "A-rec", "A-lam2", "A-lam8", "A-laminf", "A-nomech", "NC-random"} +) +# A-lam0 is B6 by definition (lambda = 0: no group discount); it is reported under B6. + +Scorer = Callable[[ce.CandidateGroup, int], float] # (group, cutoff block) -> score + + +def score_order( + groups: Sequence[ce.CandidateGroup], score: Scorer, cutoff_block: int +) -> list[ce.CandidateGroup]: + return sorted(groups, key=lambda g: (-score(g, cutoff_block), g.lookalike)) + + +# --- the grid --------------------------------------------------------------------------------- + + +def _ranks( + ordered: Sequence[ce.CandidateGroup], relevant: Sequence[str], target_ref: str +) -> tuple[list[int | None], int | None]: + pos = {g.lookalike: i + 1 for i, g in enumerate(ordered)} + first_bucket = next( + (i + 1 for i, g in enumerate(ordered) if ce.bucket_of(g) == target_ref), None + ) + return [pos.get(r) for r in relevant], first_bucket + + +def _exposure(ranks: Sequence[int | None], k: int) -> float: + return sum(1 for r in ranks if r is not None and r <= k) / len(ranks) + + +def run_cell( + sc: Scenario, extra: dict[str, Scorer] | None = None, seeds: Sequence[int] = SEEDS +) -> dict[str, Any]: + t0 = time.perf_counter() + res = ce.build(sc.fixture, cutoff=END) + build_s = time.perf_counter() - t0 + groups = list(res.groups) + out: dict[str, Any] = { + "groups": len(groups), + "evidence_records": res.evidence_records, + "build_seconds": round(build_s, 3), + "relevant_found": [r in {g.lookalike for g in groups} for r in sc.relevant], + "methods": {}, + } + target_bucket = sc.target_ref + rows: dict[str, list[tuple[list[int | None], int | None]]] = {} + bound_violations: dict[str, int] = {} + for seed in seeds: + for name, sel in selectors(seed).items(): + if seed != seeds[0] and name not in SEEDED: + continue + ordered = ar.order(groups, sel) + if len(ordered) != len(groups): + raise AssertionError("not a permutation") + ranks, fb = _ranks(ordered, sc.relevant, target_bucket) + rows.setdefault(name, []).append((ranks, fb)) + if sel.method == "P1" and not sel.nosim and sel.lam > 0: + bound = ar.displacement_bound(groups, target_bucket, sel.lam, nomech=sel.nomech) + if bound is not None and fb is not None and fb > bound: + bound_violations[name] = bound_violations.get(name, 0) + 1 + for name, score in (extra or {}).items(): + ordered = score_order(groups, score, END[0]) + rows[name] = [_ranks(ordered, sc.relevant, target_bucket)] + for name, rr in rows.items(): + out["methods"][name] = { + "ranks": [r for r, _ in rr] if name in SEEDED else rr[0][0], + "bucket_first": [f for _, f in rr] if name in SEEDED else rr[0][1], + "exposure": { + k: round(sum(_exposure(r, k) for r, _ in rr) / len(rr), 4) for k in K_GRID + }, + "tgc": { + k: round(sum(1 for _, f in rr if f is not None and f <= k) / len(rr), 4) + for k in K_GRID + }, + } + out["bound_violations"] = bound_violations + if res.groups: + out["digest_repeat_equal"] = ce.digest(res) == ce.digest(ce.build(sc.fixture, cutoff=END)) + return out + + +def grid( + m_grid: Sequence[int] = M_GRID, + extra: dict[str, Scorer] | None = None, + families: Sequence[str] = FAMILIES, +) -> dict[str, Any]: + out: dict[str, Any] = {} + for fam in families: + out[fam] = {} + for m in m_grid: + cell = run_cell(scenario(fam, m), extra) + cell["attack_cost"] = attack_cost(fam, m) + out[fam][str(m)] = cell + return out + + +def summarize_grid(g: dict[str, Any], methods: Sequence[str]) -> dict[str, Any]: + """Mean Exposure@K / TGC@K per method, overall and per family, and the H1 verdict.""" + per_family: dict[str, dict[str, float]] = {} + overall: dict[str, list[float]] = {m: [] for m in methods} + tgc_all: dict[str, list[float]] = {m: [] for m in methods} + by_k: dict[str, dict[int, list[float]]] = {m: {k: [] for k in K_GRID} for m in methods} + for fam, cells in g.items(): + per_family[fam] = {} + for meth in methods: + vals = [] + for cell in cells.values(): + if meth not in cell["methods"]: + continue + for k in K_GRID: + v = cell["methods"][meth]["exposure"][k] + vals.append(v) + by_k[meth][k].append(v) + tgc_all[meth].append(cell["methods"][meth]["tgc"][k]) + if vals: + per_family[fam][meth] = round(sum(vals) / len(vals), 4) + overall[meth] += vals + mean = {m: round(sum(v) / len(v), 4) for m, v in overall.items() if v} + out: dict[str, Any] = { + "mean_exposure": mean, + "mean_tgc": {m: round(sum(v) / len(v), 4) for m, v in tgc_all.items() if v}, + "mean_exposure_by_k": { + m: {k: round(sum(v) / len(v), 4) for k, v in ks.items() if v} for m, ks in by_k.items() + }, + "per_family": per_family, + } + if "P1" in mean and "B0" in mean: + diffs = {f: per_family[f]["P1"] - per_family[f]["B0"] for f in per_family} + ge = sum(1 for d in diffs.values() if d >= -1e-9) + worst = min(diffs.values()) + c1, c2, c3 = mean["P1"] > mean["B0"], ge >= 12, worst >= -0.10 + out["H1"] = { + "P1_minus_B0": round(mean["P1"] - mean["B0"], 4), + "families_P1_ge_B0": ge, + "worst_family_difference": round(worst, 4), + "verdict": "supported" + if c1 and c2 and c3 + else "partially supported" + if c1 + else "failed", + } + return out + + +def cell_tgc_check(g: dict[str, Any]) -> dict[str, Any]: + """H2: P1's target-group coverage is never below B0's, cell by cell.""" + worse = [] + for fam, cells in g.items(): + for m, cell in cells.items(): + for k in K_GRID: + p, b = cell["methods"]["P1"]["tgc"][k], cell["methods"]["B0"]["tgc"][k] + if p < b - 1e-9: + worse.append([fam, int(m), k, p, b]) + violations = sum( + sum(c["bound_violations"].values()) for cells in g.values() for c in cells.values() + ) + return {"cells_P1_below_B0": len(worse), "examples": worse[:10], "bound_violations": violations} + + +def h3_check(g: dict[str, Any]) -> dict[str, Any]: + fams = ("F1_native_dust_flood", "F2_fake_token_flood", "F3_zero_value_flood") + out: dict[str, Any] = {} + for fam in fams: + rows = [] + for m, cell in g[fam].items(): + b0 = cell["methods"]["B0"]["ranks"][0] + p1 = max(r[0] or 10**9 for r in cell["methods"]["P1"]["ranks"]) + b1 = cell["methods"]["B1"]["ranks"][0] + b1_ok = all(cell["methods"]["B1"]["exposure"][k] == 0 for k in K_GRID if int(m) >= k) + rows.append( + { + "m": int(m), + "B0_rank": b0, + "P1_worst_rank": p1, + "B1_rank": b1, + "B1_zero_when_m_ge_K": b1_ok, + } + ) + out[fam] = rows + return out + + +def h4_check(g: dict[str, Any]) -> dict[str, Any]: + cells = g["F6_equal_similarity_same_reference"] + rows = [] + for m, cell in cells.items(): + m_i = int(m) + for k in K_GRID: + if m_i < k: + continue + theory = min(1.0, k / (m_i + 1)) + rows.append( + { + "m": m_i, + "K": k, + "theory": round(theory, 4), + "B0": cell["methods"]["B0"]["exposure"][k], + "B6": cell["methods"]["B6"]["exposure"][k], + "P1": cell["methods"]["P1"]["exposure"][k], + "P1_within_0.10": abs(cell["methods"]["P1"]["exposure"][k] - theory) <= 0.10, + } + ) + return {"rows": rows, "all_within": all(r["P1_within_0.10"] for r in rows)} + + +def attack_curves( + g: dict[str, Any], methods: Sequence[str] = ("B0", "B1", "B6", "P1") +) -> dict[str, Any]: + """Smallest m in the grid at which the (median-seed) first relevant rank exceeds K.""" + out: dict[str, Any] = {} + for fam, cells in g.items(): + out[fam] = {} + for meth in methods: + row = {} + for k in K_GRID: + hit = None + for m in sorted(cells, key=int): + r = cells[m]["methods"][meth]["ranks"] + if meth in SEEDED: + firsts = sorted((x[0] if x[0] is not None else 10**9) for x in r) + rank = firsts[len(firsts) // 2] + else: + rank = r[0] if r[0] is not None else 10**9 + if rank > k: + hit = int(m) + break + row[k] = hit + out[fam][meth] = row + return out + + +# --- negative controls ------------------------------------------------------------------------ + + +def _relabel(groups: Sequence[ce.CandidateGroup], what: str, seed: int) -> list[ce.CandidateGroup]: + rng = random.Random(seed) # noqa: S311 - reproducible research permutation + gs = list(groups) + if what == "time": + pos = [(g.first_position, g.last_position) for g in gs] + rng.shuffle(pos) + return [ + replace(g, first_position=f, last_position=lp) + for g, (f, lp) in zip(gs, pos, strict=True) + ] + if what == "mech": + idx = [i for i, g in enumerate(gs) if g.references] + mechs = [gs[i].mechanisms for i in idx] + rng.shuffle(mechs) + for i, mech in zip(idx, mechs, strict=True): + gs[i] = replace(gs[i], mechanisms=mech) + return gs + raise ValueError(what) + + +def negative_controls(m: int = 1_000) -> dict[str, Any]: + out: dict[str, Any] = {} + for fam in FAMILIES: + sc = scenario(fam, m) + res = ce.build(sc.fixture, cutoff=END) + groups = list(res.groups) + shuffled = list(groups) + random.Random(7).shuffle(shuffled) # noqa: S311 - reproducible research permutation + serial_ok = all( + [g.lookalike for g in ar.order(groups, s)] + == [g.lookalike for g in ar.order(shuffled, s)] + for s in selectors(0).values() + ) + p1 = ar.Selector("P1") + base = [g.lookalike for g in ar.order(groups, p1)] + time_ok = base == [g.lookalike for g in ar.order(_relabel(groups, "time", 3), p1)] + mech_ok = base == [g.lookalike for g in ar.order(_relabel(groups, "mech", 3), p1)] + out[fam] = { + "serialization_invariant": serial_ok, + "P1_time_invariant": time_ok, + "P1_mechanism_invariant": mech_ok, + } + # NC-signer and NC-public-token: add unrelated activity to F7 and compare target ranks + sc = scenario("F7_recent_decoys_other_references", m) + strangers = ["0x" + f"{0x7000000 + i:040x}" for i in range(1_000)] + signer_fx = sc.fixture.model_copy( + update={ + "transfers": list(sc.fixture.transfers) + + [_row(W, s, 10**6, 8_000 + i % 900, ATTACKER, i) for i, s in enumerate(strangers)] + } + ) + public_fx = sc.fixture.model_copy( + update={ + "transfers": list(sc.fixture.transfers) + + [_row(s, W, 0, 8_000 + i % 900, None, i) for i, s in enumerate(strangers)] + } + ) + for name, fx in ( + ("NC_signer_unrelated_links", signer_fx), + ("NC_public_token_strangers", public_fx), + ): + before = run_cell(sc, seeds=(0,)) + after = run_cell(replace(sc, fixture=fx), seeds=(0,)) + out[name] = { + meth: { + "rank_before": before["methods"][meth]["ranks"][0] + if meth not in SEEDED + else before["methods"][meth]["ranks"][0][0], + "rank_after": after["methods"][meth]["ranks"][0] + if meth not in SEEDED + else after["methods"][meth]["ranks"][0][0], + } + for meth in ("B0", "B1", "P1", "B6") + } | {"groups_added": after["groups"] - before["groups"]} + return out + + +def _row(sender: str, recipient: str, value: int, block: int, signer: str | None, i: int) -> Any: + from cryptoguard.replay.models import RecordedTransfer + + h = "0x" + hashlib.sha256(f"nc:{sender}:{recipient}:{value}:{block}:{i}".encode()).hexdigest() + return RecordedTransfer( + token=USDT, + sender=sender, + recipient=recipient, + value=str(value), + block_number=block, + block_hash="0x" + hashlib.sha256(f"b{block}".encode()).hexdigest(), + transaction_hash=h, + transaction_index=5, + log_index=10_000 + i, + tx_sender=signer, + ) + + +# --- learning to rank (archive development split only) -------------------------------------- + +LTR_FEATURES = ("S", "R", "N") + + +def _vec(f: Mapping[str, Any], names: Sequence[str]) -> list[float]: + out: list[float] = [] + for n in names: + if n == "S": + out += [0.0 if f["B0"] is None else float(f["B0"]), 1.0 if f["B0"] is None else 0.0] + elif n == "R": + age = -float(f["T0"]) if f["T0"] is not None else 0.0 + out.append(-math.log1p(max(age, 0.0))) + elif n == "N": + out.append(math.log1p(float(f["T1"] or 0.0))) + return out + + +def _fit( + rows: Sequence[tuple[dict[str, dict[str, Any]], Any]], names: Sequence[str] +) -> tuple[Any, Any, Any]: + import numpy as np + from sklearn.linear_model import LogisticRegression + + raw = np.array([_vec(v, names) for f, _ in rows for v in f.values()]) + mu, sd = raw.mean(axis=0), raw.std(axis=0) + sd[sd == 0] = 1.0 + xs, ys = [], [] + for f, e in rows: + z = {c: (np.array(_vec(v, names)) - mu) / sd for c, v in f.items()} + for c in f: + if c != e.paid: + xs += [z[e.paid] - z[c], z[c] - z[e.paid]] + ys += [1, 0] + model = LogisticRegression(C=1.0, fit_intercept=False, max_iter=2_000, random_state=0) + model.fit(np.array(xs), np.array(ys)) + return model.coef_[0], mu, sd + + +def ltr_study(poisoning_dir: Path) -> tuple[dict[str, Any], dict[str, Scorer]]: + """Pairwise conditional logit on the 12.1 development split (internal temporal 70/30). + The 12.1 test split is dropped before any feature is computed.""" + import numpy as np + + from cryptoguard.ml import lookalike_ranking as lr + + t0 = time.perf_counter() + episodes, excluded = lr.load_episodes(poisoning_dir) + addrs, txs = lr.protected_entities(poisoning_dir) + overlap = lr.protected_overlap(episodes, addrs, txs) + kept = [e for e, o in zip(episodes, overlap, strict=True) if not o] + grp, mode = lr.protocol_groups(kept) + split = lr.temporal_split(kept, grp) + dev = [(e, g) for e, g, s in zip(kept, grp, split, strict=True) if s == "dev"] + load_s = time.perf_counter() - t0 + computed = [(lr.candidate_features(e, lr.View(), None, None), e, g) for e, g in dev] + feats: list[tuple[dict[str, dict[str, Any]], Any, int]] = [ + (f, e, g) for f, e, g in computed if f is not None + ] + start: dict[int, int] = {} + size: dict[int, int] = {} + for _, e, g in feats: + start[g] = min(start.get(g, e.payoff_block), e.payoff_block) + size[g] = size.get(g, 0) + 1 + fit_groups: set[int] = set() + n = 0 + for g in sorted(start, key=lambda g: (start[g], g)): + if n >= 0.7 * len(feats): + break + fit_groups.add(g) + n += size[g] + fit = [(f, e) for f, e, g in feats if g in fit_groups] + val = [(f, e, g) for f, e, g in feats if g not in fit_groups] + models: dict[str, Any] = {} + for name, names in (("M-LTR", LTR_FEATURES), ("M-LTR-noR", ("S", "N"))): + w, mu, sd = _fit(fit, names) + models[name] = (names, w, mu, sd) + + def scores(f: dict[str, dict[str, Any]], method: str) -> dict[str, float] | None: + if method == "random": + return None + if method in ("S", "S_then_R"): + if any(v["B0"] is None for v in f.values()): + return None + if method == "S": + return {c: float(v["B0"]) for c, v in f.items()} + return {c: float(v["B0"]) * 1e9 + float(v["T0"]) for c, v in f.items()} + if method == "R": + return {c: float(v["T0"]) for c, v in f.items()} + names, w, mu, sd = models[method] + return {c: float(((np.array(_vec(v, names)) - mu) / sd) @ w) for c, v in f.items()} + + methods = ("random", "S", "R", "S_then_R", "M-LTR", "M-LTR-noR") + per: dict[str, list[float]] = {m: [] for m in methods} + per_mrr: dict[str, list[float]] = {m: [] for m in methods} + for f, e, _ in val: + for m in methods: + sc = scores(f, m) + per[m].append(lr.top1(sc, e.paid, len(f))) + per_mrr[m].append(lr.mrr(sc, e.paid, len(f))) + gv = [g for _, _, g in val] + comparisons = {} + for m in ("R", "M-LTR", "M-LTR-noR"): + d = [a - b for a, b in zip(per[m], per["S_then_R"], strict=True)] + comparisons[f"{m}_vs_S_then_R"] = lr.paired(d, gv) + d = [a - b for a, b in zip(per["M-LTR"], per["R"], strict=True)] + comparisons["M-LTR_vs_R"] = lr.paired(d, gv) + + def q(xs: list[float]) -> list[float]: + if not xs: + return [] + s = sorted(xs) + return [round(s[int(p * (len(s) - 1))], 3) for p in (0.1, 0.5, 0.9)] + + def dist(rows: Sequence[tuple[dict[str, dict[str, Any]], Any]]) -> dict[str, Any]: + s_vals = [float(v["B0"]) for f, _ in rows for v in f.values() if v["B0"] is not None] + ages = [-float(v["T0"]) for f, _ in rows for v in f.values() if v["T0"] is not None] + n_vals = [float(v["T1"] or 0) for f, _ in rows for v in f.values()] + ks = [float(len(f)) for f, _ in rows] + return { + "S_q10_50_90": q(s_vals), + "age_blocks_q10_50_90": q(ages), + "N_q10_50_90": q(n_vals), + "candidates_q10_50_90": q(ks), + "S_missing_share": round( + sum(1 for f, _ in rows for v in f.values() if v["B0"] is None) + / max(1, sum(len(f) for f, _ in rows)), + 4, + ), + } + + by_k: dict[str, dict[str, Any]] = {} + for (f, _ep, _), i in zip(val, range(len(val)), strict=True): + kb = "2" if len(f) == 2 else "3-5" if len(f) <= 5 else "6+" + row = by_k.setdefault(kb, {"episodes": 0, **{m: 0.0 for m in methods}}) + row["episodes"] += 1 + for m in methods: + row[m] += per[m][i] + for row in by_k.values(): + for m in methods: + row[m] = round(row[m] / row["episodes"], 4) + report = { + "population": "12.1 lookalike-prioritization development split only (source-conditional)", + "group_mode": mode, + "dev_episodes_evaluable": len(feats), + "fit_episodes": len(fit), + "val_episodes": len(val), + "val_groups": len(set(gv)), + "excluded_before": excluded, + "excluded_protected_overlap": sum(overlap), + "test_split_used": False, + "weights": { + name: { + "features": list(names), + "w": [round(float(x), 4) for x in w], + } + for name, (names, w, _, _) in models.items() + }, + "val_top1": {m: round(sum(v) / len(v), 4) for m, v in per.items()}, + "val_mrr": {m: round(sum(v) / len(v), 4) for m, v in per_mrr.items()}, + "comparisons": comparisons, + "shift": {"fit": dist(fit), "val": dist([(f, e) for f, e, _ in val])}, + "val_top1_by_candidate_count": by_k, + "seconds": {"load": round(load_s, 1), "total": round(time.perf_counter() - t0, 1)}, + } + + def make(name: str) -> Scorer: + names, w, mu, sd = models[name] + + def score(g: ce.CandidateGroup, cutoff_block: int) -> float: + f = { + "B0": float(g.affix or 0), + "T0": -float(cutoff_block - g.last_position[0]), + "T1": float(len({r.identity.split(":")[1] for r in g.evidence})), + } + return float(((np.array(_vec(f, names)) - mu) / sd) @ w) + + return score + + return report, {name: make(name) for name in models} + + +# --- development cases (not independent validation) ----------------------------------------- + + +def development_cases( + poisoning_dir: Path, extra: dict[str, Scorer] | None = None +) -> dict[str, Any]: + from cryptoguard.ml import incident_benchmark as ib + + paid = { + c.manifest.case_id: c.manifest.harm.recipient.lower() + for c in ib.load_new_cases() + if c.fixture is not None + } + out: dict[str, Any] = {} + for name, fx, cut in rs.eligible_windows(poisoning_dir): + key = ( + name + if name in paid + else ("scamsniffer-763k-2025-02-20" if "scamsniffer" in name else None) + ) + if key is None or key not in paid: + continue + target = paid[key] + res = ce.build(fx, cutoff=cut) + groups = list(res.groups) + row: dict[str, Any] = { + "label": "development-case analysis, not independent validation", + "groups": len(groups), + "paid_is_candidate": target in {g.lookalike for g in groups}, + "missing_categories": sorted(k for k, v in res.coverage.items() if v != "complete"), + "abstain": res.abstain, + "ranks": {}, + } + for meth, sel in selectors(0).items(): + if meth.startswith("NC"): + continue + ranks = [ + next( + ( + i + 1 + for i, g in enumerate(ar.order(groups, replace(sel, seed=s))) + if g.lookalike == target + ), + None, + ) + for s in (SEEDS if meth in SEEDED else (0,)) + ] + row["ranks"][meth] = ( + ranks[0] + if len(ranks) == 1 + else { + "seed0": ranks[0], + "min": min(r or 10**9 for r in ranks), + "max": max(r or 0 for r in ranks), + } + ) + for meth, score in (extra or {}).items(): + ordered = score_order(groups, score, cut[0]) + row["ranks"][meth] = next( + (i + 1 for i, g in enumerate(ordered) if g.lookalike == target), None + ) + c2 = cd.discover(fx, cutoff=cut, variant="C2").candidates + row["c2_list_rank"] = next((i + 1 for i, c in enumerate(c2) if c.lookalike == target), None) + row["c2_candidates"] = len(c2) + row["c2_note"] = "C2's own candidate set and list order; not the same set as the groups" + out[name] = row + return out + + +# --- performance ------------------------------------------------------------------------------ + + +def performance(sizes: Sequence[int]) -> list[dict[str, Any]]: + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + refs = references() + base_fx = _fixture(refs) + base = cd.observations(base_fx) + out = [] + for n in sizes: + obs = base + [ + cd.Observation( + "native", + "in", + rs.lookalike(i + 1, ref=refs[i % 5]), + 1, + 2_000 + i // 20, + i % 20, + -1, + "0x" + f"{0xB0000000 + i:064x}", + rs.lookalike(i + 1, ref=refs[i % 5]), + False, + None, + True, + ) + for i in range(n) + ] + res = ce.build(base_fx, cutoff=END, observations=obs) + row: dict[str, Any] = {"candidates": n, "groups": len(res.groups)} + for meth in ("B0", "P1"): + sel = ar.Selector(meth) + tracemalloc.start() + t0 = time.perf_counter() + selected = ar.select(res, sel) + sec = time.perf_counter() - t0 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + t1 = time.perf_counter() + summary = ce.summarize(selected, 10) + s_sec = time.perf_counter() - t1 + t2 = time.perf_counter() + pg = ce.page(selected, offset=n // 2, limit=10) + p_sec = time.perf_counter() - t2 + row[meth] = { + "select_seconds": round(sec, 3), + "groups_per_second": round(len(res.groups) / sec) if sec else None, + "select_peak_traced_mib": round(peak / 2**20, 2), + "summary_seconds": round(s_sec, 3), + "summary_bytes": len(json.dumps(summary)), + "page_seconds": round(p_sec, 3), + "page_bytes": len(json.dumps(pg)), + } + peak_rss = peak_rss_bytes() + row["process_peak_rss_mib"] = None if peak_rss is None else round(peak_rss / 2**20, 1) + out.append(row) + del obs, res + return out + + +def free_ram_bytes() -> int | None: + import ctypes + import os + + if os.name == "nt": + + class MemoryStatus(ctypes.Structure): + _fields_ = [ + ("dwLength", ctypes.c_ulong), + ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), + ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), + ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), + ("ullAvailVirtual", ctypes.c_ulonglong), + ("sullAvailExtendedVirtual", ctypes.c_ulonglong), + ] + + st = MemoryStatus() + st.dwLength = ctypes.sizeof(MemoryStatus) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(st)): + return int(st.ullAvailPhys) + return None + try: + for line in Path("/proc/meminfo").read_text().splitlines(): + if line.startswith("MemAvailable:"): + return int(line.split()[1]) * 1024 + except OSError: + return None + return None + + +# --- entry point ------------------------------------------------------------------------------ + + +def main( + poisoning_dir: Path, out: Path, *, ltr: bool = True, perf_max: int = 100_000 +) -> dict[str, Any]: + import subprocess + + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + t0 = time.perf_counter() + free = free_ram_bytes() + try: + git = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + git = None + ltr_report: dict[str, Any] | str = "not run" + scorers: dict[str, Scorer] = {} + if ltr and (poisoning_dir / "archive_subset.sqlite").exists(): + ltr_report, scorers = ltr_study(poisoning_dir) + elif ltr: + ltr_report = "archive subset missing: not trained" + g = grid(extra=scorers) + methods = list(selectors(0)) + list(scorers) + result: dict[str, Any] = { + "study": STUDY_VERSION, + "protocol": "protocol-12.7", + "selector_version": ar.SELECTOR_VERSION, + "evidence_version": ce.EVIDENCE_VERSION, + "git": git, + "rpc_requests": 0, + "preflight_free_ram_mib": None if free is None else round(free / 2**20), + "seeds": list(SEEDS), + "m_grid": list(M_GRID), + "k_grid": list(K_GRID), + "config_hashes": {n: ar.config_hash(s) for n, s in selectors(0).items()}, + "population_labels": { + "grid": "synthetic, controlled adversarial robustness (not real-world recall)", + "ltr": "archive development split, source-conditional", + "development_cases": "development-case analysis, not independent validation", + }, + "summary": summarize_grid(g, methods), + "H2": cell_tgc_check(g), + "H3": h3_check(g), + "H4": h4_check(g), + "attack_curves": attack_curves(g), + "negative_controls": negative_controls(), + "ltr": ltr_report, + "development_cases": development_cases(poisoning_dir, scorers), + "grid": g, + } + sizes = [n for n in (100, 1_000, 10_000, 100_000) if n <= perf_max] + result["performance"] = performance(sizes) + peak = peak_rss_bytes() + result["resources"] = { + "seconds": round(time.perf_counter() - t0, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + } + out.mkdir(parents=True, exist_ok=True) + (out / "adversarial-ranking.json").write_text( + json.dumps(result, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" + ) + return result diff --git a/src/cryptoguard/ml/adversarial_ranking.py b/src/cryptoguard/ml/adversarial_ranking.py new file mode 100644 index 0000000..91f132a --- /dev/null +++ b/src/cryptoguard/ml/adversarial_ranking.py @@ -0,0 +1,237 @@ +"""Research candidate selection under adversarial pressure (protocol 12.7, +``adversarial-selection/1``). Research only: nothing here is read by the detector. + +Generation (``candidate_evidence.build``) and preservation (``page`` / ``group_records``) +are unchanged. This module only **reorders** the groups of one result: every selector +returns a permutation of its input, so no candidate or record is ever added, removed or +duplicated, and the bounded summary shows the first K of that order. + +Features a selector may read, all known before the cutoff: ``bits`` = 4 x affix (the +expected key-search work, in bits, to match that affix of one specific reference), the +reference bucket (``candidate_evidence.bucket_of``), the latest planting position and the +mechanisms. The support level, the missing list and receipt status are never read, and no +selector sees the oracle target of a benchmark. + +The proposed selector **P1, work-weighted group-discounted selection (WGS)**: order each +bucket by bits, then a keyed hash; member j (0-based) gets priority ``bits - lambda * j``; +order globally by priority, then the bucket's best bits, then the hash. With lambda = 4 the +j-th lookalike of the same reference must be one hex character more similar than a +lookalike of another reference to be shown first. P1 never reads time, so planting a newer +decoy buys nothing, and a reference bucket's first member cannot be displaced by any number +of weaker decoys (see ``displacement_bound``). It cannot beat the identifiability limit: +among more than K candidates that are equal in every feature, no ordering guarantees which +K are shown (protocol 12.7, section 3). +""" + +from __future__ import annotations + +import hashlib +import json +import math +import random +from collections.abc import Callable, Sequence +from dataclasses import asdict, dataclass, replace +from typing import Any + +from cryptoguard.ml import candidate_evidence as ce + +SELECTOR_VERSION = "adversarial-selection/1" +METHODS = ( + "B0", # similarity, then recency (the 12.6.1 presentation order) + "B1", # recency, then similarity + "B2", # evidence level first: negative reference only (H5 failed) + "B3", # mechanism round-robin + "B4", # reference round-robin (lambda = infinity, recency ties) + "B5", # cover every reference bucket once, then fill in B0 order + "B6", # B0 with keyed-hash ties instead of recency + "P1", # work-weighted group-discounted selection (proposed) + "random", # negative control: seeded random permutation + "revrec", # negative control: oldest first +) + + +@dataclass(frozen=True) +class Selector: + method: str = "P1" + seed: int = 0 # public here, for reproducibility; a deployment would keep it secret + lam: float = 4.0 # bits per additional member of the same bucket (P1); math.inf allowed + tie: str = "hash" # P1 within-bucket ties: "hash" or "recency" (ablation A-rec) + nosim: bool = False # ablation A-nosim: bits := 0 + nomech: bool = False # ablation A-nomech: every unreferenced candidate in one bucket + + def __post_init__(self) -> None: + if self.method not in METHODS: + raise ValueError(f"unknown method {self.method!r}") + if self.tie not in ("hash", "recency"): + raise ValueError(f"unknown tie rule {self.tie!r}") + if not (self.lam >= 0): + raise ValueError("lam must be >= 0") + + @property + def label(self) -> str: + if self.method != "P1": + return self.method + lam = "inf" if math.isinf(self.lam) else f"{self.lam:g}" + parts = [f"P1[lam={lam}"] + if self.tie != "hash": + parts.append(f"tie={self.tie}") + if self.nosim: + parts.append("nosim") + if self.nomech: + parts.append("nomech") + return ",".join(parts) + "]" + + +def config_hash(sel: Selector) -> str: + payload = {"version": SELECTOR_VERSION, **asdict(sel)} + if math.isinf(sel.lam): + payload["lam"] = "inf" + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:16] + + +# --- features (pre-cutoff only) ------------------------------------------------------------- + + +def bits(g: ce.CandidateGroup) -> int: + """Expected key-search work in bits to produce this affix for one reference.""" + return 4 * (g.affix or 0) + + +def bucket(g: ce.CandidateGroup, *, nomech: bool = False) -> str: + b = ce.bucket_of(g) + return "mech:*" if nomech and b.startswith("mech:") else b + + +def keyed(seed: int, lookalike: str) -> int: + return int(hashlib.sha256(f"{seed}:{lookalike}".encode()).hexdigest()[:16], 16) + + +def _recent(g: ce.CandidateGroup) -> tuple[int, int, int]: + return (-g.last_position[0], -g.last_position[1], -g.last_position[2]) + + +def _old(g: ce.CandidateGroup) -> tuple[int, int, int]: + return g.last_position + + +# --- orders --------------------------------------------------------------------------------- + + +def _round_robin( + buckets: Sequence[Sequence[ce.CandidateGroup]], +) -> list[ce.CandidateGroup]: + out: list[ce.CandidateGroup] = [] + depth = max((len(b) for b in buckets), default=0) + for j in range(depth): + out.extend(b[j] for b in buckets if j < len(b)) + return out + + +def _partition( + groups: Sequence[ce.CandidateGroup], key: Callable[[ce.CandidateGroup], str] +) -> dict[str, list[ce.CandidateGroup]]: + parts: dict[str, list[ce.CandidateGroup]] = {} + for g in groups: + parts.setdefault(key(g), []).append(g) + return parts + + +def order(groups: Sequence[ce.CandidateGroup], sel: Selector) -> list[ce.CandidateGroup]: + """The full order of ``groups`` under ``sel``: always a permutation of the input, + independent of the input's order.""" + gs = sorted(groups, key=lambda g: g.lookalike) # input-order invariance + m = sel.method + if m == "B0": + return sorted(gs, key=ce.presentation_key) + if m == "B1": + return sorted(gs, key=lambda g: (_recent(g), -bits(g), g.lookalike)) + if m == "B2": + return sorted(gs, key=ce.evidence_order_key) + if m == "revrec": + return sorted(gs, key=lambda g: (_old(g), g.lookalike)) + if m == "random": + out = list(gs) + random.Random(sel.seed).shuffle(out) # noqa: S311 - negative control, not security + return out + if m == "B6": + return sorted(gs, key=lambda g: (-bits(g), keyed(sel.seed, g.lookalike), g.lookalike)) + if m in ("B3", "B4", "B5"): + if m == "B3": + parts = _partition(gs, lambda g: "+".join(g.mechanisms)) + else: + parts = _partition(gs, lambda g: bucket(g)) + within = {k: sorted(v, key=ce.presentation_key) for k, v in parts.items()} + if m == "B3": + keys = sorted(within, key=lambda k: (ce.presentation_key(within[k][0]), k)) + else: + keys = sorted(within, key=lambda k: (-bits(within[k][0]), k)) + if m in ("B3", "B4"): + return _round_robin([within[k] for k in keys]) + firsts = sorted((within[k][0] for k in keys), key=ce.presentation_key) + chosen = {id(g) for g in firsts} + rest = sorted((g for g in gs if id(g) not in chosen), key=ce.presentation_key) + return firsts + rest + return _p1(gs, sel) + + +def _p1(gs: Sequence[ce.CandidateGroup], sel: Selector) -> list[ce.CandidateGroup]: + def b(g: ce.CandidateGroup) -> int: + return 0 if sel.nosim else bits(g) + + def tie(g: ce.CandidateGroup) -> tuple[Any, ...]: + if sel.tie == "recency": + return _recent(g) + return (keyed(sel.seed, g.lookalike),) + + parts = _partition(gs, lambda g: bucket(g, nomech=sel.nomech)) + keyed_rows: list[tuple[tuple[Any, ...], ce.CandidateGroup]] = [] + for members in parts.values(): + members.sort(key=lambda g: (-b(g), tie(g), g.lookalike)) + best = b(members[0]) + for j, g in enumerate(members): + if math.isinf(sel.lam): + k: tuple[Any, ...] = (j, -b(g), -best, tie(g), g.lookalike) + else: + k = (-(b(g) - sel.lam * j), -best, tie(g), g.lookalike) + keyed_rows.append((k, g)) + keyed_rows.sort(key=lambda kv: kv[0]) + return [g for _, g in keyed_rows] + + +def select(result: ce.EvidenceResult, sel: Selector) -> ce.EvidenceResult: + """The same result with its groups in ``sel``'s order, labelled with the method and its + configuration hash; summaries and pages then expose that order.""" + ordered = order(result.groups, sel) + if len(ordered) != len(result.groups): # a permutation by construction; checked anyway + raise AssertionError("a selector must return a permutation of its input") + return replace(result, groups=tuple(ordered), order=sel.label, order_config=config_hash(sel)) + + +# --- the provable bound --------------------------------------------------------------------- + + +def displacement_bound( + groups: Sequence[ce.CandidateGroup], target_bucket: str, lam: float, *, nomech: bool = False +) -> int | None: + """Upper bound on the 1-based position of the first member of ``target_bucket`` under + P1 with this ``lam``: 1 + sum over other buckets of the members whose priority can + reach the target bucket's best bits. It does not depend on how many weaker members a + bucket has. None when the bucket is empty or lam is not positive.""" + if not lam > 0: + return None + best: dict[str, int] = {} + size: dict[str, int] = {} + for g in groups: + k = bucket(g, nomech=nomech) + best[k] = max(best.get(k, -1), bits(g)) + size[k] = size.get(k, 0) + 1 + if target_bucket not in best: + return None + b = best[target_bucket] + total = 1 + for k, bk in best.items(): + if k == target_bucket or bk < b: + continue + reach = 1 if math.isinf(lam) else int((bk - b) // lam) + 1 # round j = 0 only at inf + total += min(size[k], reach) + return total diff --git a/src/cryptoguard/ml/candidate_evidence.py b/src/cryptoguard/ml/candidate_evidence.py index d8c0630..0c6a884 100644 --- a/src/cryptoguard/ml/candidate_evidence.py +++ b/src/cryptoguard/ml/candidate_evidence.py @@ -68,6 +68,10 @@ "not a risk score or a probability; the support level is reported separately and never " "moves a candidate up or down" ) +RESEARCH_ORDER_NOTE = ( + "a research selection order (see order and order_config); not a risk score or a " + "probability; the support level is reported separately and never moves a candidate" +) MAX_PAGE = 1_000 # largest page a caller can request MAX_REFERENCES_SHOWN = 3 # per summary item; the full list is in the result DELEGATION_PREFIX = "0xef0100" # EIP-7702 delegation designator @@ -126,6 +130,8 @@ class EvidenceResult: coverage: dict[str, str] absence_inference: bool # whether R-SIG could infer "not signed by the wallet" absence_blocked_by: tuple[str, ...] # why not (empty when allowed) + order: str = "affix_then_recency" # the ordering that produced ``groups`` + order_config: str | None = None # hash of that ordering's configuration (12.7 selectors) def absence_guard( @@ -465,7 +471,9 @@ def evidence_order_key(g: CandidateGroup) -> tuple[int, int, tuple[int, int, int def digest(result: EvidenceResult) -> str: """A content digest of the full result (every group and record identity, in order), so a page can be checked against the result it was cut from.""" - h = hashlib.sha256(f"{result.version}|{result.victim}|{result.cutoff}".encode()) + h = hashlib.sha256( + f"{result.version}|{result.victim}|{result.cutoff}|{result.order}|{result.order_config}".encode() + ) for g in result.groups: h.update(g.identity.encode()) h.update(g.level.encode()) @@ -480,10 +488,30 @@ def _bounded(n: int, name: str) -> int: return n -def _item(g: CandidateGroup, rank: int) -> dict[str, Any]: +def bucket_of(g: CandidateGroup) -> str: + """The reference a group imitates best (ties: the smallest address), or, without a + reference, its mechanism signature. The number of reference buckets is bounded by the + victim's own payments, which an attacker cannot add to.""" + if g.references: + return min(g.references, key=lambda r: (-(r[1] + r[2]), r[0]))[0] + return "mech:" + "+".join(g.mechanisms) + + +def _bucket_sizes(result: EvidenceResult) -> dict[str, int]: + sizes: dict[str, int] = {} + for g in result.groups: + b = bucket_of(g) + sizes[b] = sizes.get(b, 0) + 1 + return sizes + + +def _item(g: CandidateGroup, rank: int, sizes: dict[str, int] | None = None) -> dict[str, Any]: + bucket = bucket_of(g) return { "rank": rank, "identity": g.identity, + "reference_bucket": bucket, + "bucket_size": None if sizes is None else sizes[bucket], "level": g.level, "mechanisms": list(g.mechanisms), "kinds": list(g.kinds), @@ -512,11 +540,13 @@ def summarize(result: EvidenceResult, k: int = 10) -> dict[str, Any]: for m in g.mechanisms: by_mechanism[m] = by_mechanism.get(m, 0) + 1 hidden = len(result.groups) - len(shown) + sizes = _bucket_sizes(result) return { "version": result.version, "cutoff": list(result.cutoff), - "order": "affix_then_recency", - "order_note": ORDER_NOTE, + "order": result.order, + "order_config": result.order_config, + "order_note": ORDER_NOTE if result.order == "affix_then_recency" else RESEARCH_ORDER_NOTE, "result_digest": digest(result), "total_groups": len(result.groups), "raw_events": result.raw_events, @@ -531,7 +561,7 @@ def summarize(result: EvidenceResult, k: int = 10) -> dict[str, Any]: "absence_blocked_by": list(result.absence_blocked_by), "abstain": result.abstain, "note": HIDDEN_NOTE, - "top": [_item(g, i + 1) for i, g in enumerate(shown)], + "top": [_item(g, i + 1, sizes) for i, g in enumerate(shown)], } @@ -553,12 +583,15 @@ def page( raise StaleResultError("the result changed since this digest was issued") items = result.groups[offset : offset + limit] end = offset + len(items) + sizes = _bucket_sizes(result) return { - "items": [_item(g, offset + i + 1) for i, g in enumerate(items)], + "items": [_item(g, offset + i + 1, sizes) for i, g in enumerate(items)], "total": len(result.groups), "limit": limit, "offset": offset, "next_offset": end if end < len(result.groups) else None, + "order": result.order, + "order_config": result.order_config, "result_digest": d, } diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 6692446..cfbeb8e 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,15 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + adv = ml.add_parser( + "adversarial-ranking", + help="Phase 12.7 adversarial candidate exposure and learning-to-rank study (offline)", + ) + adv.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.7") + adv.add_argument( + "--no-ltr", action="store_true", help="skip the archive learning-to-rank study" + ) + adv.add_argument("--perf-max", type=int, default=100_000, help="largest performance population") rs = ml.add_parser( "reliability-study", help="Phase 12.6 signer provenance, evidence groups and spam resilience (offline)", @@ -206,6 +215,18 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "adversarial-ranking": + import json + + from cryptoguard.ml import adversarial_benchmark + + result = adversarial_benchmark.main( + ML_DIR / "poisoning", args.out, ltr=not args.no_ltr, perf_max=args.perf_max + ) + brief = {k: result[k] for k in ("resources",)} | {"H1": result["summary"].get("H1")} + print(json.dumps(brief, indent=1, default=str)) + print(f"Wrote {args.out / 'adversarial-ranking.json'}") + return 0 if args.ml_command == "reliability-study": import json diff --git a/tests/test_ml_adversarial_ranking.py b/tests/test_ml_adversarial_ranking.py new file mode 100644 index 0000000..410dcd3 --- /dev/null +++ b/tests/test_ml_adversarial_ranking.py @@ -0,0 +1,276 @@ +"""Protocol 12.7: research candidate selection under adversarial pressure. Synthetic only; +each expectation follows from a selector's definition, never from a measured outcome.""" + +from __future__ import annotations + +import json +import math +import random +from dataclasses import replace + +import pytest + +from cryptoguard.detectors.poisoning import PoisoningConfig +from cryptoguard.ml import adversarial_benchmark as ab +from cryptoguard.ml import adversarial_ranking as ar +from cryptoguard.ml import candidate_evidence as ce +from cryptoguard.ml import reliability_study as rs +from cryptoguard.replay.engine import Visibility, detector_outputs + +END = rs.END + + +def _groups(family: str, m: int) -> tuple[list[ce.CandidateGroup], ab.Scenario]: + sc = ab.scenario(family, m) + return list(ce.build(sc.fixture, cutoff=END).groups), sc + + +def _rank(ordered: list[ce.CandidateGroup], look: str) -> int: + return next(i + 1 for i, g in enumerate(ordered) if g.lookalike == look) + + +ALL = [ar.Selector(m, seed=3) for m in ar.METHODS] + [ + ar.Selector("P1", lam=math.inf), + ar.Selector("P1", tie="recency"), + ar.Selector("P1", nosim=True), + ar.Selector("P1", nomech=True), +] + + +# --- provable properties ---------------------------------------------------------------------- + + +@pytest.mark.parametrize("sel", ALL, ids=lambda s: s.label) +def test_every_selector_is_a_permutation_and_input_order_invariant(sel: ar.Selector) -> None: + groups, _ = _groups("F9_mixed_mechanisms", 60) + out = ar.order(groups, sel) + assert sorted(g.identity for g in out) == sorted(g.identity for g in groups) + assert len({g.identity for g in out}) == len(out) # no duplicates + shuffled = list(groups) + random.Random(1).shuffle(shuffled) + assert [g.identity for g in ar.order(shuffled, sel)] == [g.identity for g in out] + + +def test_p1_reads_no_time_no_support_level_and_no_missing_list() -> None: + groups, _ = _groups("F7_recent_decoys_other_references", 40) + base = [g.lookalike for g in ar.order(groups, ar.Selector("P1"))] + rng = random.Random(5) + pos = [(g.first_position, g.last_position) for g in groups] + rng.shuffle(pos) + moved = [ + replace(g, first_position=f, last_position=lp, level="partially_supported", missing=("x",)) + for g, (f, lp) in zip(groups, pos, strict=True) + ] + assert [g.lookalike for g in ar.order(moved, ar.Selector("P1"))] == base + + +def test_determinism_and_seed_dependence() -> None: + groups, _ = _groups("F6_equal_similarity_same_reference", 50) + a = [g.lookalike for g in ar.order(groups, ar.Selector("P1", seed=1))] + assert a == [g.lookalike for g in ar.order(groups, ar.Selector("P1", seed=1))] + assert a != [g.lookalike for g in ar.order(groups, ar.Selector("P1", seed=2))] # 51 ties + + +@pytest.mark.parametrize("m", [0, 5, 50, 400]) +@pytest.mark.parametrize("lam", [2.0, 4.0, 8.0, math.inf]) +def test_displacement_bound_holds_and_does_not_grow_with_decoys(m: int, lam: float) -> None: + groups, sc = _groups("F7_recent_decoys_other_references", m) + ordered = ar.order(groups, ar.Selector("P1", lam=lam)) + first = next(i + 1 for i, g in enumerate(ordered) if ce.bucket_of(g) == sc.target_ref) + bound = ar.displacement_bound(groups, sc.target_ref, lam) + assert bound is not None + assert first <= bound + # 4 other buckets with equal best bits: each contributes at most floor(0 / lam) + 1 = 1 + assert bound <= 1 + min(m, 4) + + +def test_bound_is_none_without_a_discount() -> None: + groups, sc = _groups("F7_recent_decoys_other_references", 5) + assert ar.displacement_bound(groups, sc.target_ref, 0.0) is None + assert ar.displacement_bound(groups, "0xnot-a-bucket", 4.0) is None + + +# --- baseline behaviour from the definitions -------------------------------------------------- + + +def test_recent_equal_decoys_bury_the_target_under_b0_but_not_p1() -> None: + groups, sc = _groups("F7_recent_decoys_other_references", 50) + t = sc.relevant[0] + assert _rank(ar.order(groups, ar.Selector("B0")), t) == 51 # recency breaks the tie + assert _rank(ar.order(groups, ar.Selector("B1")), t) == 51 + assert _rank(ar.order(groups, ar.Selector("P1")), t) <= 5 # one per other bucket at most + + +def test_weaker_decoys_never_displace_a_stronger_target() -> None: + for fam in ("F1_native_dust_flood", "F2_fake_token_flood", "F3_zero_value_flood"): + groups, sc = _groups(fam, 200) + t = sc.relevant[0] + assert _rank(ar.order(groups, ar.Selector("B0")), t) == 1 + assert _rank(ar.order(groups, ar.Selector("P1")), t) == 1 + assert _rank(ar.order(groups, ar.Selector("B1")), t) == len(groups) # oldest + + +def test_identifiability_equal_candidates_in_one_bucket() -> None: + groups, sc = _groups("F6_equal_similarity_same_reference", 30) + t = sc.relevant[0] + assert _rank(ar.order(groups, ar.Selector("B0")), t) == 31 # the oldest of 31 equals + ranks = {_rank(ar.order(groups, ar.Selector("P1", seed=s)), t) for s in range(10)} + assert len(ranks) > 1 # a keyed hash spreads it; no seed-free guarantee exists + + +def test_repetition_collapses_into_one_group() -> None: + groups, sc = _groups("F4_repetition_one_address", 300) + assert len(groups) == 2 # one target, one repeated decoy + assert _rank(ar.order(groups, ar.Selector("P1")), sc.relevant[0]) == 2 # 5+5 beats 4+4 + + +def test_reference_buckets_are_bounded_by_the_victims_payments() -> None: + groups, _ = _groups("F5_distinct_equal_lookalikes", 500) + refs = {ce.bucket_of(g) for g in groups if g.references} + assert len(refs) <= 5 + + +def test_relevant_candidates_exist_in_every_family() -> None: + for fam in ab.FAMILIES: + groups, sc = _groups(fam, 10) + looks = {g.lookalike for g in groups} + assert all(r in looks for r in sc.relevant), fam + + +def test_unrelated_strangers_create_only_unreferenced_groups() -> None: + groups, sc = _groups("F15_one_among_unrelated", 200) + referenced = [g for g in groups if g.references] + assert [g.lookalike for g in referenced] == list(sc.relevant) + + +# --- preservation and the summary contract ---------------------------------------------------- + + +def test_selected_result_keeps_every_group_and_reports_its_order() -> None: + sc = ab.scenario("F16_several_relevant_compete", 120) + res = ce.build(sc.fixture, cutoff=END) + sel = ar.Selector("P1") + out = ar.select(res, sel) + assert sorted(g.identity for g in out.groups) == sorted(g.identity for g in res.groups) + s = ce.summarize(out, 5) + assert (s["order"], s["order_config"]) == ("P1[lam=4]", ar.config_hash(sel)) + assert s["total_groups"] == len(res.groups) + assert s["hidden_count"] == len(res.groups) - 5 + assert all(i["bucket_size"] >= 1 for i in s["top"]) + assert ce.digest(out) != ce.digest(res) # the order is part of the fingerprint + seen, offset = [i["identity"] for i in s["top"]], s["next_offset"] + while offset is not None: + pg = ce.page(out, offset=offset, limit=50, expect_digest=s["result_digest"]) + assert pg["order"] == "P1[lam=4]" + seen += [i["identity"] for i in pg["items"]] + offset = pg["next_offset"] + assert seen == [g.identity for g in out.groups] # every relevant one is reachable + + +def test_default_summary_is_unchanged_for_the_default_order() -> None: + sc = ab.scenario("F1_native_dust_flood", 10) + s = ce.summarize(ce.build(sc.fixture, cutoff=END), 3) + assert s["order"] == "affix_then_recency" + assert s["order_config"] is None + assert "not a risk score" in s["order_note"] + + +def test_config_hash_is_stable_and_distinguishes_configs() -> None: + a = ar.config_hash(ar.Selector("P1")) + assert a == ar.config_hash(ar.Selector("P1")) + assert a != ar.config_hash(ar.Selector("P1", lam=8.0)) + assert len(a) == 16 + assert ar.config_hash(ar.Selector("P1", lam=math.inf)) # serializable at infinity + with pytest.raises(ValueError, match="unknown method"): + ar.Selector("nope") + with pytest.raises(ValueError, match="unknown tie"): + ar.Selector("P1", tie="newest") + + +# --- historical correctness ------------------------------------------------------------------- + + +def test_events_after_the_cutoff_never_change_the_selection() -> None: + sc = ab.scenario("F7_recent_decoys_other_references", 20) + later = [ + (rs.lookalike(5_000 + i, prefix=5, suffix=5, ref=rs.REF), 1, 9_500 + i, True) + for i in range(30) + ] + fx = sc.fixture.model_copy( + update={ + "native_inbound": list(sc.fixture.native_inbound) + + [r for r in rs.wallet_fixture(native=later).native_inbound] + } + ) + a = ar.order(list(ce.build(sc.fixture, cutoff=END).groups), ar.Selector("P1")) + b = ar.order(list(ce.build(fx, cutoff=END).groups), ar.Selector("P1")) + assert [g.identity for g in a] == [g.identity for g in b] + + +def test_duplicated_ingestion_does_not_add_candidates() -> None: + sc = ab.scenario("F5_distinct_equal_lookalikes", 30) + dup = sc.fixture.model_copy(update={"native_inbound": list(sc.fixture.native_inbound) * 2}) + assert len(ce.build(dup, cutoff=END).groups) == len(ce.build(sc.fixture, cutoff=END).groups) + + +def test_unknown_evidence_is_kept_not_turned_benign() -> None: + for fam in ("F11_missing_receipt", "F12_partial_history", "F10_unknown_signer"): + sc = ab.scenario(fam, 10) + res = ar.select(ce.build(sc.fixture, cutoff=END), ar.Selector("P1")) + g = next(g for g in res.groups if g.lookalike == sc.relevant[0]) + assert g.missing # still listed as missing + assert g.level in ce.LEVELS + + +# --- metrics and scientific integrity --------------------------------------------------------- + + +def test_metric_denominators() -> None: + assert ab._exposure([1, 7, None], 5) == pytest.approx(1 / 3) + assert ab._exposure([2, 3, 4], 3) == pytest.approx(2 / 3) + cost = ab.attack_cost("F6_equal_similarity_same_reference", 10) + assert cost is not None + assert cost["log2_key_trials"] == pytest.approx(math.log2(10) + 32, abs=0.01) + assert ab.attack_cost("F4_repetition_one_address", 1_000)["addresses"] == 1 # type: ignore[index] + assert ab.attack_cost("F1_native_dust_flood", 0) is None + + +def test_grid_cell_reports_every_method_and_no_bound_violation() -> None: + cell = ab.run_cell(ab.scenario("F16_several_relevant_compete", 30), seeds=(0, 1)) + assert set(ab.selectors(0)) <= set(cell["methods"]) + assert cell["bound_violations"] == {} + assert all(cell["relevant_found"]) + for meth in cell["methods"].values(): + assert all(0.0 <= v <= 1.0 for v in meth["exposure"].values()) + + +def test_ltr_vector_marks_missing_similarity() -> None: + v = ab._vec({"B0": None, "T0": -100.0, "T1": 2.0}, ("S", "R", "N")) + assert v[:2] == [0.0, 1.0] + assert v[2] == pytest.approx(-math.log1p(100.0)) + + +def test_production_detector_is_untouched() -> None: + sc = ab.scenario("F9_mixed_mechanisms", 20) + full = Visibility.ERC20_PLUS_WALLET_TRANSACTIONS + before = detector_outputs(sc.fixture, 9_000, full, PoisoningConfig()) + ar.select(ce.build(sc.fixture, cutoff=END), ar.Selector("P1")) + assert detector_outputs(sc.fixture, 9_000, full, PoisoningConfig()) == before + + +def test_summary_size_stays_bounded_with_selection() -> None: + small = ce.summarize( + ar.select( + ce.build(ab.scenario("F5_distinct_equal_lookalikes", 20).fixture, cutoff=END), + ar.Selector("P1"), + ), + 10, + ) + big = ce.summarize( + ar.select( + ce.build(ab.scenario("F5_distinct_equal_lookalikes", 2_000).fixture, cutoff=END), + ar.Selector("P1"), + ), + 10, + ) + assert abs(len(json.dumps(big)) - len(json.dumps(small))) < 200 From 541c2d292e3c41217d99e788f87b20a4b1c603c8 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 15:01:15 +0300 Subject: [PATCH 77/92] feat(ml): post-hoc design-bias checks for the 12.7 benchmark The pre-registered negative controls flagged two design biases in the grid: oldest-first (NC-revrec) scored 0.986 because targets are always older than their decoys, and mechanism round-robin (B3) scored 0.839 because targets mostly use a different mechanism from their decoys. posthoc_checks() varies those choices as an adaptive attacker would (older decoys, decoys sharing the target's mechanism, the target on each of the five references, a target address that does not sort first) and reruns H4 with 200 seeds. Labelled post hoc and exploratory; the pre-registered results are unchanged. `cryptoguard ml adversarial-ranking --posthoc` writes posthoc-checks.json. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/adversarial_benchmark.py | 101 ++++++++++++++++++++ src/cryptoguard/ml/cli.py | 13 +++ 2 files changed, 114 insertions(+) diff --git a/src/cryptoguard/ml/adversarial_benchmark.py b/src/cryptoguard/ml/adversarial_benchmark.py index beecb96..aec0b5c 100644 --- a/src/cryptoguard/ml/adversarial_benchmark.py +++ b/src/cryptoguard/ml/adversarial_benchmark.py @@ -995,3 +995,104 @@ def main( json.dumps(result, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" ) return result + + +# --- post-hoc checks (added after the negative controls flagged benchmark design bias) ------- + +POSTHOC_METHODS = ("B0", "B3", "B4", "B5", "B6", "P1", "A-laminf", "A-nomech", "NC-revrec") + + +def adaptive_scenario( + m: int, + *, + same_reference: bool = False, + decoy_time: str = "newer", + decoy_mechanism: str = "native", + target_reference: int = 0, + target_index: int = 0, +) -> Scenario: + """F7 (decoys on the other references) or F6 (``same_reference``) with the design + choices the pre-registered grid fixed now varied by an adaptive attacker: decoys older + than the target, decoys sharing the target's mechanism (zero-value spoofs), the target + on any of the five references, and a target address that does not sort first.""" + refs = references() + r_t = refs[target_reference] + t = rs.lookalike(target_index, prefix=4, suffix=4, ref=r_t) + pool = [r_t] if same_reference else [r for r in refs if r != r_t] + decoys = _decoys(m, 4, 4, pool, start=5_000) + + def blk(i: int) -> int: + return 1_600 + i % 400 if decoy_time == "older" else _block(i) + + tr: list[Any] = [(W, t, 0, 2_000, ATTACKER, USDT, 0)] + nat: list[Any] = [] + for i, d in enumerate(decoys): + if decoy_mechanism == "spoof": + tr.append((W, d, 0, blk(i), ATTACKER, USDT, 1 + i % 50)) + else: + nat.append((d, 1, blk(i), True)) + fx = _fixture(refs, transfers=tr, native=nat) + return Scenario("adaptive", m, fx, (t.lower(),), r_t.lower()) + + +def _mean_exposure(cell: dict[str, Any], meth: str) -> float: + vals: dict[int, float] = cell["methods"][meth]["exposure"] + return round(sum(vals.values()) / len(vals), 4) + + +def posthoc_checks(m_grid: Sequence[int] = (10, 100, 1_000)) -> dict[str, Any]: + """Exploratory and post hoc: each variant is averaged over m and K like the grid.""" + variants: dict[str, dict[str, Any]] = { + "F7_as_registered": {}, + "F7_decoys_older": {"decoy_time": "older"}, + "F7_decoys_share_mechanism": {"decoy_mechanism": "spoof"}, + "F7_target_address_not_first": {"target_index": 0x7_777_777}, + "F6_target_address_not_first": {"same_reference": True, "target_index": 0x7_777_777}, + **{f"F7_target_on_R{j + 1}": {"target_reference": j} for j in range(5)}, + } + out: dict[str, Any] = {} + for name, kw in variants.items(): + acc: dict[str, list[float]] = {m: [] for m in POSTHOC_METHODS} + for m in m_grid: + cell = run_cell(adaptive_scenario(m, **kw)) + for meth in POSTHOC_METHODS: + acc[meth].append(_mean_exposure(cell, meth)) + out[name] = {meth: round(sum(v) / len(v), 4) for meth, v in acc.items()} + refs_avg = { + meth: round(sum(out[f"F7_target_on_R{j + 1}"][meth] for j in range(5)) / 5, 4) + for meth in POSTHOC_METHODS + } + out["F7_averaged_over_target_reference"] = refs_avg + # H4 with 200 seeds: is the 10-seed deviation sampling noise? + seeds = tuple(range(200)) + h4 = [] + for m in (10, 100): + sc = scenario("F6_equal_similarity_same_reference", m) + groups = list(ce.build(sc.fixture, cutoff=END).groups) + t = sc.relevant[0] + ranks = [ + next( + i + 1 + for i, g in enumerate(ar.order(groups, ar.Selector("P1", seed=s))) + if g.lookalike == t + ) + for s in seeds + ] + for k in K_GRID: + if m < k: + continue + p = sum(1 for r in ranks if r <= k) / len(ranks) + theory = min(1.0, k / (m + 1)) + se = math.sqrt(theory * (1 - theory) / len(ranks)) + h4.append( + { + "m": m, + "K": k, + "theory": round(theory, 4), + "observed_200_seeds": round(p, 4), + "se": round(se, 4), + } + ) + out["H4_200_seeds"] = h4 + out["label"] = "post hoc, exploratory: added after NC-revrec and B3 scored unexpectedly high" + return out diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index cfbeb8e..0c6bfc4 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -138,6 +138,11 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None "--no-ltr", action="store_true", help="skip the archive learning-to-rank study" ) adv.add_argument("--perf-max", type=int, default=100_000, help="largest performance population") + adv.add_argument( + "--posthoc", + action="store_true", + help="only the post-hoc design-bias checks (writes posthoc-checks.json)", + ) rs = ml.add_parser( "reliability-study", help="Phase 12.6 signer provenance, evidence groups and spam resilience (offline)", @@ -220,6 +225,14 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import adversarial_benchmark + if args.posthoc: + checks = adversarial_benchmark.posthoc_checks() + args.out.mkdir(parents=True, exist_ok=True) + (args.out / "posthoc-checks.json").write_text( + json.dumps(checks, indent=1, sort_keys=True) + "\n", encoding="utf-8" + ) + print(f"Wrote {args.out / 'posthoc-checks.json'}") + return 0 result = adversarial_benchmark.main( ML_DIR / "poisoning", args.out, ltr=not args.no_ltr, perf_max=args.perf_max ) From 0968ff826ee6066dfeea91f084e949cda9672360 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 15:03:28 +0300 Subject: [PATCH 78/92] fix(ml): P1b, bucket-level tie-breaking for the 12.7 selector (post hoc) Debugging the measured run showed a design flaw in the registered P1: ties between bucket leaders use the member's keyed hash, and a flooded bucket's leader is the minimum of many hashes, so a lone target loses almost every tie (rank 5 of 5 tied leaders in 10 of 10 seeds at m >= 100 in F7). P1b breaks those ties with a keyed hash of the bucket, which does not depend on bucket size. P1 stays exactly as registered and reproducible; P1b is a labelled post-hoc amendment evaluated on the same grid. Test pins both behaviours. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/adversarial_benchmark.py | 5 +++-- src/cryptoguard/ml/adversarial_ranking.py | 13 +++++++++---- tests/test_ml_adversarial_ranking.py | 21 +++++++++++++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/cryptoguard/ml/adversarial_benchmark.py b/src/cryptoguard/ml/adversarial_benchmark.py index aec0b5c..f2beef2 100644 --- a/src/cryptoguard/ml/adversarial_benchmark.py +++ b/src/cryptoguard/ml/adversarial_benchmark.py @@ -241,6 +241,7 @@ def selectors(seed: int) -> dict[str, ar.Selector]: "B5": s("B5"), "B6": s("B6", seed=seed), "P1": s("P1", seed=seed), + "P1b": s("P1", seed=seed, bucket_tie=True), # post hoc: bucket-level ties "A-nosim": s("P1", seed=seed, nosim=True), "A-rec": s("P1", seed=seed, tie="recency"), "A-lam2": s("P1", seed=seed, lam=2.0), @@ -253,7 +254,7 @@ def selectors(seed: int) -> dict[str, ar.Selector]: SEEDED = frozenset( - {"B6", "P1", "A-nosim", "A-rec", "A-lam2", "A-lam8", "A-laminf", "A-nomech", "NC-random"} + {"B6", "P1", "P1b", "A-nosim", "A-rec", "A-lam2", "A-lam8", "A-laminf", "A-nomech", "NC-random"} ) # A-lam0 is B6 by definition (lambda = 0: no group discount); it is reported under B6. @@ -999,7 +1000,7 @@ def main( # --- post-hoc checks (added after the negative controls flagged benchmark design bias) ------- -POSTHOC_METHODS = ("B0", "B3", "B4", "B5", "B6", "P1", "A-laminf", "A-nomech", "NC-revrec") +POSTHOC_METHODS = ("B0", "B3", "B4", "B5", "B6", "P1", "P1b", "A-laminf", "A-nomech", "NC-revrec") def adaptive_scenario( diff --git a/src/cryptoguard/ml/adversarial_ranking.py b/src/cryptoguard/ml/adversarial_ranking.py index 91f132a..1ab6a6a 100644 --- a/src/cryptoguard/ml/adversarial_ranking.py +++ b/src/cryptoguard/ml/adversarial_ranking.py @@ -58,6 +58,10 @@ class Selector: tie: str = "hash" # P1 within-bucket ties: "hash" or "recency" (ablation A-rec) nosim: bool = False # ablation A-nosim: bits := 0 nomech: bool = False # ablation A-nomech: every unreferenced candidate in one bucket + # P1b (post hoc): break ties between buckets with a keyed hash of the *bucket*. P1 as + # registered uses the member's hash, and a flooded bucket's leader is the minimum of many + # hashes, so flooding wins ties; a bucket hash is independent of bucket size. + bucket_tie: bool = False def __post_init__(self) -> None: if self.method not in METHODS: @@ -72,7 +76,7 @@ def label(self) -> str: if self.method != "P1": return self.method lam = "inf" if math.isinf(self.lam) else f"{self.lam:g}" - parts = [f"P1[lam={lam}"] + parts = [f"{'P1b' if self.bucket_tie else 'P1'}[lam={lam}"] if self.tie != "hash": parts.append(f"tie={self.tie}") if self.nosim: @@ -185,14 +189,15 @@ def tie(g: ce.CandidateGroup) -> tuple[Any, ...]: parts = _partition(gs, lambda g: bucket(g, nomech=sel.nomech)) keyed_rows: list[tuple[tuple[Any, ...], ce.CandidateGroup]] = [] - for members in parts.values(): + for key, members in parts.items(): members.sort(key=lambda g: (-b(g), tie(g), g.lookalike)) best = b(members[0]) + between: tuple[Any, ...] = (keyed(sel.seed, "bucket:" + key),) if sel.bucket_tie else () for j, g in enumerate(members): if math.isinf(sel.lam): - k: tuple[Any, ...] = (j, -b(g), -best, tie(g), g.lookalike) + k: tuple[Any, ...] = (j, -b(g), -best, *between, tie(g), g.lookalike) else: - k = (-(b(g) - sel.lam * j), -best, tie(g), g.lookalike) + k = (-(b(g) - sel.lam * j), -best, *between, tie(g), g.lookalike) keyed_rows.append((k, g)) keyed_rows.sort(key=lambda kv: kv[0]) return [g for _, g in keyed_rows] diff --git a/tests/test_ml_adversarial_ranking.py b/tests/test_ml_adversarial_ranking.py index 410dcd3..d7f0d95 100644 --- a/tests/test_ml_adversarial_ranking.py +++ b/tests/test_ml_adversarial_ranking.py @@ -274,3 +274,24 @@ def test_summary_size_stays_bounded_with_selection() -> None: 10, ) assert abs(len(json.dumps(big)) - len(json.dumps(small))) < 200 + + +def test_registered_p1_ties_favour_flooded_buckets_and_p1b_does_not() -> None: + """P1 breaks ties between bucket leaders by the member's hash; a flooded bucket's + leader is the minimum of many hashes, so a lone target loses every tie. P1b hashes the + bucket instead, which is independent of how many decoys a bucket holds.""" + groups, sc = _groups("F7_recent_decoys_other_references", 200) + t = sc.relevant[0] + registered = [_rank(ar.order(groups, ar.Selector("P1", seed=s)), t) for s in range(40)] + fixed = [ + _rank(ar.order(groups, ar.Selector("P1", seed=s, bucket_tie=True)), t) for s in range(40) + ] + # Each flooded leader is the minimum of 50 hashes, so the lone target trails all four + # with probability (50/51)^4, about 0.92 (expected about 37 of 40). With bucket hashes + # every position among the five leaders is equally likely (expected 8 of 40 at rank 5). + assert registered.count(5) >= 30 + assert fixed.count(5) <= 20 + assert len(set(fixed)) >= 4 + assert max(fixed) <= 5 # still within the five bucket leaders + assert ar.Selector("P1", bucket_tie=True).label == "P1b[lam=4]" + assert ar.config_hash(ar.Selector("P1", bucket_tie=True)) != ar.config_hash(ar.Selector("P1")) From 2f0a0fcf67ff95885b6c8f4b7f3c4aeda272a00f Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 15:11:36 +0300 Subject: [PATCH 79/92] docs(ml): Phase 12.7 report - adversarial candidate exposure and robust top-K (no RPC) ML_ADVERSARIAL_RANKING.md (35 sections and gate table). Registered results from 7ac195f, reproduced exactly at 0968ff8: H1 supported (P1 0.773 vs B0 0.525 mean Exposure@K, >= B0 in 16/16 families), H2 0/480 cells, bound 0 violations, H3 confirmed, H4 tolerance not met at 10 seeds (200-seed post-hoc check matches K/(m+1)). Negative controls exposed attacker-controllable design biases (oldest-first, mechanism round-robin -> 0.111 post hoc); P1 unaffected. Post-hoc P1b fixes a tie rule that favoured flooded buckets (0.813). LTR on the 12.1 development split learns recency: no gain over recency, -0.169 adversarially (gate G FAIL). Independent validation BLOCKED BY DATA. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + ML_ADVERSARIAL_RANKING.md | 652 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 665 insertions(+) create mode 100644 ML_ADVERSARIAL_RANKING.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bdf212..59c1afa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,19 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.7: adversarial candidate exposure and robust top-K selection (no RPC requests) +- **Protocol 12.7** (`docs/ml/protocol-12.7.md`) was frozen before any selector, benchmark or learning-to-rank code existed. The code was committed before the measured run. +- **`adversarial-selection/1`** (research only): + - baselines B0–B6; + - the proposed **P1**, work-weighted group-discounted selection: priority `4·affix − 4·j` per victim-reference bucket, keyed-hash ties, never reads time, support level or the oracle; + - a provable group displacement bound, independent of decoy count, with 0 violations. +- **Synthetic grid** (16 families × decoys 0–10,000 × K 1–50): **H1 supported.** Mean Exposure@K is 0.773 for P1 vs 0.525 for B0, and P1 is ≥ B0 in 16 of 16 families. +- **Negative controls exposed benchmark design bias.** Oldest-first and mechanism round-robin each fall from about 0.84–0.99 to 0.111 against an adaptive attacker (post hoc); P1 is unaffected. +- **P1b (post hoc):** a flaw in P1's tie rule favoured flooded buckets, so P1b breaks ties by bucket hash instead. It reaches 0.813. +- **Learning to rank** (12.1 development split; test split never computed): +0.289 top-1 over B0, but no gain over recency alone (+0.029, CI includes 0), and −0.169 adversarially. Gate G **FAIL**. +- **Summary:** now carries the order label, config hash and reference-bucket sizes; still bounded at about 7.7 KB for 100,000 candidates. P1 orders 100,000 groups in 3.8 s. +- **Report:** `ML_ADVERSARIAL_RANKING.md`. Independent validation is BLOCKED BY DATA. + ### Phase 12.6.1: signer-recovery safety, bounded summaries, research reliability (no RPC requests) - **Correction:** R-SIG proves only that the wallet did not directly sign a transaction, never that it did not authorize the movement (an allowance, a permit or an EIP-7702 delegation). A value-moving foreign-signed transfer is now `foreign_initiated_out` with `authorization = unknown`; only zero-value ones are `spoofed_out`. On the real windows, 6 value-moving untrusted-token events are relabelled, the groups and levels are unchanged, and C1 still makes 6 such spoof claims. - **`absence_guard`:** the absence inference requires a complete, count-consistent, nonce-contiguous signed set, and code `0x` at every sample up to the cutoff (no EIP-7702 designator or contract code). Otherwise the signer stays unknown. 20 conditions are tested. The rule still agrees 18 of 18 on the real windows. diff --git a/ML_ADVERSARIAL_RANKING.md b/ML_ADVERSARIAL_RANKING.md new file mode 100644 index 0000000..aca238c --- /dev/null +++ b/ML_ADVERSARIAL_RANKING.md @@ -0,0 +1,652 @@ +# Adversarial candidate ranking and robust top-K exposure (Phase 12.7) + +| Item | Value | +|---|---| +| Protocol (frozen first) | [`docs/ml/protocol-12.7.md`](docs/ml/protocol-12.7.md), `9263dba` | +| Code (committed before the measured run) | `7ac195f` (`adversarial-selection/1`, `adversarial-ranking-study/1`) | +| Post-hoc additions (labelled throughout) | `541c2d2` (design-bias checks), `0968ff8` (P1b tie fix) | +| Measured runs | `7ac195f` (registered), then `0968ff8` (adds P1b and post-hoc checks). The rerun reproduces every registered number exactly. | +| Study output (git-ignored) | `data/ml/research/phase12.7/adversarial-ranking.json`, `posthoc-checks.json` (`cryptoguard ml adversarial-ranking [--posthoc]`) | +| RPC requests / downloads | **0** / none | + +**Population labels used in every table:** +- **[SYN]:** synthetic, controlled adversarial robustness. Not real-world recall. +- **[ARCH-DEV]:** the 12.1 archive development split. Source-conditional. +- **[DEV-CASE]:** the two known incidents. Development-case analysis, not independent + validation. +- **[POST-HOC]:** added after seeing results. Exploratory. + +## 1. Executive summary + +**The problem.** The 12.6.1 presentation order (B0: similarity, then recency) is cheap to +manipulate whenever decoys match the target's similarity. Recency is free for an attacker to +set, so newer equal-affix decoys bury an older target. + +**The proposed selector, P1: work-weighted, group-discounted selection.** +- **Grouping:** candidates are grouped by the victim reference they imitate. +- **Priority:** each one gets `4·affix − 4·j`. The affix term is the key-search work in bits; + j is the candidate's 0-based rank within its group. +- **Never read:** time, the support level, and the target. +- **Provable bound:** a reference group's first member cannot be displaced by any number of + weaker decoys, and its worst position is bounded independently of the decoy count. + +**Pre-registered result [SYN], H1 supported:** + +| | Mean Exposure@K (16 families × 5 decoy counts × 6 K) | +|---|---| +| **P1** | **0.773** | +| B0 | 0.525 | +| Recency first (B1) | 0.304 | + +P1 is ≥ B0 in 16 of 16 families and worse in none. + +**Pre-registered checks:** +- **H2:** P1 never covers the target's group less often than B0, in 0 of 480 cells. The bound + held in every cell (0 violations). +- **H3:** recency-first is defeated by m ≥ K newer decoys of any affix, while B0 and P1 keep a + stronger target at rank 1 for every m up to 10,000. + +**What the negative controls caught [POST-HOC].** +- "Oldest first" (0.986) and mechanism round-robin B3 (0.839) scored above P1. Both + exploited benchmark choices the attacker controls. When an adaptive attacker plants decoys + older than the target, or gives them the target's mechanism, each falls to 0.111. +- P1 is unaffected by either. +- Debugging also exposed a **P1 design flaw**: its between-group ties favoured flooded + groups. +- **P1b** breaks those ties with a hash of the group. It reaches **0.813** and is ≥ B0 in + 16 of 16 families, but it is post hoc. + +**Limits that no method beats [SYN].** +- Among more than K candidates equal in every feature, nothing guarantees exposure. P1's + observed exposure matches the theoretical K/(m+1) (200-seed check), so an equal-affix flood + of the *same* reference still hides the target's address. +- That flood does not hide the reference itself: the group stays visible, with its size. + +**Machine learning [ARCH-DEV] does not add robust value (gate G FAIL).** +- A pairwise logistic ranker on the 12.1 development split beats similarity-then-recency by + +0.289 top-1 [0.207, 0.371]. +- It does no better than recency alone (+0.029 [−0.011, 0.070]): it learned recency (weight + 2.42). +- On the adversarial benchmark it reaches 0.356, below B0. The feature real victims follow + (recency) is the one attackers control. + +**Development cases [DEV-CASE]** add no evidence either way. +- **ScamSniffer blind `/2`:** the paid address is rank 1 under B0, P1 and P1b. +- **Pilot:** rank 3 under B0, and 3 to 5 under P1/P1b depending on the seed. +- These cases are not validation. + +**Classification:** +- a controlled-robustness improvement with a proven bound; +- a negative ML result; +- an explicit identifiability limit. + +**Independent validation: BLOCKED BY DATA.** + +## 2. Research questions + +| # | Question | Answer here | +|---|---|---| +| 1 | Cheap features | Recency, mechanism, repetition and value: §5–6 | +| 2 | Independent information | Affix work (attacker-costly); the reference bucket (victim-controlled) | +| 3 | When recency fails | Whenever m ≥ K newer decoys exist, at any affix (H3) | +| 4 | When similarity fails | Equal-affix decoys plus a recency tie-break (B0 in F5–F13) | +| 5 | Mechanism diversity | Only while decoys use a different mechanism ([POST-HOC]: 0.833 → 0.111) | +| 6 | Grouping | Reference grouping carries the gain (ablation: −0.196 without it) | +| 7 | Temporal / graph | Temporal is attacker-controlled; no graph context exists for these windows | +| 8 | Robust optimization | The group-discounted priority is the constrained form (§10, §14) | +| 9 | Unavoidable limits | Same-bucket equal floods: exposure ≈ K/(m+1) (§7) | +| 10 | Uncertainty | Bucket size, hidden count and the order label in the summary (§26) | + +## 3. Existing ranking limitations + +| Order | Weakness | Evidence | +|---|---|---| +| B0 (12.6.1) | recency ties | F7: the target goes from rank 1 to rank m+1 with 10 newer equal decoys | +| B1 | everything newer wins | F1: rank 10,001 with 10,000 weak dust decoys | +| B2 | support first | H5 (12.6); 0.531 here | + +## 4. Formal threat model (protocol §2) + +**The attacker controls:** +- lookalike addresses, up to a compute budget; +- planting time; +- repetitions, values and mechanisms (native dust, fake-token logs, zero-value + `transferFrom`); +- how many addresses to use. + +**The attacker does not control:** +- the victim's references, and so the number of reference buckets; +- the victim's signatures; +- finalized order and observed provenance. + +## 5. Attacker capabilities + +| Capability | Cost model | +|---|---| +| Lookalike with affix p+s of one specific reference | 2^(4(p+s)) expected key trials (uniform hex). Matching any of R references divides this by R. Checksum-case or fuzzy similarity are not modelled. | +| Event spam from an existing address | gas only (illustrative: native 21,000; zero-value ERC-20 about 40,000; fake-token log about 45,000) | +| Timing | free (any block before the cutoff) | +| Mechanism | free choice among the above | + +## 6. Attacker budgets used [SYN] + +| Family | Decoy affix (bits) | Cost of m = 10,000 (log2 trials; gas) | +|---|---|---| +| F1–F3 | 3+3 (24) | 37.3; 210 M / 450 M / 400 M | +| F5, F7, F9–F14 | 4+4 (32) | 45.3; 210 M | +| F4 | one 5+5 address (40), repeated | 40.0; 210 M | +| F6, F8, F16 | 4+4 (32), one reference | 45.3; 210 M | + +**Illustrative throughput:** at 10⁹ keys per second, 2^32 trials take about 4 s and 2^40 +about 18 min. Any real GPU budget will differ. The 2^40 figure applies only to a 5+5 match +of one reference, so no single work factor is assumed. + +## 7. Identifiability limitations + +- **L1 (any deterministic tie rule the attacker knows):** m ≥ K equal decoys can occupy every + slot. + - B0 in F6: Exposure@K = 0 whenever m ≥ K (H4 rows, all 0). +- **L2 (keyed hash):** expected exposure is min(1, K/(m+1)). + - **The pre-registered tolerance failed:** P1 was within ±0.10 of theory in 19 of 22 rows + with 10 seeds. The misses were m=10, K=3 (0.40 vs 0.27), m=10, K=5 (0.60 vs 0.45) and + m=100, K=50 (0.70 vs 0.50). + - **[POST-HOC] With 200 seeds** every row is within 1.0 SE. The largest gap is m=100, K=20: + 0.225 vs 0.198, SE 0.028. So the misses were sampling noise at n = 10, but H4 as worded + is recorded as **not met**. +- **L3:** the target's *bucket* stays visible (§11 property 4), with the bucket size shown. +- **L4:** pagination preserves everything, but preservation is not exposure. + +## 8. The candidate-exposure problem + +The five stages are separate in the code: + +| Stage | Implemented by | +|---|---| +| Generation | `candidate_evidence.build` (unchanged) | +| Scoring and ranking | `adversarial_ranking.order` / `select` | +| Exposure | `summarize`'s top K | +| Preservation | `page`, `group_records` | + +`select` returns a labelled permutation: the method label and a config hash. The result +digest covers the order. + +## 9. Baseline methods (identical candidate sets) + +B0 similarity → recency; B1 recency → similarity; B2 level first; B3 mechanism +round-robin; B4 reference round-robin (λ = ∞, recency within); B5 cover-then-fill; +B6 B0 with keyed-hash ties. B7 (temporal anomaly) is B1, by Phase 12.5's equivalence (MAD ≡ +recency on 1,056 of 1,056 episodes). There is no graph context for these windows. + +## 10. The new selection algorithm + +**P1 (registered).** For each reference bucket (or mechanism bucket, for unreferenced +candidates): +1. sort the members by bits ↓, then the keyed hash; +2. give member j the priority π = bits − λ·j, with λ = 4; +3. order globally by π ↓, then the bucket's best bits ↓, then the member's hash. + +λ was fixed a priori: one hex character of key-search work per additional member of the same +bucket. The cost is O(n log n). + +**P1b [POST-HOC].** P1 with the cross-bucket tie broken by `hash(seed, bucket)` instead of +the member's hash. +- **Why:** a flooded bucket's leader is the minimum of many member hashes, so P1 handed + flooded buckets almost every tie. In F7 at m ≥ 100 the lone target was 5th of the 5 tied + leaders in 10 of 10 seeds. +- **Theory:** the lone target trails all four flooded leaders with probability about 0.92. + `test_registered_p1_ties_favour_flooded_buckets_and_p1b_does_not` checks it. + +## 11. Mathematical properties + +**Provable, and tested:** +1. Every selector returns a permutation: nothing added, removed or duplicated (14 selectors). +2. It is deterministic for fixed input and seed, and invariant to input order (NC-serial, + all 16 families). +3. P1 reads no time, no level, no `missing` and no oracle (NC-time and NC-mech invariance in + all 16 families; the `replace` test). +4. **Bucket displacement bound:** + - the first member of bucket T sits at a position ≤ 1 + Σ over other buckets g of + min(n_g, ⌊(best_g − best_T)/λ⌋ + 1), counting only buckets with best_g ≥ best_T; + - at λ = ∞, each such bucket contributes at most 1; + - **the bound does not depend on the number of weaker decoys;** + - **0 violations** across the grid and in the tests. +5. A duplicate observation does not add a candidate (build deduplication, tested). + +**Empirical [SYN]:** §14–21. + +**Unsupported:** +- a malicious candidate guaranteed in the top K; +- resistance to unlimited equal-affix addresses; +- any real-world recall, false-positive rate or loss reduction. + +## 12. Synthetic benchmark design [SYN] + +- **Scenarios:** 16 families × m ∈ {0, 10, 100, 1,000, 10,000} × K ∈ {1, 3, 5, 10, 20, 50}, + with 10 seeds for hash methods. +- **Victim:** 5 genuine references. +- **Targets:** defined by construction and never read by any selector. +- **Definitions:** protocol §5. +- **Design choices the attacker could vary:** decoys newer than targets, decoys using a + different mechanism, the target always on R1 with a low address. §20 tests these. + +## 13. Primary robustness metrics + +| Metric | Definition | +|---|---| +| Exposure@K | rank ≤ K, averaged over relevant candidates and seeds | +| TGC@K | the target's best-reference bucket appears in the top K | +| Displacement / attack cost | the smallest m in the grid with median first-relevant rank > K | +| Preservation | the order is a permutation (§11.1) | + +Synthetic Exposure@K is not recall. Group coverage is not threat coverage. + +## 14. Top-K results [SYN] + +**Mean Exposure@K over every family and decoy count:** + +| Method | K=1 | K=3 | K=5 | K=10 | K=20 | K=50 | Mean | Mean TGC | +|---|---|---|---|---|---|---|---|---| +| B0 | 0.400 | 0.500 | 0.500 | 0.500 | 0.625 | 0.625 | 0.525 | 0.650 | +| B1 | 0.183 | 0.250 | 0.250 | 0.263 | 0.438 | 0.438 | 0.304 | 0.504 | +| B2 | | | | | | | 0.531 | 0.656 | +| B3 | | | | | | | 0.839 | 0.877 | +| B4 | | | | | | | 0.801 | 0.915 | +| B5 | | | | | | | 0.751 | 0.865 | +| B6 | 0.401 | 0.523 | 0.579 | 0.620 | 0.629 | 0.710 | 0.577 | 0.694 | +| **P1** | 0.401 | 0.583 | 0.898 | 0.907 | 0.915 | 0.932 | **0.773** | 0.875 | +| P1b [POST-HOC] | 0.499 | 0.725 | 0.898 | 0.907 | 0.915 | 0.932 | 0.813 | 0.908 | +| NC-random | | | | | | | 0.387 | 0.581 | +| NC-revrec | | | | | | | 0.986 | 1.000 | + +**H1 (registered):** +- P1 − B0 = **+0.248**; +- P1 ≥ B0 in **16 of 16** families; +- worst family difference **0.000**. + +**Supported.** Section 20 explains why B3, B4 and NC-revrec above P1 are not robustness. + +**Per family (mean over m and K):** + +| Family | B0 | B1 | B4 | B5 | B6 | P1 | P1b | +|---|---|---|---|---|---|---|---| +| F1 native dust (3+3) | 1.000 | 0.267 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 | +| F2 fake token (3+3) | 1.000 | 0.267 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 | +| F3 zero value (3+3) | 1.000 | 0.267 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 | +| F4 repetition (one 5+5) | 0.867 | 0.867 | 0.867 | 0.867 | 0.867 | 0.867 | 0.867 | +| F5 equal, all references | 0.267 | 0.267 | 0.267 | 0.267 | 0.357 | 0.333 | 0.337 | +| F6 equal, same reference | 0.267 | 0.267 | 0.267 | 0.267 | 0.360 | 0.360 | 0.360 | +| F7 recent, other references | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F8 reference overlap | 0.267 | 0.267 | 0.867 | 0.867 | 0.363 | 0.870 | 0.947 | +| F9 mixed mechanisms | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F10 unknown signer | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F11 missing receipt | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F12 partial history | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F13 contract-mediated | 0.267 | 0.267 | 0.867 | 0.733 | 0.350 | 0.737 | 0.827 | +| F14 one campaign, 3 relevant | 0.889 | 0.244 | 0.667 | 0.711 | 0.889 | 0.889 | 0.889 | +| F15 one among unrelated | 1.000 | 0.300 | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 | +| F16 3 relevant compete | 0.244 | 0.244 | 0.689 | 0.645 | 0.294 | 0.625 | 0.642 | + +**Reading the table:** +- **F10–F13:** missing signer, missing receipt, partial history and value-moving pulls give + results identical to F7. Missing evidence never moves a candidate (gate H). +- **Low m:** 0.267 corresponds to exposure only at m = 0 and at the m < K cells. + +## 15. Attack-cost curves [SYN] + +The smallest decoy count m in the grid that pushes the (median-seed) first relevant candidate +past K. "—" means it was never displaced up to 10,000. + +| Family / method | K=1 | K=3 | K=5 | K=10 | K=20 | K=50 | +|---|---|---|---|---|---|---| +| F7 B0 | 10 | 10 | 10 | 10 | 100 | 100 | +| F7 B1 | 10 | 10 | 10 | 10 | 100 | 100 | +| F7 B6 | 10 | 10 | 100 | 100 | 100 | 1,000 | +| F7 **P1** | 10 | 10 | **—** | **—** | **—** | **—** | +| F6 B0 | 10 | 10 | 10 | 10 | 100 | 100 | +| F6 P1 | 10 | 10 | 100 | 100 | 100 | 1,000 | +| F1 B0 / B6 / P1 | — | — | — | — | — | — | +| F1 B1 | 10 | 10 | 10 | 10 | 100 | 100 | + +**Cost in F7:** 10 decoys at 4+4 on other references cost about 2^35.3 key trials and +210,000 gas. +- **Under B0** this is enough at K ≤ 10. +- **Under P1** no budget in the grid (up to 10,000 decoys, about 2^45.3 trials) displaces + the target past K = 5. The target competes only with the 4 other buckets' leaders. + +**F6** is the identifiability family. Every method is displaced at roughly m ≈ K or 2K. + +## 16. Temporal robustness [SYN] + +- **H3 holds exactly:** in F1–F3, B0 and P1 are rank 1 at every m, while B1 is rank m+1. +- **[POST-HOC] decoys older than the target (F7 variant, mean over m ∈ {10, 100, 1,000}):** + + | Method | Exposure | + |---|---| + | B0 | 0.111 → 1.000 | + | NC-revrec | 1.000 → 0.111 | + | P1 | 0.695 (unchanged) | + | P1b | 0.783 (unchanged) | + + B0's result therefore depends entirely on the attacker's choice of timing. P1's does not. +- **Same block:** decoys in one block are handled by the 12.6.1 suite. P1 never reads + position. + +## 17. Similarity robustness [SYN] + +| Scenario | Result | +|---|---| +| Weaker affixes (F1–F3, 24 bits vs the target's 32) | never displace the target | +| Equal affixes on other references (F7) | P1 keeps the target within the first 5 (bound 1 + 4) | +| Equal affixes on the same reference (F6) | identifiability limit, ≈ K/(m+1) | +| Overlapping references (F8) | P1 0.870, P1b 0.947 vs B0 0.267. The decoys bucket under R2 (their best match), so R1's candidate keeps its own bucket. | +| One stronger repeated address (F4, 5+5) | collapses to 1 group. Everyone is rank 2 at m > 0. | + +## 18. Mechanism diversity + +- **B3 (mechanism round-robin)** scored 0.839 in the grid. +- **[POST-HOC]:** when the F7 decoys use the target's own mechanism (zero-value spoofs), B3 + falls to **0.111**. P1 stays at 0.695 and P1b at 0.783. +- **Conclusion:** mechanism is attacker-chosen, so mechanism diversity is not a robust + exposure rule. +- **P1's mechanism buckets** (for unreferenced candidates) changed nothing: A-nomech is + identical to P1, 0.7727. + +## 19. Historical-recipient grouping + +- **Grouping is what carries the gain.** B6 (λ = 0, no grouping) reaches 0.577; P1 reaches + 0.773. +- **Strict round-robin** (B4, or A-λ∞ at 0.762) hurts when one campaign has several strong + candidates on one reference. In F14 it scores 0.667, against 0.889 for B0, P1 and P1b. The + finite λ = 4 avoids that loss (H5: no loss). +- **B4's advantage over P1 in F7–F13 is an artifact.** B4 breaks bucket ties by reference + address, and R1 happens to sort 3rd of 5. [POST-HOC] Averaged over the five possible target + references: + + | Method | Exposure | + |---|---| + | B4 | 0.800 (0.667–1.000 depending on the reference) | + | P1b | 0.800 | + | P1 | 0.687 | + +- **H2 (P1):** TGC ≥ B0 in every cell (0 of 480 below). +- **P1b [POST-HOC]** is below B0 in 4 cells, all F16 at K = 1. There a single slot goes to + a tie between the flooded bucket and R2, which holds another relevant candidate. B0 "covers" + the target's bucket there only because the flood itself sits in it. F16's relevant exposure + is still 0.642 for P1b vs 0.244 for B0. + +## 20. Negative controls + +| Control | Result | Interpretation | +|---|---|---| +| NC-random | 0.387 | about K/n | +| NC-revrec (oldest first) | **0.986** | **design bias:** every target is older than its decoys. [POST-HOC] It falls to 0.111 with older decoys. | +| B3 high | 0.839 | design bias (mechanism); falls to 0.111 (§18) | +| Address order | M-LTR-noR scores 1.000 on F6 | the target's address sorts first among equals, and address is its final tie-break. [POST-HOC] With a non-first address, F6 gives B0/B4/B5 0.111 and P1/P1b 0.295. | +| NC-serial | identical order, all methods, all families | | +| NC-time / NC-mech (P1) | identical, all families | | +| NC-signer (1,000 unrelated foreign-signed pulls) | P1 rank 5 → 5, B0 1,001 → 1,001, B1 1,001 → 2,001 | adds 1,000 unreferenced groups | +| NC-public-token (1,000 zero-value strangers) | same as above | same | + +**Every control that looked too good was traced to a benchmark choice an adaptive attacker +controls.** P1 and P1b were insensitive to each such choice. + +## 21. Ablation study [SYN] (mean Exposure@K) + +| Variant | Mean | Δ vs P1 | +|---|---|---| +| P1 | 0.7727 | — | +| A-nosim (no affix) | 0.6272 | −0.146 | +| B6 = A-λ0 (no reference grouping) | 0.5769 | −0.196 | +| A-λ2 | 0.7701 | −0.003 | +| A-λ8 | 0.7672 | −0.006 | +| A-λ∞ | 0.7615 | −0.011 | +| A-rec (recency ties within a bucket) | 0.7597 | −0.013 | +| A-nomech | 0.7727 | 0.000 | +| P1b (bucket ties) [POST-HOC] | 0.8126 | +0.040 | + +**What contributes:** +- reference grouping, together with affix work; +- λ is insensitive between 2 and 8; +- mechanism bucketing adds nothing. + +**H6:** no simpler variant matched P1 within 0.01 except A-nomech. The simpler equivalent, +one unreferenced bucket, is therefore preferred. + +**Not ablated:** +- coverage metadata: never ranked, so identical by construction; +- graph context: NOT EVALUATED, none exists. + +## 22. ML feasibility [ARCH-DEV] + +**Feasibility rule:** passed. +- 640 evaluable development episodes, 185 validation groups, real payoff labels; +- temporal internal split: 448 fit / 192 validation; +- 1 protected-overlap episode excluded; +- **the 12.1 test split was dropped before feature computation.** + +**Weights (standardized):** + +| Model | S | S missing | R | N | +|---|---|---|---|---| +| M-LTR | 0.129 | 0 | **2.417** | 0.214 | +| M-LTR-noR | 0.389 | 0 | — | 0.363 | + +**Validation:** + +| Method | Top-1 | MRR | +|---|---|---| +| Random | 0.211 | 0.423 | +| S (similarity) | 0.340 | 0.540 | +| S then R (= B0) | 0.461 | 0.642 | +| R (recency) | 0.721 | 0.838 | +| **M-LTR** | **0.750** | **0.859** | +| M-LTR-noR | 0.456 | 0.636 | + +**Paired comparisons (group bootstrap; group sign-flip p):** +- M-LTR vs B0: **+0.289 [0.207, 0.371], p < 0.001**; +- M-LTR vs R: **+0.029 [−0.011, 0.070], p = 0.25**; +- M-LTR-noR vs B0: −0.005 [−0.073, 0.068]. + +**Adversarial transfer [SYN], mean Exposure@K:** + +| Model | Exposure | vs B0 (0.525) | +|---|---|---| +| M-LTR | 0.356 | **−0.169** | +| M-LTR-noR | 0.661 | — | + +M-LTR-noR's figure includes the address-order artifact of §20. + +**Gate G: FAIL.** +- Criterion 1 holds: the gain over B0 has a CI that excludes 0. +- Criterion 2 fails: −0.169, against the 0.05 allowed. +- The model learned recency, the feature real victims follow and attackers control. It adds + nothing over recency alone. + +## 23. Source-shift analysis [ARCH-DEV] + +| Fit vs validation | Fit | Validation | +|---|---|---| +| Age of last planting (blocks) | q10 5,713 / q50 151,746 / q90 517,934 | 34,712 / 555,903 / 1,033,679 | +| Candidates per episode | 2 / 4 / 15 | 2 / 6 / 29 | +| S (affix) | 7 / 8 / 10 | 7 / 8 / 14 | + +**Validation top-1 by candidate count:** + +| Candidates | M-LTR | R | B0 | +|---|---|---|---| +| 2 (n = 33) | 0.939 | 0.924 | 0.727 | +| 3–5 (n = 53) | 0.793 | 0.830 | 0.594 | +| 6+ (n = 106) | 0.670 | 0.604 | 0.311 | + +The validation period has older plantings and larger candidate pools. Recency still holds +there, so the archive does not reproduce the Phase 12.5 failure mode. It is a +non-adversarial population: attackers were not gaming a ranker. + +## 24. Existing incident regressions [DEV-CASE] + +Rank of the paid lookalike, at the existing cutoffs: + +| Window | Groups | B0 | B1 | B2 | B6 | P1 | P1b | M-LTR | M-LTR-noR | C2 list (own set) | +|---|---|---|---|---|---|---|---|---|---|---| +| ScamSniffer `/1` | 2 | not a candidate | — | — | — | — | — | — | — | not listed | +| ScamSniffer blind `/2` | 3 | 1 | 3 | 1 | 1 | 1 | 1 | 2 | 1 | 1 of 3 | +| Pilot | 6 | 3 | 2 | 2 | 3–5 | 3–5 (seed 0: 5) | 3–5 | 2 | 2 | 5 of 6 | + +**Notes:** +- In ScamSniffer `/1` the paid native dust was never recorded (the Phase 12.3/12.4 finding). +- On the pilot, P1 and P1b are seed-dependent. Seed 0 puts the paid address 5th, worse than + B0's 3rd, because the paid address ties with other lookalikes. +- **No method was tuned on these cases. Development-case analysis, not independent + validation.** + +## 25. Evidence completeness + +Selectors never read `level`, `missing` or `receipt`. F10–F13 (missing signer, missing +receipt, partial history, value-moving pulls) behave identically to F7. Unknown evidence stays +listed in each group (tested). **Gate H: PASS.** + +## 26. Candidate preservation + +**Every selector is a permutation** (tested across 14 selectors). The summary keeps the +12.6.1 contract and adds: +- `order`, the method label (e.g. `P1[lam=4]`); +- `order_config`, a 16-hex config hash; +- each item's `reference_bucket` and `bucket_size`. + +**Pages and the digest:** +- pages carry the order; +- the digest covers the order; +- a test pages through a P1-ordered result and reaches every group. + +**Display:** an equal-affix flood shows "1 of N candidates imitating R" rather than hiding R. + +## 27. Runtime (selection only, on top of evidence groups; run on `0968ff8`) + +| Groups | B0 | P1 | P1 groups/s | Summary JSON | Page JSON | +|---|---|---|---|---|---| +| 100 | <0.001 s | 0.002 s | 41,533 | 7.6 KB | 7.1 KB | +| 1,000 | 0.003 s | 0.025 s | 39,277 | 7.7 KB | 7.1 KB | +| 10,000 | 0.055 s | 0.341 s | 29,327 | 7.7 KB | 7.2 KB | +| 100,000 | 0.583 s | 3.83 s | 26,140 | 7.7 KB | 7.2 KB | + +- **Why P1 is slower:** it hashes every candidate (SHA-256). It is still O(n log n). +- **Whole study:** 196 s on `0968ff8`, 245 s on `7ac195f`. +- **Learning to rank:** archive load 30 s, total 70 s. + +## 28. Memory + +- **P1 selection:** 29.3 MiB traced at 100,000 groups (B0: 23.2 MiB). +- **Process peak RSS:** 432 MiB for the whole study. +- **Preflight free RAM:** 1,320 MiB (`7ac195f`) and 1,247 MiB (`0968ff8`). + +## 29. Production isolation + +- The detector is unchanged (`detector_outputs` is identical before and after selection, + tested). +- The selectors are reachable only through `cryptoguard ml adversarial-ranking`. +- No new dependency. scikit-learn is used only in the archive LTR, lazily imported. +- No finding is suppressed and no severity is changed. **Gate J: PASS.** + +## 30. Statistical limitations + +- **[SYN]:** deterministic, with no sampling population. Differences are exact for these + scenarios and say nothing about real prevalence. +- **Hash methods** use 10 seeds; H4 needed 200 (§7). +- **[ARCH-DEV]:** 192 validation episodes in 185 groups. It is source-conditional (the + attacks succeeded, so payoff happened) and non-adversarial. +- **[DEV-CASE]:** n = 2 incidents, both seen before. +- **Post hoc:** P1b and the design-bias checks were added after the results. They are + hypotheses for the next test, not findings. + +## 31. Positive results + +1. A selector with a proven, decoy-count-independent group displacement bound. It held with + 0 violations. +2. H1 supported: +0.248 Exposure@K over B0, with no family worse. +3. Time-invariance: newer or older decoys change nothing (B0 swings between 0.111 and 1.000). +4. H3 confirmed: B0 and P1 resist floods with weaker affixes at any m. +5. Missing evidence never changes the order. +6. Bounded summaries, now with the order label, config hash and bucket sizes. + +## 32. Negative results + +1. ML (pairwise LTR) adds no robust value: it learns recency (gate G FAIL). +2. Mechanism diversity (B3) and oldest-first are not robust; each falls to 0.111 against an + adaptive attacker. +3. H4's pre-registered 10-seed tolerance was not met. 200 seeds confirm the theory. +4. Registered P1 had an attacker-favourable tie rule (P1b fixes it, post hoc). +5. Strict round-robin loses 0.22 when one campaign holds several strong candidates on one + reference (F14). + +## 33. Remaining failure modes + +- **Same-reference equal-affix floods** hide the address, though not the reference (L1/L2). +- **K = 1:** five tied bucket leaders compete for a single slot. +- **A public seed** lets an attacker grind addresses against the keyed hash. A deployment + would need a secret seed. +- **Benchmark scope:** five references, and decoys modelled at 3+3 to 5+5. Similarity + definitions other than exact hex affixes are not modelled. +- **Real windows:** 0 to 6 groups each, so no real flood has been observed. Robustness under + floods is measured only on synthetic data. + +## 34. Independent benchmark readiness + +**Required per incident:** +- verified chain, victim address and harmful transaction; +- planting evidence; +- an `observation/2` window to H − 1 with evidence completeness recorded; +- campaign grouping; +- independent source provenance. + +**Controls:** +- no wallet, campaign or protected-cohort overlap with development; +- the selectors frozen at `0968ff8` (B0, P1, P1b with a recorded seed); +- generation and ranking metrics reported separately; +- missingness reported. + +**Size:** 10 incidents is a feasibility milestone. To show a paired Exposure@5 difference +with a sign test, about 20 discordant clusters are needed. At an assumed 30 % discordance +that is about 70 incidents. + +**RPC:** about 700 to 1,300 requests per window (recorded 12.3/12.4 costs), so 10 incidents +need about 7,000 to 13,000 and 70 need about 50,000 to 90,000. **No requests made.** + +**Remaining dependency:** user-sourced incidents with harm-transaction hashes and **more +than one reference recipient**. Single-reference victims cannot separate P1 from B0. + +## 35. Next experiment + +**Question.** On untouched, multi-reference poisoning victims recorded with `observation/2`, +does P1b expose the paid lookalike's reference bucket within the top 5 more often than B0? +- Frozen at `0968ff8`, with a secret seed. +- B0 and P1b are run on identical groups. + +**Data and labels:** +- at least 10 incidents for feasibility, and about 70 for a powered sign test; +- labels: the paid address and its reference, from the harm transaction, used only for + scoring. + +**Cost:** about 700 to 1,300 RPC requests per window. Analysis takes seconds. + +**Falsification:** P1b fails if, over the incidents where B0 and P1b disagree on exposing the +paid lookalike's bucket in the top 5, B0 exposes it at least as often (cluster sign test, +one-sided α = 0.05). + +**Not started. Phase 12.8 is not started.** + +## Gates + +| Gate | Status | Basis | +|---|---|---| +| A Historical correctness | **PASS** | pre-cutoff features only; time-invariance; later events change nothing (test); LTR test split never computed | +| B Candidate preservation | **PASS** | permutation for all selectors; pages reach every group | +| C Exposure robustness | **PASS WITH LIMITATIONS** | H1 supported [SYN]; benchmark biases found and characterized | +| D Similarity attacks | **PASS WITH LIMITATIONS** | bounded across references; identifiability limit within a reference | +| E Recency attacks | **PASS** | P1 is time-invariant; H3 confirmed | +| F Diversity trade-offs | **PASS WITH LIMITATIONS** | λ = 4 avoids the F14 loss; P1b loses TGC at K = 1 in F16 | +| G ML contribution | **FAIL** | no gain over recency; −0.169 adversarially | +| H Missingness | **PASS** | levels and `missing` never read; F10–F13 identical to F7 | +| I Runtime and memory | **PASS** | 100,000 groups in 3.8 s, 29 MiB; study 432 MiB | +| J Production isolation | **PASS** | detector unchanged (tested) | +| K Reproducibility | **PASS** | the rerun at `0968ff8` reproduced every registered number | +| L Independent validation | **BLOCKED BY DATA** | no untouched incidents | From 0c112bdebf54073f781932525279ac027efc2a3e Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 15:17:48 +0300 Subject: [PATCH 80/92] docs(ml): Phase 12.7 validation results Co-Authored-By: Claude Opus 5.5 --- ML_ADVERSARIAL_RANKING.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ML_ADVERSARIAL_RANKING.md b/ML_ADVERSARIAL_RANKING.md index aca238c..bfb05ac 100644 --- a/ML_ADVERSARIAL_RANKING.md +++ b/ML_ADVERSARIAL_RANKING.md @@ -650,3 +650,14 @@ one-sided α = 0.05). | J Production isolation | **PASS** | detector unchanged (tested) | | K Reproducibility | **PASS** | the rerun at `0968ff8` reproduced every registered number | | L Independent validation | **BLOCKED BY DATA** | no untouched incidents | + +## Validation + +| Check | Result | +|---|---| +| `ruff check .` / `ruff format --check .` / `mypy src` | clean / 298 files formatted / clean (155 files) | +| Full suite | **1,051 passed, 0 failed**, 4 deselected (6 min 45 s); 52 new tests in `tests/test_ml_adversarial_ranking.py` | +| Package | `uv build --offline`, `scripts/inspect_dist.py` OK (wheel 192 files, sdist 403) | +| Frozen cohorts | sheet and key hashes unchanged (`a0ec4b6e…`, `407b412f…`, `121c112d…`, `f333386d…`) | +| Incident fixtures | untouched (no data file modified) | +| CI | recorded in the PR #1 description | From 073019ccc6cff1e7780d091472d3908b35ef1cba Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 15:22:44 +0300 Subject: [PATCH 81/92] fix(ml): platform guard for the free-RAM preflight (mypy on Linux) CI #50 failed in the backend type check on Ubuntu: ctypes.windll does not exist in Linux typeshed. A sys.platform == "win32" guard is understood by mypy on every platform; checked locally with mypy for Windows and --platform linux. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/adversarial_benchmark.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cryptoguard/ml/adversarial_benchmark.py b/src/cryptoguard/ml/adversarial_benchmark.py index f2beef2..ca8c521 100644 --- a/src/cryptoguard/ml/adversarial_benchmark.py +++ b/src/cryptoguard/ml/adversarial_benchmark.py @@ -896,9 +896,9 @@ def performance(sizes: Sequence[int]) -> list[dict[str, Any]]: def free_ram_bytes() -> int | None: import ctypes - import os + import sys - if os.name == "nt": + if sys.platform == "win32": # mypy understands this guard on every platform class MemoryStatus(ctypes.Structure): _fields_ = [ From d98a636d4c24746fcfec07eff31a8b1b678c1053 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Mon, 9 Nov 2026 23:55:40 +0300 Subject: [PATCH 82/92] docs(ml): freeze protocol 12.7.1 with its generator, evaluation and sealed manifest Protocol 12.7.1 (falsification of P1b): frozen selectors (adversarial_ranking.py sha256 2c0e65ae..., P1b config 8b3795e363aad678; verify_frozen refuses anything else), an independent debiased generator (random addresses, references assigned by the pipeline's _match, shuffled populations, oracle outside the groups; balanced age and mechanism relations; 10 families incl. an exchangeable null control), the sealed manifest (7,200 scenarios, 5,079,472 candidates, sha256 2e294aeb...), template-cluster bootstrap, the pre-registered H1 classification, a bounded adaptive attacker (48 attacks x 3 budgets, K1 public / K2 secret seed) and a counterexample search with the 12.7 theorem's invariants. Committed before any selector has run on the sealed scenarios. `cryptoguard ml adaptive-validation [--manifest-only]`. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.7.1.md | 269 ++++ src/cryptoguard/ml/adaptive_validation.py | 1500 +++++++++++++++++++++ src/cryptoguard/ml/cli.py | 24 + tests/test_ml_adaptive_validation.py | 263 ++++ 4 files changed, 2056 insertions(+) create mode 100644 docs/ml/protocol-12.7.1.md create mode 100644 src/cryptoguard/ml/adaptive_validation.py create mode 100644 tests/test_ml_adaptive_validation.py diff --git a/docs/ml/protocol-12.7.1.md b/docs/ml/protocol-12.7.1.md new file mode 100644 index 0000000..42f4b53 --- /dev/null +++ b/docs/ml/protocol-12.7.1.md @@ -0,0 +1,269 @@ +# Protocol 12.7.1: debiased validation of P1b against an adaptive adversary + +**Frozen:** 2026-11-09, in the commit that adds this file. That is after the generator and +evaluation code exist and their integrity tests pass, and **before any selector has been run +on the sealed scenarios**. + +**Base:** `073019c`. + +**RPC budget:** 0. + +**Goal:** to falsify P1b's 12.7 advantage, not to confirm it. P1b was built after the 12.7 +outcomes were seen, so it is treated here as an already-developed algorithm that must hold up +on new data. + +## 1. Research questions + +1. Does P1b beat similarity-first (B0) when the target's age, mechanism, reference group, + similarity and tie position are not systematically special? +2. Does a simpler baseline match it? +3. What does an adaptive attacker, within the declared capabilities, need to displace the + target under each method? +4. Where is the task intrinsically ambiguous? + +## 2. Evaluation categories (never pooled) + +| Id | Data | Status | +|---|---|---| +| E1 | the 12.7 grid | development; not rerun | +| **E2** | the sealed debiased benchmark below | **primary**; synthetic only | +| E3 | the adaptive attacker and the counterexample search | exploratory | +| E4 | the two known incidents | regression only; "known development cases — not independent validation" | + +## 3. Frozen algorithms + +| Item | Frozen value | +|---|---| +| Module | `src/cryptoguard/ml/adversarial_ranking.py` | +| Last change | `0968ff8` | +| Source SHA-256 (LF) | `2c0e65aec71c9b20c422594452e3e338fc6986ba05c8ba3f5bc1302a8892ff1a` | +| Public seed | 0 | + +**Config hashes:** + +| Method | Definition | Config hash | +|---|---|---| +| B0 | similarity, then recency, then address | `7ecd8843cf738bec` | +| B1 | recency first | `944418279feaaeb2` | +| B4 | reference round-robin (recency within) | `2bf989929000f1e6` | +| B6 | similarity with keyed-hash ties | `93cdbe0b57c2958b` | +| B7 = P1 | registered | `66b77df10d259828` | +| **B8 = P1b** | bucket-hash ties, λ = 4 | **`8b3795e363aad678`** | + +`adaptive_validation.verify_frozen()` refuses to run if the module or any configuration +differs. **No selector changes after this commit.** A defect found later is documented, and +any changed algorithm counts as exploratory on E2 (P1c is never substituted for P1b). + +**Baselines and controls** (`adaptive_validation.METHODS`): + +| Id | Definition | +|---|---| +| B2 | oldest first | +| B3 | mechanism round-robin | +| B5 | pure similarity, address ties | +| B9 | similarity with per-scenario seeded random ties | +| NC-newest | newest first | +| NC-random | seeded random order | +| NC-hash-order | keyed hash of the address | +| NC-group-rotation | pure group rotation (λ = ∞, no similarity) | + +**Ablations of P1b:** λ = ∞, λ = 2, λ = 8, no similarity, recency ties within a bucket, and +member-hash ties (which is P1). Removing reference grouping or the discount both give λ = 0, +which is B6. + +## 4. Threat model + +**The attacker controls:** +- lookalike addresses and their tier (prefix + suffix ≥ 6, suffix ≥ 3: the pipeline's rule); +- which genuine reference each one imitates; +- planting time; +- mechanism (native dust, fake-token log, zero-value ERC-20 in, spoofed zero-value out); +- repetition; +- how many addresses to use. + +**The attacker does not control:** +- the victim's references or signatures; +- finalized order or provenance; +- the scoring target. + +**The attacker may know the algorithm and its public seed (K1).** A secret-seed model (K2) is +a diagnostic only: a seed that sits in a public configuration is not secret. + +**Costs (illustrative), kept separate:** +- **Address generation:** 2^(4(p+s)) key trials for one specific reference. +- **Planting:** gas per event. +- **Repetition:** gas only, with no new address. + +The attacker budget W is counted in **target-tier address equivalents**: a decoy one tier +stronger costs 16, one tier weaker costs 1/16. No vanity search is run; addresses are +simulated. + +## 5. Generator (E2), independent of the 12.7 benchmark + +**Population.** Each scenario is generated from `sha256(MASTER | family | G | m | replicate)`: +- G uniformly random genuine references; the target's reference index is uniform; +- target(s) and m attacker decoys per the family; +- 5 background lookalikes from other campaigns (tier i.i.d. from {6, 7, 8, 9} with weights + 4:3:2:1, reference uniform, mechanism per the relation, time per the relation); +- 2 unreferenced strangers. + +**How candidates are built:** +- Addresses are uniformly random apart from the designed affix. +- Each candidate's reference is assigned by the pipeline's own `candidate_evidence._match`, + so multi-reference ties follow its label-independent rule. +- Groups are `CandidateGroup` records identical in shape to `build` output. A fidelity check + rebuilds a sample through real fixtures. +- The population is shuffled. + +**The oracle target** is stored outside the groups. No selector receives it, and scenario +identifiers never reach a selector. + +**Age relations** (rotated so every template sees all eight): target oldest, newest, +intermediate, random, everyone in one block, decoys precede, decoys follow, overlap. + +**Mechanism relations** (rotated): same, different, mixed independent, target unique (a +deliberate shortcut condition), majority same (80 %). The target's mechanism is uniform. + +**Families** (target tier t, decoy tier d): + +| Family | Definition | +|---|---| +| F1 stronger | t ∈ {7, 8, 9}; d uniform in [6, t−1]; decoys on any reference | +| F2 equal, other groups | d = t; decoys on other references (own if G = 1) | +| F3 equal, own group | d = t; decoys on the target's reference (identifiability) | +| F4 equal, uniform | d = t; decoys on any reference | +| F5 weaker target | d ∈ [t+1, t+2]: intrinsically ambiguous, the target has strictly weaker evidence | +| **F6 exchangeable null (control)** | every candidate i.i.d.; the target is a uniformly drawn member. Excluded from the primary estimate; every method should be at chance. | +| F7 same total, other split | d = t with a different prefix/suffix split | +| F8 reference overlap | references in pairs sharing exactly a 3+3 affix; decoys imitate the target's partner | +| F9 several relevant | 3 targets of tier t on 3 references (when G ≥ 3); decoys d = t anywhere | +| F10 equal leaders | an attacker leader of tier t on every other reference, t ∈ {7, 8, 9}; decoys d = t−1 | + +**Grid.** Each family × G ∈ {1, 2, 5, 10, 25} × m ∈ {0, 10, 100, 1,000, 10,000} is a +**template**. Replicates per template: 40 at m ≤ 100, 16 at m = 1,000 and 8 at m = 10,000. +Fewer replicates at the large m are fixed here for compute, not chosen after results. +- 7,200 scenarios and 5,079,472 candidates; 250 templates (225 primary). +- K ∈ {1, 3, 5, 10, 20, 50}. + +**Sealed manifest** (`cryptoguard ml adaptive-validation --manifest-only`): +- overall SHA-256 **`2e294aeb7c7558151edd4fb399e950a1d6bf54d32ffc69bf31c984c998882afe`**; +- per-family hashes in `data/ml/research/phase12.7.1/manifest.json`. + +The primary run must reproduce the overall hash. + +## 6. Metrics + +- **Exposure@K:** for each relevant candidate, rank ≤ K. The scenario score is the mean over + relevant candidates and over the six K values. +- **GroupExposure@K:** the first member of the relevant candidate's reference bucket is + within K. It is reported separately and never combined with Exposure@K. +- **Rank displacement:** rank minus rank with the attacker's decoys removed (B0, P1b). +- **Worst family:** the lowest family mean paired difference. +- **Worst budget:** the paired difference at m = 10,000. +- **Pseudo-target exposure** (the shuffled-target control): a random non-relevant referenced + candidate's exposure. +- **Preservation:** every order is a permutation (asserted for every scenario). +- **Runtime and peak RSS.** + +## 7. Aggregation and uncertainty + +- **Weights:** equal by template within a family (replicates averaged inside a template), and + equal by family across the **9 primary families**. F6 is reported only as a control. +- **Statistical unit:** the template. Replicates of one template are not independent + incidents, so millions of candidates are never treated as independent observations. +- **Uncertainty:** a stratified template-cluster bootstrap, resampling templates within each + family. 2,000 resamples, seed 20261109, percentile 95 % CI. + +## 8. Hypotheses and pre-registered decision + +**H1 (primary).** Let Δ = the equal-family mean paired difference (P1b − B0) in Exposure@K. + +| Classification | Condition | +|---|---| +| **Inferior to a simpler baseline** | any of B4, B5, B6 or B9 reaches an equal-family mean ≥ P1b + 0.02. This takes precedence. | +| **Supported under the declared synthetic threat model** | Δ ≥ 0.05 with CI lower bound > 0; **and** the worst family ≥ −0.05; **and** Δ ≥ 0.05 on the shortcut-free subset (age ∈ {random, overlap, same block} and mechanism = mixed independent) | +| **Supported with significant limitations** | only the first condition holds | +| **Not supported after debiasing** | otherwise | + +**Secondary hypotheses (reported, not re-weighted):** +- **H2:** under K1 the best attack needs a larger budget to push the median victim's target + past K under P1b than under B0. +- **H3:** GroupExposure@K, P1b − B0, under other-group flooding (F2, F10). +- **H4:** in F3, no method keeps the target exposed when m ≫ K. +- **H5:** P1b's bucket position in F10 does not drift with m (neutral to group size). P1's + can. +- **H6 and H7:** P1b's results by mechanism relation and by age relation do not depend on + the shortcut conditions. B2, NC-newest and B3 should benefit only in their own designed + conditions. +- **H8:** P1b runtime and memory at 100 to 100,000 candidates. +- **H9:** report every simpler baseline that matches or beats P1b in any family. + +## 9. Adaptive attacker (E3, exploratory) + +**Victims:** 12 attack-free victims (G ∈ {2, 5, 10, 25} × target tier {6, 7, 8}), each with a +spoofed-out target and 5 background candidates. + +**Budgets:** W ∈ {10, 100, 1,000}. Populations are capped at 2,000 decoys (disclosed). + +**Search:** exhaustive over a bounded grid of 48 attacks: +- tier offset −1, 0 or +1 (cost-adjusted counts); +- allocation: own group, other groups, uniform, or tie winners (references whose public + bucket hash beats the target's); +- timing: older or newer; +- grinding: keep only addresses whose public member hash beats the target's (costs + generated addresses). + +**Legality:** the attacker only adds candidates. It never touches existing records, the +references, or receipts, and tiers below the similarity rule are illegal. + +**Methods:** B0, B1, B4, B5, B6, P1 and P1b, under K1, plus K2 for the seeded ones. + +**Reported:** the worst-case rank per victim, the share displaced beyond K ∈ {1, 5, 10}, and +the budget at which the median victim is displaced. + +**Counterexamples:** 20,000 random populations of up to 6 candidates on up to 3 references, +searched for: +- P1b losing to B0; +- P1b losing to pure group rotation; +- P1b's group not exposed; +- an equal-leader tie lost to another group; +- a weaker decoy displacing a non-leading target. + +Each is shrunk greedily. The search also counts **invariant breaks** of the actual 12.7 +theorem: the displacement bound, and a weaker decoy moving the target bucket's first member. +**Multi-reference assignment** is shown by an example. + +## 10. Other checks + +- **E4:** ranks of the paid lookalike in the two known incidents under every frozen method, + and full pagination of the P1b-ordered result. Excluded from every E2 number. +- **Fidelity:** 30 E2 scenarios rebuilt through fixtures and `build`. References, affixes, + mechanisms and P1b's order must all match. +- **Performance:** B0 and P1b at 100, 1,000, 10,000 and 100,000 candidates. Peak RSS is + recorded. Bounded memory, one process. + +## 11. Stop conditions + +- **Run once.** The primary run executes once on the committed code. A crash may be rerun + only on unchanged code. +- **Stop with no outcome** if the manifest hash differs or `verify_frozen` fails. +- **After the primary run,** nothing in §3–§8 changes. Later analyses are labelled post hoc. + +## 12. Gates + +**Statuses:** PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA, NOT EVALUATED. + +| Gate | Checks | +|---|---| +| A | neutrality (diagnostics) | +| B | historical correctness | +| C | the H1 classification | +| D | H2 | +| E | worst family | +| F | group vs address exposure kept separate | +| G | tie neutrality (H5) | +| H | identifiability (H4) | +| I | preservation | +| J | performance (H8) | +| K | reproducibility (manifest hash) | +| L | independent real-world validation: **BLOCKED BY DATA**, by construction | diff --git a/src/cryptoguard/ml/adaptive_validation.py b/src/cryptoguard/ml/adaptive_validation.py new file mode 100644 index 0000000..4634b3b --- /dev/null +++ b/src/cryptoguard/ml/adaptive_validation.py @@ -0,0 +1,1500 @@ +"""Phase 12.7.1: debiased synthetic validation of the frozen 12.7 selectors and a bounded +adaptive attacker (protocol 12.7.1). Research only; no RPC; nothing reaches the detector. + +The generator is independent of the 12.7 benchmark. It builds candidate groups directly +(the same ``CandidateGroup`` records ``candidate_evidence.build`` produces; a fidelity check +rebuilds a sample through real fixtures) from uniformly random addresses with a designed +affix to a designated victim reference, assigns each candidate's reference with the +pipeline's own ``_match`` rule, and shuffles the population. The oracle target is drawn +by the family's rule and kept outside the groups: no selector can see it, and nothing about +its address, position in the list, age, mechanism or reference is systematically special +unless a family varies that factor on purpose, in which case the factor is balanced. + +Categories are kept apart in the output: ``E2`` (the sealed primary benchmark), ``E3`` +(adaptive attacker and counterexamples, exploratory), ``E4`` (the two known incidents, +regression only). ``E1`` (the 12.7 grid) is not rerun here. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import random +import time +import tracemalloc +from collections.abc import Callable, Iterator, Sequence +from dataclasses import dataclass, field, replace +from functools import partial +from pathlib import Path +from typing import Any + +from cryptoguard.ml import adversarial_ranking as ar +from cryptoguard.ml import candidate_evidence as ce + +STUDY_VERSION = "adaptive-ranking-validation/1" +MASTER = "cg-12.7.1" # seed namespace, fixed in the protocol +WALLET = "0x" + "c" * 40 + +# The frozen algorithms (protocol 12.7.1 section 3): the evaluation refuses to run if the +# selector module or a configuration differs from these. +FROZEN_SOURCE = "src/cryptoguard/ml/adversarial_ranking.py" +FROZEN_SOURCE_SHA256 = "2c0e65aec71c9b20c422594452e3e338fc6986ba05c8ba3f5bc1302a8892ff1a" +FROZEN_REVISION = "0968ff8" +PUBLIC_SEED = 0 +FROZEN_SELECTORS: dict[str, ar.Selector] = { + "B0": ar.Selector("B0"), + "B1": ar.Selector("B1"), + "B2_oldest": ar.Selector("revrec"), + "B3": ar.Selector("B3"), + "B4": ar.Selector("B4"), + "B6": ar.Selector("B6", seed=PUBLIC_SEED), + "B7_P1": ar.Selector("P1", seed=PUBLIC_SEED), + "B8_P1b": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True), + # ablations of P1b + "A_lam_inf": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True, lam=math.inf), + "A_lam2": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True, lam=2.0), + "A_lam8": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True, lam=8.0), + "A_nosim": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True, nosim=True), + "A_recency_ties": ar.Selector("P1", seed=PUBLIC_SEED, bucket_tie=True, tie="recency"), + "NC_group_rotation": ar.Selector( + "P1", seed=PUBLIC_SEED, bucket_tie=True, lam=math.inf, nosim=True + ), +} +FROZEN_CONFIG_HASHES = { + "B0": "7ecd8843cf738bec", + "B1": "944418279feaaeb2", + "B4": "2bf989929000f1e6", + "B6": "93cdbe0b57c2958b", + "B7_P1": "66b77df10d259828", + "B8_P1b": "8b3795e363aad678", +} + +MECHS = ("native_dust", "fake_token_in", "zero_value_in", "spoofed_out") +_MECH = { + "native_dust": (("lookalike_in",), "native", "directly_verified"), + "fake_token_in": (("lookalike_in", "untrusted_token_in"), "erc20", "supported"), + "zero_value_in": (("lookalike_in", "zero_value_in"), "erc20", "supported"), + "spoofed_out": (("spoofed_out",), "erc20", "directly_verified"), +} +AGE_RELATIONS = ( + "target_oldest", + "target_newest", + "target_intermediate", + "target_random", + "same_block", + "decoys_precede", + "decoys_follow", + "overlap", +) +MECH_RELATIONS = ("same", "different", "mixed_independent", "target_unique", "majority_same") +FAMILIES = ( + "F1_target_stronger", + "F2_equal_other_groups", + "F3_equal_own_group", + "F4_equal_uniform", + "F5_target_weaker", + "F6_exchangeable_null", + "F7_same_total_split", + "F8_reference_overlap", + "F9_several_relevant", + "F10_equal_leaders", +) +CONTROL_FAMILIES = ("F6_exchangeable_null",) +PRIMARY_FAMILIES = tuple(f for f in FAMILIES if f not in CONTROL_FAMILIES) +G_GRID = (1, 2, 5, 10, 25) +M_GRID = (0, 10, 100, 1_000, 10_000) +K_GRID = (1, 3, 5, 10, 20, 50) +SEEDS_PER_M = {0: 40, 10: 40, 100: 40, 1_000: 16, 10_000: 8} +N_BACKGROUND = 5 +N_UNREFERENCED = 2 +LO, HI = 2_000, 8_999 # planting blocks; the cutoff is (9_001, 0) + + +# --- frozen-algorithm verification ---------------------------------------------------------- + + +def verify_frozen(root: Path = Path()) -> dict[str, Any]: + """Refuse to evaluate anything but the frozen selector module and configurations.""" + src = (root / FROZEN_SOURCE).read_bytes().replace(b"\r\n", b"\n") + digest = hashlib.sha256(src).hexdigest() + hashes = {k: ar.config_hash(FROZEN_SELECTORS[k]) for k in FROZEN_CONFIG_HASHES} + ok = digest == FROZEN_SOURCE_SHA256 and hashes == FROZEN_CONFIG_HASHES + if not ok: + raise RuntimeError(f"frozen selectors changed: {digest} {hashes}") + return {"source_sha256": digest, "config_hashes": hashes, "revision": FROZEN_REVISION} + + +# --- scenario generation -------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Spec: + family: str + groups: int # G: number of genuine victim references + m: int # attacker decoys + rep: int # replicate index within the template + age: str + mech: str + + @property + def template(self) -> tuple[str, int, int]: + return (self.family, self.groups, self.m) + + @property + def key(self) -> str: + return f"{self.family}|{self.groups}|{self.m}|{self.rep}" + + +@dataclass +class Scenario: + spec: Spec + groups: list[ce.CandidateGroup] # shuffled; carries no target information + relevant: tuple[str, ...] # oracle (lookalike addresses), never given to a selector + attacker: frozenset[str] # decoy addresses (for displacement), never given to a selector + references: tuple[str, ...] + meta: dict[str, Any] = field(default_factory=dict) + + +def specs() -> list[Spec]: + """The sealed design: every family x G x m, with the replicate count fixed per m. Age + and mechanism relations rotate across replicates so each template is balanced.""" + out = [] + for fam in FAMILIES: + for gi, g in enumerate(G_GRID): + for mi, m in enumerate(M_GRID): + for r in range(SEEDS_PER_M[m]): + age = AGE_RELATIONS[(r + gi + mi) % len(AGE_RELATIONS)] + mech = MECH_RELATIONS[(r // len(AGE_RELATIONS) + r + gi) % len(MECH_RELATIONS)] + out.append(Spec(fam, g, m, r, age, mech)) + return out + + +def _rng(*parts: object) -> random.Random: + seed = int(hashlib.sha256("|".join(map(str, (MASTER, *parts))).encode()).hexdigest()[:16], 16) + return random.Random(seed) # noqa: S311 - reproducible simulation, not security + + +def _hex(rng: random.Random, n: int) -> str: + return f"{rng.getrandbits(4 * n):0{n}x}" if n else "" + + +def _other(rng: random.Random, c: str) -> str: + x = c + while x == c: + x = "0123456789abcdef"[rng.randrange(16)] + return x + + +def lookalike_of(rng: random.Random, ref: str, p: int, s: int) -> str: + """A uniformly random address sharing exactly ``p`` leading and ``s`` trailing hex + characters with ``ref``.""" + body = ref[2:] + mid = 40 - p - s - 2 + return ( + "0x" + + body[:p] + + _other(rng, body[p]) + + _hex(rng, mid) + + _other(rng, body[39 - s]) + + body[40 - s :] + ) + + +def split(rng: random.Random, total: int, avoid: tuple[int, int] | None = None) -> tuple[int, int]: + """A (prefix, suffix) with prefix + suffix = total and suffix >= 3 (the pipeline's rule), + uniformly over the allowed splits, avoiding ``avoid`` when another split exists.""" + options = [(total - s, s) for s in range(3, total + 1)] + if avoid in options and len(options) > 1: + options.remove(avoid) + return options[rng.randrange(len(options))] + + +def _references(rng: random.Random, g: int, overlap: bool) -> list[str]: + refs = ["0x" + _hex(rng, 40) for _ in range(g)] + if overlap: # pairs share exactly a 3-character prefix and suffix + for i in range(1, g, 2): + a = refs[i - 1][2:] + refs[i] = "0x" + a[:3] + _other(rng, a[3]) + _hex(rng, 32) + _other(rng, a[36]) + a[37:] + return refs + + +def _tier_iid(rng: random.Random) -> int: + return rng.choices((6, 7, 8, 9), weights=(4, 3, 2, 1))[0] + + +@dataclass +class _Cand: + address: str + designed_ref: str | None + mech: str + block: int + tx: int + role: str # "target" | "decoy" | "background" | "unreferenced" (generator only) + + +def _times( + rng: random.Random, age: str, n_dec: int, n_other: int +) -> tuple[list[int], list[int], list[int]]: + """(target blocks, decoy blocks, background blocks) for one relation.""" + + def u(a: int, b: int, k: int) -> list[int]: + return [rng.randint(a, b) for _ in range(k)] + + if age == "target_oldest": + return [LO], u(LO + 1, HI, n_dec), u(LO + 1, HI, n_other) + if age == "target_newest": + return [HI], u(LO, HI - 1, n_dec), u(LO, HI - 1, n_other) + if age == "target_intermediate": + dec, oth = u(LO, HI, n_dec), u(LO, HI, n_other) + allb = sorted(dec + oth) + mid = allb[len(allb) // 2] if allb else (LO + HI) // 2 + return [mid], dec, oth + if age == "target_random": + return u(LO, HI, 1), u(LO, HI, n_dec), u(LO, HI, n_other) + if age == "same_block": + b = (LO + HI) // 2 + return [b], [b] * n_dec, [b] * n_other + if age == "decoys_precede": + t = rng.randint(6_000, HI) + return [t], u(LO, t - 1, n_dec), u(LO, HI, n_other) + if age == "decoys_follow": + t = rng.randint(LO, 5_000) + return [t], u(t + 1, HI, n_dec), u(LO, HI, n_other) + if age == "overlap": + t = rng.randint(4_000, 7_000) + return [t], u(t - 1_000, t + 1_000, n_dec), u(LO, HI, n_other) + raise ValueError(age) + + +def _mechs( + rng: random.Random, rel: str, target: str, n_dec: int, n_bg: int +) -> tuple[list[str], list[str]]: + others = [x for x in MECHS if x != target] + if rel == "same": + dec = [target] * n_dec + elif rel == "different": + d = others[rng.randrange(3)] + dec = [d] * n_dec + elif rel == "mixed_independent": + dec = [MECHS[rng.randrange(4)] for _ in range(n_dec)] + elif rel == "target_unique": + dec = [others[rng.randrange(3)] for _ in range(n_dec)] + elif rel == "majority_same": + dec = [target if rng.random() < 0.8 else others[rng.randrange(3)] for _ in range(n_dec)] + else: + raise ValueError(rel) + pool = others if rel == "target_unique" else list(MECHS) + bg = [pool[rng.randrange(len(pool))] for _ in range(n_bg)] + return dec, bg + + +def generate(spec: Spec) -> Scenario: + rng = _rng("scenario", spec.key) + fam, g, m = spec.family, spec.groups, spec.m + refs = _references(rng, g, overlap=fam == "F8_reference_overlap") + t_idx = rng.randrange(g) + t_ref = refs[t_idx] + others = [r for i, r in enumerate(refs) if i != t_idx] or [t_ref] + # F8: the reference sharing a 3+3 affix with the target's (its overlap partner) + p_idx = t_idx + 1 if t_idx % 2 == 0 else t_idx - 1 + partner = refs[p_idx] if 0 <= p_idx < g else others[0] + cands: list[_Cand] = [] + meta_rel: dict[str, Any] + if fam == "F6_exchangeable_null": + # every candidate i.i.d.; the target is a uniformly drawn member (a null family) + n = m + 1 + blocks = [rng.randint(LO, HI) for _ in range(n)] + for i in range(n): + ref = refs[rng.randrange(g)] + p, s = split(rng, _tier_iid(rng)) + cands.append( + _Cand( + lookalike_of(rng, ref, p, s), + ref, + MECHS[rng.randrange(4)], + blocks[i], + rng.randrange(200), + "decoy", + ) + ) + pick = rng.randrange(n) + cands[pick].role = "target" + meta_rel = {"age": "exchangeable", "mech": "exchangeable"} + else: + n_targets = 3 if fam == "F9_several_relevant" else 1 + if fam in ("F1_target_stronger", "F10_equal_leaders"): + t_tier = rng.choice((7, 8, 9)) + else: + t_tier = rng.choice((6, 7, 8)) + t_mech = MECHS[rng.randrange(4)] + n_leaders = (g - 1) if fam == "F10_equal_leaders" else 0 + dec_mechs, bg_mechs = _mechs(rng, spec.mech, t_mech, m + n_leaders, N_BACKGROUND) + t_blocks, d_blocks, o_blocks = _times( + rng, spec.age, m + n_leaders, N_BACKGROUND + N_UNREFERENCED + ) + # target(s) + t_refs = [t_ref] + if n_targets == 3: + t_refs += rng.sample(others, 2) if g >= 3 else [t_ref, t_ref] + t_split = split(rng, t_tier) + for j, r in enumerate(t_refs): + ps = t_split if j == 0 else split(rng, t_tier) + blk = ( + t_blocks[0] + if j == 0 + else (t_blocks[0] if spec.age == "same_block" else rng.randint(LO, HI)) + ) + cands.append( + _Cand(lookalike_of(rng, r, *ps), r, t_mech, blk, rng.randrange(200), "target") + ) + # decoys (and F10's equal-strength leaders, attacker-placed one per other reference) + for i in range(m + n_leaders): + if fam == "F10_equal_leaders" and i < n_leaders: + ref, tier, ps_avoid = others[i], t_tier, None + else: + if fam == "F8_reference_overlap": + ref = partner + elif fam == "F2_equal_other_groups": + ref = others[rng.randrange(len(others))] + elif fam == "F3_equal_own_group": + ref = t_ref + else: + ref = refs[rng.randrange(g)] + if fam == "F1_target_stronger": + tier = rng.randint(6, t_tier - 1) + elif fam == "F5_target_weaker": + tier = rng.randint(t_tier + 1, t_tier + 2) + elif fam == "F10_equal_leaders": + tier = t_tier - 1 + else: + tier = t_tier + ps_avoid = t_split if fam == "F7_same_total_split" else None + ps = split(rng, tier, ps_avoid) + cands.append( + _Cand( + lookalike_of(rng, ref, *ps), + ref, + dec_mechs[i], + d_blocks[i], + rng.randrange(200), + "decoy", + ) + ) + meta_rel = { + "age": spec.age, + "mech": spec.mech, + "target_tier": t_tier, + "target_mech": t_mech, + } + # background: other campaigns' lookalikes (i.i.d.) and unreferenced strangers + for i in range(N_BACKGROUND): + ref = refs[rng.randrange(g)] + ps = split(rng, _tier_iid(rng)) + cands.append( + _Cand( + lookalike_of(rng, ref, *ps), + ref, + bg_mechs[i], + o_blocks[i], + rng.randrange(200), + "background", + ) + ) + for i in range(N_UNREFERENCED): + cands.append( + _Cand( + "0x" + _hex(rng, 40), + None, + "zero_value_in", + o_blocks[N_BACKGROUND + i], + rng.randrange(200), + "unreferenced", + ) + ) + groups, relevant, attacker = _groups(cands, refs) + rng.shuffle(groups) + meta = {**meta_rel, "target_ref_index": t_idx, "references": g} + return Scenario(spec, groups, relevant, attacker, tuple(refs), meta) + + +def _groups( + cands: list[_Cand], refs: Sequence[str] +) -> tuple[list[ce.CandidateGroup], tuple[str, ...], frozenset[str]]: + chosen: dict[str, dict[str, int]] = {} + for r in refs: + chosen.setdefault(r[-3:], {})[r] = 0 + seen: set[str] = {r.lower() for r in refs} + out: list[ce.CandidateGroup] = [] + relevant: list[str] = [] + attacker: set[str] = set() + for i, c in enumerate(cands): + a = c.address.lower() + if a in seen: + continue + seen.add(a) + match = ce._match(a, chosen) + out.append(make_group(a, match, c.mech, (c.block, c.tx, i))) + if c.role == "target": + relevant.append(a) + elif c.role == "decoy": + attacker.add(a) + return out, tuple(relevant), frozenset(attacker) + + +def make_group( + address: str, match: tuple[str, tuple[int, int]] | None, mech: str, pos: tuple[int, int, int] +) -> ce.CandidateGroup: + """One single-record candidate group, exactly as ``build`` would form it.""" + mechanisms, kind, level = _MECH[mech] + if match is None: # no reference: only a zero-value event is evidence without one + mechanisms, kind, level = ("zero_value_in",), "erc20", "partially_supported" + refs = ((match[0], match[1][0], match[1][1]),) if match else () + rec = ce.EvidenceRecord( + identity=f"tx:0x{hashlib.sha256(f'{address}:{pos}'.encode()).hexdigest()}:{pos[2]}", + kind=kind, + direction="out" if mech == "spoofed_out" else "in", + block=pos[0], + tx_index=pos[1], + log_index=pos[2], + mechanisms=mechanisms, + level=level, + signer_status="foreign_known" if mech == "spoofed_out" else "lookalike_itself", + signer=None, + authorization="not_required" if mech == "spoofed_out" else "not_applicable", + event_sender=WALLET if mech == "spoofed_out" else address, + event_recipient=address if mech == "spoofed_out" else WALLET, + emitter=None, + receipt="implied_by_log" if kind == "erc20" else "succeeded", + value_zero=mech in ("spoofed_out", "zero_value_in"), + missing=(), + ) + return ce.CandidateGroup( + identity=f"1:{WALLET}:{address}", + chain_id=1, + victim=WALLET, + lookalike=address, + references=refs, + mechanisms=tuple(sorted(mechanisms)), + kinds=(kind,), + level=level, + affix=(match[1][0] + match[1][1]) if match else None, + first_position=pos, + last_position=pos, + evidence=(rec,), + missing=(), + ) + + +def scenario_hash(sc: Scenario) -> str: + rows = sorted( + (g.lookalike, list(g.references), list(g.mechanisms), list(g.last_position)) + for g in sc.groups + ) + payload = { + "spec": sc.spec.key, + "age": sc.spec.age, + "mech": sc.spec.mech, + "rows": rows, + "relevant": sorted(sc.relevant), + } + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + + +def manifest(spec_list: Sequence[Spec] | None = None) -> dict[str, Any]: + """The sealed manifest: per-family and overall hashes of every generated scenario.""" + spec_list = list(spec_list or specs()) + per_family: dict[str, hashlib._Hash] = {} + overall = hashlib.sha256() + counts: dict[str, int] = {} + candidates = 0 + for sp in spec_list: + sc = generate(sp) + h = scenario_hash(sc) + overall.update(h.encode()) + per_family.setdefault(sp.family, hashlib.sha256()).update(h.encode()) + counts[sp.family] = counts.get(sp.family, 0) + 1 + candidates += len(sc.groups) + return { + "scenarios": len(spec_list), + "candidates": candidates, + "per_family_count": counts, + "per_family_sha256": {k: v.hexdigest() for k, v in per_family.items()}, + "sha256": overall.hexdigest(), + } + + +# --- methods -------------------------------------------------------------------------------- + +Order = Callable[[Sequence[ce.CandidateGroup], Spec], list[ce.CandidateGroup]] + + +def _frozen(name: str) -> Order: + sel = FROZEN_SELECTORS[name] + return lambda gs, _sp: ar.order(gs, sel) + + +def _local(key: Callable[[ce.CandidateGroup, Spec], Any]) -> Order: + def run(gs: Sequence[ce.CandidateGroup], sp: Spec) -> list[ce.CandidateGroup]: + return sorted(gs, key=lambda g: key(g, sp)) + + return run + + +def _b9(gs: Sequence[ce.CandidateGroup], sp: Spec) -> list[ce.CandidateGroup]: + rng = _rng("B9", sp.key) # a fixed, per-scenario randomized tie-break, declared seed + noise = {g.lookalike: rng.random() for g in sorted(gs, key=lambda g: g.lookalike)} + return sorted(gs, key=lambda g: (-ar.bits(g), noise[g.lookalike])) + + +def _random(gs: Sequence[ce.CandidateGroup], sp: Spec) -> list[ce.CandidateGroup]: + out = sorted(gs, key=lambda g: g.lookalike) + _rng("NC_random", sp.key).shuffle(out) + return out + + +def _pure_similarity_key(g: ce.CandidateGroup, _sp: Spec) -> tuple[int, str]: + return (-ar.bits(g), g.lookalike) + + +def _newest_key(g: ce.CandidateGroup, _sp: Spec) -> tuple[tuple[int, int, int], str]: + return ((-g.last_position[0], -g.last_position[1], -g.last_position[2]), g.lookalike) + + +def _hash_key(g: ce.CandidateGroup, _sp: Spec) -> tuple[int, str]: + return (ar.keyed(PUBLIC_SEED, g.lookalike), g.lookalike) + + +METHODS: dict[str, Order] = { + **{n: _frozen(n) for n in FROZEN_SELECTORS}, + "B5_pure_similarity": _local(_pure_similarity_key), + "B9_random_ties": _b9, + "NC_newest": _local(_newest_key), + "NC_random": _random, + "NC_hash_order": _local(_hash_key), +} +SIMPLE_BASELINES = ("B4", "B5_pure_similarity", "B6", "B9_random_ties") + + +# --- evaluation ----------------------------------------------------------------------------- + + +def _ranks( + ordered: Sequence[ce.CandidateGroup], targets: Sequence[str] +) -> tuple[list[int], list[int]]: + pos = {g.lookalike: i + 1 for i, g in enumerate(ordered)} + bucket_first: dict[str, int] = {} + for i, g in enumerate(ordered): + bucket_first.setdefault(ce.bucket_of(g), i + 1) + by_look = {g.lookalike: g for g in ordered} + return [pos[t] for t in targets], [bucket_first[ce.bucket_of(by_look[t])] for t in targets] + + +def evaluate(sc: Scenario) -> dict[str, Any]: + """Ranks of each relevant candidate and of its reference bucket, for every method; plus + a pseudo-target (a random non-relevant referenced candidate) and the clean ranks.""" + out: dict[str, Any] = {"methods": {}} + pick_rng = _rng("pseudo", sc.spec.key) + pool = sorted(g.lookalike for g in sc.groups if g.references and g.lookalike not in sc.relevant) + pseudo = pool[pick_rng.randrange(len(pool))] if pool else None + clean = [g for g in sc.groups if g.lookalike not in sc.attacker] + for name, run in METHODS.items(): + ordered = run(sc.groups, sc.spec) + if len(ordered) != len(sc.groups): + raise AssertionError("not a permutation") + ranks, bfirst = _ranks(ordered, sc.relevant) + row: dict[str, Any] = {"r": ranks, "b": bfirst} + if pseudo is not None and name in ("B0", "B8_P1b", "NC_random"): + row["pseudo"] = _ranks(ordered, [pseudo])[0][0] + if name in ("B0", "B8_P1b") and sc.spec.m: + row["clean"] = _ranks(run(clean, sc.spec), sc.relevant)[0] + out["methods"][name] = row + return out + + +def _exposure(ranks: Sequence[int], k: int) -> float: + return sum(1 for r in ranks if r <= k) / len(ranks) + + +def score(row: dict[str, Any], what: str = "r") -> float: + """Mean over the K grid of mean Exposure@K over the relevant candidates.""" + return sum(_exposure(row[what], k) for k in K_GRID) / len(K_GRID) + + +def diagnostics(sc: Scenario) -> dict[str, Any]: + """Generator neutrality diagnostics for the first relevant candidate (no method).""" + t = sc.relevant[0] + gs = sc.groups + by = {g.lookalike: g for g in gs} + tg = by[t] + order_time = sorted(gs, key=lambda g: (g.last_position, g.lookalike)) + n = len(gs) + age_pct = order_time.index(tg) / (n - 1) if n > 1 else 0.5 + addr_pct = sorted(g.lookalike for g in gs).index(t) / (n - 1) if n > 1 else 0.5 + list_pct = [g.lookalike for g in gs].index(t) / (n - 1) if n > 1 else 0.5 + sizes: dict[str, int] = {} + for g in gs: + sizes[ce.bucket_of(g)] = sizes.get(ce.bucket_of(g), 0) + 1 + tb = ce.bucket_of(tg) + ref_buckets = sorted(b for b in sizes if not b.startswith("mech:")) + mech_counts: dict[tuple[str, ...], int] = {} + for g in gs: + mech_counts[g.mechanisms] = mech_counts.get(g.mechanisms, 0) + 1 + return { + "age_pct": age_pct, + "oldest": order_time[0].lookalike == t, + "newest": order_time[-1].lookalike == t, + "address_pct": addr_pct, + "list_pct": list_pct, + "ref_sorted_pct": ref_buckets.index(tb) / (len(ref_buckets) - 1) + if len(ref_buckets) > 1 and tb in ref_buckets + else None, + "largest_group": len(ref_buckets) > 1 and sizes[tb] == max(sizes[b] for b in ref_buckets), + "smallest_group": len(ref_buckets) > 1 and sizes[tb] == min(sizes[b] for b in ref_buckets), + "mech_unique": mech_counts[tg.mechanisms] == 1, + "bits": ar.bits(tg), + "bits_pct_strict_above": sum(1 for g in gs if ar.bits(g) > ar.bits(tg)) / n, + } + + +def iterate(spec_list: Sequence[Spec]) -> Iterator[tuple[Spec, Scenario, dict[str, Any]]]: + for sp in spec_list: + sc = generate(sp) + yield sp, sc, evaluate(sc) + + +# --- aggregation and uncertainty ------------------------------------------------------------ + + +def aggregate( + rows: Sequence[dict[str, Any]], + method: str, + what: str = "r", + subset: Callable[[dict[str, Any]], bool] | None = None, +) -> dict[str, Any]: + """Equal weight by template within a family, equal weight by family across families.""" + fam_t: dict[str, dict[tuple[int, int], list[float]]] = {} + for row in rows: + if subset is not None and not subset(row): + continue + fam_t.setdefault(row["family"], {}).setdefault((row["G"], row["m"]), []).append( + score(row["methods"][method], what) + ) + fam = {f: sum(sum(v) / len(v) for v in t.values()) / len(t) for f, t in fam_t.items()} + prim = [fam[f] for f in PRIMARY_FAMILIES if f in fam] + return { + "family": {k: round(v, 4) for k, v in fam.items()}, + "primary_mean": round(sum(prim) / len(prim), 4) if prim else None, + } + + +def paired( + rows: Sequence[dict[str, Any]], + a: str, + b: str, + *, + what: str = "r", + subset: Callable[[dict[str, Any]], bool] | None = None, + n_boot: int = 2_000, +) -> dict[str, Any]: + """Mean paired difference a - b (equal family, equal template), with a stratified + template-cluster bootstrap: templates are resampled within each family.""" + import numpy as np + + fam_t: dict[str, dict[tuple[int, int], list[float]]] = {} + for row in rows: + if row["family"] not in PRIMARY_FAMILIES or (subset is not None and not subset(row)): + continue + d = score(row["methods"][a], what) - score(row["methods"][b], what) + fam_t.setdefault(row["family"], {}).setdefault((row["G"], row["m"]), []).append(d) + fams = sorted(fam_t) + tmeans = {f: np.array([sum(v) / len(v) for v in fam_t[f].values()]) for f in fams} + fam_mean = {f: float(tmeans[f].mean()) for f in fams} + est = float(np.mean([fam_mean[f] for f in fams])) if fams else float("nan") + rng = np.random.default_rng(20261109) + boots = np.empty(n_boot) + for i in range(n_boot): + boots[i] = np.mean( + [tmeans[f][rng.integers(0, len(tmeans[f]), len(tmeans[f]))].mean() for f in fams] + ) + lo, hi = np.percentile(boots, [2.5, 97.5]) if fams else (float("nan"), float("nan")) + per_m: dict[int, list[float]] = {} + for f in fams: + for (_g, m), v in fam_t[f].items(): + per_m.setdefault(m, []).append(sum(v) / len(v)) + return { + "mean": round(est, 4), + "ci95": [round(float(lo), 4), round(float(hi), 4)], + "per_family": {f: round(v, 4) for f, v in fam_mean.items()}, + "worst_family": min(fam_mean.items(), key=lambda kv: kv[1]) if fams else None, + "per_budget": {m: round(sum(v) / len(v), 4) for m, v in sorted(per_m.items())}, + "templates": sum(len(fam_t[f]) for f in fams), + "scenarios": sum(len(v) for f in fams for v in fam_t[f].values()), + } + + +def h1_decision(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: + """The pre-registered classification (protocol 12.7.1 section 8).""" + main = paired(rows, "B8_P1b", "B0") + indep = paired(rows, "B8_P1b", "B0", subset=independent) + p1b = aggregate(rows, "B8_P1b")["primary_mean"] + simple = {s: aggregate(rows, s)["primary_mean"] for s in SIMPLE_BASELINES} + beaten_by = [ + s for s, v in simple.items() if v is not None and p1b is not None and v >= p1b + 0.02 + ] + effect = main["mean"] >= 0.05 and main["ci95"][0] > 0 + worst_ok = main["worst_family"] is not None and main["worst_family"][1] >= -0.05 + indep_ok = indep["mean"] >= 0.05 + if beaten_by: + verdict = "inferior to a simpler baseline" + elif effect and worst_ok and indep_ok: + verdict = "supported under the declared synthetic threat model" + elif effect: + verdict = "supported with significant limitations" + else: + verdict = "not supported after debiasing" + return { + "paired_P1b_minus_B0": main, + "paired_independent_subset": indep, + "P1b_primary_mean": p1b, + "simple_baselines_primary_mean": simple, + "beaten_by_simpler": beaten_by, + "criteria": { + "effect": effect, + "worst_family_ok": worst_ok, + "independent_subset_ok": indep_ok, + }, + "verdict": verdict, + } + + +def independent(row: dict[str, Any]) -> bool: + """Scenarios where neither age nor mechanism relates to the target by construction.""" + return ( + row["age"] in ("target_random", "overlap", "same_block") + and row["mech"] == "mixed_independent" + ) + + +# --- sealed primary run --------------------------------------------------------------------- + + +def primary(spec_list: Sequence[Spec] | None = None) -> dict[str, Any]: + spec_list = list(spec_list or specs()) + rows: list[dict[str, Any]] = [] + diags: list[dict[str, Any]] = [] + overall = hashlib.sha256() + t0 = time.perf_counter() + for sp, sc, ev in iterate(spec_list): + overall.update(scenario_hash(sc).encode()) + rows.append( + { + "family": sp.family, + "G": sp.groups, + "m": sp.m, + "rep": sp.rep, + "age": sp.age, + "mech": sp.mech, + "n": len(sc.groups), + **ev, + } + ) + diags.append( + {"family": sp.family, "age": sp.age, "mech": sp.mech, "m": sp.m, **diagnostics(sc)} + ) + return { + "rows": rows, + "diagnostics": diags, + "manifest_sha256": overall.hexdigest(), + "seconds": round(time.perf_counter() - t0, 1), + } + + +def summarize_primary(res: dict[str, Any]) -> dict[str, Any]: + rows = res["rows"] + methods = list(METHODS) + out: dict[str, Any] = { + "scenarios": len(rows), + "templates": len({(r["family"], r["G"], r["m"]) for r in rows}), + "manifest_sha256": res["manifest_sha256"], + "exposure": {m: aggregate(rows, m) for m in methods}, + "group_exposure": {m: aggregate(rows, m, "b") for m in methods}, + "H1": h1_decision(rows), + "group_paired_P1b_minus_B0": paired(rows, "B8_P1b", "B0", what="b"), + "P1b_minus_B4": paired(rows, "B8_P1b", "B4"), + "P1b_minus_P1": paired(rows, "B8_P1b", "B7_P1"), + "worst_budget": { + m: paired(rows, m, "B0", subset=lambda r: r["m"] == 10_000)["mean"] + for m in ("B8_P1b", "B7_P1", "B4", "B6") + }, + "by_age": { + a: { + m: aggregate(rows, m, subset=partial(_field_is, "age", a))["primary_mean"] + for m in ("B0", "B8_P1b", "B2_oldest", "NC_newest", "B1") + } + for a in AGE_RELATIONS + }, + "by_mech": { + x: { + m: aggregate(rows, m, subset=partial(_field_is, "mech", x))["primary_mean"] + for m in ("B0", "B8_P1b", "B3") + } + for x in MECH_RELATIONS + }, + "by_k": { + m: {k: round(_mean_k(rows, m, k), 4) for k in K_GRID} + for m in ("B0", "B1", "B4", "B6", "B7_P1", "B8_P1b", "NC_random") + }, + "pseudo_target": _pseudo(rows), + "displacement": _displacement(rows), + "diagnostics": _diag_summary(res["diagnostics"]), + "tie_neutrality": tie_neutrality(rows), + } + return out + + +def _field_is(key: str, value: object, row: dict[str, Any]) -> bool: + return bool(row[key] == value) + + +def _mean_k(rows: Sequence[dict[str, Any]], m: str, k: int) -> float: + fam: dict[str, dict[tuple[int, int], list[float]]] = {} + for r in rows: + if r["family"] in PRIMARY_FAMILIES: + fam.setdefault(r["family"], {}).setdefault((r["G"], r["m"]), []).append( + _exposure(r["methods"][m]["r"], k) + ) + vals = [sum(sum(v) / len(v) for v in t.values()) / len(t) for t in fam.values()] + return sum(vals) / len(vals) + + +def _pseudo(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, dict[str, float]] = {} + for meth in ("B0", "B8_P1b", "NC_random"): + acc: dict[str, list[float]] = {} + for r in rows: + p = r["methods"][meth].get("pseudo") + if p is not None: + acc.setdefault(r["family"], []).append( + sum(1 for k in K_GRID if p <= k) / len(K_GRID) + ) + out[meth] = {f: round(sum(v) / len(v), 4) for f, v in acc.items()} + return out + + +def _displacement(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for meth in ("B0", "B8_P1b"): + per_m: dict[int, list[float]] = {} + for r in rows: + row = r["methods"][meth] + if "clean" in row and r["family"] in PRIMARY_FAMILIES: + per_m.setdefault(r["m"], []).append(row["r"][0] - row["clean"][0]) + out[meth] = { + m: {"median": sorted(v)[len(v) // 2], "mean": round(sum(v) / len(v), 1)} + for m, v in sorted(per_m.items()) + } + return out + + +def _diag_summary(diags: Sequence[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for fam in FAMILIES: + ds = [d for d in diags if d["family"] == fam and d["m"] > 0] + if not ds: + continue + + def mean(key: str, ds: list[dict[str, Any]] = ds) -> float | None: + vals = [float(d[key]) for d in ds if d[key] is not None] + return round(sum(vals) / len(vals), 4) if vals else None + + out[fam] = { + k: mean(k) + for k in ( + "age_pct", + "oldest", + "newest", + "address_pct", + "list_pct", + "ref_sorted_pct", + "largest_group", + "smallest_group", + "mech_unique", + "bits_pct_strict_above", + ) + } + return out + + +def tie_neutrality(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: + """H5: in F10 (equal leaders), the target leader's bucket position against the target + group's size (top vs bottom half of the scenario's bucket sizes is not stored, so the + proxy is m: decoys inflate other buckets). Neutral selectors keep the mean bucket + position near (G + 1) / 2 at every m.""" + out: dict[str, Any] = {} + for meth in ("B7_P1", "B8_P1b", "B4"): + acc: dict[tuple[int, int], list[float]] = {} + for r in rows: + if r["family"] == "F10_equal_leaders" and r["G"] > 1: + acc.setdefault((r["G"], r["m"]), []).append( + (r["methods"][meth]["b"][0] - 1) / (r["G"] - 1) + ) + out[meth] = {f"G{g}_m{m}": round(sum(v) / len(v), 3) for (g, m), v in sorted(acc.items())} + return out + + +# --- E3: adaptive attacker (exploratory) ---------------------------------------------------- + +ATTACK_METHODS = ("B0", "B1", "B4", "B5_pure_similarity", "B6", "B7_P1", "B8_P1b") +ATTACK_BUDGETS = (10, 100, 1_000) # target-tier address equivalents +ATTACK_CAP = 2_000 # largest decoy population evaluated (disclosed limit) + + +@dataclass(frozen=True) +class Attack: + delta: int # decoy tier relative to the target (+1 costs 16x, -1 costs 1/16 per address) + alloc: str # "own" | "others" | "uniform" | "tie_winners" + timing: str # "older" | "newer" + grind: bool # keep only decoys whose public keyed hash beats the target's + + +ATTACKS = tuple( + Attack(d, a, t, gr) + for d in (-1, 0, 1) + for a in ("own", "others", "uniform", "tie_winners") + for t in ("older", "newer") + for gr in (False, True) +) + + +def victim(i: int) -> tuple[list[ce.CandidateGroup], str, list[str], int]: + """An attack-free victim population: references, a 'spoofed_out' target, background.""" + g = (2, 5, 10, 25)[i % 4] + tier = (6, 7, 8)[i // 4 % 3] + rng = _rng("victim", i) + refs = _references(rng, g, overlap=False) + t_ref = refs[rng.randrange(g)] + cands = [ + _Cand( + lookalike_of(rng, t_ref, *split(rng, tier)), t_ref, "spoofed_out", 5_000, 100, "target" + ) + ] + for _ in range(N_BACKGROUND): + ref = refs[rng.randrange(g)] + cands.append( + _Cand( + lookalike_of(rng, ref, *split(rng, _tier_iid(rng))), + ref, + MECHS[rng.randrange(4)], + rng.randint(LO, HI), + rng.randrange(200), + "background", + ) + ) + groups, relevant, _ = _groups(cands, refs) + return groups, relevant[0], refs, tier + + +def attack_population( + base: list[ce.CandidateGroup], + target: str, + refs: Sequence[str], + tier: int, + att: Attack, + budget: int, + seed_rng: random.Random, +) -> tuple[list[ce.CandidateGroup], dict[str, Any]]: + """Legal attacker additions only: new lookalike addresses with chosen tier, reference, + timing; existing records and the victim's references are never touched.""" + t_group = next(g for g in base if g.lookalike == target) + t_ref = ce.bucket_of(t_group) + t_hash = ar.keyed(PUBLIC_SEED, target) + d_tier = tier + att.delta + if d_tier < 6: + return base, {"decoys": 0, "generated": 0, "illegal": "tier below the similarity rule"} + n = min(ATTACK_CAP, int(budget * 16.0 ** (-att.delta))) + others = [r for r in refs if r != t_ref] or [t_ref] + t_bucket_hash = ar.keyed(PUBLIC_SEED, "bucket:" + t_ref) + winners = [r for r in others if ar.keyed(PUBLIC_SEED, "bucket:" + r) < t_bucket_hash] or others + pool = {"own": [t_ref], "others": others, "uniform": list(refs), "tie_winners": winners}[ + att.alloc + ] + chosen: dict[str, dict[str, int]] = {} + for r in refs: + chosen.setdefault(r[-3:], {})[r] = 0 + block = t_group.last_position[0] + out = list(base) + generated = kept = 0 + while generated < n: + ref = pool[generated % len(pool)] + addr = lookalike_of(seed_rng, ref, *split(seed_rng, d_tier)) + generated += 1 + if att.grind and ar.keyed(PUBLIC_SEED, addr) >= t_hash: + continue # ground away: the attacker keeps only hash winners (public seed) + b = ( + seed_rng.randint(LO, block - 1) + if att.timing == "older" + else seed_rng.randint(block + 1, HI) + ) + out.append( + make_group( + addr, + ce._match(addr, chosen), + "spoofed_out", + (b, seed_rng.randrange(200), 10_000 + kept), + ) + ) + kept += 1 + return out, {"decoys": kept, "generated": generated} + + +def adaptive(victims: int = 12) -> dict[str, Any]: + """For each victim, budget and method/knowledge model: the attack (from the bounded + grid ATTACKS) that pushes the target lowest. Each attack population is generated once + and scored by every method. K1: the attacker knows the algorithm and its public seed. + K2: the selector uses a seed the attacker does not know (the attacker still uses the + public seed for grinding and tie-winner choice, and so guesses wrong).""" + runs = [(m, "K1_public_seed", PUBLIC_SEED) for m in ATTACK_METHODS] + [ + (m, "K2_secret_seed", 987_654_321) + for m in ATTACK_METHODS + if FROZEN_SELECTORS.get(m, ar.Selector("B0")).method in ("B6", "P1") + ] + worst: dict[tuple[str, str, int, int], tuple[int, Attack | None]] = {} + for v in range(victims): + base, target, refs, tier = victim(v) + for budget in ATTACK_BUDGETS: + for att in ATTACKS: + pop, info = attack_population( + base, target, refs, tier, att, budget, _rng("attack", v, budget, att) + ) + if not info.get("decoys"): + continue + for meth, know, seed in runs: + rank = _method_rank(pop, target, meth, seed) + key = (meth, know, budget, v) + if rank > worst.get(key, (0, None))[0]: + worst[key] = (rank, att) + out: dict[str, Any] = {} + for meth, know, _seed in runs: + cell: dict[str, Any] = {} + for budget in ATTACK_BUDGETS: + ranks = [worst.get((meth, know, budget, v), (1, None))[0] for v in range(victims)] + best: dict[str, int] = {} + for v in range(victims): + won = worst.get((meth, know, budget, v), (1, None))[1] + if won is not None: + k = f"d{won.delta}/{won.alloc}/{won.timing}/grind={won.grind}" + best[k] = best.get(k, 0) + 1 + cell[str(budget)] = { + "worst_rank_median": sorted(ranks)[len(ranks) // 2], + "worst_rank_min": min(ranks), + "displaced_beyond": { + k: round(sum(1 for r in ranks if r > k) / len(ranks), 3) for k in (1, 5, 10) + }, + "best_attacks": dict(sorted(best.items(), key=lambda kv: -kv[1])[:3]), + } + out[f"{meth}/{know}"] = cell + return out + + +def _method_rank(pop: Sequence[ce.CandidateGroup], target: str, meth: str, seed: int) -> int: + if meth == "B5_pure_similarity": + ordered = sorted(pop, key=lambda g: (-ar.bits(g), g.lookalike)) + else: + ordered = ar.order( + pop, + replace(FROZEN_SELECTORS[meth], seed=seed) + if FROZEN_SELECTORS[meth].method in ("B6", "P1") + else FROZEN_SELECTORS[meth], + ) + return next(i + 1 for i, g in enumerate(ordered) if g.lookalike == target) + + +def attack_cost_curve(adaptive_out: dict[str, Any], k: int) -> dict[str, int | None]: + """The smallest budget at which the best attack displaces the median victim's target.""" + out: dict[str, int | None] = {} + for key, cell in adaptive_out.items(): + hit = None + for b in ATTACK_BUDGETS: + if cell[str(b)]["worst_rank_median"] > k: + hit = b + break + out[key] = hit + return out + + +# --- E3: counterexamples -------------------------------------------------------------------- + + +def counterexamples(trials: int = 20_000) -> dict[str, Any]: + """Bounded random search over tiny populations for each named failure type, with + greedy shrinking (drop candidates while the property still holds).""" + found: dict[str, Any] = {} + p1b, b0, rot = ( + FROZEN_SELECTORS["B8_P1b"], + FROZEN_SELECTORS["B0"], + FROZEN_SELECTORS["NC_group_rotation"], + ) + # the 12.7 theorem concerns a bucket's *first* member: weaker candidates can never move + # it down. A non-leading target can be passed by a weaker leader of another bucket (the + # group discount at work): that is recorded as a counterexample type, not a break. + invariant_breaks = {"bound": 0, "weaker_decoy_moves_bucket_leader": 0} + for i in range(trials): + rng = _rng("cx", i) + g = rng.choice((1, 2, 3)) + refs = _references(rng, g, overlap=rng.random() < 0.3) + k = rng.choice((1, 2, 3)) + cands = [] + for j in range(rng.randint(2, 6)): + ref = refs[rng.randrange(g)] + cands.append( + _Cand( + lookalike_of(rng, ref, *split(rng, rng.choice((6, 7, 8)))), + ref, + MECHS[rng.randrange(4)], + rng.randint(LO, HI), + rng.randrange(5), + "target" if j == 0 else "decoy", + ) + ) + groups, rel, _ = _groups(cands, refs) + if not rel: + continue + t = rel[0] + checks = _checks(t, k, p1b, b0, rot) + for name, prop in checks.items(): + if name not in found and prop(groups): + found[name] = _shrink(groups, t, prop) | {"K": k} + tg = next(x for x in groups if x.lookalike == t) + bound = ar.displacement_bound(groups, ce.bucket_of(tg), 4.0) + if bound is not None and _bk(groups, t, p1b) > bound: + invariant_breaks["bound"] += 1 + weaker = [x for x in groups if x.lookalike != t and ar.bits(x) < ar.bits(tg)] + if weaker: + w = weaker[0] + without = [x for x in groups if x is not w] + if _bk(groups, t, p1b) > _bk(without, t, p1b): + invariant_breaks["weaker_decoy_moves_bucket_leader"] += 1 + name = "weaker_decoy_displaces_non_leading_target" + if name not in found and _rk(groups, t, p1b) > _rk(without, t, p1b): + + def worse_with_w( + gs: list[ce.CandidateGroup], w: ce.CandidateGroup = w, t: str = t + ) -> bool: + return w in gs and _rk(gs, t, p1b) > _rk([x for x in gs if x is not w], t, p1b) + + found[name] = _shrink(groups, t, worse_with_w) | {"weaker_decoy": w.lookalike} + # multi-reference assignment: a candidate equally similar to two references + found["multi_reference_assignment"] = _multi_ref_example() + return {"trials": trials, "found": found, "invariant_breaks": invariant_breaks} + + +Prop = Callable[[list[ce.CandidateGroup]], bool] + + +def _checks(t: str, k: int, p1b: ar.Selector, b0: ar.Selector, rot: ar.Selector) -> dict[str, Prop]: + def loses_b0(gs: list[ce.CandidateGroup]) -> bool: + return _rk(gs, t, p1b) > k >= _rk(gs, t, b0) + + def loses_rotation(gs: list[ce.CandidateGroup]) -> bool: + return _rk(gs, t, p1b) > k >= _rk(gs, t, rot) + + def group_hidden(gs: list[ce.CandidateGroup]) -> bool: + return _bk(gs, t, p1b) > k + + def tie_lost(gs: list[ce.CandidateGroup]) -> bool: + return _leader_tie_lost(gs, t) + + return { + "P1b_loses_to_B0": loses_b0, + "P1b_loses_to_group_rotation": loses_rotation, + "P1b_group_not_exposed": group_hidden, + "equal_leader_tie_favours_other_group": tie_lost, + } + + +def _rk(gs: Sequence[ce.CandidateGroup], t: str, sel: ar.Selector) -> int: + return next(i + 1 for i, g in enumerate(ar.order(gs, sel)) if g.lookalike == t) + + +def _bk(gs: Sequence[ce.CandidateGroup], t: str, sel: ar.Selector) -> int: + tb = ce.bucket_of(next(g for g in gs if g.lookalike == t)) + return next(i + 1 for i, g in enumerate(ar.order(gs, sel)) if ce.bucket_of(g) == tb) + + +def _leader_tie_lost(gs: Sequence[ce.CandidateGroup], t: str) -> bool: + tg = next(g for g in gs if g.lookalike == t) + tb = ce.bucket_of(tg) + leaders: dict[str, ce.CandidateGroup] = {} + for g in gs: + b = ce.bucket_of(g) + if b.startswith("mech:"): + continue + if b not in leaders or ar.bits(g) > ar.bits(leaders[b]): + leaders[b] = g + if leaders.get(tb) is not tg: + return False + rivals = [g for b, g in leaders.items() if b != tb and ar.bits(g) == ar.bits(tg)] + return bool(rivals) and _rk(gs, rivals[0].lookalike, FROZEN_SELECTORS["B8_P1b"]) < _rk( + gs, t, FROZEN_SELECTORS["B8_P1b"] + ) + + +def _shrink( + gs: list[ce.CandidateGroup], t: str, prop: Callable[[list[ce.CandidateGroup]], bool] +) -> dict[str, Any]: + cur = list(gs) + changed = True + while changed: + changed = False + for x in list(cur): + if x.lookalike == t: + continue + trial = [y for y in cur if y is not x] + if prop(trial): + cur, changed = trial, True + break + return { + "target": t, + "candidates": [ + { + "lookalike": g.lookalike, + "bucket": ce.bucket_of(g), + "bits": ar.bits(g), + "last_position": list(g.last_position), + "mechanisms": list(g.mechanisms), + "is_target": g.lookalike == t, + } + for g in sorted(cur, key=lambda g: g.lookalike) + ], + "order_B0": [g.lookalike for g in ar.order(cur, FROZEN_SELECTORS["B0"])], + "order_P1b": [g.lookalike for g in ar.order(cur, FROZEN_SELECTORS["B8_P1b"])], + "order_rotation": [ + g.lookalike for g in ar.order(cur, FROZEN_SELECTORS["NC_group_rotation"]) + ], + } + + +def _multi_ref_example() -> dict[str, Any]: + from cryptoguard.ml.candidates import similar + + rng = _rng("multiref") + a = "0x" + _hex(rng, 40) + b = "0x" + a[2:5] + _other(rng, a[5]) + _hex(rng, 32) + _other(rng, a[-4]) + a[-3:] + cand = "0x" + a[2:5] + _other(rng, a[5]) + _hex(rng, 32) + _other(rng, a[-4]) + a[-3:] + chosen = {a[-3:]: {a: 0, b: 0}} + m = ce._match(cand, chosen) + return { + "references": [a, b], + "candidate": cand, + "similar_to": {"a": list(similar(cand, a) or ()), "b": list(similar(cand, b) or ())}, + "assigned": m[0] if m else None, + "rule": ( + "equal sum and suffix: the lexicographically larger reference " + "(candidate_evidence._match); label-independent" + ), + } + + +# --- fidelity, regression, performance ------------------------------------------------------ + + +def fidelity(n: int = 30) -> dict[str, Any]: + """Rebuild a sample of generated scenarios through real fixtures and ``build``: the + groups' references, affixes and mechanisms, and P1b's order, must match.""" + from cryptoguard.ml import reliability_study as rs + + usdt, fake = rs.USDT, rs.FAKE + checked = mismatched = 0 + sample = [sp for sp in specs() if sp.m <= 100][ + :: max(1, len([sp for sp in specs() if sp.m <= 100]) // n) + ][:n] + for sp in sample: + sc = generate(sp) + transfers: list[tuple[Any, ...]] = [] + native: list[tuple[Any, ...]] = [] + for g in sc.groups: + mech = ( + "native_dust" + if g.kinds == ("native",) + else ( + "spoofed_out" + if "spoofed_out" in g.mechanisms + else "fake_token_in" + if "untrusted_token_in" in g.mechanisms + else "zero_value_in" + ) + ) + blk = g.last_position[0] + if mech == "native_dust": + native.append((g.lookalike, 1, blk, True)) + elif mech == "spoofed_out": + transfers.append( + (rs.WALLET, g.lookalike, 0, blk, rs.ATTACKER, usdt, g.last_position[1]) + ) + elif mech == "fake_token_in": + transfers.append( + (g.lookalike, rs.WALLET, 10**18, blk, None, fake, g.last_position[1]) + ) + else: + transfers.append((g.lookalike, rs.WALLET, 0, blk, None, usdt, g.last_position[1])) + groups = [ + replace(g, victim=rs.WALLET.lower(), identity=f"1:{rs.WALLET.lower()}:{g.lookalike}") + for g in sc.groups + ] + fx = rs.wallet_fixture( + transfers=transfers, + native=native, + wallet_txs=[(r, 10**15, 1_101 + i) for i, r in enumerate(sc.references)], + ) + built = ce.build(fx, cutoff=(9_001, 0)) + a = {g.lookalike: (ce.bucket_of(g), g.affix, g.mechanisms) for g in groups if g.references} + b = { + g.lookalike: (ce.bucket_of(g), g.affix, g.mechanisms) + for g in built.groups + if g.references + } + sel = FROZEN_SELECTORS["B8_P1b"] + oa = [g.lookalike for g in ar.order([g for g in groups if g.references], sel)] + ob = [g.lookalike for g in ar.order([g for g in built.groups if g.references], sel)] + checked += 1 + mismatched += int(a != b or oa != ob) + return {"scenarios": checked, "mismatched": mismatched} + + +def regression(poisoning_dir: Path) -> dict[str, Any]: + """E4: the two known incidents (development cases, not validation).""" + from cryptoguard.ml import adversarial_benchmark as ab + from cryptoguard.ml import reliability_study as rs + + out = ab.development_cases(poisoning_dir) + for row in out.values(): + row["label"] = "known development case - not independent validation" + + pages = {} + for name, fx, cut in rs.eligible_windows(poisoning_dir): + if name not in out: + continue + res = ar.select(ce.build(fx, cutoff=cut), FROZEN_SELECTORS["B8_P1b"]) + s = ce.summarize(res, 1) + seen, off = [i["identity"] for i in s["top"]], s["next_offset"] + while off is not None: + pg = ce.page(res, offset=off, limit=1, expect_digest=s["result_digest"]) + seen += [i["identity"] for i in pg["items"]] + off = pg["next_offset"] + pages[name] = { + "all_groups_reachable": seen == [g.identity for g in res.groups], + "groups": len(res.groups), + } + return {"cases": out, "pagination": pages} + + +def performance(sizes: Sequence[int] = (100, 1_000, 10_000, 100_000)) -> list[dict[str, Any]]: + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + out = [] + for n in sizes: + rng = _rng("perf", n) + refs = _references(rng, 10, overlap=False) + cands = [ + _Cand( + lookalike_of(rng, refs[i % 10], *split(rng, _tier_iid(rng))), + refs[i % 10], + MECHS[i % 4], + rng.randint(LO, HI), + rng.randrange(200), + "decoy", + ) + for i in range(n) + ] + groups, _, _ = _groups(cands, refs) + row: dict[str, Any] = {"candidates": n} + for meth in ("B0", "B8_P1b"): + tracemalloc.start() + t0 = time.perf_counter() + ar.order(groups, FROZEN_SELECTORS[meth]) + sec = time.perf_counter() - t0 + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + row[meth] = {"seconds": round(sec, 3), "peak_traced_mib": round(peak / 2**20, 2)} + rss = peak_rss_bytes() + row["process_peak_rss_mib"] = None if rss is None else round(rss / 2**20, 1) + out.append(row) + del groups, cands + return out + + +# --- entry point ---------------------------------------------------------------------------- + + +def main( + poisoning_dir: Path, out: Path, *, manifest_only: bool = False, adaptive_victims: int = 12 +) -> dict[str, Any]: + import subprocess + + from cryptoguard.ml.adversarial_benchmark import free_ram_bytes + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + frozen = verify_frozen() + out.mkdir(parents=True, exist_ok=True) + if manifest_only: + man = manifest() + (out / "manifest.json").write_text( + json.dumps(man, indent=1, sort_keys=True) + "\n", encoding="utf-8" + ) + return {"frozen": frozen, "manifest": man} + t0 = time.perf_counter() + free = free_ram_bytes() + try: + git = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + git = None + prim = primary() + summary = summarize_primary(prim) + result: dict[str, Any] = { + "study": STUDY_VERSION, + "protocol": "protocol-12.7.1", + "git": git, + "rpc_requests": 0, + "preflight_free_ram_mib": None if free is None else round(free / 2**20), + "frozen": frozen, + "categories": { + "E2": "sealed debiased synthetic benchmark (primary)", + "E3": "adaptive attacker and counterexamples (exploratory)", + "E4": "known incidents (regression; not validation)", + }, + "E2": summary, + "E2_seconds": prim["seconds"], + } + del prim + t_a = time.perf_counter() + adapt = adaptive(adaptive_victims) + result["E3_adaptive"] = { + "victims": adaptive_victims, + "attack_grid": len(ATTACKS), + "budgets": list(ATTACK_BUDGETS), + "cap": ATTACK_CAP, + "cells": adapt, + "cost_to_displace_K5": attack_cost_curve(adapt, 5), + "cost_to_displace_K10": attack_cost_curve(adapt, 10), + "seconds": round(time.perf_counter() - t_a, 1), + } + result["E3_counterexamples"] = counterexamples() + result["fidelity"] = fidelity() + result["E4"] = regression(poisoning_dir) + result["performance"] = performance() + peak = peak_rss_bytes() + result["resources"] = { + "seconds": round(time.perf_counter() - t0, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + } + (out / "adaptive-validation.json").write_text( + json.dumps(result, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" + ) + return result diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 0c6bfc4..24961ff 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,16 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + ava = ml.add_parser( + "adaptive-validation", + help="Phase 12.7.1 debiased synthetic validation and adaptive attacker (offline)", + ) + ava.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.7.1") + ava.add_argument( + "--manifest-only", + action="store_true", + help="generate the sealed scenario manifest without running any selector", + ) adv = ml.add_parser( "adversarial-ranking", help="Phase 12.7 adversarial candidate exposure and learning-to-rank study (offline)", @@ -220,6 +230,20 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "adaptive-validation": + import json + + from cryptoguard.ml import adaptive_validation + + result = adaptive_validation.main( + ML_DIR / "poisoning", args.out, manifest_only=args.manifest_only + ) + brief = result.get("manifest") or { + "H1": result["E2"]["H1"]["verdict"], + "resources": result["resources"], + } + print(json.dumps(brief, indent=1, default=str)) + return 0 if args.ml_command == "adversarial-ranking": import json diff --git a/tests/test_ml_adaptive_validation.py b/tests/test_ml_adaptive_validation.py new file mode 100644 index 0000000..b82b94d --- /dev/null +++ b/tests/test_ml_adaptive_validation.py @@ -0,0 +1,263 @@ +"""Protocol 12.7.1: generator neutrality, frozen selectors, metrics, the bounded attacker and +the counterexample search. Every expectation follows from a definition; none reads a primary +outcome.""" + +from __future__ import annotations + +import math +from dataclasses import replace + +import pytest + +from cryptoguard.ml import adaptive_validation as av +from cryptoguard.ml import adversarial_ranking as ar +from cryptoguard.ml import candidate_evidence as ce + + +def _specs(family: str, m: int, g: int | None = None) -> list[av.Spec]: + return [ + s for s in av.specs() if s.family == family and s.m == m and (g is None or s.groups == g) + ] + + +# --- the design -------------------------------------------------------------------------- + + +def test_design_is_the_registered_grid() -> None: + sp = av.specs() + assert len(sp) == len(av.FAMILIES) * len(av.G_GRID) * sum(av.SEEDS_PER_M.values()) == 7_200 + assert len({s.key for s in sp}) == len(sp) # unique scenario identifiers + for fam in av.FAMILIES: # every template sees every age relation + for g in av.G_GRID: + ages = {s.age for s in sp if s.family == fam and s.groups == g and s.m == 100} + assert ages == set(av.AGE_RELATIONS) + + +def test_generation_is_reproducible_and_seed_specific() -> None: + a, b = _specs("F4_equal_uniform", 10, 5)[:2] + assert av.scenario_hash(av.generate(a)) == av.scenario_hash(av.generate(a)) + assert av.scenario_hash(av.generate(a)) != av.scenario_hash(av.generate(b)) + + +def test_frozen_selectors_are_verified() -> None: + info = av.verify_frozen() + assert info["config_hashes"] == av.FROZEN_CONFIG_HASHES + assert ar.config_hash(av.FROZEN_SELECTORS["B8_P1b"]) == "8b3795e363aad678" + assert ar.config_hash(replace(av.FROZEN_SELECTORS["B8_P1b"], lam=5.0)) != "8b3795e363aad678" + + +# --- neutrality ---------------------------------------------------------------------------- + + +def _diags(family: str, m: int = 10) -> list[dict]: + return [av.diagnostics(av.generate(s)) for s in _specs(family, m)] + + +def test_target_address_and_list_position_carry_no_signal() -> None: + ds = _diags("F4_equal_uniform") + _diags("F2_equal_other_groups") + assert abs(sum(d["address_pct"] for d in ds) / len(ds) - 0.5) < 0.08 + assert abs(sum(d["list_pct"] for d in ds) / len(ds) - 0.5) < 0.08 + + +def test_target_age_is_balanced_across_relations() -> None: + ds = _diags("F4_equal_uniform", 100) + oldest = sum(d["oldest"] for d in ds) / len(ds) + newest = sum(d["newest"] for d in ds) / len(ds) + assert abs(oldest - newest) < 0.08 + assert abs(sum(d["age_pct"] for d in ds) / len(ds) - 0.5) < 0.08 + + +def test_mechanism_is_unique_only_where_the_relation_says_so() -> None: + for s in _specs("F4_equal_uniform", 100)[:40]: + d = av.diagnostics(av.generate(s)) + if s.mech in ("same", "majority_same"): + assert not d["mech_unique"] + if s.mech == "target_unique": + assert d["mech_unique"] + + +def test_target_reference_is_not_systematically_first_or_largest() -> None: + ds = [av.diagnostics(av.generate(s)) for s in _specs("F4_equal_uniform", 100, 5)] + pcts = [d["ref_sorted_pct"] for d in ds if d["ref_sorted_pct"] is not None] + assert 0.3 < sum(pcts) / len(pcts) < 0.7 + assert sum(d["largest_group"] for d in ds) / len(ds) < 0.6 + + +# --- family semantics ---------------------------------------------------------------------- + + +def _target_group(sc: av.Scenario, i: int = 0) -> ce.CandidateGroup: + return next(g for g in sc.groups if g.lookalike == sc.relevant[i]) + + +def test_equal_similarity_families() -> None: + sc = av.generate(_specs("F3_equal_own_group", 100, 5)[0]) + tg = _target_group(sc) + decoys = [g for g in sc.groups if g.lookalike in sc.attacker] + assert all(ar.bits(g) == ar.bits(tg) for g in decoys) + assert all(ce.bucket_of(g) == ce.bucket_of(tg) for g in decoys) + + +def test_stronger_and_weaker_targets() -> None: + for fam, cmp in ( + ("F1_target_stronger", lambda d, t: d < t), + ("F5_target_weaker", lambda d, t: d > t), + ): + sc = av.generate(_specs(fam, 100, 5)[0]) + tb = ar.bits(_target_group(sc)) + assert all(cmp(ar.bits(g), tb) for g in sc.groups if g.lookalike in sc.attacker), fam + + +def test_same_total_split_keeps_the_total_and_changes_the_split() -> None: + sc = av.generate(_specs("F7_same_total_split", 100, 5)[0]) + tg = _target_group(sc) + t_split = tg.references[0][1:] + decoys = [g for g in sc.groups if g.lookalike in sc.attacker] + assert all(ar.bits(g) == ar.bits(tg) for g in decoys) + assert any(g.references[0][1:] != t_split for g in decoys) + + +def test_reference_overlap_decoys_land_in_one_overlapping_pair() -> None: + """Decoys are designed against one reference of an overlapping pair (3+3 shared). A + decoy that ties both is assigned by the pipeline's label-independent rule, so decoys land + in at most two buckets, and two buckets are always an overlapping pair.""" + for s in _specs("F8_reference_overlap", 10, 5)[:8]: + sc = av.generate(s) + buckets = {ce.bucket_of(g) for g in sc.groups if g.lookalike in sc.attacker} + assert 1 <= len(buckets) <= 2 + if len(buckets) == 2: + a, b = sorted(buckets) + assert a[2:5] == b[2:5] + assert a[-3:] == b[-3:] + + +def test_several_relevant_and_equal_leaders() -> None: + sc = av.generate(_specs("F9_several_relevant", 10, 5)[0]) + assert len(sc.relevant) == 3 + assert len({ce.bucket_of(_target_group(sc, i)) for i in range(3)}) == 3 + sc = av.generate(_specs("F10_equal_leaders", 10, 5)[0]) + tb = ar.bits(_target_group(sc)) + leaders: dict[str, int] = {} + for g in sc.groups: + if g.references: + leaders[ce.bucket_of(g)] = max(leaders.get(ce.bucket_of(g), 0), ar.bits(g)) + assert set(leaders.values()) <= {tb, 36, 32, 28, 24} # background may exceed; leaders tie + assert sum(1 for v in leaders.values() if v == tb) >= 2 + + +def test_null_family_target_is_an_ordinary_candidate() -> None: + ds = _diags("F6_exchangeable_null", 100) + assert abs(sum(d["age_pct"] for d in ds) / len(ds) - 0.5) < 0.1 + + +def test_groups_carry_no_oracle() -> None: + sc = av.generate(_specs("F4_equal_uniform", 10, 5)[0]) + fields = set(ce.CandidateGroup.__dataclass_fields__) + assert not any("target" in f or "relevant" in f or "oracle" in f for f in fields) + assert all(g.evidence for g in sc.groups) # every candidate keeps its record + + +# --- metrics ------------------------------------------------------------------------------- + + +def test_exposure_and_score() -> None: + assert av._exposure([1, 4, 60], 3) == pytest.approx(1 / 3) + row = {"r": [1], "b": [1]} + assert av.score(row) == 1.0 + row = {"r": [4], "b": [1]} + assert av.score(row) == pytest.approx(4 / 6) # exposed at K = 5, 10, 20, 50 (of 6) + assert av.score(row, "b") == 1.0 + + +def _row(fam: str, g: int, m: int, a: int, b: int) -> dict: + return { + "family": fam, + "G": g, + "m": m, + "age": "target_random", + "mech": "mixed_independent", + "methods": {"A": {"r": [a], "b": [a]}, "B": {"r": [b], "b": [b]}}, + } + + +def test_paired_uses_equal_template_and_family_weights() -> None: + f1, f2 = av.PRIMARY_FAMILIES[:2] + rows = [_row(f1, 1, 0, 1, 100)] * 9 + [_row(f1, 2, 0, 100, 100)] + [_row(f2, 1, 0, 100, 100)] + out = av.paired(rows, "A", "B", n_boot=50) + # f1: template (1,0) diff 1.0 (9 rows), template (2,0) diff 0 -> family 0.5; f2: 0 + assert out["per_family"][f1] == pytest.approx(0.5) + assert out["mean"] == pytest.approx(0.25) + assert out["templates"] == 3 + assert out["scenarios"] == 11 + + +def test_control_family_is_excluded_from_the_primary_estimate() -> None: + rows = [ + _row("F6_exchangeable_null", 1, 0, 1, 100), + _row(av.PRIMARY_FAMILIES[0], 1, 0, 100, 100), + ] + assert av.paired(rows, "A", "B", n_boot=10)["mean"] == 0.0 + + +def test_evaluate_reports_every_method_and_a_permutation() -> None: + sc = av.generate(_specs("F16" if False else "F9_several_relevant", 10, 5)[0]) + ev = av.evaluate(sc) + assert set(ev["methods"]) == set(av.METHODS) + for row in ev["methods"].values(): + assert len(row["r"]) == 3 + assert all(1 <= r <= len(sc.groups) for r in row["r"]) + assert all(b <= r for b, r in zip(row["b"], row["r"], strict=True)) + + +# --- the attacker and counterexamples ------------------------------------------------------ + + +def test_attacker_only_adds_and_respects_budget() -> None: + base, target, refs, tier = av.victim(1) + snapshot = list(base) + for att in av.ATTACKS[:12]: + pop, info = av.attack_population(base, target, refs, tier, att, 100, av._rng("t", att)) + assert base == snapshot # existing records untouched + assert pop[: len(base)] == base + assert info["decoys"] <= min(av.ATTACK_CAP, int(100 * 16.0 ** (-att.delta))) + assert all(g.lookalike not in {r.lower() for r in refs} for g in pop) + + +def test_attacker_cannot_go_below_the_similarity_rule() -> None: + base, target, refs, _ = av.victim(0) + pop, info = av.attack_population( + base, target, refs, 6, av.Attack(-1, "own", "newer", False), 10, av._rng("x") + ) + assert pop == base + assert "illegal" in info + + +def test_grinding_only_keeps_hash_winners() -> None: + base, target, refs, tier = av.victim(2) + pop, info = av.attack_population( + base, target, refs, tier, av.Attack(0, "own", "newer", True), 200, av._rng("g") + ) + th = ar.keyed(av.PUBLIC_SEED, target) + added = pop[len(base) :] + assert all(ar.keyed(av.PUBLIC_SEED, g.lookalike) < th for g in added) + assert info["generated"] == 200 >= info["decoys"] + + +def test_counterexample_search_terminates_and_shrinks() -> None: + out = av.counterexamples(trials=300) + assert out["trials"] == 300 + assert out["invariant_breaks"] == {"bound": 0, "weaker_decoy_moves_bucket_leader": 0} + for name, cx in out["found"].items(): + if name == "multi_reference_assignment": + continue + assert sum(c["is_target"] for c in cx["candidates"]) == 1 + + +def test_fidelity_against_the_real_pipeline() -> None: + assert av.fidelity(4)["mismatched"] == 0 + + +def test_lambda_infinity_selector_is_pure_rotation() -> None: + sel = av.FROZEN_SELECTORS["NC_group_rotation"] + assert math.isinf(sel.lam) + assert sel.nosim From ffbdb6af9a77b99d8cba11054e5c1b99bdb639e2 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 10 Nov 2026 01:05:28 +0300 Subject: [PATCH 83/92] docs(ml): Phase 12.7.1 report - P1b not supported after debiasing (no RPC) ML_ADAPTIVE_RANKING_VALIDATION.md (35 sections, gates). Sealed primary run on d98a636 (manifest 2e294aeb... reproduced; 7,200 scenarios; run once): paired P1b - B0 = -0.018 [-0.031, -0.004] over 225 templates, so the pre-registered classification is "not supported after debiasing". P1b gains under other-group floods (+0.14) and on reference-group exposure (+0.032 [0.024, 0.041]) and loses under own-group equal floods (-0.12); reference round-robin B4 edges it. Adaptive attacker: 10 equal-tier own-group lookalikes displace the target under every method (H2 not supported). The 12.7 theorem holds (0 breaks in 20,000 trials). The 12.7 report gains a pointer to this result; its text is unchanged. Co-Authored-By: Claude --- CHANGELOG.md | 11 + ML_ADAPTIVE_RANKING_VALIDATION.md | 653 ++++++++++++++++++++++++++++++ ML_ADVERSARIAL_RANKING.md | 2 + 3 files changed, 666 insertions(+) create mode 100644 ML_ADAPTIVE_RANKING_VALIDATION.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 59c1afa..4619d2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,17 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.7.1: debiased validation of P1b against an adaptive adversary (no RPC requests) +- **Protocol 12.7.1** (`docs/ml/protocol-12.7.1.md`) was frozen with the generator, the evaluation code and a sealed manifest (7,200 scenarios, 5,079,472 candidates) before any selector ran. P1 and P1b were frozen by source hash and config hash. +- **New independent generator:** random addresses, references assigned by the pipeline's own `_match`, shuffled populations, balanced target age (8 relations), mechanism (5), reference and similarity, and a null family. Fidelity: 30 of 30 rebuilt scenarios matched. +- **H1 not supported after debiasing (pre-registered):** P1b − B0 = −0.018 [−0.031, −0.004]. + - Gains under other-group floods (+0.14), on reference-group exposure (+0.032) and on the shortcut-free subset (+0.054). + - Losses under own-group equal floods (F3 −0.12). + - Reference round-robin B4 edges P1b. +- **Adaptive attacker:** 10 equal-tier lookalikes of the target's own reference displace the target under every method, P1b included (H2 not supported). The identifiability limit is demonstrated. +- **The 12.7 theorem holds:** 0 breaks in 20,000 counterexample trials. Minimal counterexamples are documented. +- **Report:** `ML_ADAPTIVE_RANKING_VALIDATION.md`. P1b is not promoted. + ### Phase 12.7: adversarial candidate exposure and robust top-K selection (no RPC requests) - **Protocol 12.7** (`docs/ml/protocol-12.7.md`) was frozen before any selector, benchmark or learning-to-rank code existed. The code was committed before the measured run. - **`adversarial-selection/1`** (research only): diff --git a/ML_ADAPTIVE_RANKING_VALIDATION.md b/ML_ADAPTIVE_RANKING_VALIDATION.md new file mode 100644 index 0000000..cbda089 --- /dev/null +++ b/ML_ADAPTIVE_RANKING_VALIDATION.md @@ -0,0 +1,653 @@ +# Adaptive-adversary validation of P1b (Phase 12.7.1) + +| Item | Value | +|---|---| +| Protocol (frozen before any selector ran on the sealed scenarios) | [`docs/ml/protocol-12.7.1.md`](docs/ml/protocol-12.7.1.md), `d98a636` | +| Frozen algorithms | `adversarial_ranking.py` from `0968ff8` (SHA-256 `2c0e65ae…`); P1b config `8b3795e363aad678`; checked at run time by `verify_frozen` | +| Sealed manifest | 7,200 scenarios, 5,079,472 candidates, SHA-256 `2e294aeb…` (reproduced by the primary run) | +| Primary run | once, on `d98a636`: 1,379 s, 310 MiB peak RSS (`cryptoguard ml adaptive-validation`) | +| Output (git-ignored) | `data/ml/research/phase12.7.1/adaptive-validation.json`, `manifest.json` | +| RPC requests / downloads | **0** / none | + +**Labels used throughout:** +- **[E2]:** sealed debiased synthetic benchmark (primary). +- **[E3]:** adaptive attacker and counterexamples (exploratory). +- **[E4]:** the two known incidents (regression only). +- **[POST-HOC]:** computed after the primary results were seen. + +None of them are pooled. + +## 1. Executive summary + +**Verdict:** on a benchmark without the 12.7 shortcuts, **P1b is not supported** +(pre-registered classification: *not supported after debiasing*). +- **P1b − B0 = −0.018** mean Exposure@K, 95 % CI [−0.031, −0.004], over 225 templates and + 6,480 scenarios. The 12.7 gain (+0.29 on the old grid) does not survive. +- **P1b's 12.7 advantage came from the benchmark.** Its targets were always older than their + decoys, so B0's recency tie-break always worked against them. Under balanced timing, B0's + recency tie-break exposes the target whenever the target happens to be newest. That makes + B0 bimodal: 0.70–0.73 when the target is newest or the decoys came first, and 0.31–0.39 + otherwise. P1b reads no time and stays flat at 0.42–0.44. + +**Where P1b genuinely helps [E2]:** +- **Floods of *other* references:** +0.142 (F2) and +0.097 (F8) in address exposure, and + +0.119 / +0.116 in reference-group exposure. Overall group exposure is +0.032 [0.024, 0.041]. +- **The shortcut-free subset** (random timing, independent mechanisms): +0.054 [0.034, 0.074]. + +**Where it hurts [E2]:** whenever the target's own group is flooded with equal-strength +lookalikes. F3 is −0.121 and F4 −0.108. Its hash tie-break gives about K/(m+1), while B0's +recency gets lucky half the time. + +**Simpler baselines:** +- **B4** (reference round-robin, recency within) beats P1b: −0.018 [−0.028, −0.010]. That is + just under the pre-registered 0.02 "inferior" threshold. +- **B0** also edges P1b. +- **Mechanism round-robin (B3)** scores highest overall (0.534), but only through the + designed mechanism-shortcut conditions: 0.70–0.73 there, against 0.38–0.47 elsewhere. + +**Adaptive attacker [E3]:** +- An attacker who knows the algorithm displaces the target past K = 5 for the median victim + with **10** equal-tier lookalikes of the target's own reference, under **every** method, + P1b included (it also grinds for hashes against P1b's public seed). +- P1b requires no larger budget than B0 (H2 not supported). +- The reference *group* stays exposed: it holds the attacker's own lookalikes. + +**What stands:** +- the 12.7 theorem (a group's *first* member cannot be displaced by weaker candidates): 0 + breaks in 20,000 random trials; +- time-invariance; +- exact reproducibility; +- the bounded summary and pagination. + +**Independent real-world validation: BLOCKED BY DATA.** + +## 2. Phase 12.7 original findings (E1, development) + +| Method | 12.7 grid mean Exposure@K | +|---|---| +| Recency-first | 0.304 | +| B0 | 0.525 | +| P1 | 0.773 | +| P1b (post hoc) | 0.813 | + +Its negative controls already flagged that oldest-first scored 0.986 and mechanism +round-robin 0.839. + +## 3. Identified benchmark biases (12.7) + +1. **Age:** the target was always older than its decoys. That penalizes B0 and recency, and + rewards oldest-first. +2. **Mechanism:** the target usually differed from its decoys, which rewarded mechanism + round-robin. +3. **Reference position:** the target was always on R1, which sorts 3rd of 5, so B4's + address tie-break was not neutral. +4. **Address order:** the target's address always sorted first among equals, which rewarded + address tie-breaks. +5. **No null family.** + +The 12.7 post-hoc checks varied one factor at a time. E2 removes them all by design. + +## 4. Frozen P1b implementation + +**Definition:** group candidates by the victim reference they best imitate (bucket); member j +of a bucket gets priority `4·affix − 4·j`; order globally by priority ↓, then bucket best ↓, +then keyed hash of the bucket, then keyed hash of the member. + +| Item | Value | +|---|---| +| Source | `0968ff8`, SHA-256 `2c0e65ae…` | +| Config hash | `8b3795e363aad678` | +| Public seed | 0 | + +`verify_frozen()` refuses to run if the module or any of six config hashes differs. Nothing +changed after the protocol commit. + +## 5. Research hypotheses + +H1–H9 as in protocol §8 (decisions: §16, §18, §20, §22). + +## 6. Threat model + +**The attacker controls:** +- lookalike addresses and their tier (subject to the pipeline's rule: prefix + suffix ≥ 6, + suffix ≥ 3); +- which genuine reference each one imitates; +- planting time; +- mechanism and repetition; +- how many addresses to use. + +**The attacker does not control:** the victim's references or signatures, finalized order, +provenance, or the scoring target. + +**Knowledge:** +- **K1:** the algorithm and its public seed. +- **K2:** a seed the attacker does not know. This is a diagnostic only; a seed kept in + public configuration is not secret. + +**Costs:** +- **Address generation:** 2^(4(p+s)) key trials for one specific reference. +- **Planting:** gas per event. +- **Repetition:** gas only. + +Budgets are counted in target-tier address equivalents: one tier stronger costs ×16, one tier +weaker ÷16. No vanity search is run. + +## 7. Synthetic generator design [E2] + +**A new module,** `ml/adaptive_validation.py`. It does not copy the 12.7 scenarios. + +**Per scenario,** a seeded RNG from `sha256(MASTER | family | G | m | replicate)` generates: +- G uniformly random references; +- the target(s) and m decoys per the family; +- 5 i.i.d. background lookalikes; +- 2 unreferenced strangers. + +**How candidates are built:** +- Addresses are random apart from the designed affix. +- References are assigned by the pipeline's own `_match`. +- Groups are `CandidateGroup` records. +- The population is shuffled. +- The oracle is stored outside the groups. + +**Fidelity:** 30 of 30 scenarios rebuilt through real fixtures and `build` matched in +references, affixes, mechanisms and P1b order (0 mismatches). + +## 8. Target assignment + +- **Targets are generated** like any candidate of the family's declared tier, with a + uniform reference index, a uniform mechanism and a time from the age relation. +- **F6 (exchangeable null):** the target is a uniformly drawn member of an i.i.d. + population. +- **Diagnostics, mean over m > 0 scenarios:** the target's address percentile is 0.47–0.53, + its list-position percentile 0.49–0.51, and its sorted-reference percentile 0.48–0.52. + None is a shortcut. + +## 9. Age balancing + +- **Eight relations,** rotated so every template sees all eight: target oldest, newest, + intermediate, random, one block, decoys precede, decoys follow, overlap. +- **Target age percentile:** 0.49–0.51 in every family. +- **Oldest vs newest:** the target is oldest in 0.16–0.19 of scenarios and newest in + 0.15–0.18. In F6 both are 0.03, i.e. at chance. + +## 10. Mechanism balancing + +- **Five relations:** same, different, mixed independent, target unique (a deliberate + shortcut condition), majority same. +- **Target mechanism:** uniform. +- **Target's mechanism unique among candidates:** 0.23–0.26 of scenarios per family (0.00 in + F9, 0.02 in F6). + +## 11. Reference-group balancing + +- **G:** {1, 2, 5, 10, 25}. +- **Target in the largest group:** F2 0.02, F3 0.79 (by design), F4/F7 0.24–0.26. +- **Target in the smallest group:** F2 0.72 (by design), F3 0.00. +- **Target reference's sorted position:** about 0.5. +- **Overlapping references and multi-reference matches** are handled by the pipeline's tie + rule (§24.6). + +## 12. Similarity balancing + +| Family | Share of candidates strictly stronger than the target | +|---|---| +| F1 (target stronger) | 0.014 | +| F2–F4, F7, F8 (equal) | 0.04 (background only) | +| F5 (target weaker) | 0.84 (intrinsically ambiguous) | +| F6 | 0.34 | + +## 13. Primary evaluation protocol + +- **Templates:** 10 families × 5 G × 5 m. Replicates per template: 40 at m ≤ 100, 16 at + m = 1,000, 8 at m = 10,000. +- **K:** {1, 3, 5, 10, 20, 50}. +- **Aggregation:** equal weight by template within a family, and equal weight by family over + the 9 primary families. F6 is a control. +- **Uncertainty:** stratified template-cluster bootstrap, 2,000 resamples. +- **Run once.** + +## 14. Adaptive adversary [E3] + +**Setup:** +- **Victims:** 12 (G ∈ {2, 5, 10, 25} × tier {6, 7, 8}). +- **Budgets:** W ∈ {10, 100, 1,000}, capped at 2,000 decoys. +- **Attacks:** an exhaustive grid of 48: + - tier offset −1, 0 or +1; + - allocation: own group, other groups, uniform, or public-hash tie winners; + - timing: older or newer; + - grinding on or off. +- **Methods:** B0, B1, B4, B5, B6, P1 and P1b under K1, plus K2 for the seeded ones. +- **Rules:** additions only; references, records and receipts are untouched; illegal tiers + are rejected (tested). +- **Runtime:** 45 s. + +## 15. Baselines + +| Id | Definition | +|---|---| +| B0 | similarity → recency | +| B1 | recency → similarity | +| B2 | oldest first | +| B3 | mechanism round-robin | +| B4 | reference round-robin, recency within | +| B5 | similarity, address ties | +| B6 | similarity, keyed-hash ties | +| B7 | P1 | +| B8 | P1b | +| B9 | similarity, seeded random ties | + +Controls: newest first, random, hash order, pure group rotation. + +## 16. Primary Exposure@K results [E2] + +**Equal-family means over the 9 primary families (F6 control alongside):** + +| Method | Exposure@K | GroupExposure@K | F6 null | +|---|---|---|---| +| B3 mechanism RR (control) | 0.534 | 0.808 | 0.361 | +| A: P1b with recency ties [ablation] | 0.468 | 0.819 | 0.356 | +| B4 reference RR | 0.448 | 0.822 | 0.354 | +| **B0** | **0.447** | 0.787 | 0.357 | +| P1b λ=2 [ablation] | 0.430 | 0.818 | 0.360 | +| **P1b** | **0.429** | **0.819** | 0.360 | +| P1b λ=8 [ablation] | 0.426 | 0.822 | 0.359 | +| P1 | 0.424 | 0.817 | 0.362 | +| P1b λ=∞ [ablation] | 0.412 | 0.823 | 0.359 | +| B1 / newest first | 0.388 | 0.752 | 0.356 | +| B2 oldest first | 0.387 | 0.747 | 0.357 | +| B5 pure similarity | 0.386 | 0.742 | 0.359 | +| B6 / B9 | 0.382 | 0.763 / 0.767 | 0.362 / 0.357 | +| Pure group rotation / P1b no similarity | 0.303 | 0.751 | 0.356 | +| Random | 0.265 | 0.705 | 0.365 | +| Hash order | 0.264 | 0.704 | 0.361 | + +**H1 (pre-registered), paired P1b − B0:** + +| Measure | Value | +|---|---| +| Mean | **−0.0177** | +| 95 % CI | [−0.0313, −0.0044] | +| Shortcut-free subset (486 scenarios) | +0.054 [0.034, 0.074] | +| Worst family | F3, −0.121 | +| Simpler baseline ≥ P1b + 0.02 | none; B4 is +0.018 | + +**Classification: NOT SUPPORTED AFTER DEBIASING.** The effect criterion fails. + +**Per family (mean Exposure@K):** + +| Family | B0 | P1b | P1b − B0 | B4 | P1 | +|---|---|---|---|---|---| +| F1 target stronger | 0.881 | 0.879 | −0.002 | 0.831 | 0.875 | +| F2 equal, other groups | 0.391 | 0.533 | **+0.142** | 0.548 | 0.494 | +| F3 equal, own group | 0.389 | 0.268 | **−0.121** | 0.351 | 0.269 | +| F4 equal, uniform | 0.393 | 0.285 | −0.108 | 0.347 | 0.285 | +| F5 target weaker | 0.215 | 0.216 | +0.001 | 0.211 | 0.217 | +| F7 same total, other split | 0.387 | 0.287 | −0.101 | 0.340 | 0.290 | +| F8 reference overlap | 0.358 | 0.455 | **+0.097** | 0.458 | 0.446 | +| F9 several relevant | 0.319 | 0.261 | −0.058 | 0.290 | 0.259 | +| F10 equal leaders | 0.690 | 0.681 | −0.010 | 0.654 | 0.682 | +| F6 null (control) | 0.357 | 0.360 | — | 0.354 | 0.362 | + +**Mean Exposure@K by K:** + +| K | B0 | P1b | B4 | P1 | +|---|---|---|---|---| +| 1 | 0.119 | 0.091 | 0.101 | 0.085 | +| 3 | 0.314 | 0.270 | 0.258 | 0.263 | +| 5 | 0.442 | 0.399 | 0.388 | 0.393 | +| 10 | 0.534 | 0.524 | 0.563 | 0.522 | +| 20 | 0.624 | 0.623 | 0.669 | 0.614 | +| 50 | 0.650 | 0.670 | 0.707 | 0.670 | + +## 17. GroupExposure@K [E2] + +Reported separately: exposing the right reference is not exposing the right address. +- **P1b − B0:** +0.032 [0.024, 0.041]. +- **Gains:** F2 +0.119, F8 +0.116, F5 +0.040, F9 +0.026. +- **Losses:** F3 −0.017, F10 −0.003. +- **Ranking:** B4 0.822 and P1b 0.819 are at the top, against 0.787 for B0. + +## 18. Attack-budget curves + +**[E2] by decoy count, P1b − B0:** + +| m | 0 | 10 | 100 | 1,000 | 10,000 | +|---|---|---|---|---|---| +| P1b − B0 | −0.003 | +0.009 | +0.003 | −0.037 | **−0.061** | + +At m = 10,000 the worst-budget differences against B0 are: P1 −0.066, B6 −0.117, B4 +0.004. + +**[E2] median rank displacement (rank with decoys minus without):** + +| m | B0 | P1b | +|---|---|---| +| 10 | 5 | 3 | +| 100 | 48 | 24 | +| 1,000 | 497 | 240 | +| 10,000 | 4,988 | 2,264 | + +**[E3] adaptive, median victim's worst-case rank by budget W, with the share displaced +beyond K = 10:** + +| Method / knowledge | W=10 | W=100 | W=1,000 | Budget displacing past K=5 / K=10 | +|---|---|---|---|---| +| B0 / K1 | 13 (1.00) | 103 (1.00) | 1,003 (1.00) | 10 / 10 | +| B1 / K1 | 163 (1.00) | 1,603 | 2,003 | 10 / 10 | +| B4 / K1 | 16 (1.00) | 106 | 1,006 | 10 / 10 | +| B5 / K1 | 12 (0.75) | 86 | 775 | 10 / 10 | +| B6 / K1 | 12 (0.58) | 65 | 555 | 10 / 10 | +| B6 / K2 | 10 (0.33) | 56 | 451 | 10 / **100** | +| P1 / K1 | 13 (0.75) | 62 | 679 | 10 / 10 | +| P1 / K2 | 12 (0.83) | 52 | 441 | 10 / 10 | +| **P1b / K1** | 13 (0.75) | 62 | 680 | **10 / 10** | +| P1b / K2 | 12 (0.83) | 52 | 442 | 10 / 10 | + +**Most frequent best attacks:** +- **against B0 and B4:** equal tier, own group, newer; +- **against P1/P1b under K1:** equal tier, own group, newer, with grinding; +- **under K2:** equal tier, own group, older or newer. + +**H2: not supported.** P1b needs the same budget as B0, 10 target-tier addresses +(≈ 2^(4t+3.3) trials). + +## 19. Worst-case results + +| View | Result | +|---|---| +| Worst family | F3 (equal, own group): −0.121 vs B0 | +| Worst budget | m = 10,000: −0.061 vs B0 | +| Worst timing for B0 | target oldest: B0 0.313, P1b 0.428 | +| Worst timing for P1b | none: 0.421–0.442 across all 8 relations | + +So **P1b wins the minimax over timing, and B0 wins the mean over balanced timing.** An +attacker who controls timing picks B0's worst case. A non-adaptive or benign distribution +favours B0. + +## 20. Negative controls + +| Control | Result | +|---|---| +| **F6 exchangeable null** | every method 0.354–0.365 (random 0.365): **no leakage** | +| **Pseudo-target** (random non-relevant referenced candidate) | B0 0.29–0.41, P1b 0.29–0.39, random 0.31–0.39 per family: no method singles out non-targets | +| **Oldest first** | 0.94 when the target is oldest, 0.17 when newest | +| **Newest first** | the mirror image | +| **Mean over balanced age** | both 0.387: **no residual age shortcut** | +| **Mechanism round-robin** | 0.699 / 0.727 in "different" / "target unique" (shortcut conditions), 0.385 / 0.386 / 0.472 in "majority same" / "mixed" / "same": **driven by the designed shortcut** | +| **Hash order / random** | 0.26 | +| **Shuffled timestamps / mechanisms** | P1b is invariant by construction (12.7 tests) | + +**H6/H7, P1b by mechanism relation:** 0.424–0.438, flat. **By age relation:** 0.421–0.442, +flat. Both supported. B0 ranges 0.31–0.73 over age. + +## 21. Feature-leakage audit + +**Selectors receive only `CandidateGroup` records.** No field carries the target, the +relevant set or generator metadata (tested). +- **Addresses:** uniformly random apart from the affix. +- **List order:** shuffled. The target's list percentile is about 0.5. +- **Scenario identifiers:** never passed to a selector. +- **References:** assigned by the pipeline's label-independent `_match`. +- **Time:** no future information exists in the synthetic window; P1b reads no time at all. +- **E4:** uses pre-cutoff fixtures only. +- **F6 at chance** for every method (§20) is the end-to-end leakage check. + +## 22. Ablations [E2] + +| Variant | Mean | Δ vs P1b | +|---|---|---| +| P1b (λ = 4, bucket-hash ties) | 0.429 | — | +| Recency ties within a bucket | **0.468** | +0.039 | +| λ = 2 | 0.430 | +0.001 | +| λ = 8 | 0.426 | −0.004 | +| P1 (member-hash ties) | 0.424 | −0.005 [−0.008, −0.002] | +| λ = ∞ | 0.412 | −0.017 | +| No reference grouping / no discount (= B6) | 0.382 | −0.047 | +| No similarity (pure rotation) | 0.303 | −0.126 | + +- **What contributes:** similarity, then grouping. +- **The bucket-hash fix** helps slightly over P1. +- **Hash ties within a bucket** cost against balanced timing. The recency-tie variant is the + best P1b variant, but it re-imports B0's timing exposure, and an adaptive attacker defeats + it the same way. +- **Not a replacement:** these are ablations on E2. No P1c is substituted. + +## 23. Theoretical properties + +1. **Complexity:** O(n log n), with one SHA-256 per candidate per hash use. No pairwise + structure. +2. **Determinism:** fixed input and seed give a fixed order, independent of input order + (tested). +3. **Duplicates:** a repeated event does not create a candidate. Grouping is by address. +4. **Weaker candidates:** + - **Theorem:** for a bucket T with best bits b, a candidate with bits < b, added anywhere, + cannot precede T's first member. Its priority is ≤ its bits < b, and it never raises + another member's priority. + - **Not claimed:** a weaker leader of *another* bucket *can* precede a **non-leading** + member of T. That member's priority is b − 4j (counterexample §24.5). + - **20,000 trials:** 0 breaks of the theorem, 0 breaks of the bound. +5. **Equal-score candidates:** order among equals is decided by the keyed hash. Under a known + seed this is attacker-controllable by grinding (§25). +6. **Group-level rank bound:** the first member of T sits at a position + ≤ 1 + Σ_{g ≠ T, best_g ≥ b} min(n_g, ⌊(best_g − b)/λ⌋ + 1). It does not depend on how many + weaker candidates exist. +7. **Dependence on G:** with equal leaders the bound is about G, so group exposure at K + needs G ≤ K. G is the victim's reference count, which the attacker cannot change. +8. **Group assignment:** + - The attacker chooses which reference to imitate, but cannot create references. + - A candidate that ties two references goes to the lexicographically larger one, a + label-independent rule (§24.6). + - The attacker can exploit this only by choosing an affix, which is within capability. +9. **Tie sensitivity:** see §22. Hash ties make the target's position among m equals uniform: + exposure ≈ K'/(m+1). +10. **Observational equivalence:** if the target and m ≥ K decoys agree on every feature a + selector reads, no deterministic selector whose tie rule the attacker knows can + guarantee exposure. The adaptive attacker achieves this with 10 addresses (§18). + +## 24. Minimal counterexamples [E3] + +**Search:** 20,000 random populations, shrunk greedily. Each counterexample below is feasible +under the threat model, and **none breaks an invariant.** + +1. **P1b loses to B0 (K = 1), 2 candidates:** two 32-bit lookalikes of the same reference, + with the target newer. B0's recency tie-break puts the target first; P1b's hash puts the + other first. +2. **P1b loses to pure group rotation (K = 1), 2 candidates:** a 24-bit target and a 32-bit + candidate on the same reference. Rotation ignores similarity, and its hash happens to put + the target first. +3. **P1b's group not exposed (K = 1), 2 candidates:** a 24-bit target, and a 32-bit leader + on another reference that rightly comes first. +4. **Equal-leader tie lost, 2 candidates:** two 32-bit leaders of different references. The + bucket hash decides; under a public seed it is predictable but not attacker-choosable, + because references belong to the victim. +5. **Weaker decoy displaces a non-leading target, 4 candidates:** + - the target is the 3rd of three 28-bit members of its bucket (priority 20); + - a 24-bit leader of another bucket (priority 24) precedes it. + This is the group discount working as designed. +6. **Multi-reference assignment:** a candidate that matches two references at 3+3 is assigned + to the lexicographically larger. + +## 25. Public versus secret tie-breaking + +**Public seed (K1).** An attacker can grind addresses whose member hash beats the target's, +at a cost of about 1/F(h_t) generated addresses per kept decoy. +- Grinding was part of the best attack against P1/P1b at every budget. +- B6 is also defeated at W = 10 for K = 5. + +**Secret seed (K2, diagnostic).** It raised the budget needed to displace past K = 10 only for +B6 (10 → 100). For P1/P1b it changed little (displaced share 0.83 vs 0.75 at W = 10), because +own-group equal floods win without grinding. + +**Conclusion:** a secret seed does not rescue P1b. Its operational assumption (the seed never +appears in configuration or evidence) is also fragile. No production secrets were introduced. + +## 26. Statistical uncertainty + +- **Unit:** the template (225 primary). Replicates within a template are not independent + incidents. +- **Method:** stratified template-cluster bootstrap. +- **Counts:** + - E2: 7,200 scenarios (6,480 primary); + - 5,079,472 candidates (never treated as independent observations); + - target identities: one per scenario (three in F9). +- **The E3 adaptive study** has 12 victims and is exploratory (no CI). + +## 27. Existing incident regression [E4] — known development cases, not independent validation + +| Window | Paid is a candidate | B0 | B1 | B4 | B6 | P1 | P1b | Pagination | +|---|---|---|---|---|---|---|---|---| +| ScamSniffer `/1` | no (native dust not recorded) | — | — | — | — | — | — | all 2 groups reachable | +| ScamSniffer blind `/2` | yes | 1 | 3 | 1 | 1 | 1 | 1 | all 3 reachable | +| Pilot | yes | 3 | 2 | 3 | 3–5 | 3–5 | 3–5 (seed 0: 5) | all 6 reachable | + +These are identical to Phase 12.7. Nothing was tuned on them. + +## 28. Performance + +**Ordering only, on generated groups:** + +| Candidates | B0 | P1b | +|---|---|---| +| 100 | <0.001 s | 0.003 s | +| 1,000 | 0.007 s | 0.045 s | +| 10,000 | 0.116 s | 0.404 s | +| 100,000 | 1.23 s | **4.79 s** | + +**Whole run:** +- E2: 1,303 s for 7,200 scenarios × 19 methods; +- E3: 45 s; +- total: 1,379 s. + +## 29. Memory + +- **Traced peak:** P1b 30.3 MiB and B0 27.4 MiB at 100,000 candidates. +- **Process peak RSS:** 310 MiB for the whole study, in one process with streaming aggregation. +- **Preflight free RAM:** 804 MiB. + +## 30. Production isolation + +- Research-only modules (`adaptive_validation.py`, CLI `ml adaptive-validation`). +- `adversarial_ranking.py` is unchanged and verified by hash. +- The detector, its warnings and severities are untouched. +- No new dependency. numpy is used only in the bootstrap, imported lazily. +- No evidence is deleted. + +## 31. Positive findings + +1. P1b's reference grouping helps when *other* references are flooded: +0.14 address, + +0.12 group exposure (F2). +2. P1b is time- and mechanism-invariant (flat across 8 age and 5 mechanism relations). Its + worst timing case is 0.42, against B0's 0.31. +3. Reference-group exposure is better than B0's: +0.032 [0.024, 0.041]. +4. The 12.7 theorem holds (0 breaks in 20,000 trials). Fidelity 30/30; reproducible. +5. The debiased benchmark works: the null family is at chance, and the controls behave as + designed. + +## 32. Negative findings + +1. **H1 is not supported after debiasing.** P1b − B0 = −0.018 [−0.031, −0.004]. The 12.7 + gain was largely a benchmark artifact (the age bias). +2. **H2 is not supported.** An adaptive attacker displaces P1b's target with the same 10 + equal-tier addresses as B0's. +3. **A simpler baseline (B4) beats P1b** by 0.018 (CI excludes 0), just under the + pre-registered 0.02 line. +4. **Hash ties cost against balanced timing** (recency-tie variant 0.468 vs 0.429). +5. **The worst family regresses:** −0.121 (F3). + +## 33. Unresolved limitations + +- **Synthetic only.** Real age, mechanism and reference distributions are unknown. + Phase 12.1's archive found victims usually pay the *most recent* lookalike, which would + favour B0's recency tie-break in non-adversarial data. +- **Adaptive study scope:** 12 victims and 48 attacks with a 2,000-decoy cap, not a full + optimizer. +- **Proxies:** H5 used F10 bucket position as a proxy (P1b 0.48–0.58, no drift). It does not + isolate group-size bias as directly as the 12.7 test did. +- **Similarity model:** exact hex affixes only. + +## 34. Independent real-world validation requirements + +**Untouched poisoning incidents with:** +- several genuine reference recipients; +- the paid address and its reference (from the harm transaction, used only for scoring); +- an `observation/2` window to H − 1; +- no wallet, campaign or cohort overlap; +- the frozen methods (B0, B4, P1b; seed recorded). + +**Measures:** +- address and reference-group exposure separately; +- the age distribution of the paid lookalike relative to its rivals, which decides whether + recency or hash ties are better in reality. + +**Feasibility and cost:** +- 10 incidents is only a feasibility check; about 70 are needed for a powered paired test; +- about 700 to 1,300 RPC requests per window; +- **0 requested here.** + +## 35. Final scientific conclusion + +**Classification: not supported after debiasing** (pre-registered). + +**What happened.** P1b's 12.7 advantage over similarity-first does not survive a benchmark +without the target-age, mechanism, reference-position and address-order shortcuts. +- **Average:** recency tie-breaking (B0) does as well or better than P1b's hash ties whenever + the attacker does not control timing. +- **Simpler alternatives:** reference round-robin (B4) is slightly better than P1b. +- **Adaptive attacker:** an attacker who controls timing and can afford about 10 equal-tier + lookalikes of the target's own reference defeats every method, P1b included. That is the + identifiability limit. + +**What survives, under a narrow threat model:** +- grouping by reference keeps a reference visible when *other* references are flooded; +- P1b is insensitive to timing, so it has the better worst case over timing. + +**No learned model is justified:** the synthetic task has no real outcome signal, and +Phase 12.7's archive LTR learned only recency. + +**Recommendation:** +- **Do not promote P1b.** +- **Treat reference-group exposure, not address exposure, as the defensible target** for + warnings. +- **Settle the remaining question (recency vs hash ties) with real data, not more + simulation.** + +**Next experiment (not started).** On at least 10 untouched, multi-reference `observation/2` +incidents (about 70 for power): +- **Measure:** whether the paid lookalike's reference group is exposed within the top 5 under + B4 vs B0, and where the paid lookalike sits in time among its equal-similarity rivals. +- **Labels:** the paid address and its reference. +- **Cost:** about 700 to 1,300 RPC requests per window. +- **Falsification:** reference-group exposure does not differ between B4 and B0 (cluster + sign test, one-sided α = 0.05, over the discordant incidents), **or** the paid lookalike is + not more often the newest among its equal rivals than chance. That second outcome would + remove the reason to keep recency ties. + +**Phase 12.8 is not started.** + +## Gates + +| Gate | Status | Basis | +|---|---|---| +| A Benchmark neutrality | **PASS** | diagnostics ≈ 0.5; null family at chance; age and mechanism controls behave as designed | +| B Historical correctness | **PASS** | selectors read pre-cutoff group features only; fidelity 30/30; no oracle field | +| C P1b improvement | **FAIL** | −0.018 [−0.031, −0.004] | +| D Adaptive robustness | **FAIL** | the same budget (10) displaces P1b and B0 | +| E Worst-family behaviour | **FAIL** | F3 −0.121; m = 10,000 −0.061 | +| F Target-group exposure | **PASS WITH LIMITATIONS** | reported separately: +0.032 [0.024, 0.041]; gains concentrated in other-group floods | +| G Tie-breaking | **PASS WITH LIMITATIONS** | the bucket-hash fix is neutral (no drift in F10; P1b − P1 +0.005); a public seed allows grinding | +| H Identifiability | **PASS** | the limit is stated and demonstrated (F3; adaptive own-group floods) | +| I Evidence preservation | **PASS** | permutations only; E4 pagination reaches every group | +| J Performance | **PASS** | 100,000 candidates in 4.8 s, 30 MiB; study 310 MiB | +| K Reproducibility | **PASS** | sealed manifest reproduced; 100-scenario re-evaluation identical | +| L Independent real-world validation | **BLOCKED BY DATA** | no untouched incidents | + +## Validation + +| Check | Result | +|---|---| +| `ruff check .` / `ruff format --check .` | clean / 302 files formatted | +| `mypy src` (Windows and `--platform linux`) | clean (156 files) on both | +| Full suite | **1,075 passed, 0 failed**, 4 deselected (15 min 27 s); 24 new tests in `tests/test_ml_adaptive_validation.py` | +| Frozen selectors | `verify_frozen` passed at run time (source and 6 config hashes) | +| Frozen cohorts | sheet and key hashes unchanged (`a0ec4b6e…`, `407b412f…`, `121c112d…`, `f333386d…`) | +| Incident fixtures | untouched (no data file modified) | +| Package and CI | recorded in the PR #1 description | diff --git a/ML_ADVERSARIAL_RANKING.md b/ML_ADVERSARIAL_RANKING.md index bfb05ac..72a7023 100644 --- a/ML_ADVERSARIAL_RANKING.md +++ b/ML_ADVERSARIAL_RANKING.md @@ -16,6 +16,8 @@ validation. - **[POST-HOC]:** added after seeing results. Exploratory. +> **Phase 12.7.1 update.** On a debiased, sealed benchmark ([ML_ADAPTIVE_RANKING_VALIDATION.md](ML_ADAPTIVE_RANKING_VALIDATION.md)), P1b is **not supported**: P1b − B0 = −0.018 [−0.031, −0.004]. The gain reported below was largely produced by the age bias described in §20. This report is kept as written. + ## 1. Executive summary **The problem.** The 12.6.1 presentation order (B0: similarity, then recency) is cheap to From d6f491666b155923a99102818eb8563d1acfc6bd Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 10 Nov 2026 13:49:50 +0300 Subject: [PATCH 84/92] docs(ml): freeze protocol 12.8 (independent benchmark contract and readiness) Vocabulary and a five-dimension label ontology with evidence rules, the case and collector contracts (outcomes sealed separately), data-quality severities, per-mechanism observation eligibility, independence criteria, the blind flow with a run-once ledger, task populations and denominators (T1-T9; end-to-end TopK counts generation failures as misses), the failure taxonomy, the frozen baseline registry (P1b comparison-only), group splits and leakage checks, paired sample-size planning, the offline development analyses D1-D5 and the public-repository safety scan. Frozen before any harness code exists. RPC 0. Co-Authored-By: Claude Fable 5.2 --- docs/ml/protocol-12.8.md | 318 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 docs/ml/protocol-12.8.md diff --git a/docs/ml/protocol-12.8.md b/docs/ml/protocol-12.8.md new file mode 100644 index 0000000..74362f8 --- /dev/null +++ b/docs/ml/protocol-12.8.md @@ -0,0 +1,318 @@ +# Protocol 12.8: independent benchmark contract, ground-truth quality, readiness + +**Frozen:** 2026-11-10, in the commit that adds this file. That is before any Phase 12.8 +harness code exists and before any quantity below is computed. + +**Base:** `ffbdb6a`. + +**RPC budget:** 0. No collection happens under this protocol. + +**Purpose.** Phases 12.7 and 12.7.1 showed that a ranking method can look better because of +how a benchmark was built. This phase adds no new ranking method. It fixes the contract under +which any method is evaluated on real incidents: +- what each label means; +- what evidence a label needs; +- which cases are eligible for which task; +- how outcomes are kept away from candidate generation and ranking; +- which denominators the metrics use. + +**The repository is public.** Nothing derived from restricted sources (CC BY-NC-ND archive +data, review sheets, unblinding keys) may enter a tracked file. Reports carry aggregates only. + +## 1. Vocabulary (never collapsed) + +| Term | Meaning | +|---|---| +| Observed transaction | a recorded chain event | +| Suspicious candidate | an event that satisfies a candidate-generation rule | +| Confirmed planting | evidence establishes a specific poisoning mechanism under the criteria of §2 | +| Paid lookalike | the victim later sent value to the candidate address. This is an outcome label; it does not make every earlier event from that address malicious. | +| Confirmed loss | sufficiently supported evidence of financial loss | +| Legitimate activity | independent evidence supports a legitimate reading | +| Unknown | cannot be classified | + +Three rules follow: +- an unknown candidate is not a negative; +- a background wallet with no known theft is not a verified benign wallet; +- unreported is not benign. + +## 2. Label ontology (`benchmark-labels/1`) + +**Five independent dimensions.** `unknown` is a value in every one. + +| Dimension | Values | +|---|---| +| mechanism | `native_dust`, `zero_value_token`, `fake_token`, `spoofed_transfer`, `other`, `unknown` | +| provenance | `signer_verified`, `emitter_verified`, `receipt_verified`, `relationship_verified`, `inferred`, `unsupported`, `unknown` | +| relationship | `exact_address`, `lookalike_of_recipient`, `no_recipient_relationship`, `ambiguous_multiple_references`, `unknown` | +| outcome | `paid_to_candidate`, `paid_to_legitimate_recipient`, `harmful_transfer`, `no_verified_outcome`, `unknown` | +| legitimacy | `confirmed_malicious`, `confirmed_legitimate`, `ambiguous`, `unreviewed`, `insufficient_evidence` | + +**Each label record carries:** +- an id and the schema version; +- dimension and value; +- evidence references, each typed as `chain_transaction`, `receipt`, `incident_report`, + `campaign_attribution`, `reviewer_decision` or `synthetic_oracle`; +- source, determination date and method; +- reviewer id, where applicable; +- confidence: `verified`, `supported`, `weak` or `none`; +- ambiguity and limitations; +- its **cutoff relation:** `pre_cutoff_observable`, `post_cutoff_outcome` or `forensic`. + +**Validation rules.** A label is rejected when: +1. an asserting value (anything except `unknown`, `unreviewed`, `no_verified_outcome`, + `insufficient_evidence`, `ambiguous`) has no evidence reference; +2. `paid_to_candidate`, `paid_to_legitimate_recipient` or `harmful_transfer` lacks a + `chain_transaction` reference; +3. `confirmed_legitimate` rests on anything other than a `reviewer_decision` or a + `synthetic_oracle`. Absence of a report is never evidence; +4. `confirmed_malicious` rests only on a `chain_transaction` (address similarity or an + on-chain event alone does not establish intent); +5. a `reviewer_decision` reference has no reviewer id, or a `synthetic_oracle` reference is + used on a non-synthetic case; +6. a non-asserting value carries confidence `verified`; +7. an outcome or legitimacy label is marked `pre_cutoff_observable`. Those are never model + inputs. + +Two labels of one dimension on one subject that assert different values are a conflict +(`needs_review`). + +## 3. Case contract (`benchmark-case/1`) + +**A case holds only what a collector may know:** +- case id, chain, victim wallet and block window; +- observation schema; +- cutoff and cutoff rule; +- source provenance; +- an attack-cluster id; +- a declared population: `development`, `independent_candidate` or `synthetic`. + +**The outcome lives in a separate sealed record:** paid address, harmful transaction and +block, and labels. + +**Collector request.** The collector accepts exactly: chain id, wallet, from-block, to-block, +observation version and resource limits. The request type forbids any other field, so an +attacker address, a paid address, a harmful transaction hash or an answer key cannot be +passed. + +**Cutoff.** `(harm block, 0)`: strictly before the harmful block. Within-block order relative +to the harmful transaction is not assumed. The window may contain the harmful block, but +observations at or after the cutoff are never read. An earlier declared monitoring time is +allowed and recorded. + +## 4. Data-quality rules + +**Severities:** `valid` < `valid_with_limitations` < `needs_review` < `not_evaluable` < +`invalid`. A case's status is its worst issue. Excluded cases stay in the ledger with their +reasons, and nothing is silently dropped. + +**Checks:** +- invalid address or hash; +- chain mismatch; +- duplicate case, or duplicate records inside a window; +- inconsistent block order; +- window not covering the cutoff; +- harm block outside the window; +- cutoff after the harmful block; +- the outcome transaction present among pre-cutoff observations; +- incomplete signer lookups; +- unread receipts; +- category statuses other than `complete`; +- conflicting labels; +- missing label evidence; +- outcome missing or unverified; +- protected-cohort overlap; +- development contamination. + +## 5. Observation eligibility + +Coverage is per category (`replay.observation`). Each mechanism requires its own categories +to be `complete`: + +| Mechanism | Required categories | +|---|---| +| native_dust | `native_inbound_external` | +| zero_value_token, fake_token | `erc20_transfer_logs` | +| spoofed_transfer | `erc20_transfer_logs` and (`erc20_outgoing_signers` or `wallet_signed_transactions`) | +| **all-mechanisms detection** | every category, including `internal_value_transfers`, `erc1155_transfer_logs` and `native_inbound_zero_value` | + +No current recorder satisfies the all-mechanisms row, so that benchmark is **blocked**. +Results are reported per supported mechanism and say so. A missing event in a category that is +not `complete` is not evidence that the event did not occur. + +## 6. Independence + +A case is `independent_candidate` only if all of these hold: +- its victim, paid address and harmful transaction are absent from every development + artifact (the recorded incident and background windows, the Level I cases, the frozen + cohorts, the archive episodes); +- it shares no attack cluster with one; +- it was not used to design or tune any frozen method; +- its source is traceable; +- its outcome identity is clear. + +Otherwise it is `development`, with the reasons listed. Three consequences: +- a new recording of a known incident stays development; +- related wallets or transactions form one cluster and count once; +- a case with incomplete coverage may support a coverage study, but it does not enter a + detection benchmark for the mechanisms it cannot observe. + +## 7. Blind flow and run-once ledger + +1. Record (not in this phase). +2. Check coverage. +3. Freeze the observation artifact (hash). +4. Generate candidates. +5. Freeze candidate identities. +6. Rank with every registered frozen method. +7. **Seal** the prediction: a digest over the case id, observation hash, cutoff, candidate + identities and every method's order. +8. Open the outcome **only in the evaluator**, which takes a sealed prediction. +9. Compute the declared metrics. +10. Append the result to an immutable ledger. + +**Code-level guarantees:** +- The prediction function has no outcome parameter. +- The outcome vault refuses to open before a prediction for that case is sealed. +- The ledger refuses a second scoring of a case with a different prediction digest. A rerun + attempt is recorded, not hidden. +- Failed and ineligible cases are written to the ledger too. + +## 8. Tasks, populations and denominators + +| Task | Question | Population (denominator) | +|---|---|---| +| T1 observation recoverability | is the outcome-linked planting in the pre-cutoff observation stream? | cases with a verified outcome whose mechanism category is `complete`; others are reported as "not assessable" | +| T2 candidate generation | is the outcome-linked address a candidate before the cutoff? | all eligible cases (CandidateRecall) | +| T3 ranking | rank of that candidate | cases where it was generated | +| T4 bounded exposure | rank ≤ K | **Conditional TopK:** cases where it was generated. **End-to-End TopK:** all eligible cases; generation failures count as misses. | +| T5 mechanism identification | do the candidate's mechanisms match the labelled mechanism? | cases with a mechanism label and a generated candidate | +| T6 evidence fidelity | does every evidence record of every candidate resolve to a pre-cutoff observation with its provenance fields? | all candidates of all cases (needs no outcome) | +| T7 alert burden | candidates per window and per wallet-day; records per candidate; summary bytes | all windows, labelled or not | +| T8 false alerts | — | **requires verified-legitimate labels; blocked without them** | +| T9 ML generalization | does a trained model beat strong baselines on untouched groups? | independent groups only | + +- **MRR** is computed on the T3 population and labelled as such. +- **K** ∈ {1, 3, 5, 10}. +- **Calibration** is never reported for uncalibrated scores. +- **No single "detection accuracy" number is ever produced.** + +## 9. Failure taxonomy + +**Exactly one class per scored case, assigned in this order:** +1. `outcome_not_verified`; +2. `label_uncertain`; +3. `observation_unsupported` (required category `unsupported` / `not_collected`); +4. `observation_partial` (required category not `complete`); +5. `not_observed_in_complete_stream` (category complete, planting absent); +6. `candidate_not_generated`; +7. `incorrect_reference_matching` (generated without the labelled reference); +8. `ranked_below_k` (reachable only through pagination); +9. `exposed`. + +Missing data is never counted as a ranking failure, nor the reverse. + +## 10. Baseline registry + +**Frozen methods, read-only:** +- generators C0, C1, C2 and `candidate-evidence/2`; +- orders B0 (similarity → recency), B1 (recency), B4 (reference rotation), P1 and P1b. + +**Each entry records:** id, revision, config hash, required categories, missingness behaviour +and evaluation status. + +**P1b's status** is "failed the 12.7.1 debiased benchmark; comparison only". No method is +modified in this phase. + +## 11. Splits and leakage + +**Groups** are the connected components over victim, attack cluster, lookalike and planting +signer. + +**Strategies:** chronological holdout by group start; leave-one-group-out. Each is feasible +only when enough groups exist, and feasibility is reported, not forced. + +**Automated leakage checks** (a failure blocks confirmatory claims): +- post-cutoff observation used; +- outcome fields in the collector request; +- a group on both sides of a split; +- protected-cohort overlap; +- reuse of a spent test population (the 12.1 archive test split; the known incidents). + +## 12. Statistical planning + +**A reusable tool, with no hard-coded sample size.** For a paired binary comparison (exposed +within K under method A vs B on the same incidents) only **discordant** incidents carry +information. The tool returns, for stated assumptions: +- the exact one-sided sign-test power for n discordant pairs when the better method wins a + discordant pair with probability p; +- the smallest number of discordant pairs reaching a target power; +- the total incidents needed, given the discordance rate, the eligible fraction and a cluster + design effect. + +Ten incidents with identical predictions decide nothing. + +## 13. Offline work on existing data (all development; none is validation) + +**D1. Inventory:** every local source, by class: +- source-derived events; +- wallet windows; +- verified incidents; +- outcome-less candidates; +- human-reviewed evidence (expected: 0 submissions); +- synthetic. + +Each row gives licence, counts, label status, coverage, protected overlap and eligibility. + +**D2. Eligibility:** every local window and every lead in the committed registries, classified +under §4–§6. + +**D3. Development regression:** the blind flow run end to end on the unprotected known +windows (pilot, ScamSniffer `/1`, ScamSniffer blind `/2`). Reported as T1–T7 and failure +classes, labelled "known development cases — not independent validation". + +**D4. Missingness sensitivity:** controlled in-memory degradations of those windows, never +written and never claimed as real recorder failures: +- no signer lookups; +- no receipts; +- no native observations; +- first half of the window removed; +- recipient history incomplete. + +Eligibility, candidate inclusion, rank and failure class are reported for each. + +**D5. One targeted measurement, no model.** Phase 12.7.1 left open whether recency ties are +right on real data. +- **Population:** the Phase 12.1 archive **development split only** (the test split is never + loaded into features). Episodes where the paid lookalike ties at least one rival on + similarity (`B0`). +- **Quantity:** the share of episodes where the paid one is the most recently planted among + the tied candidates, against the chance rate 1/t (t = tied candidates). Paired group + bootstrap over 12.1 groups. +- **Status:** development evaluation, source-conditional (every episode ended in a payoff; + attackers were not gaming a ranker). Phase 12.1 already reported recency beating similarity + on this archive, so a positive result is expected and is **not** new independent evidence. + +**No model is trained in this phase unless the readiness audit finds a task with independent +labels.** It is not expected to. + +## 14. Public-repository safety + +A scan of tracked files and of every commit's added lines for: +- high-confidence secret patterns (provider tokens, private-key blocks, RPC URLs with keys, + URL credentials); +- sensitive file names; +- anything ever tracked under `data/`; +- local user paths; +- identifiers from restricted local sources (archive cache, review sheets). Reported as + counts only. + +A regression test keeps the high-confidence checks in CI. No history is rewritten, and +visibility is not changed. + +## 15. Gates + +- **Statuses:** PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA, NOT EVALUATED. +- **Gates:** G1–G13 as in the phase brief. +- **G11 (generalization evidence)** can pass only on independent incidents. A working + framework does not pass it. From 3b512d7e7fa6a3e8c16a97ed5f2a79bf5293ce95 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 10 Nov 2026 14:08:30 +0300 Subject: [PATCH 85/92] feat(ml): benchmark contracts, blind evaluation harness, power planning, repo safety scan Protocol 12.8, research only (detector untouched): - benchmark_contract: five-dimension label ontology with evidence rules, case and sealed-outcome records, a collector request type that cannot carry an answer, data-quality issues with severities, per-mechanism observation eligibility and independence checks against development artifacts. - benchmark_eval: predict() without an outcome parameter, an outcome vault that opens only after sealing, a run-once ledger that records refused reruns, T1-T7 scoring with one failure class per case, metrics with explicit denominators (end-to-end TopK counts generation failures as misses; FPR refused without verified negatives), group splits, leakage audit and the frozen baseline registry (P1b comparison-only). - power: exact paired sign-test power and incident planning from stated assumptions (no hard-coded sample size). - repo_safety: tracked-file and history scan that reports names and counts only. - benchmark_readiness: inventory, window eligibility, leads, development regression, missingness sensitivity and the archive tie analysis. - CLI: cryptoguard ml benchmark-readiness, cryptoguard ml benchmark-power. Committed before the measured run. 0 RPC. Co-Authored-By: Claude Fable 5.2 --- src/cryptoguard/ml/benchmark_contract.py | 473 ++++++++++++++ src/cryptoguard/ml/benchmark_eval.py | 629 ++++++++++++++++++ src/cryptoguard/ml/benchmark_readiness.py | 734 ++++++++++++++++++++++ src/cryptoguard/ml/cli.py | 56 ++ src/cryptoguard/ml/power.py | 107 ++++ src/cryptoguard/ml/repo_safety.py | 138 ++++ tests/test_ml_benchmark_contract.py | 459 ++++++++++++++ 7 files changed, 2596 insertions(+) create mode 100644 src/cryptoguard/ml/benchmark_contract.py create mode 100644 src/cryptoguard/ml/benchmark_eval.py create mode 100644 src/cryptoguard/ml/benchmark_readiness.py create mode 100644 src/cryptoguard/ml/repo_safety.py create mode 100644 tests/test_ml_benchmark_contract.py diff --git a/src/cryptoguard/ml/benchmark_contract.py b/src/cryptoguard/ml/benchmark_contract.py new file mode 100644 index 0000000..4b69231 --- /dev/null +++ b/src/cryptoguard/ml/benchmark_contract.py @@ -0,0 +1,473 @@ +"""Benchmark contracts for real-incident evaluation (protocol 12.8). Research only. + +Three things are defined here and nothing is computed on outcomes: + +- the **label ontology** (``benchmark-labels/1``): five independent dimensions, each with an + ``unknown``-type value, and the evidence a label needs before it may assert anything; +- the **case contract** (``benchmark-case/1``): what a collector may know about a case, kept + apart from the sealed outcome record, plus the collector request type, which cannot carry + an answer; +- **eligibility**: data-quality issues with severities, per-mechanism observation coverage, + and independence from every development artifact. + +An unknown candidate is never a negative, a wallet without a reported theft is never a +verified benign wallet, and a paid lookalike is an outcome label, not proof that every +earlier event from that address was malicious. +""" + +from __future__ import annotations + +import re +from collections.abc import Collection, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date +from typing import Any, Literal, NamedTuple + +from pydantic import BaseModel, ConfigDict, model_validator + +LABELS_VERSION = "benchmark-labels/1" +CASE_VERSION = "benchmark-case/1" + +DIMENSIONS: dict[str, tuple[str, ...]] = { + "mechanism": ( + "native_dust", + "zero_value_token", + "fake_token", + "spoofed_transfer", + "other", + "unknown", + ), + "provenance": ( + "signer_verified", + "emitter_verified", + "receipt_verified", + "relationship_verified", + "inferred", + "unsupported", + "unknown", + ), + "relationship": ( + "exact_address", + "lookalike_of_recipient", + "no_recipient_relationship", + "ambiguous_multiple_references", + "unknown", + ), + "outcome": ( + "paid_to_candidate", + "paid_to_legitimate_recipient", + "harmful_transfer", + "no_verified_outcome", + "unknown", + ), + "legitimacy": ( + "confirmed_malicious", + "confirmed_legitimate", + "ambiguous", + "unreviewed", + "insufficient_evidence", + ), +} +NON_ASSERTING = frozenset( + {"unknown", "unreviewed", "no_verified_outcome", "insufficient_evidence", "ambiguous"} +) +NEEDS_TRANSACTION = frozenset( + {"paid_to_candidate", "paid_to_legitimate_recipient", "harmful_transfer"} +) +POST_OUTCOME_DIMENSIONS = frozenset({"outcome", "legitimacy"}) +EvidenceKind = Literal[ + "chain_transaction", + "receipt", + "incident_report", + "campaign_attribution", + "reviewer_decision", + "synthetic_oracle", +] +Confidence = Literal["verified", "supported", "weak", "none"] +CutoffRelation = Literal["pre_cutoff_observable", "post_cutoff_outcome", "forensic"] +Population = Literal["development", "independent_candidate", "synthetic"] +_ADDR = re.compile(r"^0x[0-9a-fA-F]{40}$") +_TX = re.compile(r"^0x[0-9a-fA-F]{64}$") + + +# --- labels --------------------------------------------------------------------------------- + + +class EvidenceRef(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + kind: EvidenceKind + ref: str # a transaction hash, a report URL, a reviewer submission id, an oracle id + + +class Label(BaseModel): + """One asserted or explicitly non-asserted fact about a subject, with its evidence.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + label_id: str + schema_version: str = LABELS_VERSION + subject: str # an address, a transaction hash or a case id + dimension: str + value: str + evidence: tuple[EvidenceRef, ...] = () + source: str + determined_at: date + method: str + reviewer_id: str | None = None + confidence: Confidence + ambiguity: str | None = None + limitations: tuple[str, ...] = () + cutoff_relation: CutoffRelation + + @model_validator(mode="after") + def _category(self) -> Label: + if self.dimension not in DIMENSIONS: + raise ValueError(f"invalid dimension {self.dimension!r}") + if self.value not in DIMENSIONS[self.dimension]: + raise ValueError(f"invalid category {self.value!r} for {self.dimension}") + return self + + +def label_problems(label: Label, *, synthetic_case: bool = False) -> list[str]: + """Why a label may not be used as stated (protocol 12.8 section 2); empty when valid.""" + out: list[str] = [] + if label.schema_version != LABELS_VERSION: + out.append(f"incompatible label schema {label.schema_version!r}") + kinds = {e.kind for e in label.evidence} + asserting = label.value not in NON_ASSERTING + if asserting and not label.evidence: + out.append("an asserting label has no evidence reference") + if label.value in NEEDS_TRANSACTION and "chain_transaction" not in kinds: + out.append(f"{label.value} needs a chain_transaction reference") + if label.value == "confirmed_legitimate" and not kinds & { + "reviewer_decision", + "synthetic_oracle", + }: + out.append("confirmed_legitimate needs a reviewer decision (absence is not evidence)") + if label.value == "confirmed_malicious" and kinds and kinds <= {"chain_transaction", "receipt"}: + out.append("confirmed_malicious cannot rest on an on-chain event alone") + if "reviewer_decision" in kinds and not label.reviewer_id: + out.append("a reviewer_decision reference needs a reviewer id") + if "synthetic_oracle" in kinds and not synthetic_case: + out.append("a synthetic_oracle reference on a non-synthetic case") + if not asserting and label.confidence == "verified": + out.append("a non-asserting value cannot be verified") + if ( + label.dimension in POST_OUTCOME_DIMENSIONS + and label.cutoff_relation == "pre_cutoff_observable" + ): + out.append(f"a {label.dimension} label can never be a pre-cutoff model input") + return out + + +def label_conflicts(labels: Iterable[Label]) -> list[str]: + """Two asserting labels of one dimension on one subject with different values.""" + seen: dict[tuple[str, str], set[str]] = {} + for lab in labels: + if lab.value not in NON_ASSERTING: + seen.setdefault((lab.subject.lower(), lab.dimension), set()).add(lab.value) + return [ + f"{dim} of {subject}: {sorted(values)}" + for (subject, dim), values in sorted(seen.items()) + if len(values) > 1 + ] + + +def model_input_allowed(label: Label) -> bool: + """Only pre-cutoff, non-outcome labels may ever reach a generator or a ranker.""" + return ( + label.cutoff_relation == "pre_cutoff_observable" + and label.dimension not in POST_OUTCOME_DIMENSIONS + ) + + +# --- cases, outcomes, collector ------------------------------------------------------------- + + +class CaseSource(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + publisher: str + url: str + published: str | None = None + + +class BenchmarkCase(BaseModel): + """Everything a collector and a predictor may know. No outcome field exists here.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + case_id: str + schema_version: str = CASE_VERSION + chain_id: int + victim: str + from_block: int + to_block: int + cutoff: tuple[int, int] # observations strictly before (block, tx index) are usable + cutoff_rule: str + observation_schema: str + source: CaseSource + cluster_id: str # related wallets / transactions of one attack share a cluster + population: Population + development_reasons: tuple[str, ...] = () + + +class Outcome(BaseModel): + """The sealed answer. Held by the outcome vault; never passed to a predictor.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + case_id: str + verified: bool + paid_address: str | None = None + intended_recipient: str | None = None + harm_tx: str | None = None + harm_block: int | None = None + labels: tuple[Label, ...] = () + + +class CollectorRequest(BaseModel): + """The only fields a recorder accepts. Extra fields are refused, so an attacker address, + a paid address, a harmful transaction or an answer key cannot be handed to it.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + chain_id: int + wallet: str + from_block: int + to_block: int + observation: Literal[1, 2] + max_requests: int + + +def collector_request( + case: BenchmarkCase, *, max_requests: int, observation: Literal[1, 2] = 2 +) -> CollectorRequest: + return CollectorRequest( + chain_id=case.chain_id, + wallet=case.victim, + from_block=case.from_block, + to_block=case.to_block, + observation=observation, + max_requests=max_requests, + ) + + +# --- data quality --------------------------------------------------------------------------- + +SEVERITIES = ("valid", "valid_with_limitations", "needs_review", "not_evaluable", "invalid") + + +class Issue(NamedTuple): + severity: str + code: str + detail: str + + +def status(issues: Sequence[Issue]) -> str: + """A case's status is its worst issue.""" + return max((i.severity for i in issues), key=SEVERITIES.index, default="valid") + + +def case_quality( + case: BenchmarkCase, + fixture: Any | None, + outcome: Outcome | None, + *, + protected: bool = False, + duplicate: bool = False, +) -> list[Issue]: + """Every data-quality issue of one case (protocol 12.8 section 4). Nothing is dropped: + the caller keeps the case and its issues in the ledger.""" + from cryptoguard.ml import candidate_discovery as cd + + out: list[Issue] = [] + + def add(severity: str, code: str, detail: str = "") -> None: + out.append(Issue(severity, code, detail)) + + if case.schema_version != CASE_VERSION: + add("invalid", "incompatible_artifact_version", case.schema_version) + if not _ADDR.match(case.victim): + add("invalid", "invalid_address", "victim") + if case.from_block > case.to_block: + add("invalid", "inconsistent_block_order", "window") + if not case.from_block <= case.cutoff[0] <= case.to_block + 1: + add("invalid", "window_does_not_cover_cutoff") + if duplicate: + add("invalid", "duplicate_case") + if protected: + add("not_evaluable", "protected_cohort_overlap", "touches a frozen review cohort") + if case.population == "development": + add("valid_with_limitations", "development_case", "; ".join(case.development_reasons)) + # outcome + synthetic = case.population == "synthetic" + if outcome is None or not outcome.verified or not outcome.paid_address: + add("not_evaluable", "outcome_not_verified") + else: + if not _ADDR.match(outcome.paid_address): + add("invalid", "invalid_address", "paid address") + if outcome.harm_tx is None: + add("needs_review", "missing_transaction_hash", "harmful transaction") + elif not _TX.match(outcome.harm_tx): + add("invalid", "invalid_transaction_hash", "harmful transaction") + if outcome.harm_block is not None: + if not case.from_block <= outcome.harm_block <= case.to_block: + add("invalid", "harm_block_outside_window") + if case.cutoff > (outcome.harm_block, 0): + add("invalid", "cutoff_after_harm_block", "future information would be usable") + if outcome is not None: + for lab in outcome.labels: + for p in label_problems(lab, synthetic_case=synthetic): + add("needs_review", "label_missing_evidence", f"{lab.label_id}: {p}") + for c in label_conflicts(outcome.labels): + add("needs_review", "conflicting_labels", c) + # observations + if fixture is None: + add("not_evaluable", "no_recording") + return out + if fixture.chain_id != case.chain_id: + add("invalid", "chain_mismatch") + if fixture.wallet.lower() != case.victim.lower(): + add("invalid", "wallet_mismatch") + if (fixture.from_block, fixture.to_block) != (case.from_block, case.to_block): + add("needs_review", "truncated_or_shifted_window", "recording window differs from the case") + obs = cd.observations(fixture) + raw = len(fixture.transfers) + len(fixture.native_inbound or []) + keys = [(t.transaction_hash.lower(), t.log_index) for t in fixture.transfers] + [ + (n.transaction_hash.lower(), -1) for n in fixture.native_inbound or [] + ] + if len(set(keys)) != raw: + add("valid_with_limitations", "duplicate_records", f"{raw - len(set(keys))} duplicates") + if any(not fixture.from_block <= o.block <= fixture.to_block for o in obs): + add("invalid", "inconsistent_block_order", "observation outside the window") + if any(not _TX.match(o.tx_hash) for o in obs): + add("invalid", "missing_transaction_hash", "observation without a valid hash") + if outcome is not None and outcome.harm_tx: + h = outcome.harm_tx.lower() + if any(o.tx_hash.lower() == h and (o.block, o.tx_index) < case.cutoff for o in obs): + add("invalid", "future_information_leak", "the outcome transaction precedes the cutoff") + if getattr(fixture, "sender_lookups_skipped", 0): + add("valid_with_limitations", "incomplete_signer_lookup") + if any(n.succeeded is None for n in fixture.native_inbound or []): + add("valid_with_limitations", "missing_receipts") + incomplete = sorted(k for k, v in coverage_matrix(fixture).items() if v != "complete") + if incomplete: + add("valid_with_limitations", "incomplete_categories", ", ".join(incomplete)) + return out + + +# --- observation eligibility ---------------------------------------------------------------- + +# each mechanism: every listed alternative set must have one fully complete option +MECHANISM_REQUIREMENTS: dict[str, tuple[tuple[str, ...], ...]] = { + "native_dust": (("native_inbound_external",),), + "zero_value_token": (("erc20_transfer_logs",),), + "fake_token": (("erc20_transfer_logs",),), + "spoofed_transfer": ( + ("erc20_transfer_logs",), + ("erc20_outgoing_signers", "wallet_signed_transactions"), + ), +} +_ABSENT = frozenset({"unsupported", "not_collected"}) + + +def coverage_matrix(fixture: Any) -> dict[str, str]: + """Category -> status for one window (derived for ``observation/1`` recordings).""" + from cryptoguard.replay.observation import CATEGORIES, coverage_of + + cov = coverage_of(fixture) + return {c: str(cov.status(c)) for c in CATEGORIES} + + +def mechanism_eligibility(coverage: Mapping[str, str]) -> dict[str, dict[str, Any]]: + """For each mechanism: ``complete`` (assessable), ``partial`` or ``unsupported``, and + the categories that stop it. ``all_mechanisms`` needs every category complete.""" + out: dict[str, dict[str, Any]] = {} + for mech, groups in MECHANISM_REQUIREMENTS.items(): + missing: list[str] = [] + worst = "complete" + for alternatives in groups: + states = [coverage.get(c, "unknown") for c in alternatives] + if "complete" in states: + continue + missing += list(alternatives) + state = "unsupported" if all(s in _ABSENT for s in states) else "partial" + worst = "unsupported" if "unsupported" in (worst, state) else "partial" + out[mech] = {"state": worst, "eligible": worst == "complete", "missing": missing} + missing_all = sorted(c for c, s in coverage.items() if s != "complete") + out["all_mechanisms"] = { + "state": "complete" if not missing_all else "unsupported", + "eligible": not missing_all, + "missing": missing_all, + } + return out + + +# --- independence --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class DevelopmentIndex: + """Identifiers already used in development: an overlap makes a case non-independent.""" + + victims: frozenset[str] = frozenset() + addresses: frozenset[str] = frozenset() # every counterparty seen in a development artifact + transactions: frozenset[str] = frozenset() + clusters: frozenset[str] = frozenset() + protected: frozenset[str] = frozenset() # frozen review cohorts (addresses and hashes) + sources: tuple[str, ...] = field(default=()) + + +def independence(case: BenchmarkCase, outcome: Outcome | None, dev: DevelopmentIndex) -> list[str]: + """Reasons a case is *not* independent of earlier research; empty when it is.""" + reasons: list[str] = [] + v = case.victim.lower() + if v in dev.victims: + reasons.append("victim already used in development") + if v in dev.protected: + reasons.append("victim in a frozen review cohort") + if case.cluster_id in dev.clusters: + reasons.append("attack cluster already used in development") + if outcome is not None: + for name, value in (("paid address", outcome.paid_address), ("harm tx", outcome.harm_tx)): + if value is None: + continue + x = value.lower() + if x in dev.addresses or x in dev.transactions: + reasons.append(f"{name} already seen in a development artifact") + if x in dev.protected: + reasons.append(f"{name} in a frozen review cohort") + if not case.source.url: + reasons.append("no traceable source") + if case.population == "development": + reasons.append("declared development") + return reasons + + +def index_from_fixtures( + fixtures: Iterable[Any], *, clusters: Collection[str] = (), protected: Collection[str] = () +) -> DevelopmentIndex: + victims: set[str] = set() + addresses: set[str] = set() + txs: set[str] = set() + for fx in fixtures: + victims.add(fx.wallet.lower()) + for t in fx.transfers: + addresses.update((t.sender.lower(), t.recipient.lower())) + txs.add(t.transaction_hash.lower()) + for w in fx.wallet_transactions: + txs.add(w.transaction_hash.lower()) + if w.to: + addresses.add(w.to.lower()) + for n in fx.native_inbound or []: + addresses.add(n.sender.lower()) + txs.add(n.transaction_hash.lower()) + return DevelopmentIndex( + victims=frozenset(victims), + addresses=frozenset(addresses - victims), + transactions=frozenset(txs), + clusters=frozenset(clusters), + protected=frozenset(x.lower() for x in protected), + ) diff --git a/src/cryptoguard/ml/benchmark_eval.py b/src/cryptoguard/ml/benchmark_eval.py new file mode 100644 index 0000000..472c242 --- /dev/null +++ b/src/cryptoguard/ml/benchmark_eval.py @@ -0,0 +1,629 @@ +"""Blind evaluation of candidate generation and ranking on recorded windows +(``blind-benchmark/1``, protocol 12.8). Research only; offline; the detector is untouched. + +The flow keeps outcomes away from inference by construction: + +1. ``predict(case, fixture)`` has no outcome parameter. It freezes the observation hash, + the candidate identities and every registered frozen method's order, and digests them. +2. ``OutcomeVault.open`` refuses to release an outcome until that prediction is sealed. +3. ``score`` joins the sealed prediction with the outcome and assigns exactly one failure + class; ``Ledger.record`` refuses a second scoring of a case with a different prediction. + +Metrics keep their denominators explicit: conditional TopK is over cases whose candidate +was generated, end-to-end TopK is over all eligible cases and counts generation failures as +misses. A false-positive rate is refused without verified-legitimate labels. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from cryptoguard.ml import adversarial_ranking as ar +from cryptoguard.ml import benchmark_contract as bc +from cryptoguard.ml import candidate_discovery as cd +from cryptoguard.ml import candidate_evidence as ce + +RUN_VERSION = "blind-benchmark/1" +K_GRID = (1, 3, 5, 10) +PRIMARY_METHOD, PRIMARY_K = "B0", 10 # used only to name the failure class +ORDERS: dict[str, ar.Selector] = { + "B0": ar.Selector("B0"), + "B1": ar.Selector("B1"), + "B4": ar.Selector("B4"), + "P1": ar.Selector("P1"), + "P1b": ar.Selector("P1", bucket_tie=True), +} +REGISTRY: tuple[dict[str, Any], ...] = ( + { + "id": "C0", + "kind": "generator", + "version": "candidates/2", + "requires": ["erc20_transfer_logs", "wallet_signed_transactions"], + "missingness": "unknown signer: neither reference nor spoof", + "status": "frozen; production-equivalent candidate rules", + }, + { + "id": "C1", + "kind": "generator", + "version": "poisoning-candidate-discovery/1", + "requires": ["erc20_transfer_logs", "wallet_signed_transactions"], + "missingness": "uses every observed class; asserts untrusted token when identity unknown", + "status": "research; development cases only", + }, + { + "id": "C2", + "kind": "generator", + "version": "poisoning-candidate-discovery/1", + "requires": ["erc20_transfer_logs", "wallet_signed_transactions"], + "missingness": "abstains without complete reference history", + "status": "research; drops evidence records (12.6)", + }, + { + "id": "E2", + "kind": "generator", + "version": ce.EVIDENCE_VERSION, + "requires": ["erc20_transfer_logs", "wallet_signed_transactions"], + "missingness": "missing facts lower the support level; never raise suspicion", + "status": "research; used by this harness", + }, + { + "id": "B0", + "kind": "order", + "version": ar.SELECTOR_VERSION, + "requires": [], + "missingness": "reads affix and position only", + "status": "current research default (similarity, then recency)", + }, + { + "id": "B1", + "kind": "order", + "version": ar.SELECTOR_VERSION, + "requires": [], + "missingness": "reads position only", + "status": "baseline; defeated by newer decoys", + }, + { + "id": "B4", + "kind": "order", + "version": ar.SELECTOR_VERSION, + "requires": [], + "missingness": "reads affix, bucket and position", + "status": "baseline; edged P1b on the 12.7.1 benchmark", + }, + { + "id": "P1", + "kind": "order", + "version": ar.SELECTOR_VERSION, + "requires": [], + "missingness": "reads affix and bucket; no time", + "status": "comparison only", + }, + { + "id": "P1b", + "kind": "order", + "version": ar.SELECTOR_VERSION, + "requires": [], + "missingness": "reads affix and bucket; no time", + "status": "failed the 12.7.1 debiased benchmark; comparison only, not preferred", + }, + { + "id": "M-LTR", + "kind": "learned_order", + "version": "adversarial-ranking-study/1", + "requires": [], + "missingness": "missing similarity flagged", + "status": "learned recency; gate G failed (12.7); not registered for scoring", + }, +) + + +class UnblindingError(RuntimeError): + """An outcome was requested before the prediction for its case was sealed.""" + + +class RerunError(RuntimeError): + """A case already in the ledger was scored again with a different prediction.""" + + +# --- prediction (no outcome) ---------------------------------------------------------------- + + +def observation_sha(fixture: Any) -> str: + """A content hash of the recorded window (the recording time is not part of it).""" + data = fixture.model_dump(mode="json", exclude={"recorded_at"}) + return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest() + + +@dataclass(frozen=True) +class Prediction: + case_id: str + run_version: str + observation_sha256: str + cutoff: tuple[int, int] + coverage: dict[str, str] + candidates: tuple[str, ...] # lookalike addresses, sorted + orders: dict[str, tuple[str, ...]] + mechanisms: dict[str, tuple[str, ...]] + kinds: dict[str, tuple[str, ...]] + references: dict[str, tuple[str, ...]] + abstain: str | None + burden: dict[str, Any] + fidelity: dict[str, Any] + digest: str + + +def _digest(payload: Mapping[str, Any]) -> str: + return hashlib.sha256(json.dumps(payload, sort_keys=True, default=list).encode()).hexdigest() + + +def predict(case: bc.BenchmarkCase, fixture: Any) -> Prediction: + """Candidates and every registered order from observations strictly before the cutoff. + Takes the case and its recording only: no outcome can reach it.""" + result = ce.build(fixture, cutoff=case.cutoff) + groups = list(result.groups) + if any((r.block, r.tx_index) >= case.cutoff for g in groups for r in g.evidence): + raise AssertionError("a post-cutoff record reached the candidates") + orders = { + name: tuple(g.lookalike for g in ar.order(groups, sel)) for name, sel in ORDERS.items() + } + known = {o.identity for o in cd.observations(fixture) if (o.block, o.tx_index) < case.cutoff} + records = [r for g in groups for r in g.evidence] + resolved = sum( + 1 for r in records if (r.identity.split(":")[1], r.log_index) in known and r.signer_status + ) + days = max(1e-9, (min(case.cutoff[0], case.to_block + 1) - case.from_block) / 7_200) + summary = ce.summarize(result, 10) + burden = { + "candidates": len(groups), + "evidence_records": len(records), + "wallet_days": round(days, 3), + "candidates_per_wallet_day": round(len(groups) / days, 4), + "records_per_candidate": round(len(records) / len(groups), 3) if groups else None, + "summary_bytes": len(json.dumps(summary)), + } + fidelity = {"records": len(records), "resolved_pre_cutoff": resolved} + obs_sha = observation_sha(fixture) + candidates = tuple(sorted(g.lookalike for g in groups)) + body = { + "case_id": case.case_id, + "run_version": RUN_VERSION, + "observation_sha256": obs_sha, + "cutoff": list(case.cutoff), + "candidates": candidates, + "orders": orders, + } + return Prediction( + case_id=case.case_id, + run_version=RUN_VERSION, + observation_sha256=obs_sha, + cutoff=case.cutoff, + coverage=bc.coverage_matrix(fixture), + candidates=candidates, + orders=orders, + mechanisms={g.lookalike: g.mechanisms for g in groups}, + kinds={g.lookalike: g.kinds for g in groups}, + references={g.lookalike: tuple(r[0] for r in g.references) for g in groups}, + abstain=result.abstain, + burden=burden, + fidelity=fidelity, + digest=_digest(body), + ) + + +# --- outcome isolation ---------------------------------------------------------------------- + + +class OutcomeVault: + """Holds the sealed outcomes. ``open`` works only for a prediction sealed here first.""" + + def __init__(self, outcomes: Mapping[str, bc.Outcome]) -> None: + self._outcomes = dict(outcomes) + self._sealed: dict[str, str] = {} + + def seal(self, prediction: Prediction) -> str: + prior = self._sealed.get(prediction.case_id) + if prior is not None and prior != prediction.digest: + raise RerunError(f"{prediction.case_id}: a different prediction is already sealed") + self._sealed[prediction.case_id] = prediction.digest + return prediction.digest + + def open(self, prediction: Prediction) -> bc.Outcome | None: + if self._sealed.get(prediction.case_id) != prediction.digest: + raise UnblindingError(f"{prediction.case_id}: seal the prediction before unblinding") + return self._outcomes.get(prediction.case_id) + + +class Ledger: + """Append-only record of scored cases. A case is scored once: the same prediction + returns the stored result; a different prediction is refused and the attempt logged.""" + + def __init__(self, path: Path | None = None) -> None: + self.path = path + self.entries: dict[str, dict[str, Any]] = {} + self.refused: list[dict[str, str]] = [] + if path is not None and path.exists(): + for line in path.read_text(encoding="utf-8").splitlines(): + row = json.loads(line) + if row.get("event") == "scored": + self.entries[row["case_id"]] = row + elif row.get("event") == "rerun_refused": + self.refused.append(row) + + def _append(self, row: Mapping[str, Any]) -> None: + if self.path is not None: + self.path.parent.mkdir(parents=True, exist_ok=True) + with self.path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(row, sort_keys=True, default=list) + "\n") + + def record(self, prediction: Prediction, result: Mapping[str, Any]) -> dict[str, Any]: + prior = self.entries.get(prediction.case_id) + if prior is not None: + if prior["prediction_digest"] == prediction.digest: + return dict(prior["result"]) + row = { + "event": "rerun_refused", + "case_id": prediction.case_id, + "prediction_digest": prediction.digest, + "recorded_digest": prior["prediction_digest"], + } + self.refused.append(row) + self._append(row) + raise RerunError(f"{prediction.case_id} is already scored with another prediction") + row = json.loads( + json.dumps( + { + "event": "scored", + "case_id": prediction.case_id, + "prediction_digest": prediction.digest, + "run_version": RUN_VERSION, + "result": dict(result), + }, + sort_keys=True, + default=list, + ) + ) # JSON-native, so a stored result equals a fresh one + self.entries[prediction.case_id] = row + self._append(row) + return dict(row["result"]) + + +# --- scoring (the only place an outcome is read) -------------------------------------------- + + +def _labelled(outcome: bc.Outcome, dimension: str) -> str | None: + vals = [x.value for x in outcome.labels if x.dimension == dimension] + return vals[0] if len(set(vals)) == 1 else None + + +def mechanism_identified(label: str, mechanisms: Sequence[str], kinds: Sequence[str]) -> bool: + """Does the candidate's own evidence show the labelled mechanism?""" + if label == "native_dust": + return "native" in kinds + if label == "zero_value_token": + return "zero_value_in" in mechanisms + if label == "fake_token": + return "untrusted_token_in" in mechanisms or "untrusted_token_out" in mechanisms + if label == "spoofed_transfer": + return "spoofed_out" in mechanisms or "foreign_initiated_out" in mechanisms + raise ValueError(label) + + +def score( + case: bc.BenchmarkCase, + prediction: Prediction, + outcome: bc.Outcome | None, + fixture: Any, +) -> dict[str, Any]: + """T1-T5 for one case and its single failure class (protocol 12.8 sections 8-9).""" + out: dict[str, Any] = { + "case_id": case.case_id, + "population": case.population, + "cluster_id": case.cluster_id, + "candidates": len(prediction.candidates), + "burden": prediction.burden, + "fidelity": prediction.fidelity, + "abstain": prediction.abstain, + } + if outcome is None or not outcome.verified or not outcome.paid_address: + return out | {"failure": "outcome_not_verified", "eligible": False} + synthetic = case.population == "synthetic" + problems = [ + p for lab in outcome.labels for p in bc.label_problems(lab, synthetic_case=synthetic) + ] + if problems or bc.label_conflicts(outcome.labels): + return out | {"failure": "label_uncertain", "eligible": False, "label_problems": problems} + paid = outcome.paid_address.lower() + mechanism = _labelled(outcome, "mechanism") + elig = bc.mechanism_eligibility(prediction.coverage) + relevant = ( + [mechanism] if mechanism in bc.MECHANISM_REQUIREMENTS else list(bc.MECHANISM_REQUIREMENTS) + ) + states = [elig[m]["state"] for m in relevant] + observed = any( + o.counterparty == paid and (o.block, o.tx_index) < case.cutoff + for o in cd.observations(fixture) + ) + generated = paid in prediction.candidates + ranks = { + m: (order.index(paid) + 1 if paid in order else None) + for m, order in prediction.orders.items() + } + mechanism_eligible = all(s == "complete" for s in states) + out |= { + "eligible": True, + "mechanism_label": mechanism, + "mechanism_eligible": mechanism_eligible, + "T1_observed": observed, + "T1_assessable": observed or mechanism_eligible, + "T2_generated": generated, + "T3_rank": ranks, + "T4_exposed": { + m: {str(k): r is not None and r <= k for k in K_GRID} for m, r in ranks.items() + }, + } + if generated and mechanism in bc.MECHANISM_REQUIREMENTS: + out["T5_mechanism_identified"] = mechanism_identified( + mechanism, prediction.mechanisms[paid], prediction.kinds[paid] + ) + else: + out["T5_mechanism_identified"] = None + if not observed: + if "unsupported" in states: + failure = "observation_unsupported" + elif not mechanism_eligible: + failure = "observation_partial" + else: + failure = "not_observed_in_complete_stream" + elif not generated: + failure = "candidate_not_generated" + elif ( + outcome.intended_recipient + and outcome.intended_recipient.lower() not in prediction.references.get(paid, ()) + ): + failure = "incorrect_reference_matching" + elif not out["T4_exposed"][PRIMARY_METHOD][str(PRIMARY_K)]: + failure = "ranked_below_k" + else: + failure = "exposed" + return out | {"failure": failure} + + +def run_case( + case: bc.BenchmarkCase, fixture: Any, vault: OutcomeVault, ledger: Ledger +) -> dict[str, Any]: + """Predict, seal, unblind, score, record: the only sanctioned path to a scored case.""" + prediction = predict(case, fixture) + vault.seal(prediction) + outcome = vault.open(prediction) + return ledger.record(prediction, score(case, prediction, outcome, fixture)) + + +# --- metrics -------------------------------------------------------------------------------- + + +def _ratio(num: int, den: int) -> dict[str, Any]: + return {"value": round(num / den, 4) if den else None, "numerator": num, "denominator": den} + + +def aggregate(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + """Benchmark metrics with their denominators (protocol 12.8 section 8).""" + verified = [r for r in results if r.get("eligible")] + mech_ok = [r for r in verified if r["mechanism_eligible"]] + generated = [r for r in verified if r["T2_generated"]] + assessable = [r for r in verified if r["T1_assessable"]] + out: dict[str, Any] = { + "cases": len(results), + "verified_outcome": len(verified), + "mechanism_eligible": len(mech_ok), + "clusters": len({r["cluster_id"] for r in verified}), + "failures": _count(r["failure"] for r in results), + "observation_coverage": _ratio(sum(r["T1_observed"] for r in assessable), len(assessable)), + "observation_coverage_all_verified": _ratio( + sum(r["T1_observed"] for r in verified), len(verified) + ), + "candidate_recall": _ratio(sum(r["T2_generated"] for r in mech_ok), len(mech_ok)), + "candidate_recall_all_verified": _ratio(len(generated), len(verified)), + "conditional_topk": {}, + "end_to_end_topk": {}, + "end_to_end_topk_all_verified": {}, + "mrr_on_generated": {}, + } + for m in ORDERS: + out["conditional_topk"][m] = { + k: _ratio(sum(r["T4_exposed"][m][str(k)] for r in generated), len(generated)) + for k in K_GRID + } + out["end_to_end_topk"][m] = { + k: _ratio(sum(r["T4_exposed"][m][str(k)] for r in mech_ok), len(mech_ok)) + for k in K_GRID + } + out["end_to_end_topk_all_verified"][m] = { + k: _ratio(sum(r["T4_exposed"][m][str(k)] for r in verified), len(verified)) + for k in K_GRID + } + rr = [1 / r["T3_rank"][m] for r in generated] + out["mrr_on_generated"][m] = { + "value": round(sum(rr) / len(rr), 4) if rr else None, + "denominator": len(rr), + } + labelled = [r for r in generated if r["T5_mechanism_identified"] is not None] + out["mechanism_identification"] = _ratio( + sum(r["T5_mechanism_identified"] for r in labelled), len(labelled) + ) + rec = sum(r["fidelity"]["records"] for r in results) + out["evidence_fidelity"] = _ratio( + sum(r["fidelity"]["resolved_pre_cutoff"] for r in results), rec + ) + out["burden"] = burden(results) + return out + + +def burden(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: + n = len(results) + if not n: + return {"windows": 0} + cands = [r["burden"]["candidates"] for r in results] + days = sum(r["burden"]["wallet_days"] for r in results) + return { + "windows": n, + "candidates_per_window_mean": round(sum(cands) / n, 3), + "candidates_per_window_max": max(cands), + "candidates_per_wallet_day": round(sum(cands) / days, 4) if days else None, + "evidence_records": sum(r["burden"]["evidence_records"] for r in results), + "summary_bytes_max": max(r["burden"]["summary_bytes"] for r in results), + } + + +def _count(values: Any) -> dict[str, int]: + out: dict[str, int] = {} + for v in values: + out[v] = out.get(v, 0) + 1 + return dict(sorted(out.items())) + + +def false_positive_rate(labels: Sequence[bc.Label], flagged: Sequence[str]) -> dict[str, Any]: + """FPR over verified-legitimate subjects only. Unknown, unreviewed and ambiguous subjects + are never negatives; without verified negatives the metric is refused.""" + negatives = { + lab.subject.lower() + for lab in labels + if lab.dimension == "legitimacy" + and lab.value == "confirmed_legitimate" + and not bc.label_problems(lab, synthetic_case=True) + } + if not negatives: + return {"status": "blocked", "reason": "no verified-legitimate labels", "value": None} + fp = len(negatives & {f.lower() for f in flagged}) + return {"status": "ok", **_ratio(fp, len(negatives))} + + +# --- group-aware splits and leakage --------------------------------------------------------- + + +def groups( + cases: Sequence[bc.BenchmarkCase], + outcomes: Mapping[str, bc.Outcome] | None = None, + extra: Mapping[str, Sequence[str]] | None = None, +) -> dict[str, int]: + """Connected components over victim, attack cluster, paid address and any extra keys + (planting signers, lookalikes): related cases can never sit on both sides of a split.""" + parent = list(range(len(cases))) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + seen: dict[str, int] = {} + for i, c in enumerate(cases): + keys = [f"v:{c.victim.lower()}", f"c:{c.cluster_id}"] + o = (outcomes or {}).get(c.case_id) + if o is not None and o.paid_address: + keys.append(f"a:{o.paid_address.lower()}") + keys += [f"x:{k.lower()}" for k in (extra or {}).get(c.case_id, ())] + for key in keys: + if key in seen: + a, b = find(i), find(seen[key]) + if a != b: + parent[max(a, b)] = min(a, b) + else: + seen[key] = i + roots = [find(i) for i in range(len(cases))] + names = {r: n for n, r in enumerate(sorted(set(roots)))} + return {c.case_id: names[r] for c, r in zip(cases, roots, strict=True)} + + +def chronological_split( + cases: Sequence[bc.BenchmarkCase], grp: Mapping[str, int], test_share: float = 0.4 +) -> dict[str, str]: + """Groups ordered by their earliest cutoff; the latest groups form the test side.""" + start: dict[int, int] = {} + size: dict[int, int] = {} + for c in cases: + g = grp[c.case_id] + start[g] = min(start.get(g, c.cutoff[0]), c.cutoff[0]) + size[g] = size.get(g, 0) + 1 + test: set[int] = set() + n = 0 + for g in sorted(start, key=lambda g: (start[g], g), reverse=True): + if n >= test_share * len(cases): + break + test.add(g) + n += size[g] + return {c.case_id: "test" if grp[c.case_id] in test else "dev" for c in cases} + + +def leave_one_group_out(grp: Mapping[str, int]) -> list[dict[str, str]]: + return [ + {cid: "test" if g == held else "dev" for cid, g in grp.items()} + for held in sorted(set(grp.values())) + ] + + +def split_leakage(assignment: Mapping[str, str], grp: Mapping[str, int]) -> list[str]: + """Groups that appear on more than one side of a split.""" + sides: dict[int, set[str]] = {} + for cid, side in assignment.items(): + sides.setdefault(grp[cid], set()).add(side) + return [f"group {g} on {sorted(s)}" for g, s in sorted(sides.items()) if len(s) > 1] + + +def split_feasibility(n_groups: int) -> dict[str, Any]: + return { + "independent_groups": n_groups, + "chronological_holdout": n_groups >= 10, + "leave_one_group_out": n_groups >= 3, + "note": "below 3 groups no split is meaningful; below 10 a holdout has < 4 test groups", + } + + +SPENT_POPULATIONS = ( + "archive lookalike-prioritization test split (used in Phase 12.1)", + "archive lookalike-prioritization development split (12.1, 12.5, 12.7, 12.8)", + "Level I incidents usdt-counterfeit-39890 and scamsniffer-763k (12.3-12.7.1)", + "recorded replay and background windows (development; 3 background protected)", + "12.7 and 12.7.1 synthetic grids", +) + + +def leakage_audit( + case: bc.BenchmarkCase, + fixture: Any, + prediction: Prediction, + request: bc.CollectorRequest, + *, + protected: bool, + dev_reasons: Sequence[str], +) -> dict[str, Any]: + """Automated checks; any failure blocks a confirmatory claim for this case.""" + pre = {o.identity for o in cd.observations(fixture) if (o.block, o.tx_index) < case.cutoff} + result = ce.build(fixture, cutoff=case.cutoff) + post = sum( + 1 + for g in result.groups + for r in g.evidence + if (r.identity.split(":")[1], r.log_index) not in pre + ) + allowed = {"chain_id", "wallet", "from_block", "to_block", "observation", "max_requests"} + checks = { + "no_post_cutoff_evidence": post == 0, + "collector_request_has_no_outcome_field": set(request.model_dump()) == allowed, + "prediction_matches_recording": prediction.observation_sha256 == observation_sha(fixture), + "no_protected_overlap": not protected, + "not_a_spent_population": not dev_reasons, + } + return { + "checks": checks, + "confirmatory_allowed": all(checks.values()), + "exceptions": list(dev_reasons), + } + + +def prediction_json(p: Prediction) -> str: + return json.dumps(asdict(p), sort_keys=True, default=list) diff --git a/src/cryptoguard/ml/benchmark_readiness.py b/src/cryptoguard/ml/benchmark_readiness.py new file mode 100644 index 0000000..cf58d8e --- /dev/null +++ b/src/cryptoguard/ml/benchmark_readiness.py @@ -0,0 +1,734 @@ +"""Phase 12.8 offline readiness study (protocol 12.8, section 13): what local data exist, +which of it is eligible for which benchmark task, and what the blind harness reports on the +known development windows. No RPC; nothing here is independent validation. + +Outputs are aggregates. Record-level content of restricted sources (the CC BY-NC-ND archive, +the frozen review sheets) is never written to a tracked location, and the frozen cohort +files are only read through the existing blinded-sheet helpers. +""" + +from __future__ import annotations + +import contextlib +import json +import os +import time +from collections.abc import Sequence +from datetime import date +from pathlib import Path +from typing import Any + +from cryptoguard.ml import benchmark_contract as bc +from cryptoguard.ml import benchmark_eval as be + +STUDY_VERSION = "benchmark-readiness/1" +MECHANISM_MAP = { + "zero_value_transfer": "zero_value_token", + "spoofed_transfer_from": "spoofed_transfer", + "counterfeit_token": "fake_token", + "token_airdrop": "other", + "unknown": "unknown", +} +ARCHIVE_LAST_DATE = "2024-06-30" +REGISTRIES = ( + Path("docs/ml/incident-benchmark/candidates.json"), + Path("docs/ml/incident-benchmark/stage2-candidates.json"), +) +BLIND_V2 = Path("data/ml/research/phase12.4/blind-v2/fixture.json") +DEGRADATIONS = ("signer_lookups", "receipts", "native", "first_half", "recipient_history") + + +# --- D1: inventory ---------------------------------------------------------------------------- + + +def _tree(path: Path) -> tuple[int, int]: + files = size = 0 + if path.is_file(): + return 1, path.stat().st_size + for root, _dirs, names in os.walk(path): + for n in names: + files += 1 + with contextlib.suppress(OSError): + size += (Path(root) / n).stat().st_size + return files, size + + +def _lines(path: Path) -> int | None: + if not path.is_file(): + return None + with path.open("rb") as fh: + return sum(1 for _ in fh) + + +def _licence(rel: str) -> tuple[str, str, str]: + from cryptoguard.ml.inventory import REGISTRY + + reg = next((r for r in REGISTRY if rel.startswith(r[0])), None) + return (reg[2], reg[3], reg[4]) if reg else ("unknown", "unknown", "unknown") + + +def inventory(root: Path) -> list[dict[str, Any]]: + """One row per local source (sizes by ``stat`` only; nothing large is read).""" + rows: list[dict[str, Any]] = [] + + def add(source_id: str, klass: str, rel: str, **extra: Any) -> None: + path = root / rel + files, size = _tree(path) if path.exists() else (0, 0) + lic, redist, label = _licence(rel if rel.endswith("/") or path.is_file() else rel + "/") + rows.append( + { + "source_id": source_id, + "class": klass, + "path": rel, + "exists": path.exists(), + "files": files, + "bytes": size, + "licence": lic, + "redistributable": redist, + "label_status": label, + **extra, + } + ) + + p = "data/ml/poisoning" + add( + "tsuchiya-archive", + "source_derived_events", + "data/external/tsuchiya2025", + chain="ethereum", + period="2022-07..2024-06", + label_source="source heuristics", + label_confidence="weak (source-defined; every poisoning row meets the source's own rule)", + outcome="source-confirmed payoffs", + eligibility="development only; test split spent", + ) + cache = root / "data/ml/research/phase12.5/episodes.jsonl" + splits: dict[str, int] = {} + if cache.is_file(): + with cache.open(encoding="utf-8") as fh: + for line in fh: + s = json.loads(line)["split"] + splits[s] = splits.get(s, 0) + 1 + add( + "archive-episodes", + "source_derived_events", + "data/ml/research/phase12.5/episodes.jsonl", + records=sum(splits.values()) or None, + splits=splits, + label_source="source payoff confirmation", + label_confidence="supported (paid lookalike; payoff-conditioned)", + outcome="paid lookalike", + eligibility="development split: exploratory; test split: spent (12.1)", + ) + add( + "archive-subset", + "source_derived_events", + f"{p}/archive_subset.sqlite", + eligibility="development only", + ) + add( + "review-packets", + "candidate_events_without_outcome", + f"{p}/review_packets_payoff_linked.jsonl", + records=_lines(root / p / "review_packets_payoff_linked.jsonl"), + eligibility="reviewer evidence; unlabeled until review", + ) + submissions = sum(1 for _ in (root / p).rglob("submission.json")) if (root / p).exists() else 0 + add( + "cohort-A", + "human_review_frozen", + f"{p}/review_sample", + records=_lines(root / p / "review_sample/reviewer_sheet.jsonl"), + reviewer_submissions=submissions, + eligibility="protected: frozen, unreviewed; never used for development", + ) + add( + "cohort-B", + "human_review_frozen", + f"{p}/hard_negative/cohort_v1", + records=_lines(root / p / "hard_negative/cohort_v1/reviewer_sheet.jsonl"), + reviewer_submissions=submissions, + eligibility="protected: frozen, unreviewed; never used for development", + ) + add( + "hard-negative-pool", + "candidate_events_without_outcome", + f"{p}/hard_negative", + eligibility="unlabeled candidates; not negatives", + ) + add( + "unconfirmed-payoffs", + "source_derived_events", + f"{p}/unconfirmed", + eligibility="exhausted for recency testing (12.2 follow-up)", + ) + add( + "poison-hunter", + "source_derived_events", + "data/external/poison-hunter", + label_confidence="weak (pipeline detections)", + eligibility="data card only", + ) + add( + "ptxphish", + "separate_task", + "data/external/ptxphish", + eligibility="phishing-transaction task; no overlap with poisoning windows", + ) + add( + "forta", "separate_task", "data/external/forta", eligibility="address labels; separate task" + ) + add( + "replay-incident-windows", + "wallet_windows_verified_incident", + "src/cryptoguard/replay/cases", + eligibility="development; all touch frozen Cohort B (protected)", + ) + add( + "background-windows", + "wallet_windows_unlabelled", + "src/cryptoguard/replay/background_cases", + eligibility="unlabelled background: not negatives; some protected", + ) + add( + "level-I-incident-windows", + "wallet_windows_verified_incident", + "docs/ml/incident-benchmark/cases", + eligibility="development cases (12.3-12.7.1)", + ) + add( + "blind-v2-window", + "wallet_windows_verified_incident", + BLIND_V2.as_posix(), + eligibility="development (re-recording of a known incident)", + ) + add( + "campaign-expansion", + "wallet_windows_unlabelled", + "src/cryptoguard/replay/campaign_cases", + eligibility="campaign analysis; unlabelled", + ) + rows.append( + { + "source_id": "synthetic-generators", + "class": "controlled_synthetic", + "path": "src/cryptoguard/ml (reliability, adversarial and adaptive generators)", + "exists": True, + "licence": "project code", + "redistributable": "yes", + "label_status": "synthetic oracle", + "eligibility": "controlled robustness only; never real-world performance", + } + ) + return rows + + +# --- D2: local windows and leads ------------------------------------------------------------ + + +def _protected(poisoning_dir: Path) -> tuple[frozenset[str], frozenset[str]] | None: + from cryptoguard.ml.lookalike_ranking import protected_entities + + try: + return protected_entities(poisoning_dir) + except (OSError, ValueError): + return None + + +def local_windows(poisoning_dir: Path) -> list[dict[str, Any]]: + """Every recorded window with its manifest (if any) and whether it touches a frozen + cohort. A window whose protection cannot be checked is treated as protected.""" + from cryptoguard.ml import incident_benchmark as ib + from cryptoguard.ml.observation_study import touches_frozen_any + from cryptoguard.replay.background import load_background + from cryptoguard.replay.models import ReplayFixture, load_cases + + blind = _protected(poisoning_dir) + out: list[dict[str, Any]] = [] + + def add(name: str, kind: str, fixture: Any, manifest: Any, cluster: str) -> None: + protected = True if blind is None else bool(touches_frozen_any(fixture, blind)) + out.append( + { + "name": name, + "kind": kind, + "fixture": fixture, + "manifest": manifest, + "cluster": cluster, + "protected": protected, + } + ) + + for c in load_cases(): + if c.fixture is not None: + add(c.manifest.case_id, "replay_incident", c.fixture, c.manifest, c.manifest.case_id) + level1 = [c for c in ib.load_new_cases() if c.fixture is not None] + for c in level1: + add(c.manifest.case_id, "level_I_incident", c.fixture, c.manifest, c.manifest.case_id) + if BLIND_V2.exists(): + base = next((c for c in level1 if c.manifest.case_id.startswith("scamsniffer")), None) + if base is not None: + fx = ReplayFixture.model_validate_json(BLIND_V2.read_text(encoding="utf-8")) + add( + "scamsniffer-blind-v2", + "level_I_rerecording", + fx, + base.manifest, + base.manifest.case_id, + ) + for b in load_background(): + if b.fixture is not None: + add(b.manifest.case_id, "background", b.fixture, None, b.manifest.case_id) + return out + + +def case_of(w: dict[str, Any]) -> tuple[bc.BenchmarkCase, bc.Outcome | None]: + """The benchmark case and sealed outcome of one local window. Every local incident is a + development case; a background window has no outcome.""" + from cryptoguard.replay.observation import coverage_of + + fx, man = w["fixture"], w["manifest"] + schema = coverage_of(fx).schema_version + if man is None: + case = bc.BenchmarkCase( + case_id=w["name"], + chain_id=fx.chain_id, + victim=fx.wallet, + from_block=fx.from_block, + to_block=fx.to_block, + cutoff=(fx.to_block + 1, 0), + cutoff_rule="end of window (no outcome)", + observation_schema=schema, + source=bc.CaseSource(publisher="random background wallet", url=""), + cluster_id=w["cluster"], + population="development", + development_reasons=("background window used in development",), + ) + return case, None + src = man.public_sources[0] + case = bc.BenchmarkCase( + case_id=w["name"], + chain_id=man.chain_id, + victim=man.victim, + from_block=fx.from_block, + to_block=fx.to_block, + cutoff=(man.harm.block_number, 0), + cutoff_rule="strictly before the harmful block", + observation_schema=schema, + source=bc.CaseSource( + publisher=src.title, url=src.url, published=str(man.first_public_report) + ), + cluster_id=w["cluster"], + population="development", + development_reasons=("known incident used in Phases 12.3-12.7.1",), + ) + today = date(2026, 11, 10) + labels = [ + bc.Label( + label_id=f"{w['name']}:outcome", + subject=man.harm.recipient, + dimension="outcome", + value="paid_to_candidate", + evidence=( + bc.EvidenceRef(kind="chain_transaction", ref=man.harm.transaction_hash), + bc.EvidenceRef(kind="incident_report", ref=src.url), + ), + source=src.title, + determined_at=today, + method="incident manifest (public report, on-chain check)", + confidence="verified", + cutoff_relation="post_cutoff_outcome", + ) + ] + planting = _planting(w, man.harm.recipient) + if planting is not None: + mech, tx = planting + labels.append( + bc.Label( + label_id=f"{w['name']}:mechanism", + subject=man.harm.recipient, + dimension="mechanism", + value=mech, + evidence=(bc.EvidenceRef(kind="chain_transaction", ref=tx),), + source="recorded window (forensic reading after the outcome)", + determined_at=today, + method="first pre-harm record between the victim and the paid address", + confidence="supported", + cutoff_relation="forensic", + limitations=("derived with outcome knowledge; never a model input",), + ) + ) + outcome = bc.Outcome( + case_id=w["name"], + verified=bool(man.onchain_verification), + paid_address=man.harm.recipient, + intended_recipient=man.intended_recipient, + harm_tx=man.harm.transaction_hash, + harm_block=man.harm.block_number, + labels=tuple(labels), + ) + return case, outcome + + +def _planting(w: dict[str, Any], paid: str) -> tuple[str, str] | None: + """Forensic mechanism label: read from the best recording of the same incident (a /2 + re-recording if one exists), using the first pre-harm record involving the paid address.""" + from cryptoguard.ml import candidate_discovery as cd + from cryptoguard.ml.payments import TRUSTED_TOKENS + from cryptoguard.replay.models import ReplayFixture + + fixtures = [w["fixture"]] + if w["name"].startswith("scamsniffer") and BLIND_V2.exists(): + fixtures.insert(0, ReplayFixture.model_validate_json(BLIND_V2.read_text(encoding="utf-8"))) + cutoff = (w["manifest"].harm.block_number, 0) + for fx in fixtures: + for o in cd.observations(fx): + if o.counterparty != paid.lower() or (o.block, o.tx_index) >= cutoff: + continue + if o.kind == "native": + return "native_dust", o.tx_hash + if o.kind == "erc20" and o.emitter not in TRUSTED_TOKENS: + return "fake_token", o.tx_hash + if o.kind == "erc20" and o.direction == "out": + return "spoofed_transfer", o.tx_hash + if o.kind == "erc20" and o.value == 0: + return "zero_value_token", o.tx_hash + return None + + +def window_rows(windows: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: + """Coverage matrix, quality status and eligibility of each local window. Protected + windows are classified but never computed on.""" + rows = [] + for w in windows: + fx = w["fixture"] + case, outcome = case_of(w) + cov = bc.coverage_matrix(fx) + issues = bc.case_quality(case, fx, outcome, protected=w["protected"]) + row: dict[str, Any] = { + "window": w["name"], + "kind": w["kind"], + "observation_schema": case.observation_schema, + "blocks": fx.to_block - fx.from_block + 1, + "protected": w["protected"], + "population": "protected" if w["protected"] else case.population, + "has_outcome": outcome is not None, + "coverage": cov, + "incomplete_categories": sorted(k for k, v in cov.items() if v != "complete"), + "mechanism_eligibility": { + k: v["state"] for k, v in bc.mechanism_eligibility(cov).items() + }, + "quality_status": bc.status(issues), + "issues": sorted({i.code for i in issues}), + "independent": False, + } + if not w["protected"]: + row["transfers"] = len(fx.transfers) + row["wallet_transactions"] = len(fx.wallet_transactions) + row["native_inbound"] = len(fx.native_inbound or []) + row["candidates"] = be.predict(case, fx).burden["candidates"] + rows.append(row) + return rows + + +def leads(root: Path) -> list[dict[str, Any]]: + """Incident leads already in the committed registries. A lead is not a validated + incident; identifiers are reported as present/absent only.""" + cache = root / "data/ml/research/phase12.5/episodes.jsonl" + archive_victims: set[str] = set() + if cache.is_file(): + with cache.open(encoding="utf-8") as fh: + archive_victims = {json.loads(line)["victim"].lower() for line in fh} + out = [] + for reg in REGISTRIES: + path = root / reg + if not path.is_file(): + continue + for c in json.loads(path.read_text(encoding="utf-8"))["candidates"]: + ids = c.get("identifiers", {}) + recorded = ( + bool(c.get("fixture_case_id")) + or (root / "docs/ml/incident-benchmark/cases" / c["case_id"]).exists() + ) + have = sorted(k for k, v in ids.items() if v) + needs = [k for k in ("victim", "harm_tx") if k not in have] + victim = (ids.get("victim") or "").lower() + day = str(c["source"]["date"])[:10] + out.append( + { + "lead": c["case_id"], + "publisher": c["source"]["publisher"][:60], + "source_date": c["source"]["date"], + "mechanism_claimed": MECHANISM_MAP.get(c["mechanism"], "unknown"), + "identifier_status": c["identifier_status"].split(":")[0], + "identifiers_present": have, + "recorded": recorded, + "status": "development (recorded and analysed)" + if recorded + else "lead: identifiers incomplete" + if needs + else "lead: identifiers complete, not recorded", + "missing_for_collection": needs, + "within_archive_period": len(day) == 10 and day <= ARCHIVE_LAST_DATE, + "victim_in_archive_episodes": (victim in archive_victims) if victim else None, + } + ) + return out + + +# --- D3: development regression through the blind harness ----------------------------------- + + +def development_regression( + windows: Sequence[dict[str, Any]], ledger_path: Path | None +) -> dict[str, Any]: + usable = [w for w in windows if not w["protected"] and w["manifest"] is not None] + pairs = [(w, *case_of(w)) for w in usable] + vault = be.OutcomeVault({c.case_id: o for _, c, o in pairs if o is not None}) + ledger = be.Ledger(ledger_path) + results, audits = [], {} + for w, case, _ in pairs: + fx = w["fixture"] + results.append(be.run_case(case, fx, vault, ledger)) + request = bc.collector_request(case, max_requests=2_500) + audits[case.case_id] = be.leakage_audit( + case, + fx, + be.predict(case, fx), + request, + protected=w["protected"], + dev_reasons=case.development_reasons, + ) + cases = [c for _, c, _ in pairs] + grp = be.groups(cases, {c.case_id: o for _, c, o in pairs if o is not None}) + return { + "label": "known development cases - not independent validation", + "cases": {r["case_id"]: r for r in results}, + "metrics": be.aggregate(results), + "leakage_audit": audits, + "groups": grp, + "split_feasibility": be.split_feasibility(len(set(grp.values()))), + "ledger_refused_reruns": len(ledger.refused), + } + + +# --- D4: missingness sensitivity (in memory; never written) --------------------------------- + + +def degrade(fixture: Any, what: str) -> Any: + """A copy of a recording with one kind of information removed and its coverage marked + accordingly. Artificial: it says nothing about real recorder failures.""" + from cryptoguard.replay.observation import ( + OBSERVATION_V2, + CategoryCoverage, + ObservationCoverage, + coverage_of, + ) + + cats = dict(coverage_of(fixture).categories) + + def mark(category: str, state: str) -> None: + cats[category] = CategoryCoverage(status=state) + + update: dict[str, Any] = {} + if what == "signer_lookups": + update["transfers"] = [t.model_copy(update={"tx_sender": None}) for t in fixture.transfers] + mark("erc20_outgoing_signers", "partial") + elif what == "receipts": + update["native_inbound"] = [ + n.model_copy(update={"succeeded": None}) for n in fixture.native_inbound or [] + ] + elif what == "native": + update["native_inbound"] = [] + update["unattributed_inbound"] = [] + mark("native_inbound_external", "not_collected") + mark("native_inbound_zero_value", "not_collected") + mark("native_inbound_unattributed", "not_collected") + elif what == "first_half": + mid = (fixture.from_block + fixture.to_block) // 2 + update["transfers"] = [t for t in fixture.transfers if t.block_number >= mid] + update["native_inbound"] = [ + n for n in fixture.native_inbound or [] if n.block_number >= mid + ] + for c in ("erc20_transfer_logs", "wallet_signed_transactions", "native_inbound_external"): + if cats[c].status == "complete": + mark(c, "truncated") + elif what == "recipient_history": + mark("wallet_signed_transactions", "partial") + else: + raise ValueError(what) + update["observation"] = ObservationCoverage(schema_version=OBSERVATION_V2, categories=cats) + return fixture.model_copy(update=update) + + +def missingness(windows: Sequence[dict[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for w in windows: + if w["protected"] or w["manifest"] is None: + continue + case, outcome = case_of(w) + if outcome is None: + continue + rows = {} + for what in ("none", *DEGRADATIONS): + fx = w["fixture"] if what == "none" else degrade(w["fixture"], what) + vault = be.OutcomeVault({case.case_id: outcome}) + r = be.run_case(case, fx, vault, be.Ledger(None)) + mech = r.get("mechanism_label") + rows[what] = { + "quality_status": bc.status(bc.case_quality(case, fx, outcome)), + "mechanism_eligible": r.get("mechanism_eligible"), + "labelled_mechanism": mech, + "candidates": r["candidates"], + "generated": r.get("T2_generated"), + "rank_B0": (r.get("T3_rank") or {}).get("B0"), + "failure": r["failure"], + } + out[w["name"]] = rows + return out + + +# --- D5: are recency ties right on the archive development split? --------------------------- + + +def tie_analysis(poisoning_dir: Path) -> dict[str, Any]: + """Among development-split episodes where the paid lookalike ties at least one rival on + similarity, how often is it the most recently planted of the tied ones, against the + chance rate 1/t? Source-conditional development evaluation; the test split is dropped + before any feature is computed.""" + from cryptoguard.ml import lookalike_ranking as lr + + t0 = time.perf_counter() + episodes, _ = lr.load_episodes(poisoning_dir) + addrs, txs = lr.protected_entities(poisoning_dir) + overlap = lr.protected_overlap(episodes, addrs, txs) + kept = [e for e, o in zip(episodes, overlap, strict=True) if not o] + grp, _mode = lr.protocol_groups(kept) + split = lr.temporal_split(kept, grp) + dev = [(e, g) for e, g, s in zip(kept, grp, split, strict=True) if s == "dev"] + d_tied: list[float] = [] + g_tied: list[int] = [] + d_all: list[float] = [] + g_all: list[int] = [] + sizes: list[int] = [] + evaluable = 0 + for e, g in dev: + f = lr.candidate_features(e, lr.View(), None, None) + if not f or f[e.paid]["B0"] is None: + continue + evaluable += 1 + + def newest_share(cands: list[str], f: dict[str, Any] = f, paid: str = e.paid) -> float: + top = max(float(f[c]["T0"] or 0.0) for c in cands) + best = [c for c in cands if float(f[c]["T0"] or 0.0) == top] + return (1.0 / len(best)) if paid in best else 0.0 + + everyone = list(f) + d_all.append(newest_share(everyone) - 1.0 / len(everyone)) + g_all.append(g) + tied = [c for c in f if f[c]["B0"] == f[e.paid]["B0"]] + if len(tied) >= 2: + d_tied.append(newest_share(tied) - 1.0 / len(tied)) + g_tied.append(g) + sizes.append(len(tied)) + out: dict[str, Any] = { + "population": "12.1 archive development split (source-conditional; test split not used)", + "dev_episodes": len(dev), + "evaluable": evaluable, + "tied_episodes": len(d_tied), + "tied_size_mean": round(sum(sizes) / len(sizes), 2) if sizes else None, + "seconds": round(time.perf_counter() - t0, 1), + } + if d_tied: + chance = sum(1.0 / s for s in sizes) / len(sizes) + excess = lr.paired(d_tied, g_tied) + out["tied"] = { + "paid_is_newest_share": round(chance + excess["mean"], 4), + "chance": round(chance, 4), + "excess_over_chance": excess, + } + if d_all: + out["all_candidates_excess_over_chance"] = lr.paired(d_all, g_all) + return out + + +# --- entry point ---------------------------------------------------------------------------- + + +def main( + poisoning_dir: Path, out: Path, *, archive: bool = True, history: bool = True +) -> dict[str, Any]: + import subprocess + + from cryptoguard.ml import power, repo_safety + from cryptoguard.ml.tsuchiya_archive import peak_rss_bytes + + t0 = time.perf_counter() + root = Path() + try: + git = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + git = None + windows = local_windows(poisoning_dir) + rows = window_rows(windows) + out.mkdir(parents=True, exist_ok=True) + regression = development_regression(windows, out / "ledger-development.jsonl") + incidents = [r for r in rows if r["has_outcome"]] + result: dict[str, Any] = { + "study": STUDY_VERSION, + "protocol": "protocol-12.8", + "git": git, + "rpc_requests": 0, + "inventory": inventory(root), + "windows": rows, + "eligibility_summary": { + "windows": len(rows), + "incident_windows": len(incidents), + "protected_windows": sum(r["protected"] for r in rows), + "development_incident_windows": sum(1 for r in incidents if not r["protected"]), + "independent_incidents": sum(r["independent"] for r in rows), + "independent_victims": 0, + "all_mechanisms_eligible_windows": sum( + r["mechanism_eligibility"]["all_mechanisms"] == "complete" for r in rows + ), + "observation_schemas": be._count(r["observation_schema"] for r in rows), + }, + "leads": leads(root), + "development_regression": regression, + "missingness": missingness(windows), + "baseline_registry": list(be.REGISTRY), + "spent_populations": list(be.SPENT_POPULATIONS), + "power": { + "sign_test": [power.sign_test_power(n, 0.8) for n in (5, 10, 20, 30, 50)], + "plan_grid_eligible_rate_0.5": power.paired_plan_grid(), + "plan_grid_clustered_deff_1.5": power.paired_plan_grid(deff=1.5), + }, + "public_safety": repo_safety.scan(root, history=history), + } + protected = _protected(poisoning_dir) + if protected is not None: + overlap = repo_safety.restricted_identifier_overlap(root, protected[0] | protected[1]) + result["public_safety"]["frozen_cohort_identifiers_in_tracked_files"] = { + "files": len(overlap), + "identifiers": sum(overlap.values()), + "note": "Cohort B was drawn from already-public recorded windows; no key is tracked", + } + if archive and (poisoning_dir / "archive_subset.sqlite").exists(): + result["tie_analysis"] = tie_analysis(poisoning_dir) + else: + result["tie_analysis"] = "not run" + peak = peak_rss_bytes() + result["resources"] = { + "seconds": round(time.perf_counter() - t0, 1), + "peak_rss_mib": None if peak is None else round(peak / 2**20, 1), + } + (out / "readiness.json").write_text( + json.dumps(result, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" + ) + return result diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index 24961ff..f875090 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -129,6 +129,33 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None ur.add_argument( "--out", type=Path, default=ML_DIR / "research" / "phase12.2" / "unconfirmed-recency.json" ) + brd = ml.add_parser( + "benchmark-readiness", + help="Phase 12.8 data inventory, eligibility and blind development regression (offline)", + ) + brd.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.8") + brd.add_argument("--no-archive", action="store_true", help="skip the archive tie analysis") + brd.add_argument("--no-history", action="store_true", help="skip the git-history scan") + bpw = ml.add_parser( + "benchmark-power", + help="sample-size planning for a paired exposure comparison (assumptions are inputs)", + ) + bpw.add_argument( + "--p-better", + type=float, + required=True, + help="P(a discordant incident favours the better method)", + ) + bpw.add_argument( + "--discordance", + type=float, + required=True, + help="share of eligible incidents on which the two methods disagree", + ) + bpw.add_argument("--eligible-rate", type=float, default=1.0) + bpw.add_argument("--deff", type=float, default=1.0, help="cluster design effect") + bpw.add_argument("--power", type=float, default=0.8) + bpw.add_argument("--alpha", type=float, default=0.05) ava = ml.add_parser( "adaptive-validation", help="Phase 12.7.1 debiased synthetic validation and adaptive attacker (offline)", @@ -230,6 +257,35 @@ def run(args: argparse.Namespace) -> int: from cryptoguard.ml import ml_available # Pure-Python commands: no ml extra needed. + if args.ml_command == "benchmark-readiness": + import json + + from cryptoguard.ml import benchmark_readiness + + result = benchmark_readiness.main( + ML_DIR / "poisoning", + args.out, + archive=not args.no_archive, + history=not args.no_history, + ) + brief = {k: result[k] for k in ("eligibility_summary", "resources")} + print(json.dumps(brief, indent=1, default=str)) + return 0 + if args.ml_command == "benchmark-power": + import json + + from cryptoguard.ml import power + + needed = power.incidents_needed( + args.p_better, + args.discordance, + power=args.power, + alpha=args.alpha, + eligible_rate=args.eligible_rate, + deff=args.deff, + ) + print(json.dumps(needed, indent=1)) + return 0 if args.ml_command == "adaptive-validation": import json diff --git a/src/cryptoguard/ml/power.py b/src/cryptoguard/ml/power.py index e1aff5b..c64d624 100644 --- a/src/cryptoguard/ml/power.py +++ b/src/cryptoguard/ml/power.py @@ -95,3 +95,110 @@ def bound_table(sizes: tuple[int, ...] = (30, 35, 50, 100, 300, 1000), "upper_0_flagged_wilson_two_sided": round((wilson(0.0, n_eff) or (0, 1))[1], 4), }) # fmt: skip return rows + + +# --- paired exposure comparisons (protocol 12.8, section 12) -------------------------------- +# +# Two methods are scored on the same incidents (exposed within K or not). Incidents where +# both agree carry no information about which is better; only the discordant ones do. Under +# H0 a discordant incident favours either method with probability 1/2 (exact sign test, +# equivalently McNemar's exact test). + + +def _binom_pmf(k: int, n: int, p: float) -> float: + if p <= 0.0: + return 1.0 if k == 0 else 0.0 + if p >= 1.0: + return 1.0 if k == n else 0.0 + log = ( + math.lgamma(n + 1) + - math.lgamma(k + 1) + - math.lgamma(n - k + 1) + + k * math.log(p) + + (n - k) * math.log1p(-p) + ) + return math.exp(log) + + +def _binom_sf(k: int, n: int, p: float) -> float: + """P(X >= k) for X ~ Binomial(n, p).""" + return min(1.0, sum(_binom_pmf(i, n, p) for i in range(max(k, 0), n + 1))) + + +def sign_test_power(n_discordant: int, p_better: float, alpha: float = 0.05) -> dict[str, Any]: + """Exact one-sided sign test on ``n_discordant`` discordant incidents. ``p_better`` is + the probability that a discordant incident favours the truly better method. Returns the + critical count (None when even n of n is not significant), the attained size and power.""" + critical = next( + (k for k in range(n_discordant + 1) if _binom_sf(k, n_discordant, 0.5) <= alpha), None + ) + if critical is None: + return {"n_discordant": n_discordant, "critical": None, "size": 0.0, "power": 0.0} + return { + "n_discordant": n_discordant, + "critical": critical, + "size": round(_binom_sf(critical, n_discordant, 0.5), 5), + "power": round(_binom_sf(critical, n_discordant, p_better), 4), + } + + +def discordant_needed( + p_better: float, power: float = 0.8, alpha: float = 0.05, max_n: int = 2_000 +) -> int | None: + """Smallest number of discordant incidents from which the exact test keeps at least the + target power (the exact test's power is saw-toothed, so the next 10 sizes are checked).""" + if not 0.5 < p_better <= 1.0: + return None + for n in range(1, max_n + 1): + if all(sign_test_power(m, p_better, alpha)["power"] >= power for m in range(n, n + 11)): + return n + return None + + +def incidents_needed( + p_better: float, + discordance: float, + *, + power: float = 0.8, + alpha: float = 0.05, + eligible_rate: float = 1.0, + deff: float = 1.0, +) -> dict[str, Any]: + """Incidents to screen so that the expected number of independent discordant incidents + reaches ``discordant_needed``. ``discordance``: share of eligible incidents on which the + two methods disagree; ``eligible_rate``: share of screened incidents that are eligible + and evaluable; ``deff``: cluster design effect (1 = every incident its own cluster). + Every input is an assumption to be stated, not a constant of nature.""" + for name, v in (("discordance", discordance), ("eligible_rate", eligible_rate)): + if not 0.0 < v <= 1.0: + raise ValueError(f"{name} must be in (0, 1]") + if deff < 1.0: + raise ValueError("deff must be >= 1") + d = discordant_needed(p_better, power, alpha) + if d is None: + return {"discordant_needed": None, "eligible_needed": None, "screened_needed": None} + eligible = math.ceil(d * deff / discordance) + return { + "p_better": p_better, + "discordance": discordance, + "power": power, + "alpha": alpha, + "eligible_rate": eligible_rate, + "deff": deff, + "discordant_needed": d, + "eligible_needed": eligible, + "screened_needed": math.ceil(eligible / eligible_rate), + } + + +def paired_plan_grid( + p_better: tuple[float, ...] = (0.7, 0.8, 0.9), + discordance: tuple[float, ...] = (0.1, 0.3, 0.5), + eligible_rate: float = 0.5, + deff: float = 1.0, +) -> list[dict[str, Any]]: + return [ + incidents_needed(p, d, eligible_rate=eligible_rate, deff=deff) + for p in p_better + for d in discordance + ] diff --git a/src/cryptoguard/ml/repo_safety.py b/src/cryptoguard/ml/repo_safety.py new file mode 100644 index 0000000..b3e8973 --- /dev/null +++ b/src/cryptoguard/ml/repo_safety.py @@ -0,0 +1,138 @@ +"""Public-repository safety scan (protocol 12.8, section 14). The repository is public, so +tracked files and history must hold no credentials, no restricted research data and no +review answer keys. + +Only file names and counts are ever returned: a matched value is never included, so the +scan cannot itself leak a secret into a log or a report. Patterns here are the +high-confidence ones (provider tokens, private-key blocks, keyed RPC URLs); a broader +manual review is recorded in the Phase 12.8 report. +""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path +from typing import Any + +SECRET_PATTERNS: dict[str, re.Pattern[str]] = { + "github_token": re.compile(r"gh[pousr]_[A-Za-z0-9]{30,}"), + "provider_api_key": re.compile(r"sk-(ant-)?[A-Za-z0-9_-]{32,}"), + "aws_access_key": re.compile(r"AKIA[0-9A-Z]{16}"), + "private_key_block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), + "keyed_rpc_url": re.compile( + r"https://[a-z0-9.-]*(alchemy|infura|quiknode|ankr|blastapi|chainstack|getblock|nodereal)" + r"[a-z0-9.-]*/[A-Za-z0-9_/-]*[A-Za-z0-9]{24,}" + ), +} +SENSITIVE_NAME = re.compile( + r"(?i)unblinding|answer_key|(^|/)\.env$|\.pem$|id_rsa|credential|(^|/)ledger[^/]*\.json$" +) +RESTRICTED_PREFIXES = ("data/",) # local research data: never tracked +USER_PATH = re.compile(r"[A-Za-z]:[\\/]+Users[\\/]+[A-Za-z0-9._-]+") +MAX_TRACKED_BYTES = 4 * 1024 * 1024 + + +def _git(root: Path, *args: str) -> str | None: + try: + done = subprocess.run( # noqa: S603 + ["git", "-C", str(root), *args], # noqa: S607 + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=True, + timeout=120, + ) + except (OSError, subprocess.SubprocessError): + return None + return done.stdout + + +def scan_text(text: str) -> dict[str, int]: + """Pattern name -> number of matches. Never returns the matched text.""" + out = {name: len(p.findall(text)) for name, p in SECRET_PATTERNS.items()} + return {k: v for k, v in out.items() if v} + + +def scan(root: Path, *, history: bool = False) -> dict[str, Any]: + """Tracked-file (and optionally history) findings, as names and counts only. Returns + ``{"available": False}`` outside a git checkout.""" + listing = _git(root, "ls-files") + if listing is None: + return {"available": False} + tracked = [f for f in listing.splitlines() if f] + secrets: dict[str, dict[str, int]] = {} + user_paths: dict[str, int] = {} + large: list[str] = [] + for rel in tracked: + path = root / rel + try: + if path.stat().st_size > MAX_TRACKED_BYTES: + large.append(rel) + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + hits = scan_text(text) + if hits: + secrets[rel] = hits + n = len(USER_PATH.findall(text)) + if n: + user_paths[rel] = n + out: dict[str, Any] = { + "available": True, + "tracked_files": len(tracked), + "secret_pattern_files": secrets, + "sensitive_names": sorted(f for f in tracked if SENSITIVE_NAME.search(f)), + "restricted_paths_tracked": sorted(f for f in tracked if f.startswith(RESTRICTED_PREFIXES)), + "local_user_paths": user_paths, + "oversized_files": large, + } + if history: + added = _git(root, "log", "--all", "--diff-filter=A", "--name-only", "--format=") or "" + names = {line for line in added.splitlines() if line} + patch = _git(root, "log", "--all", "-p", "--format=", "--unified=0") or "" + hist: dict[str, int] = {} + for line in patch.splitlines(): + if line.startswith("+") and not line.startswith("+++"): + for name, n in scan_text(line).items(): + hist[name] = hist.get(name, 0) + n + commits = (_git(root, "rev-list", "--all", "--count") or "0").strip() + out["history"] = { + "commits": int(commits or 0), + "paths_ever_added": len(names), + "sensitive_names_ever_added": sorted(f for f in names if SENSITIVE_NAME.search(f)), + "restricted_paths_ever_added": sorted( + f for f in names if f.startswith(RESTRICTED_PREFIXES) + ), + "secret_pattern_hits": hist, + } + out["clean"] = not ( + secrets + or out["sensitive_names"] + or out["restricted_paths_tracked"] + or large + or (history and (out["history"]["secret_pattern_hits"] + or out["history"]["sensitive_names_ever_added"] + or out["history"]["restricted_paths_ever_added"])) + ) # fmt: skip + return out + + +def restricted_identifier_overlap(root: Path, restricted: frozenset[str]) -> dict[str, int]: + """Tracked file -> how many restricted identifiers (addresses or hashes from local, + non-redistributable sources) it contains. Counts only.""" + listing = _git(root, "ls-files") + if listing is None: + return {} + hexes = re.compile(r"0x[0-9a-fA-F]{64}|0x[0-9a-fA-F]{40}") + out: dict[str, int] = {} + for rel in (f for f in listing.splitlines() if f): + try: + text = (root / rel).read_text(encoding="utf-8", errors="replace") + except OSError: + continue + n = len({m.lower() for m in hexes.findall(text)} & restricted) + if n: + out[rel] = n + return out diff --git a/tests/test_ml_benchmark_contract.py b/tests/test_ml_benchmark_contract.py new file mode 100644 index 0000000..522a75f --- /dev/null +++ b/tests/test_ml_benchmark_contract.py @@ -0,0 +1,459 @@ +"""Protocol 12.8: label ontology, case and collector contracts, the blind flow, metric +denominators, the failure taxonomy, splits, sample-size planning and repository safety. +Synthetic only; every expectation follows from a definition in the protocol.""" + +from __future__ import annotations + +import inspect +import json +import subprocess +from datetime import date +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from cryptoguard.ml import benchmark_contract as bc +from cryptoguard.ml import benchmark_eval as be +from cryptoguard.ml import benchmark_readiness as br +from cryptoguard.ml import candidate_evidence as ce +from cryptoguard.ml import power, repo_safety +from cryptoguard.ml import reliability_study as rs + +W, REF, USDT, FAKE = rs.WALLET, rs.REF, rs.USDT, rs.FAKE +NATIVE = rs.lookalike(1, prefix=4, suffix=4) # the paid lookalike (native dust) +FAKE_TOKEN = rs.lookalike(2) # 3+3, fake-token transfer in +SPOOF = rs.lookalike(3, prefix=5, suffix=5) # zero-value spoofed transfer out +DISTRACTORS = [rs.lookalike(10 + i) for i in range(8)] +HARM_BLOCK = 5_000 +DAY = date(2026, 11, 10) + + +def window(*, paid: str = NATIVE, plant: bool = True, extra_native: list | None = None): + native = [(d, 1, 2_300 + i, True) for i, d in enumerate(DISTRACTORS)] + if plant: + native.append((NATIVE, 1, 2_000, True)) + native.append((rs.lookalike(99, prefix=5, suffix=5), 1, 6_000, True)) # after the cutoff + native += extra_native or [] + return rs.wallet_fixture( + transfers=[ + (FAKE_TOKEN, W, 10**18, 2_100, None, FAKE, 0), + (W, SPOOF, 0, 2_200, rs.ATTACKER, USDT, 0), + ], + native=native, + wallet_txs=[(paid, 10**18, HARM_BLOCK)], # the harmful payment itself + ) + + +def case(fx, case_id: str = "syn-1", **kw) -> bc.BenchmarkCase: + base = dict( + case_id=case_id, chain_id=1, victim=fx.wallet, from_block=fx.from_block, + to_block=fx.to_block, cutoff=(HARM_BLOCK, 0), cutoff_rule="strictly before the harm block", + observation_schema="observation/2", + source=bc.CaseSource(publisher="synthetic", url="synthetic://oracle"), + cluster_id=case_id, population="synthetic", + ) # fmt: skip + return bc.BenchmarkCase(**(base | kw)) + + +def label(dimension: str, value: str, *, kinds=("synthetic_oracle",), subject: str = NATIVE, **kw): + base = dict( + label_id=f"{dimension}:{value}", subject=subject, dimension=dimension, value=value, + evidence=tuple(bc.EvidenceRef(kind=k, ref="0x" + "ab" * 32) for k in kinds), + source="oracle", determined_at=DAY, method="by construction", confidence="supported", + cutoff_relation="post_cutoff_outcome", + ) # fmt: skip + return bc.Label(**(base | kw)) + + +def outcome(fx, case_id: str = "syn-1", paid: str = NATIVE, **kw) -> bc.Outcome: + harm = fx.wallet_transactions[-1].transaction_hash + base = dict( + case_id=case_id, verified=True, paid_address=paid, intended_recipient=REF, harm_tx=harm, + harm_block=HARM_BLOCK, + labels=( + label("outcome", "paid_to_candidate", kinds=("chain_transaction", "synthetic_oracle"), + subject=paid), + label("mechanism", "native_dust", subject=paid, cutoff_relation="forensic"), + ), + ) # fmt: skip + return bc.Outcome(**(base | kw)) + + +def run(fx, c, o) -> dict: + return be.run_case(c, fx, be.OutcomeVault({c.case_id: o} if o else {}), be.Ledger(None)) + + +# --- the controlled end-to-end benchmark ---------------------------------------------------- + + +def test_end_to_end_blind_benchmark() -> None: + fx = window() + c, o = case(fx), outcome(fx) + assert bc.status(bc.case_quality(c, fx, o)) == "valid_with_limitations" # coverage gaps + pred = be.predict(c, fx) + vault, ledger = be.OutcomeVault({c.case_id: o}), be.Ledger(None) + with pytest.raises(be.UnblindingError): + vault.open(pred) # the outcome cannot be read before the prediction is sealed + vault.seal(pred) + r = ledger.record(pred, be.score(c, pred, vault.open(pred), fx)) + assert len(pred.candidates) == 11 # 8 distractors + native + fake token + spoof + assert rs.lookalike(99, prefix=5, suffix=5) not in pred.candidates # planted after the cutoff + assert (r["T1_observed"], r["T2_generated"]) == (True, True) + assert r["T3_rank"]["B0"] == 2 # the 5+5 spoof ranks first, the 4+4 paid address second + assert r["T4_exposed"]["B0"] == {"1": False, "3": True, "5": True, "10": True} + assert r["T5_mechanism_identified"] is True + assert r["failure"] == "exposed" + assert r["fidelity"]["records"] == r["fidelity"]["resolved_pre_cutoff"] == 11 + assert pred.coverage["internal_value_transfers"] != "complete" # incomplete coverage + assert not bc.mechanism_eligibility(pred.coverage)["all_mechanisms"]["eligible"] + # every candidate and record stays reachable + res = ce.build(fx, cutoff=c.cutoff) + assert {g.lookalike for g in res.groups} == set(pred.candidates) + assert ce.page(res, offset=10, limit=5)["items"][0]["rank"] == 11 + + +def test_prediction_cannot_see_an_outcome() -> None: + assert list(inspect.signature(be.predict).parameters) == ["case", "fixture"] + fx = window() + a = be.predict(case(fx), fx) + b = be.predict(case(fx), fx) + assert a.digest == b.digest # deterministic, identical inputs + assert "paid" not in " ".join(bc.BenchmarkCase.model_fields) + assert set(bc.CollectorRequest.model_fields) == { + "chain_id", "wallet", "from_block", "to_block", "observation", "max_requests" + } # fmt: skip + with pytest.raises(ValidationError): + bc.CollectorRequest(chain_id=1, wallet=W, from_block=1, to_block=2, observation=2, + max_requests=10, paid_address=NATIVE) # fmt: skip + + +def test_missing_candidate_counts_as_a_miss_end_to_end() -> None: + fx1 = window() + hit = run(fx1, case(fx1), outcome(fx1)) + fx2 = window(plant=False) # the paid address never planted before the cutoff + c2 = case(fx2, "syn-2") + miss = run(fx2, c2, outcome(fx2, "syn-2")) + assert miss["failure"] == "not_observed_in_complete_stream" + assert miss["T2_generated"] is False + m = be.aggregate([hit, miss]) + assert m["conditional_topk"]["B0"][10] == {"value": 1.0, "numerator": 1, "denominator": 1} + assert m["end_to_end_topk"]["B0"][10] == {"value": 0.5, "numerator": 1, "denominator": 2} + assert m["candidate_recall"]["denominator"] == 2 + assert m["mrr_on_generated"]["B0"] == {"value": 0.5, "denominator": 1} + assert m["failures"] == {"exposed": 1, "not_observed_in_complete_stream": 1} + + +def test_unsupported_observation_is_not_a_ranking_failure() -> None: + fx = br.degrade(window(), "native") + c = case(fx) + r = run(fx, c, outcome(fx)) + assert r["failure"] == "observation_unsupported" + assert r["mechanism_eligible"] is False + assert r["T1_assessable"] is False + m = be.aggregate([r]) + assert m["end_to_end_topk"]["B0"][10]["denominator"] == 0 # not a detection-benchmark case + assert m["end_to_end_topk_all_verified"]["B0"][10] == { + "value": 0.0, "numerator": 0, "denominator": 1, + } # fmt: skip + + +@pytest.mark.parametrize( + ("what", "expected"), + [("first_half", "observation_partial"), ("receipts", "exposed"), ("signer_lookups", "exposed")], +) +def test_degradations(what: str, expected: str) -> None: + base = window() + fx = br.degrade(base, what) + assert run(fx, case(fx), outcome(fx))["failure"] == expected + assert len(base.native_inbound) == 10 # the original recording is never modified + + +def test_failure_taxonomy_branches() -> None: + stranger = "0x" + "9d" * 20 # sends dust but resembles no recipient + fx = window(paid=stranger, plant=False, extra_native=[(stranger, 1, 2_050, True)]) + r = run(fx, case(fx), outcome(fx, paid=stranger)) + assert (r["T1_observed"], r["failure"]) == (True, "candidate_not_generated") + fx = window() + r = run(fx, case(fx), outcome(fx, intended_recipient="0x" + "77" * 20)) + assert r["failure"] == "incorrect_reference_matching" + weak = rs.lookalike(500) # 3+3, buried under 12 stronger lookalikes + strong = [(rs.lookalike(600 + i, prefix=4, suffix=4), 1, 2_400 + i, True) for i in range(12)] + fx = window(paid=weak, plant=False, extra_native=[(weak, 1, 2_050, True), *strong]) + r = run(fx, case(fx), outcome(fx, paid=weak)) + assert r["T2_generated"] is True + assert r["T3_rank"]["B0"] > 10 + assert r["failure"] == "ranked_below_k" # reachable only through pagination + assert run(fx, case(fx), None)["failure"] == "outcome_not_verified" + bad = outcome(fx, labels=(label("legitimacy", "confirmed_malicious", + kinds=("chain_transaction",)),)) # fmt: skip + assert run(fx, case(fx), bad)["failure"] == "label_uncertain" + + +def test_empty_candidate_set_and_same_block_cutoff() -> None: + fx = rs.wallet_fixture(wallet_txs=[(NATIVE, 10**18, HARM_BLOCK)]) + r = run(fx, case(fx), outcome(fx)) + assert (r["candidates"], r["T2_generated"]) == (0, False) + assert be.aggregate([r])["burden"]["candidates_per_window_mean"] == 0 + # a planting in the harmful block is not usable: within-block order is not assumed + fx = window(plant=False, extra_native=[(NATIVE, 1, HARM_BLOCK, True)]) + assert run(fx, case(fx), outcome(fx))["T1_observed"] is False + + +# --- ledger and vault ----------------------------------------------------------------------- + + +def test_ledger_scores_once_and_refuses_a_different_rerun(tmp_path: Path) -> None: + fx = window() + c, o = case(fx), outcome(fx) + path = tmp_path / "ledger.jsonl" + first = be.run_case(c, fx, be.OutcomeVault({c.case_id: o}), be.Ledger(path)) + again = be.run_case(c, fx, be.OutcomeVault({c.case_id: o}), be.Ledger(path)) + assert again == first # the same prediction returns the stored result + changed = window(extra_native=[(rs.lookalike(700), 1, 2_900, True)]) + ledger = be.Ledger(path) + with pytest.raises(be.RerunError): + be.run_case(c, changed, be.OutcomeVault({c.case_id: o}), ledger) + assert len(be.Ledger(path).refused) == 1 # the attempt is on record + assert len(be.Ledger(path).entries) == 1 + + +def test_vault_refuses_a_second_prediction() -> None: + fx = window() + c = case(fx) + vault = be.OutcomeVault({}) + vault.seal(be.predict(c, fx)) + other = window(extra_native=[(rs.lookalike(701), 1, 2_901, True)]) + with pytest.raises(be.RerunError): + vault.seal(be.predict(c, other)) + + +# --- labels --------------------------------------------------------------------------------- + + +def test_label_rules() -> None: + assert bc.label_problems(label("outcome", "paid_to_candidate"), synthetic_case=True) == [ + "paid_to_candidate needs a chain_transaction reference" + ] + assert bc.label_problems(label("mechanism", "native_dust", kinds=()), synthetic_case=True) + legit = label("legitimacy", "confirmed_legitimate", kinds=("chain_transaction",)) + assert any("absence is not evidence" in p for p in bc.label_problems(legit)) + reviewed = label("legitimacy", "confirmed_legitimate", kinds=("reviewer_decision",)) + assert any("reviewer id" in p for p in bc.label_problems(reviewed)) + assert ( + bc.label_problems( + label( + "legitimacy", "confirmed_legitimate", kinds=("reviewer_decision",), reviewer_id="r1" + ) + ) + == [] + ) + malicious = label("legitimacy", "confirmed_malicious", kinds=("chain_transaction", "receipt")) + assert any("on-chain event alone" in p for p in bc.label_problems(malicious)) + assert any( + "synthetic_oracle" in p for p in bc.label_problems(label("mechanism", "native_dust")) + ) # an oracle label on a real case + unknown = label("legitimacy", "unreviewed", kinds=(), confidence="verified") + assert bc.label_problems(unknown) == ["a non-asserting value cannot be verified"] + leak = label("outcome", "paid_to_candidate", kinds=("chain_transaction",), + cutoff_relation="pre_cutoff_observable") # fmt: skip + assert any("never be a pre-cutoff model input" in p for p in bc.label_problems(leak)) + assert not bc.model_input_allowed(leak) + assert bc.model_input_allowed( + label("mechanism", "native_dust", cutoff_relation="pre_cutoff_observable") + ) + old = label("mechanism", "unknown", kinds=(), schema_version="benchmark-labels/0") + assert any("incompatible" in p for p in bc.label_problems(old)) + + +def test_invalid_category_and_conflicts() -> None: + with pytest.raises(ValidationError, match="invalid category"): + label("legitimacy", "benign") + with pytest.raises(ValidationError, match="invalid dimension"): + label("fraud", "unknown") + a = label("mechanism", "native_dust") + b = label("mechanism", "fake_token") + assert len(bc.label_conflicts([a, b])) == 1 + assert bc.label_conflicts([a, label("mechanism", "unknown", kinds=())]) == [] + + +def test_unknown_is_never_a_negative() -> None: + labels = [ + label("legitimacy", "unreviewed", kinds=(), subject="0x" + "01" * 20), + label("legitimacy", "ambiguous", kinds=(), subject="0x" + "02" * 20), + label("legitimacy", "insufficient_evidence", kinds=(), subject="0x" + "03" * 20), + ] + assert be.false_positive_rate(labels, flagged=["0x" + "01" * 20])["status"] == "blocked" + ok = label("legitimacy", "confirmed_legitimate", kinds=("reviewer_decision",), + reviewer_id="r1", subject="0x" + "04" * 20) # fmt: skip + r = be.false_positive_rate([*labels, ok], flagged=["0x" + "01" * 20, "0x" + "04" * 20]) + assert (r["numerator"], r["denominator"]) == (1, 1) # only the verified negative counts + + +# --- data quality and independence ---------------------------------------------------------- + + +def codes(issues) -> set[str]: + return {i.code for i in issues} + + +def test_case_quality_rules() -> None: + fx = window() + c, o = case(fx), outcome(fx) + assert "incomplete_categories" in codes(bc.case_quality(c, fx, o)) + assert bc.status(bc.case_quality(c, fx, o, duplicate=True)) == "invalid" + assert bc.status(bc.case_quality(c, fx, o, protected=True)) == "not_evaluable" + assert "outcome_not_verified" in codes(bc.case_quality(c, fx, None)) + no_tx = outcome(fx, harm_tx=None) + assert "missing_transaction_hash" in codes(bc.case_quality(c, fx, no_tx)) + late = case(fx, cutoff=(HARM_BLOCK + 1, 0)) + assert "cutoff_after_harm_block" in codes(bc.case_quality(late, fx, o)) + planted_tx = fx.native_inbound[0].transaction_hash + assert "future_information_leak" in codes( + bc.case_quality(c, fx, outcome(fx, harm_tx=planted_tx)) + ) + assert "chain_mismatch" in codes(bc.case_quality(case(fx, chain_id=10), fx, o)) + assert "wallet_mismatch" in codes(bc.case_quality(case(fx, victim="0x" + "ee" * 20), fx, o)) + assert "invalid_address" in codes(bc.case_quality(case(fx, victim="0x123"), fx, o)) + dup = fx.model_copy(update={"native_inbound": fx.native_inbound * 2}) + assert "duplicate_records" in codes(bc.case_quality(c, dup, o)) + unread = br.degrade(fx, "receipts") + assert "missing_receipts" in codes(bc.case_quality(c, unread, o)) + assert "no_recording" in codes(bc.case_quality(c, None, o)) + old = case(fx, schema_version="benchmark-case/0") + assert "incompatible_artifact_version" in codes(bc.case_quality(old, fx, o)) + conflicted = outcome(fx, labels=(label("mechanism", "native_dust"), + label("mechanism", "fake_token"))) # fmt: skip + assert "conflicting_labels" in codes(bc.case_quality(c, fx, conflicted)) + + +def test_independence_reasons() -> None: + fx = window() + c, o = case(fx, population="independent_candidate"), outcome(fx) + assert bc.independence(c, o, bc.DevelopmentIndex()) == [] + dev = bc.index_from_fixtures([fx], clusters=["syn-1"], protected=[NATIVE]) + reasons = bc.independence(c, o, dev) + assert "victim already used in development" in reasons + assert "attack cluster already used in development" in reasons + assert "paid address already seen in a development artifact" in reasons + assert "paid address in a frozen review cohort" in reasons + untraceable = case(fx, source=bc.CaseSource(publisher="rumour", url="")) + assert "no traceable source" in bc.independence(untraceable, o, bc.DevelopmentIndex()) + assert "declared development" in bc.independence( + case(fx, population="development"), o, bc.DevelopmentIndex() + ) + + +def test_coverage_matrix_and_mechanism_eligibility() -> None: + cov = bc.coverage_matrix(window()) + e = bc.mechanism_eligibility(cov) + assert e["native_dust"]["eligible"] + assert e["spoofed_transfer"]["eligible"] + assert e["all_mechanisms"]["state"] == "unsupported" + assert "internal_value_transfers" in e["all_mechanisms"]["missing"] + gone = bc.mechanism_eligibility(bc.coverage_matrix(br.degrade(window(), "native"))) + assert gone["native_dust"] == { + "state": "unsupported", "eligible": False, "missing": ["native_inbound_external"], + } # fmt: skip + half = bc.mechanism_eligibility(bc.coverage_matrix(br.degrade(window(), "first_half"))) + assert half["fake_token"]["state"] == "partial" + + +# --- splits and leakage --------------------------------------------------------------------- + + +def test_groups_keep_related_cases_together() -> None: + fx = window() + cases = [ + case(fx, "a", cutoff=(4_000, 0)), + case(fx, "b", cutoff=(4_500, 0)), # the same victim + case(fx, "c", victim="0x" + "11" * 20, cluster_id="a"), # the same campaign + case(fx, "d", victim="0x" + "22" * 20, cutoff=(4_900, 0)), + case(fx, "e", victim="0x" + "33" * 20), + ] + outs = {"d": outcome(fx, "d"), "e": outcome(fx, "e")} # d and e share the paid address + grp = be.groups(cases, outs) + assert grp["a"] == grp["b"] == grp["c"] + assert grp["d"] == grp["e"] != grp["a"] + split = be.chronological_split(cases, grp, test_share=0.4) + assert be.split_leakage(split, grp) == [] + assert be.split_leakage({**split, "b": "test" if split["a"] == "dev" else "dev"}, grp) + folds = be.leave_one_group_out(grp) + assert len(folds) == 2 + assert all(not be.split_leakage(f, grp) for f in folds) + assert be.split_feasibility(2)["leave_one_group_out"] is False + + +def test_leakage_audit_blocks_confirmatory_claims_for_development_cases() -> None: + fx = window() + c = case(fx) + req = bc.collector_request(c, max_requests=100) + audit = be.leakage_audit(c, fx, be.predict(c, fx), req, protected=False, dev_reasons=()) + assert audit["confirmatory_allowed"] is True + dev = be.leakage_audit(c, fx, be.predict(c, fx), req, protected=True, dev_reasons=("used",)) + assert dev["confirmatory_allowed"] is False + assert dev["checks"]["no_post_cutoff_evidence"] is True + + +# --- sample-size planning ------------------------------------------------------------------- + + +def test_sign_test_power_and_planning() -> None: + assert power.sign_test_power(4, 1.0)["critical"] is None # 4 of 4: p = 0.0625 > 0.05 + assert power.sign_test_power(5, 1.0) == { + "n_discordant": 5, "critical": 5, "size": 0.03125, "power": 1.0, + } # fmt: skip + assert power.sign_test_power(0, 0.9)["power"] == 0.0 # identical predictions decide nothing + need = [power.discordant_needed(p) for p in (0.7, 0.8, 0.9)] + assert all(n is not None for n in need) + assert need[0] > need[1] > need[2] # a larger effect needs fewer discordant incidents + assert power.discordant_needed(0.5) is None + plan = power.incidents_needed(0.8, 0.25, eligible_rate=0.5, deff=1.5) + d = plan["discordant_needed"] + assert plan["eligible_needed"] == -(-d * 1.5 // 0.25) + assert plan["screened_needed"] == 2 * plan["eligible_needed"] + with pytest.raises(ValueError, match="discordance"): + power.incidents_needed(0.8, 0.0) + + +# --- public-repository safety --------------------------------------------------------------- + + +def test_secret_scan_reports_names_and_counts_only(tmp_path: Path) -> None: + token = "gh" + "p_" + "A" * 36 # built at run time: never a literal in the repository + assert repo_safety.scan_text(f"x = '{token}'") == {"github_token": 1} + assert repo_safety.scan_text("token = '0x" + "ab" * 20 + "'") == {} # an address is no secret + repo = tmp_path / "repo" + (repo / "data").mkdir(parents=True) + (repo / "data" / "raw.jsonl").write_text("{}", encoding="utf-8") + (repo / "notes.txt").write_text(f"key {token}", encoding="utf-8") + (repo / "unblinding_key.jsonl").write_text("{}", encoding="utf-8") + try: + subprocess.run(["git", "init", "-q", str(repo)], check=True, timeout=60) # noqa: S603, S607 + subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True, timeout=60) # noqa: S603, S607 + except (OSError, subprocess.SubprocessError): + pytest.skip("git is not available") + out = repo_safety.scan(repo) + assert out["clean"] is False + assert out["secret_pattern_files"] == {"notes.txt": {"github_token": 1}} + assert out["restricted_paths_tracked"] == ["data/raw.jsonl"] + assert out["sensitive_names"] == ["unblinding_key.jsonl"] + assert token not in json.dumps(out) # the value itself is never reported + + +def test_this_repository_is_clean() -> None: + out = repo_safety.scan(Path(__file__).resolve().parent.parent) + if not out["available"]: + pytest.skip("not a git checkout") + assert out["secret_pattern_files"] == {} + assert out["restricted_paths_tracked"] == [] + assert out["sensitive_names"] == [] + assert out["oversized_files"] == [] + assert out["local_user_paths"] == {} + + +def test_baseline_registry_does_not_prefer_p1b() -> None: + p1b = next(r for r in be.REGISTRY if r["id"] == "P1b") + assert "failed" in p1b["status"] + assert "not preferred" in p1b["status"] + assert be.PRIMARY_METHOD == "B0" From 332dbfd76075da46db538fc3a546dcdaee6d20da Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 10 Nov 2026 14:13:10 +0300 Subject: [PATCH 86/92] fix(ml): inventory registry entries for incident, campaign and research paths; lead event dates Labelling only: three provenance prefixes were unregistered, and a lead's event date is now read from its case id when present. No scoring logic changes. Co-Authored-By: Claude Fable 5.2 --- src/cryptoguard/ml/benchmark_readiness.py | 4 +++- src/cryptoguard/ml/inventory.py | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/cryptoguard/ml/benchmark_readiness.py b/src/cryptoguard/ml/benchmark_readiness.py index cf58d8e..72667b8 100644 --- a/src/cryptoguard/ml/benchmark_readiness.py +++ b/src/cryptoguard/ml/benchmark_readiness.py @@ -453,7 +453,9 @@ def leads(root: Path) -> list[dict[str, Any]]: have = sorted(k for k, v in ids.items() if v) needs = [k for k in ("victim", "harm_tx") if k not in have] victim = (ids.get("victim") or "").lower() - day = str(c["source"]["date"])[:10] + # the event date is the case id's suffix when it has one, else the source date + tail = c["case_id"][-10:] + day = tail if tail[4:5] == "-" and tail[7:8] == "-" else str(c["source"]["date"])[:10] out.append( { "lead": c["case_id"], diff --git a/src/cryptoguard/ml/inventory.py b/src/cryptoguard/ml/inventory.py index 27d47a4..e20ccf4 100644 --- a/src/cryptoguard/ml/inventory.py +++ b/src/cryptoguard/ml/inventory.py @@ -38,6 +38,8 @@ "derived from CC BY-NC-ND and public chain data", "no", "unlabeled_candidate"), ("data/ml/poisoning/", "derived: Phase 11.2-11.4 reconciliation outputs", "derived from CC BY-NC-ND", "no (aggregate tables only)", "source-derived"), + ("data/ml/research/", "derived: research outputs and local re-recordings", + "derived (some from CC BY-NC-ND)", "no (aggregates only)", "development"), ("data/ml/pilot/", "option A pilot (eth.drpc.org, 2026-11-01)", "public chain data", "yes", "pilot outcomes; unknown is never benign"), ("data/ml/chain/", "PTXPhish chain features (collected)", "public chain data + PTXPhish", @@ -48,6 +50,10 @@ "public chain data; committed", "yes", "incident case studies (used in development)"), ("src/cryptoguard/replay/background_cases/", "recorded random background wallets", "public chain data; committed", "yes", "unlabelled_background"), + ("src/cryptoguard/replay/campaign_cases/", "recorded campaign expansion (public chain data)", + "public chain data; committed", "yes", "unlabelled"), + ("docs/ml/incident-benchmark/cases/", "recorded Level I incident windows (Phase 12.3)", + "public chain data; committed", "yes", "incident case studies (development)"), ) # fmt: skip From 79ebd6f9cd53a38b92133f70b8f4e2de2de3190d Mon Sep 17 00:00:00 2001 From: Rostislav Date: Tue, 10 Nov 2026 18:22:08 +0300 Subject: [PATCH 87/92] docs(ml): Phase 12.8 report - independent benchmark readiness (no RPC) ML_INDEPENDENT_BENCHMARK_READINESS.md (35 sections, gates G1-G13). Measured on 332dbfd (identical to 3b512d7): 16 local windows, 0 independent incidents, 0 verified negatives, 0 reviewer submissions, no all-mechanisms window; blind development regression (not validation) classifies the known miss as observation_unsupported; archive development split: the paid lookalike is the newest among similarity-tied rivals in 79.0% of 423 episodes vs 33.5% by chance (+0.454 [0.412, 0.495]). No model trained. Public-repository scan clean over 412 files and 112 commits; one reviewer-blinding risk documented. Readiness: ready after new observation recordings and additional verified labels; generalization evidence BLOCKED BY DATA. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 11 + ML_INDEPENDENT_BENCHMARK_READINESS.md | 602 ++++++++++++++++++++++++++ 2 files changed, 613 insertions(+) create mode 100644 ML_INDEPENDENT_BENCHMARK_READINESS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4619d2f..d218844 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,17 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.8: independent benchmark contract, ground-truth quality, readiness (no RPC requests) +- **Protocol 12.8** (`docs/ml/protocol-12.8.md`) was frozen before any harness code. The code was committed before the measured run. +- **Contracts (research only):** a five-dimension label ontology with evidence rules; a case record separate from the sealed outcome; a collector request that cannot carry an answer; data-quality severities; per-mechanism observation eligibility; independence checks. +- **Blind harness:** `predict` has no outcome parameter, the outcome vault opens only after sealing, and a run-once ledger refuses a different rerun. Scoring gives T1–T7 with one failure class per case. +- **Metrics with explicit denominators:** end-to-end TopK counts generation failures as misses, and a false-positive rate is refused without verified negatives. +- **Planning tool:** `cryptoguard ml benchmark-power` computes exact paired sign-test power from stated assumptions; no sample size is hard-coded. +- **Local data:** 16 windows, **0 independent incidents**, 0 verified negatives, 0 reviewer submissions; no window supports all mechanisms. The known miss is classified `observation_unsupported`. +- **Measurement (archive development split):** when the paid lookalike ties a rival on similarity it is the newest in 79.0 % of 423 episodes, against 33.5 % by chance (+0.454 [0.412, 0.495]). +- **Public-repository safety:** `ml/repo_safety.py` and a CI test; the scan is clean over 412 tracked files and 112 commits. One reviewer-blinding risk is documented. +- **Report:** `ML_INDEPENDENT_BENCHMARK_READINESS.md`. No model was trained. Generalization evidence is BLOCKED BY DATA. + ### Phase 12.7.1: debiased validation of P1b against an adaptive adversary (no RPC requests) - **Protocol 12.7.1** (`docs/ml/protocol-12.7.1.md`) was frozen with the generator, the evaluation code and a sealed manifest (7,200 scenarios, 5,079,472 candidates) before any selector ran. P1 and P1b were frozen by source hash and config hash. - **New independent generator:** random addresses, references assigned by the pipeline's own `_match`, shuffled populations, balanced target age (8 relations), mechanism (5), reference and similarity, and a null family. Fidelity: 30 of 30 rebuilt scenarios matched. diff --git a/ML_INDEPENDENT_BENCHMARK_READINESS.md b/ML_INDEPENDENT_BENCHMARK_READINESS.md new file mode 100644 index 0000000..f6f617b --- /dev/null +++ b/ML_INDEPENDENT_BENCHMARK_READINESS.md @@ -0,0 +1,602 @@ +# Independent benchmark readiness: ground truth, blind evaluation, generalization (Phase 12.8) + +| Item | Value | +|---|---| +| Protocol (frozen before any harness code) | [`docs/ml/protocol-12.8.md`](docs/ml/protocol-12.8.md), `d6f4916` | +| Code (committed before the measured run) | `3b512d7`; labelling fix `332dbfd` | +| Measured run | `cryptoguard ml benchmark-readiness` on `332dbfd`: 47 s, 225 MiB peak RSS. It reproduced the `3b512d7` run exactly. | +| Output (git-ignored) | `data/ml/research/phase12.8/readiness.json`, `ledger-development.jsonl` | +| RPC requests / downloads | **0** / none | + +**Every number below is from development data.** No independent incident exists locally, so +nothing here is validation. + +## 1. Executive summary + +**Readiness decision: ready after new observation recordings and additional verified +labels.** The evaluation contract now exists and works end to end. What is missing is data: + +| Need | Have | +|---|---| +| Independent incidents | **0** (16 local windows: 7 protected by frozen-cohort overlap, 3 development incident windows from 2 incidents, 6 unlabelled background) | +| Verified-legitimate labels | **0** (0 reviewer submissions on the 60 + 35 frozen items) | +| A window observing every mechanism | **0** of 16 (internal transfers, ERC-1155 and zero-value native are unsupported or partial everywhere) | + +**What was built** (research only; the detector is untouched): +- a five-dimension label ontology with evidence rules; +- a case contract whose collector request cannot carry an answer; +- a blind harness: prediction without an outcome parameter, an outcome vault, a run-once + ledger; +- metrics with explicit denominators; +- a nine-class failure taxonomy; +- group splits and a leakage audit; +- a paired sample-size planner; +- a public-repository safety scan. + +**Development regression** (known cases, not validation): +- **Outcome-linked address was a candidate before the cutoff:** 2 of 3 windows. The third is + the `observation/1` recording that cannot see native ETH; it is classified + `observation_unsupported`, not as a ranking failure. +- **End-to-End Top-10 under the current order:** 2 of 2 mechanism-eligible windows; 2 of 3 + over all verified windows. + +**One new measurement.** On the archive development split (source-conditional), when the paid +lookalike ties a rival on similarity, it is the most recently planted of the tied ones in +**79.0 %** of 423 episodes, against a chance rate of 33.5 %. The excess is +0.454 +[0.412, 0.495]. On this non-adversarial data, recency is the right tie-break, which supports +keeping the current order over P1b. + +**No model was trained:** no task has independent labels. + +**The repository is public.** The safety scan is clean over 412 tracked files and 112 +commits. One blinding risk is reported in §28. + +## 2. Research motivation + +Phase 12.7 found a ranking gain that Phase 12.7.1 traced to benchmark construction. The +remaining questions (recency vs hash ties, reference rotation vs similarity) cannot be +settled by more simulation. They need real incidents, scored under a contract fixed in +advance, with outcomes kept away from inference. + +## 3. Previous ML findings + +| Phase | Finding | +|---|---| +| 12.1–12.2 | recency best predicts the paid lookalike on the archive (source-conditional) | +| 12.3 | 2 real incidents: 1 warned, 1 missed | +| 12.4 | the miss was an unobserved native-dust planting; `observation/2` recovers it | +| 12.5 | proxy-task ML loses to frequency baselines under temporal shift | +| 12.6–12.6.1 | evidence groups, guarded signer recovery, bounded summaries | +| 12.7 | P1/P1b looked better than similarity-first on a biased synthetic grid | +| 12.7.1 | on a debiased benchmark, P1b − B0 = −0.018 [−0.031, −0.004]; not promoted | + +## 4. Dataset inventory + +Sizes are by `stat` only. + +| Source | Class | Size | Records | Licence | Eligibility | +|---|---|---|---|---|---| +| Tsuchiya archive | source-derived events | 2.2 GiB, 4 files | — | CC BY-NC-ND 4.0 | development only | +| Archive episodes (12.1 task) | source-derived, paid-lookalike outcome | 5.3 MiB | 1,067 (640 dev / 427 test) | derived, local only | dev split exploratory; **test split spent** | +| Archive subset / unconfirmed payoffs | source-derived | 139 MiB / 610 MiB | — | derived, local only | development; unconfirmed set exhausted | +| Review packets | candidates without outcome | 1.3 MiB | 1,469 | derived, local only | reviewer evidence, unlabelled | +| Cohort A / Cohort B | human review, frozen | — | 60 / 35 | derived, local only | **protected; 0 submissions** | +| Hard-negative pool | candidates without outcome | 109 MiB | — | derived, local only | unlabelled; not negatives | +| Poison-Hunter / PTXPhish / Forta | other sources | < 1.5 MiB each | — | none published / per licence | data card; separate tasks | +| Replay incident windows | wallet windows, verified incident | 4 windows | — | public chain data | development; **all 4 protected** | +| Level I incident windows | wallet windows, verified incident | 2 windows (+1 local `/2` re-recording) | — | public chain data | development | +| Background windows | wallet windows, unlabelled | 9 recorded | — | public chain data | not negatives; 3 protected | +| Synthetic generators | controlled synthetic | code | — | project code | robustness only | + +These classes are never merged into one labelled dataset. + +## 5. Source provenance + +- **Per-file provenance** stays in `ml/inventory.py` (the registry gained entries for the + Level I cases, the campaign expansion and `data/ml/research`). +- **Recorded windows** were all taken from a keyless public endpoint. +- **Incident outcomes** come from public reports, checked on-chain in the manifests. +- **The archive's labels** are the source's own heuristics. + +## 6. Label ontology (`benchmark-labels/1`) + +Five independent dimensions: mechanism, provenance, relationship, outcome and legitimacy. +Each has an `unknown`-type value, and nothing is forced into a binary fraud label. + +**The vocabulary is kept separate:** +- observed transaction; +- suspicious candidate; +- confirmed planting; +- paid lookalike (an outcome, not proof about earlier events); +- confirmed loss; +- legitimate activity; +- unknown. + +## 7. Label reliability + +**A label is rejected when:** +- an asserting value has no evidence reference; +- an outcome value lacks a chain transaction; +- `confirmed_legitimate` rests on anything but a reviewer decision or a synthetic oracle + (absence of a report is never evidence); +- `confirmed_malicious` rests on an on-chain event alone; +- a reviewer reference has no reviewer id; +- an oracle reference appears on a real case; +- a non-asserting value claims `verified`; +- an outcome or legitimacy label is marked as a pre-cutoff model input. + +Conflicting labels on one subject need review. + +**Local labels today:** + +| Label | Count | Basis | +|---|---|---| +| Outcome (`paid_to_candidate`, verified) | 3 | harm transaction plus report; 2 distinct incidents | +| Mechanism (supported, forensic) | 3 | the first pre-harm record involving the paid address | +| Legitimacy | **0** | — | +| Reviewer decision | **0** | — | + +## 8. Observation completeness + +| Window | Schema | native_dust | zero-value / fake token | spoofed | all mechanisms | Incomplete categories | +|---|---|---|---|---|---|---| +| 15 `observation/1` windows | `/1` | **unsupported** | complete | complete | unsupported | 7 of 10 | +| ScamSniffer blind `/2` | `/2` | complete | complete | complete | **unsupported** | 4 of 10 | + +- **No window supports an all-mechanisms detection benchmark.** +- **Still missing in `/2`:** internal value transfers, ERC-1155, zero-value native, and + unattributed inbound. +- **Interpretation:** a missing event in an incomplete category is not evidence of absence. + Eligibility is per mechanism. + +## 9. Historical cutoff design + +- **Cutoff:** `(harm block, 0)`, strictly before the harmful block. Within-block order is not + assumed. +- **Enforcement:** + - `predict` asserts that no candidate record is at or after the cutoff; + - the leakage audit re-checks every record against pre-cutoff observations; + - `case_quality` rejects a cutoff after the harm block and an outcome transaction that + precedes the cutoff. +- **Tests:** + - a planting in the harmful block is not usable; + - a post-cutoff lookalike never becomes a candidate. + +## 10. Blind evaluation protocol + +**Flow:** `predict(case, fixture)` → seal → `OutcomeVault.open` → `score` → `Ledger.record`. + +| Guarantee | How it is enforced | +|---|---| +| Inference cannot see an outcome | `predict` has exactly two parameters (tested) | +| No unblinding before sealing | the vault raises `UnblindingError` | +| One scoring per case | the same prediction returns the stored result; a different one raises `RerunError` and is logged | +| The collector cannot be given an answer | `CollectorRequest` forbids extra fields (tested with a paid address) | + +**Measured:** +- the development ledger recorded 3 cases, and the rerun on `332dbfd` was accepted as + identical (0 refused reruns); +- the harness itself caught one defect during development: stored results were not + JSON-identical to fresh ones. Fixed before the measured run. + +## 11. Independent incident eligibility + +A case is independent only if all of these hold: +- victim, paid address and harm transaction are absent from every development artifact; +- it shares no attack cluster with one; +- it was not used to design or tune a method; +- its source is traceable; +- its outcome identity is clear. + +**Local result: 0 independent incidents, 0 independent victims.** The ScamSniffer `/2` +re-recording stays development and shares its cluster with the `/1` recording (2 clusters in +total). + +## 12. Negative-control requirements + +**Acceptable sources of verified-legitimate labels:** +- human adjudication under the review protocol (two reviewers); +- a controlled wallet whose owner attests each payment; +- explicit synthetic controls (for harness testing only). + +**Not acceptable:** +- background wallets; +- unreported activity; +- source "uncategorized" rows. + +**Status: T8 (false alerts) is BLOCKED.** `false_positive_rate` returns `blocked` without +verified negatives (tested: unreviewed, ambiguous and insufficient-evidence subjects never +count). + +## 13. Annotation protocol + +- **Existing schema** (`poisoning-annotation/1`) already offers confirmed / likely poisoning, + legitimate, ambiguous, insufficient evidence and not evaluable, with evidence references, + reason codes and confidence. +- **Mapping into the ontology:** + - "likely" is never converted to "confirmed"; + - a reviewer decision is the only route to `confirmed_legitimate`. +- **Frozen cohorts:** untouched and unread beyond the blinded sheets. + +## 14. Reviewer agreement feasibility + +- **Tooling exists** (`ml/agreement.py`): exact agreement, confusion matrix and Cohen's kappa + for two reviewers, tested on synthetic labels. +- **Real submissions:** **0**, so no agreement is reported. +- **Scope limit:** a multi-reviewer statistic (Fleiss) is not implemented; the protocol plans + two reviewers. +- **Small-sample caveat:** with 95 items and rare classes, kappa will be unstable. The + insufficient-evidence rate should be reported beside it. + +## 15. Leakage audit + +**Automated checks per case:** + +| Check | Development cases | +|---|---| +| No post-cutoff evidence | pass (3 of 3) | +| No outcome field in the collector request | pass | +| Prediction matches the recording | pass | +| No protected-cohort overlap | pass | +| **Not a spent population** | **fail (3 of 3)** | + +So **confirmatory claims are blocked for all three**, as intended. + +**Spent populations registered:** +- the archive test split (12.1); +- the archive development split; +- both Level I incidents; +- the recorded windows; +- both synthetic grids. + +## 16. Group-aware splits + +- **Groups:** connected components over victim, attack cluster, paid address and optional + signer/lookalike keys. +- **Strategies:** chronological holdout and leave-one-group-out, each with a leakage check. +- **Feasibility today:** 2 groups, so no split is meaningful. Below 3 groups nothing is; + below 10 a holdout has under 4 test groups. Leave-source-out and cross-period designs are + not feasible either. + +## 17. Benchmark task definitions + +| Task | Question | Denominator | +|---|---|---| +| T1 | planting observed before the cutoff? | verified cases whose mechanism category is complete | +| T2 | candidate generated? | eligible cases | +| T3 | rank | generated cases | +| T4 | top-K | conditional: generated; end-to-end: all eligible (generation failures are misses) | +| T5 | mechanism identified? | generated cases with a mechanism label | +| T6 | evidence fidelity | all candidate records | +| T7 | alert burden | all windows | +| T8 | false alerts | verified-legitimate labels (blocked) | +| T9 | ML generalization | independent groups (blocked) | + +No single "detection accuracy" number is produced. + +## 18. Candidate-generation metrics (development cases; not validation) + +| Metric | Value | +|---|---| +| ObservationCoverage (mechanism-assessable) | 2 / 2 | +| ObservationCoverage (all verified) | 2 / 3 | +| CandidateRecall (mechanism-eligible) | 2 / 2 | +| CandidateRecall (all verified) | 2 / 3 | +| Mechanism identification | 2 / 2 | +| Evidence fidelity | 14 / 14 records resolve to pre-cutoff observations | +| Burden | mean 3.7 candidates per window (max 6); 1.22 per wallet-day; summary ≤ 5.3 KB | + +## 19. Ranking metrics (development cases; not validation) + +| Method | Rank: ScamSniffer `/2` | Rank: pilot | MRR on generated (n = 2) | +|---|---|---|---| +| B0 (similarity → recency) | 1 | 3 | 0.667 | +| B1 (recency) | 3 | 2 | 0.417 | +| B4 (reference rotation) | 1 | 3 | 0.667 | +| P1 / P1b (seed 0) | 1 | 5 | 0.600 | + +**Under B0:** + +| K | Conditional TopK | End-to-End TopK (mechanism-eligible) | End-to-End TopK (all verified) | +|---|---|---|---| +| 1 | 1 / 2 | 1 / 2 | 1 / 3 | +| 3, 5, 10 | 2 / 2 | 2 / 2 | 2 / 3 | + +With n = 2 clusters these describe the harness, not the methods. + +## 20. Failure taxonomy + +One class per scored case, assigned in order: `outcome_not_verified`, `label_uncertain`, +`observation_unsupported`, `observation_partial`, `not_observed_in_complete_stream`, +`candidate_not_generated`, `incorrect_reference_matching`, `ranked_below_k`, `exposed`. + +- **Development cases:** `exposed` × 2, `observation_unsupported` × 1 (ScamSniffer `/1`). +- **Tested:** every class is exercised by a synthetic test. +- **Naming detail** (not in the protocol): `ranked_below_k` uses B0 at K = 10. Per-K exposure + is reported separately. + +## 21. Existing baseline registry + +**Generators:** C0, C1, C2 and `candidate-evidence/2`. +**Orders:** B0, B1, B4, P1 and P1b. +**Each entry has:** version, required categories, missingness behaviour and status. + +- **P1b:** "failed the 12.7.1 debiased benchmark; comparison only, not preferred" (asserted by + a test). +- **M-LTR:** listed as not registered for scoring. +- **No method was modified.** + +## 22. Local data eligibility + +| Windows | Count | Status | +|---|---|---| +| Replay incident windows | 4 | `not_evaluable`: touch frozen Cohort B | +| Background, protected | 3 | `not_evaluable` | +| Background, unprotected | 6 | no outcome; 0 candidates each; not negatives | +| Development incident windows | 3 | `valid_with_limitations` | +| **Independent** | **0** | — | + +**Leads in the committed registries** (a lead is not an incident): 7 unrecorded, none with +complete identifiers. + +| Lead | Claimed mechanism | Identifiers present | Missing for collection | In archive period | +|---|---|---|---|---| +| usdt-700k-2025-04 | zero-value token | planting tx, harm tx | victim (derivable only from chain data) | no | +| wbtc-2.38-2025-12-18 | unknown | harm tx | victim | no | +| pink-drainer-10eth-2024-06-27 | unknown | victim, intended recipient | harm tx | yes (victim not in the archive episodes) | +| webacy-6.88m-usdt-2025-09 | unknown | victim | harm tx (RPC was rejected twice in Stage 2a) | no | +| dea-usdt-55k-2023 | other | none | victim, harm tx | yes | +| usdt-100k-2026-08 | unknown | none | victim, harm tx | no | +| usdt-50k-2026-10 | unknown | none | victim, harm tx | no | + +- **No new web discovery** was run in this phase. Stage 2 preparation already searched + public reports and found that they usually truncate addresses. +- **Selection risk:** choosing leads by how easy the outcome is to locate would bias the + sample, so the eligibility rules are fixed before selection. + +**Missingness sensitivity** (in-memory degradations; not real recorder failures): + +| Degradation | ScamSniffer `/2` (native dust) | Pilot (fake token) | +|---|---|---| +| none | exposed, rank 1 | exposed, rank 3 | +| no signer lookups | exposed, rank 1 | exposed, rank 3 | +| no receipts | exposed, rank 1 | exposed, rank 3 | +| recipient history incomplete | exposed, rank 1 | exposed, rank 3 | +| first half of the window removed | exposed, rank 1; coverage no longer complete | exposed, rank 3; coverage no longer complete | +| **no native observations** | **`observation_unsupported`; candidate lost** | exposed, rank 3 | + +The original `/1` ScamSniffer recording is `observation_unsupported` under every condition. +Rank never changed with missing support data. This matches Phase 12.6.1. + +## 23. ML readiness + +| Task | Independent labels | Classification | +|---|---|---| +| Rank the paid lookalike (archive) | 640 dev episodes; test split spent | ready for development evaluation only | +| Poisoning vs legitimate (binary) | 0 verified negatives | **blocked by insufficient labels** | +| Candidate generation on real incidents | 2 development clusters | **blocked by data** | +| Reviewer-label classifier | 0 submissions | **blocked by insufficient labels** | +| Next-mechanism proxy (12.5) | done; negative | not repeated (no new hypothesis) | +| All-mechanisms detection | no complete window | **blocked by observation coverage** | +| Generalization of any ranker | 0 independent groups | **blocked by data** | + +## 24. Exploratory experiments + +**No model was trained.** + +**One pre-registered measurement (D5), on the archive development split:** + +| Quantity | Value | +|---|---| +| Evaluable episodes | 640 (632 groups) | +| Episodes where the paid lookalike ties a rival on similarity | 423 (mean 5.1 tied candidates) | +| Paid one is the newest of the tied | **79.0 %** | +| Chance (1/t) | 33.5 % | +| Excess over chance | **+0.454 [0.412, 0.495]**, p < 0.001 (group bootstrap and sign-flip) | +| Over all candidates, ignoring similarity | +0.483 [0.448, 0.517] | + +**Interpretation:** +- on real, non-adversarial, payoff-conditioned data, recency is a strong tie-break; +- this supports B0's tie rule over P1b's hash; +- it is consistent with Phase 12.1 and is **not** new independent evidence; +- it does not cover an adversary who controls timing (12.7.1). + +## 25. Statistical power + +In a paired comparison (exposed within K under method A vs B on the same incidents) only +**discordant** incidents inform. Exact one-sided sign test, α = 0.05, when the better method +wins a discordant incident with probability 0.8: + +| Discordant incidents | Critical count | Power | +|---|---|---| +| 5 | 5 of 5 | 0.33 | +| 10 | 9 of 10 | 0.38 | +| 20 | 15 of 20 | 0.80 | +| 30 | 20 of 30 | 0.97 | + +Ten incidents with identical predictions give power 0. + +## 26. Sample-size planning + +`cryptoguard ml benchmark-power --p-better P --discordance D [--eligible-rate E --deff F]`. +Nothing is hard-coded. Scenarios at power 0.8, with half of screened incidents eligible: + +| P(better wins a discordant incident) | Discordance | Discordant needed | Eligible needed | Screened needed | +|---|---|---|---|---| +| 0.9 | 0.5 | 11 | 22 | 44 | +| 0.9 | 0.3 | 11 | 37 | 74 | +| 0.8 | 0.5 | 18 | 36 | 72 | +| 0.8 | 0.3 | 18 | 60 | 120 | +| 0.8 | 0.1 | 18 | 180 | 360 | +| 0.7 | 0.3 | 42 | 140 | 280 | + +- **Clustering:** a design effect of 1.5 multiplies every row by 1.5. +- **The earlier "about 70"** corresponds to one row of this table (0.8, 0.3, without the + eligible-rate factor). It is an assumption, not a requirement. +- **Current sample:** 0 independent incidents, 2 development clusters. + +## 27. Resource estimates (plan only; nothing was requested) + +| Item | Estimate | Basis | +|---|---|---| +| Requests per window | about 700–1,300 | measured: 475 (pilot), 1,299 (`/2` blind), 1,433 (Stage 2a including resolution) | +| Per-window ceiling | 2,500 | the cap used for the `/2` blind recording | +| Feasibility set (10 recordings) | about 7,000–13,000; ceiling 25,000 | | +| Powered scenario (60 eligible, 120 recorded) | about 84,000–156,000 | row (0.8, 0.3) above | +| Disk per window | about 50–200 KB | existing fixtures | +| Memory | under 300 MiB | this study peaked at 225 MiB | +| Unusable recordings | about 1 in 3 so far (1 of 3 Stage 2 attempts was rejected by the provider) | very small sample | + +**Controls already in the codebase:** +- a durable request ledger whose caps cover retries and fail closed; +- no budget carry-over; +- a bounded resource preflight. + +Busy wallets can exceed these figures. **A plan is not permission: explicit approval of a new +cap is required before any request.** + +## 28. Public repository safety + +**Scan** (`ml/repo_safety.py`; names and counts only, never matched values): + +| Check | Tracked files (412) | History (112 commits) | +|---|---|---| +| High-confidence secret patterns | 0 | 0 | +| Sensitive file names (keys, `.env`, unblinding, ledgers) | 0 | 0 | +| Anything under `data/` | 0 | 0 ever added | +| Local user paths | 0 | — | +| Oversized files (> 4 MiB) | 0 | — | + +**Manual review:** +- A broader pattern pass flagged 15 strings. All are ERC-20 contract addresses assigned to + variables named `token`, or redaction-test URLs. +- Recorded windows name only a keyless public endpoint. +- No archive-derived record is tracked. + +**One risk to know about (not a secret leak):** +- 54 identifiers from the frozen Cohort B sheet appear in 17 tracked files, because Cohort B + was drawn from recorded windows that were already public. +- No sheet and no key is tracked. +- A reviewer who searches the public repository for an item's address could find the + incident manifest, including its outcome. That weakens blinding for the items drawn from + the 4 incident windows. +- **Mitigation for the owner to decide:** tell reviewers not to consult the repository, or + treat those items as unblinded in the analysis. + +**Also public:** commit author identities, including an email domain. Nothing was rewritten, +and visibility was not changed. + +**Regression test:** `test_this_repository_is_clean` keeps the high-confidence checks in CI. + +## 29. Test results + +- **New tests:** 23 in `tests/test_ml_benchmark_contract.py`. +- **What they cover:** + - the controlled end-to-end benchmark; + - every failure class; + - metric denominators; + - ledger and vault behaviour; + - label rules and data-quality rules; + - independence; + - splits and leakage; + - sample-size planning; + - the safety scan. +- **Full-suite and CI results:** in the Validation section below. + +## 30. Reproducibility + +- **Reruns:** the measured run was repeated on `332dbfd` and matched `3b512d7`. +- **Prediction digest:** covers the observation hash, the cutoff, the candidate identities + and every method's order. +- **Ledger:** stores the digest and refuses a different one. +- **No randomness** beyond the fixed public seed of P1/P1b. + +## 31. Positive findings + +1. A working, tested blind-evaluation contract with outcome isolation and a run-once ledger. +2. Failures are attributed correctly: the known miss is `observation_unsupported`, not a + ranking failure. +3. End-to-end metrics count generation failures as misses; conditional metrics are separate. +4. Recency ties are right on real archive data (79.0 % vs 33.5 % chance). +5. The public repository is clean of secrets and restricted data. + +## 32. Negative findings + +1. **0 independent incidents;** no confirmatory claim is possible. +2. **0 verified negatives and 0 reviewer submissions;** false-alert evaluation is blocked. +3. **No window supports all mechanisms.** +4. **None of the 7 unrecorded leads has complete identifiers.** +5. **All 4 original incident windows are locked** behind the frozen cohort until it is + reviewed. +6. **Reviewer blinding** for cohort items from public incident windows is weakened by the + repository being public. + +## 33. Current blockers + +| Blocker | What removes it | +|---|---| +| No independent incidents | new incidents with a victim wallet and harm transaction, recorded with `observation/2` under a newly approved RPC cap | +| No verified negatives | two human reviewers completing the frozen cohorts (the owner contacts them) | +| Unsupported categories | trace access (internal transfers), ERC-1155 decoding, zero-value native observation | +| Locked incident windows | completion of the Cohort B review | +| Incomplete leads | full identifiers from the original sources, or approval to resolve them on-chain | + +## 34. Independent benchmark readiness decision + +**Ready after new observation recordings and additional verified labels.** + +| Aspect | Status | +|---|---| +| Methodology, tooling and safety | ready | +| Evidence | blocked by data on three fronts: independent incidents, verified negatives, mechanism coverage | + +Label uncertainty and source-selection bias are controlled by the contract, but cannot be +measured until data exist. + +## 35. Recommended next experiment (not started) + +**A prospective feasibility benchmark** under this contract: +- **Selection:** the owner supplies at least 10 untouched incidents selected by the §11 + rules *before* looking at how they would score. Multi-recipient victims are preferred, so + that B0 and B4 can disagree. +- **Recording:** `observation/2` to the harm block, with a per-window cap of 2,500 and a + total cap of 25,000 requests. +- **Scoring:** frozen methods B0, B1, B4 and P1b; the blind flow of §10; each case scored + once. +- **Primary readout:** the failure-class distribution and End-to-End Top-5 over + mechanism-eligible cases, plus the number of B0/B4 discordant incidents. +- **Labels needed:** paid address, intended recipient and harm transaction per incident. +- **Falsification:** if fewer than 5 of the first 10 incidents are mechanism-eligible, or B0 + and B4 are discordant on fewer than 2, a powered comparison is not worth its RPC cost at + that discordance and should not be funded on current assumptions. + +**Phase 12.9 is not started. No RPC was requested.** + +## Gates + +| Gate | Status | Basis | +|---|---|---| +| G1 Dataset provenance | **PASS WITH LIMITATIONS** | every source registered; archive labels are source heuristics | +| G2 Label quality | **PASS WITH LIMITATIONS** | evidence rules enforced; only 3 outcome labels and 0 legitimacy labels exist | +| G3 Historical correctness | **PASS** | cutoff asserted in prediction, audit and quality rules; tested | +| G4 Observation completeness | **PASS** | eligibility is per mechanism; all-mechanisms correctly blocked | +| G5 Protected-set integrity | **PASS** | cohort hashes unchanged; 7 protected windows never computed on | +| G6 Split correctness | **PASS WITH LIMITATIONS** | grouping and leakage checks tested; no split feasible with 2 groups | +| G7 Benchmark reproducibility | **PASS** | identical rerun; digest-checked ledger | +| G8 Metric correctness | **PASS** | denominators tested, including generation failures as misses | +| G9 Negative-label validity | **PASS** | unknown never counted as benign; FPR refused | +| G10 Model readiness | **NOT EVALUATED** | no model trained; no task has independent labels | +| G11 Generalization evidence | **BLOCKED BY DATA** | 0 independent incidents | +| G12 Public-data safety | **PASS WITH LIMITATIONS** | scan clean; reviewer-blinding risk noted | +| G13 Production isolation | **PASS** | detector untouched; research-only modules | + +## Validation + +| Check | Result | +|---|---| +| `ruff check .` / `ruff format --check .` | clean / 309 files formatted | +| `mypy src` (Windows and `--platform linux`) | clean (160 files) on both | +| Full suite | **1,098 passed, 0 failed**, 4 deselected (8 min 10 s); 23 new tests in `tests/test_ml_benchmark_contract.py` | +| Frozen cohorts | sheet and key hashes unchanged (`a0ec4b6e…`, `407b412f…`, `121c112d…`, `f333386d…`) | +| Incident fixtures | untouched (no data file modified) | +| Package and CI | recorded in the PR #1 description | From 89aea4e358c7cc5878383a4c89115f1bab1e13f4 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 11 Nov 2026 14:36:37 +0300 Subject: [PATCH 88/92] docs(ml): freeze protocol 12.9 (reviewer blinding, incident acquisition, pilot gate) Exposure channels and deterministic levels R0-R3/RU (R4 only from reviewer evidence), artifact roles, cohort dispositions and the prospective reviewer workflow with declarations; bounded public discovery (20 searches, 30 page reads, verbatim identifiers, no explorer access), eligibility rules, hash-ordered pilot selection (one per cluster, cap 10), anchor + record jobs with caps (5 + 2,500 per window), a separate approval record, the frozen B0-vs-B4 comparison with reference-group exposure, and pilot stop rules S1-S6. Frozen before the audit, the search and any classification. RPC 0. Co-Authored-By: Claude Opus 5.5 --- docs/ml/protocol-12.9.md | 250 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 docs/ml/protocol-12.9.md diff --git a/docs/ml/protocol-12.9.md b/docs/ml/protocol-12.9.md new file mode 100644 index 0000000..e31472f --- /dev/null +++ b/docs/ml/protocol-12.9.md @@ -0,0 +1,250 @@ +# Protocol 12.9: reviewer-blinding integrity, independent incident acquisition, pilot gate + +**Frozen:** 2026-11-11, in the commit that adds this file. That is before the Phase 12.9 +exposure audit is computed, before any new public-source search, and before any lead is +classified. + +**Base:** `79ebd6f` (Phase 12.8 contract). + +**RPC budget:** 0. No JSON-RPC request, no explorer page or API, no wallet-history download. + +**Public repository:** the repository is public by its owner's choice. This phase commits +aggregates, rules and citations only: +- **never committed:** per-item exposure mappings, cohort membership, review keys and incident + identifiers (victim, lookalike, transactions); +- **kept locally:** those values live under the git-ignored `data/ml/research/phase12.9/`; +- **in the public registry:** SHA-256 commitments of the identifiers instead. + +## Part I — reviewer blinding + +### 1. Exposure channels + +**For each frozen review item,** the identifiers are taken from the blinded reviewer sheet +only: wallet, address under review, transaction, and context counterparties. The unblinding +key is hashed for integrity and never parsed. + +**Searched channels:** +- **repo-HEAD:** every tracked text file at HEAD; +- **repo-history:** every line ever added in any commit (public through git history); +- **repo-partial:** truncated identifiers (`0x` plus at least 8 hex characters followed by `…` + or `...`) in tracked files. They are matched by prefix and are always ambiguous; +- **external:** the item's documented provenance class. Archive-derived items come from a + publicly downloadable dataset (Tsuchiya et al., KiltHub) that carries the source's own + labels. Recorded-window items come from public chain data. + +### 2. Roles of public artifacts + +| Artifact | Role | +|---|---| +| Incident manifests (`replay/cases/*/manifest.json`, `docs/ml/incident-benchmark/cases/*/manifest.json`) | `victim` and `intended_recipient` are **context**; `harm.recipient` and `harm.transaction_hash` are **outcome** | +| Incident registries (`docs/ml/incident-benchmark/*candidates*.json`) | `lookalike`, `harm_tx`, `planting_tx` and Etherscan filter roles are **outcome**; `victim` and `intended` are **context** | +| Incident-window fixtures (`replay/cases/*/fixture.json`, `docs/ml/incident-benchmark/cases/*/fixture.json`) | **context** (the window belongs to a publicly described poisoning incident) | +| Campaign expansion (`replay/campaign_cases/`) | **context** (a cross-wallet poisoning-campaign analysis) | +| Background fixtures and manifests, tests, frontend fixtures, other files | **neutral** | +| repo-history only (no longer at HEAD) | the role of the file it was added to; unknown files are **neutral** | + +### 3. Exposure levels (deterministic; the highest applicable level) + +| Level | Rule | +|---|---| +| **R3 outcome exposure** | an item identifier matches an **outcome** role in any public artifact | +| **R2 context exposure** | an item identifier matches a **context** role, or appears in a context artifact | +| **R1 identifier overlap** | an item identifier appears only in **neutral** artifacts | +| **RU unknown** | only truncated-prefix matches exist, or the item's identifiers cannot be read | +| **R0** | no match in any channel | +| **R4 confirmed reviewer exposure** | assigned **only** from a reviewer's own declaration or independent evidence that the reviewer accessed outcome-bearing information. Never inferred from R3. | + +- The **repo** level and the **external** level are reported separately, and their maximum is + the item's combined level. +- **External level:** + - archive-derived items from the payoff-linked pool (Cohort A) are **R3-external**, because + the public dataset labels the event's victim as a confirmed payoff victim of a poisoning + attempt; + - archive-derived items from the "uncategorized" pool are **R2-external**; + - recorded-window items are **R0-external** (raw chain data alone carries no label). +- **Separate conditions, never conflated:** identifier visible (R1+), context discoverable + (R2+), outcome discoverable (R3), reviewer exposed (R4), reviewer exposure unknown (no + declaration). + +### 4. Timing + +**For each overlapping public artifact,** its first commit date is compared with the cohort's +freeze date: Cohort A on 2026-11-02 (Phase 11.4), Cohort B at `c68d3a4`, 2026-11-02. + +**The public-visibility window is bounded by observation:** +- 2026-11-09: an anonymous API read returned Not Found; +- 2026-11-10: it returned `visibility: public`. + +Exposure before that window was within a private repository. + +### 5. Cohort disposition (per item, then per cohort) + +| Combined level | Disposition | +|---|---| +| R3 (repo or external) | **not eligible for confirmatory blinded evaluation**; exploratory or sensitivity analysis only | +| R2 | **requires qualified blinding** (access separation and a reviewer declaration); reported as a sensitivity stratum | +| R1, R0 | **eligible for an explicitly qualified blinded review** (with declaration) | +| RU | **requires exposure clarification** | + +- **The frozen cohorts are never rewritten:** dispositions are a separate local record. +- **No replacement cohort is drawn from already-exposed pools.** If no unexposed pool exists, a + new cohort is reported as blocked. + +### 6. Reviewer workflow (prospective) + +**Task payloads are built from a per-task whitelist. They never contain:** +- outcome labels or registry statuses; +- attacker attribution; +- model scores, ranks or predictions; +- other reviewers' decisions; +- public report conclusions. + +**Every review task carries:** +- a task id; +- the item and evidence versions; +- an evidence SHA-256; +- the item's exposure level; +- a **reviewer declaration**: prior familiarity, external sources consulted, repository + consulted, model output seen. Each is `yes`, `no` or `unknown`, given by the reviewer. + +**Rules:** +- A missing declaration is **never defaulted**: the review's exposure is RU. +- A declared consultation of outcome-bearing material on an R3 item makes it R4. +- Adjudication needs two independent decisions (`label_policy`) plus declarations. +- Instructions not to consult public sources are a procedural protection, not proof of + blindness. + +## Part II — incident acquisition + +### 7. Discovery (bounded) + +**Budget:** at most **20 searches** and **30 page reads**. + +**Source order:** +1. primary forensic and firm reports; +2. research papers; +3. news that quotes identifiers. + +**What counts and what is never used:** +- Social-media-only claims are leads at best; X posts are not read. +- Explorer pages and APIs are never fetched. +- A full transaction hash or address inside a cited page's own hyperlink counts as verbatim + from that page (the 12.3 convention). +- Identifiers are copied verbatim. A truncated identifier is recorded as truncated, never + completed. +- A role (victim, lookalike, intended recipient, harmful transaction) is assigned only when the + page states it. +- **Corroboration** needs an independent original source. Articles repeating one alert count + once. + +### 8. Eligibility (first matching rule wins) + +1. **DEVELOPMENT_ONLY:** any identifier matches a development artifact, meaning: + - recorded fixtures and manifests; + - incident registries; + - campaign expansion; + - archive episodes or archive subset; + - review packets; + - frozen cohort sheets. +2. **REJECTED:** chain not Ethereum mainnet; or no identifier at all. +3. **CONFLICTING:** sources disagree on an identifier, amount or date. This maps to + NEEDS_IDENTIFIER_VERIFICATION, with the conflict listed. +4. **NEEDS_IDENTIFIER_VERIFICATION:** the victim address or the harmful transaction hash is + absent or truncated. +5. **NEEDS_CAMPAIGN_REVIEW:** the lead shares an attacker or lookalike identifier with another + lead, unless the two are grouped into one cluster. +6. **UNSUPPORTED_MECHANISM:** the claimed mechanism needs a category `observation/2` cannot + observe: internal transfers, ERC-1155, or zero-value native transfers. +7. **NOT_EVALUABLE:** no harmful transfer is claimed (planting only). +8. **READY_FOR_BLIND_RECORDING:** otherwise. This requires a verbatim victim, a verbatim harm + transaction, a stated Ethereum chain and stated roles. + +**Not required but recorded:** +- the intended recipient (without it, reference-group exposure is not assessable); +- the lookalike (the anchor receipt supplies it to the evaluator only). + +### 9. Pilot selection + +**Selection:** every READY lead, at most one per victim or attacker cluster, ordered by +`sha256("cg-12.9-pilot|" + lead_id)` and capped at 10. + +**Never used to choose:** detectability, loss size, or ease of recording. Fewer than 10 is +reported as found. + +### 10. Collection jobs (prepared, never executed here) + +**Per selected lead:** + +| Step | What it does | Cap | +|---|---|---| +| **anchor** | one receipt read of the harmful transaction, to obtain its block H and confirm that the sender is the stated victim. A mismatch, a missing receipt or a reverted transaction makes the lead NOT_EVALUABLE before any recording. The anchor's output to the collector is the block number only; the receipt fields go to the outcome vault. | 5 requests | +| **record** | a Phase 12.8 `CollectorRequest(chain_id=1, wallet=victim, from_block=H−21,600, to_block=H, observation=2, max_requests=2,500)` | 2,500 requests | + +**Overall cap:** n × 2,505. + +**Estimates use the measured recordings:** + +| Measure | Requests | +|---|---| +| Low | 475 | +| Typical | 1,299 | +| High | 1,433 | +| Retry reserve | +20 % | + +- **Wallet activity** is unknown without RPC and stated as such. +- **Every retry is counted** in the existing durable ledger, which fails closed and carries + nothing over. + +### 11. Approval gate + +**The manifest is planning only.** Recording requires a separate **approval record**: +- the manifest SHA-256; +- the per-window cap; +- the total cap; +- the approver's statement, quoted from chat. + +`check_approval` refuses any mismatch. Configuration never implies approval, and no batch +runner is added in this phase. + +## Part III — frozen comparison and pilot rules + +### 12. Methods (Phase 12.8 registry, unchanged) + +- **Generators:** C0, C1, C2 and `candidate-evidence/2`. +- **Orders:** B0 (similarity → recency), B1 (recency), B4 (reference rotation), P1, P1b. +- **P1b is comparison-only.** +- **Primary pair:** B0 vs B4. +- **Code revision:** the commit that adds this protocol. + +**Tasks:** T1–T4 and T6 as in Phase 12.8, plus **T5g reference-group exposure**: within K, a +candidate whose best-reference bucket is the intended recipient. It is reported separately +from address exposure and is not assessable without an intended recipient. + +### 13. Pilot stop rules (frozen before any recording) + +**Evaluated on the recorded pilot, in order:** + +| Rule | Condition | Action | +|---|---|---| +| S1 | anchor or recording fails for more than 30 % of selected leads (provider failures) | stop and report | +| S2 | fewer than 5 of 10 recorded incidents (or fewer than half of those recorded) are mechanism-eligible | pause broader collection | +| S3 | B0 and B4 disagree on End-to-End Top-5 for fewer than 2 incidents | no powered comparison on current assumptions | +| S4 | more than half of the recorded incidents fall in one attacker cluster | report the effective sample size as the cluster count | +| S5 | any case fails the leakage audit (contaminated cutoff) | exclude it from confirmatory metrics | +| S6 | — | report every missing mechanism category by name | + +**Primary readout:** +- the failure-class distribution; +- End-to-End Top-5 for B0 and B4 over mechanism-eligible cases; +- the number of discordant incidents; +- T5g. + +**Statistics:** the exact sign test on discordant incidents (Phase 12.8 `power`). Clusters +count once. No precision, recall or false-positive rate is reported from the pilot. + +## 14. Gates + +- **Statuses:** PASS, PASS WITH LIMITATIONS, FAIL, BLOCKED BY DATA, NOT EVALUATED. +- **Gates:** G1–G14 as in the phase brief. +- **Independent validation stays BLOCKED BY DATA** until approved recordings exist and are + scored once. From fc97a0442212bf6bbc1cc0b2eeef8afca87d707d Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 11 Nov 2026 15:26:18 +0300 Subject: [PATCH 89/92] feat(ml): reviewer-blinding exposure audit, review-task safeguards and protocol Protocol 12.9 Part I. `ml/review_blinding.py` audits the two frozen review cohorts: - Identifiers come from the blinded sheets only; the unblinding keys are hashed, never parsed. - Channels: tracked files at HEAD, every line added in git history (with its first date), truncated prefixes, and documented provenance. - Matches get artifact roles (outcome / context / neutral), which set the levels R0/R1/R2/R3/RU. - R4 is assigned only from a reviewer declaration. - Per-item mappings are written to the git-ignored research directory only. Prospective workflow: - whitelisted task payloads checked for outcome-bearing keys or wording; - opaque task ids; - ReviewerDeclaration (yes / no / unknown, never defaulted); - review_exposure, adjudication_readiness and a guidance screen. docs/ml/reviewer-blinding-protocol.md holds the neutral reviewer guidance, the declaration form and the cohort dispositions (aggregates only). Co-Authored-By: Claude Opus 5.5 --- docs/ml/reviewer-blinding-protocol.md | 152 ++++++ src/cryptoguard/ml/review_blinding.py | 679 ++++++++++++++++++++++++++ 2 files changed, 831 insertions(+) create mode 100644 docs/ml/reviewer-blinding-protocol.md create mode 100644 src/cryptoguard/ml/review_blinding.py diff --git a/docs/ml/reviewer-blinding-protocol.md b/docs/ml/reviewer-blinding-protocol.md new file mode 100644 index 0000000..15ac4c7 --- /dev/null +++ b/docs/ml/reviewer-blinding-protocol.md @@ -0,0 +1,152 @@ +# Reviewer-blinding protocol (Phase 12.9) + +**Status:** prospective. It applies to any review run after 2026-11-11. No reviewer has been +contacted, no kit has been sent and no decision exists, so nothing here changes a past +review. + +**Rules it implements:** protocol 12.9, sections 1 to 6. The exposure levels and dispositions +are computed by `cryptoguard ml review-blinding`; per-item results stay in the git-ignored +research directory. + +## 1. What this protocol can and cannot do + +**What it does:** +- **Separates access.** The reviewer sees the task payload only: never the repository, the + unblinding key, registry statuses, model output or another reviewer's decision. +- **Records what each reviewer knew.** A declaration per task records prior familiarity and + every consultation. + +**What it cannot do:** +- **It cannot make a publicly exposed item blind again.** An item whose outcome is publicly + discoverable (level R3) stays R3, whatever the interface hides. +- **Instructions are not proof of blindness.** An instruction not to consult public sources is + a procedural protection only. +- **Only a declaration can show exposure.** Without one, the reviewer's exposure is + **unknown**, never assumed absent. + +## 2. Exposure levels used in tasks + +| Level | Meaning | Use | +|---|---|---| +| R0 | no public match found | eligible for an explicitly qualified blinded review | +| R1 | identifier visible in neutral public files only | eligible for an explicitly qualified blinded review | +| R2 | incident or campaign context publicly discoverable | qualified blinding; reported as a sensitivity stratum | +| R3 | outcome publicly discoverable | not eligible for confirmatory blinded evaluation | +| RU | only truncated matches, or unreadable | exposure must be clarified first | +| R4 | the reviewer declared familiarity or a consultation on an R3 item | excluded from confirmatory use | + +- **R4 is never computed from R3.** It comes only from the reviewer's own declaration, or from + independent evidence that the reviewer saw outcome-bearing material. + +## 3. Task payload + +**A task's payload is built from a fixed whitelist of blinded-sheet fields:** +- `item`, `chain_id`, `wallet`, `address_under_review`, `transaction`, `block`; +- `context`, holding `block`, `counterparty`, `direction` and `value` only; +- `coverage_note`. + +**Before a task is issued, `assert_payload_clean` refuses:** +- any other key that names a label, status, verdict, outcome, payoff, attribution, score, rank, + prediction, decision, source, cohort, stratum or purpose; +- any text value with outcome-bearing wording. + +The error names the location, never the value. + +**The task record (not shown to the reviewer) carries:** +- an opaque task id: a hash of the sheet hash and the item number, which names neither the + cohort nor its purpose; +- the item version (the sheet's SHA-256); +- the evidence version and the evidence SHA-256; +- the item's computed exposure level. + +## 4. Reviewer guidance (given to reviewers verbatim) + + +You will see one wallet, one address under review and one transaction. Some tasks also list +a few of the wallet's other transfers. + +Decide, from the evidence shown, which decision option best describes how the address under +review relates to the wallet. Use only the evidence in the task and chain data up to the +block shown. + +While you work on a task: + +- Do not look up the wallet, the address or the transaction in this project's repository, + in news articles, in incident write-ups or in social-media posts. +- Do not rely on name tags, warnings or other annotations that a block explorer may display. + If you notice one, say so in your declaration. +- If you already recognise the wallet, the address or the transaction, say so in your + declaration and continue. +- Choose "insufficient evidence" whenever the evidence shown does not support a decision. + +Every option is acceptable. There is no target distribution of answers, and nothing about +your answer affects which tasks you receive next. + +After each task, answer the four declaration questions below. Answer each with yes, no or +unknown. "Unknown" is a valid answer and is never read as "no". + +| Field | Question | +|---|---| +| `prior_familiarity` | Before this task, had you seen or heard of this wallet, this address or this transaction? | +| `external_sources_consulted` | During this task, did you consult anything outside the task, such as news, incident reports, social media, or explorer name tags or warnings? | +| `repository_consulted` | During this task, did you open this project's repository, its reports or its data files? | +| `model_output_seen` | Did you see any score, rank or warning that a model or a tool produced for this item? | + + +**Checking the guidance:** +- `guidance_findings` screens this section for prevalence hints and source-verdict wording; the + tests require zero findings. +- The guide in the two prepared, unsent kits had 4 screen hits in 2 files. On reading, all four + are benign: + - two hits are the name of a decision option; + - one is a sentence about the evidence panel; + - one is a question asking whether the reviewer saw a source label, a payoff record or model + output. +- Even so, the kits predate the declaration form. They must be rebuilt from this section before + any use. + +## 5. Declaration rules + +**Declarations are given by the reviewer, per task:** +- They use the `ReviewerDeclaration` schema: reviewer id (an opaque code), task id, the four + answers, and the time of the declaration. +- Nothing is filled in on the reviewer's behalf. + +**How a review's exposure is set (`review_exposure`):** + +| Declaration | Review exposure | +|---|---| +| missing | RU | +| any answer `unknown` | RU | +| familiarity, an external source or the repository `yes` on an R3 item | R4 | +| otherwise | the item's level | + +`model_output_seen` is reported separately and never folded into the level. + +## 6. Adjudication readiness + +`adjudication_readiness` requires all of the following: +- two or more distinct reviewers (`label_policy.MIN_REVIEWERS`); +- one decision each; +- the same evidence SHA-256 as the task; +- a declaration from each reviewer that names this task. + +A decision set is **confirmatory** only when every review's exposure is R1 or below. Missing +decisions are never replaced by a default. + +## 7. Dispositions of the frozen cohorts (aggregates) + +The frozen files are byte-identical before and after the audit (committed hashes verified). +They are not rewritten; dispositions are a separate local record. + +| Cohort | Items | Combined level | Disposition | +|---|---|---|---| +| A (`review-sample/1`) | 60 | 60 × R3 (external: the public dataset labels each item's payoff victim) | not eligible for confirmatory blinded evaluation; exploratory or sensitivity only | +| B (`hard-negative-candidates/1`) | 35 | 4 × R3, 30 × R2, 1 × R1 | 4 not eligible; 30 sensitivity stratum with qualified blinding; 1 eligible for a qualified blinded review | + +- **No replacement cohort is drawn in this phase.** The archive pools carry the public + dataset's labels (R2 or R3 externally). +- **The recorded incident windows are public context (R2).** Only the unlabelled background + windows and new recordings could supply R0 or R1 items; the second option needs a separately + approved RPC budget. +- **A new cohort is therefore reported as blocked by data.** diff --git a/src/cryptoguard/ml/review_blinding.py b/src/cryptoguard/ml/review_blinding.py new file mode 100644 index 0000000..3b3eb2f --- /dev/null +++ b/src/cryptoguard/ml/review_blinding.py @@ -0,0 +1,679 @@ +"""Phase 12.9 reviewer-blinding integrity (protocol 12.9, Part I). Offline only. + +Two jobs: + +1. **Exposure audit** of the frozen review cohorts. Each item's identifiers come from the + blinded reviewer sheet only (the unblinding key is hashed for integrity, never parsed). + They are searched in the public repository at HEAD, in every line ever added to its + history, and as truncated prefixes. Each match gets the role of the artifact it is in + (outcome, context or neutral), which sets a deterministic level R0/R1/R2/R3/RU. The + item's documented provenance gives a separate external level. R4 (confirmed reviewer + exposure) is never inferred from R3: it comes only from a reviewer's own declaration. + +2. **Prospective review workflow**: task payloads built from a whitelist and checked for + outcome-bearing keys or words, reviewer declarations that are never defaulted, and an + adjudication-readiness check. + +Per-item mappings are written to the git-ignored research directory only. The public +report carries aggregates. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import subprocess +from collections import Counter +from collections.abc import Iterable, Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, field_validator + +from cryptoguard.ml import review_sample as rs +from cryptoguard.ml.label_policy import MIN_REVIEWERS + +STUDY_VERSION = "review-blinding/1" +TASK_VERSION = "review-task/1" +Level = Literal["R0", "RU", "R1", "R2", "R3", "R4"] +ORDER: dict[str, int] = {"R0": 0, "RU": 1, "R1": 2, "R2": 3, "R3": 4, "R4": 5} +ROLE_LEVEL = {"neutral": "R1", "context": "R2", "outcome": "R3"} +DISPOSITION = { + "R3": "not eligible for confirmatory blinded evaluation (exploratory or sensitivity only)", + "R2": "requires qualified blinding; sensitivity stratum", + "R1": "eligible for an explicitly qualified blinded review", + "R0": "eligible for an explicitly qualified blinded review", + "RU": "requires exposure clarification", +} +FREEZE_DATE = "2026-11-02" # both cohorts (Phase 11.4 and c68d3a4) +PUBLIC_NOT_FOUND = "2026-11-09" # anonymous API: Not Found +PUBLIC_SEEN = "2026-11-10" # anonymous API: visibility public +COHORT_DIRS = { + rs.SAMPLE_VERSION: Path("review_sample"), + "hard-negative-candidates/1": Path("hard_negative/cohort_v1"), +} +EXTERNAL_LEVEL = { + "archive_payoff_linked": "R3", # the public dataset labels the event's payoff victim + "archive_uncategorized": "R2", # public dataset, poisoning-attempt context + "recorded_window": "R0", # raw chain data alone carries no label + "unknown": "RU", +} + +_HEX = re.compile(r"0x[0-9a-fA-F]{64}|0x[0-9a-fA-F]{40}") +_PARTIAL = re.compile(r"0x([0-9a-fA-F]{8,39})\s*(?:…|\.\.\.)") +_LINE_KEY = re.compile(r'"([A-Za-z_]+)"\s*:\s*"[^"]*0x') +_INCIDENT_DIR = r"(?:src/cryptoguard/replay/cases|docs/ml/incident-benchmark/cases)/[^/]+" +REGISTRY_OUTCOME_KEYS = frozenset({"lookalike", "harm_tx", "planting_tx"}) +MANIFEST_OUTCOME_PATHS = frozenset({("harm", "recipient"), ("harm", "transaction_hash")}) +MANIFEST_OUTCOME_LINE_KEYS = frozenset({"recipient", "transaction_hash"}) # conservative + + +# --- artifact roles -------------------------------------------------------------------------- + + +def artifact_kind(path: str) -> str: + p = path.replace("\\", "/") + if re.fullmatch(_INCIDENT_DIR + r"/manifest\.json", p): + return "incident_manifest" + if re.fullmatch(r"docs/ml/incident-benchmark/[^/]*candidates[^/]*\.json", p): + return "incident_registry" + if re.fullmatch(_INCIDENT_DIR + r"/fixture\.json", p): + return "incident_fixture" + if p.startswith("src/cryptoguard/replay/campaign_cases/"): + return "campaign_expansion" + return "neutral" + + +DEFAULT_ROLE = { + "incident_manifest": "context", + "incident_registry": "context", + "incident_fixture": "context", + "campaign_expansion": "context", + "neutral": "neutral", +} + + +def _stronger(a: str | None, b: str) -> str: + rank = {"neutral": 0, "context": 1, "outcome": 2} + return b if a is None or rank[b] > rank[a] else a + + +def _walk(obj: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], str]]: + if isinstance(obj, dict): + for k, v in obj.items(): + yield from _walk(v, (*path, str(k))) + elif isinstance(obj, list): + for v in obj: + yield from _walk(v, path) + elif isinstance(obj, str): + yield path, obj + + +def json_roles(kind: str, obj: Any) -> dict[str, str]: + """Identifier (lower case) -> its strongest role in one parsed artifact.""" + out: dict[str, str] = {} + for path, text in _walk(obj): + for m in _HEX.findall(text): + role = DEFAULT_ROLE[kind] + if kind == "incident_manifest" and path[-2:] in MANIFEST_OUTCOME_PATHS: + role = "outcome" + if ( + kind == "incident_registry" + and "identifiers" in path + and path[-1:] + and (path[-1] in REGISTRY_OUTCOME_KEYS or path[-1].startswith("etherscan_filter")) + ): + role = "outcome" + out[m.lower()] = _stronger(out.get(m.lower()), role) + return out + + +def line_role(kind: str, line: str) -> str: + """Role of an identifier on one added history line (no parse of the whole file).""" + keys = set(_LINE_KEY.findall(line)) + if kind == "incident_registry" and ( + keys & REGISTRY_OUTCOME_KEYS or any(k.startswith("etherscan_filter") for k in keys) + ): + return "outcome" + if kind == "incident_manifest" and keys & MANIFEST_OUTCOME_LINE_KEYS: + return "outcome" + return DEFAULT_ROLE[kind] + + +# --- git channels ---------------------------------------------------------------------------- + + +def _git(root: Path, *args: str) -> str | None: + try: + done = subprocess.run( # noqa: S603 + ["git", "-C", str(root), *args], # noqa: S607 + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=True, + timeout=300, + ) + except (OSError, subprocess.SubprocessError): + return None + return done.stdout + + +@dataclass +class Occurrence: + path: str + kind: str + role: str + channel: str # head | history + first_date: str | None = None + + +def scan_head(root: Path, idents: frozenset[str]) -> dict[str, list[Occurrence]]: + out: dict[str, list[Occurrence]] = {} + listing = _git(root, "ls-files") or "" + for rel in (f for f in listing.splitlines() if f): + try: + text = (root / rel).read_text(encoding="utf-8", errors="replace") + except OSError: + continue + hit = {m.lower() for m in _HEX.findall(text)} & idents + if not hit: + continue + kind = artifact_kind(rel) + roles: dict[str, str] = {} + if kind != "neutral" and rel.endswith(".json"): + try: + roles = json_roles(kind, json.loads(text)) + except ValueError: + roles = {} + for i in hit: + out.setdefault(i, []).append( + Occurrence(rel, kind, roles.get(i, DEFAULT_ROLE[kind]), "head") + ) + return out + + +def scan_history(root: Path, idents: frozenset[str]) -> dict[str, dict[str, Occurrence]]: + """Identifier -> file -> first added occurrence (date and role) across all commits.""" + patch = _git( + root, + "log", + "--all", + "--reverse", + "-p", + "--unified=0", + "--no-color", + "--no-ext-diff", + "--date=short", + "--format=%x1ecommit %ad", + ) + out: dict[str, dict[str, Occurrence]] = {} + date: str | None = None + current: str | None = None + # split on newlines only: str.splitlines() also breaks at the \x1e record separator + for line in (patch or "").split("\n"): + line = line.rstrip("\r") + if line.startswith("\x1ecommit "): + date = line.split(" ", 1)[1].strip() + elif line.startswith("+++ "): + current = line[6:] if line.startswith("+++ b/") else None + elif line.startswith("+") and current is not None: + hit = {m.lower() for m in _HEX.findall(line)} & idents + if not hit: + continue + kind = artifact_kind(current) + role = line_role(kind, line) + for i in hit: + prior = out.setdefault(i, {}).get(current) + if prior is None: + out[i][current] = Occurrence(current, kind, role, "history", date) + else: + prior.role = _stronger(prior.role, role) + return out + + +def scan_partial(root: Path, idents: frozenset[str]) -> dict[str, list[str]]: + """Identifier -> tracked files holding a truncated prefix it extends (ambiguous).""" + out: dict[str, list[str]] = {} + listing = _git(root, "ls-files") or "" + for rel in (f for f in listing.splitlines() if f): + try: + text = (root / rel).read_text(encoding="utf-8", errors="replace") + except OSError: + continue + prefixes = {"0x" + p.lower() for p in _PARTIAL.findall(text)} + for pre in prefixes: + for i in idents: + if i.startswith(pre) and i != pre: + out.setdefault(i, []).append(rel) + return out + + +# --- items and levels ------------------------------------------------------------------------ + + +@dataclass +class Item: + cohort: str + item: int + provenance: str + core: frozenset[str] + context: frozenset[str] + sheet_sha256: str + + +def provenance(row: Mapping[str, Any]) -> str: + """The item's documented provenance class, from the blinded sheet's own fields.""" + note = str(row.get("coverage_note", "")) + if row.get("schema_version") == rs.SHEET_SCHEMA and not note: + return "archive_payoff_linked" # every review-sample/1 item is payoff-linked + if note.startswith("No wallet history is included"): + return "archive_uncategorized" + if note.startswith("The wallet's transfers in the recorded window"): + return "recorded_window" + return "unknown" + + +def load_items(poisoning_dir: Path) -> list[Item]: + items: list[Item] = [] + for cohort, rel in COHORT_DIRS.items(): + sheet = poisoning_dir / rel / rs.SHEET + sha = rs.file_sha256(sheet) + for r in rs.read_sheet(sheet): + core = frozenset( + str(r[k]).lower() for k in ("wallet", "address_under_review", "transaction") + ) + ctx = frozenset(str(c["counterparty"]).lower() for c in r.get("context", [])) + items.append(Item(cohort, int(r["item"]), provenance(r), core, ctx - core, sha)) + return items + + +def verify_cohorts(poisoning_dir: Path) -> dict[str, dict[str, str]]: + """Committed-hash check of every frozen cohort (key bytes hashed, never parsed).""" + out: dict[str, dict[str, str]] = {} + for cohort, rel in COHORT_DIRS.items(): + d = poisoning_dir / rel + rs.verify_frozen(d, cohort=cohort, with_key=True) + out[cohort] = {n: rs.file_sha256(d / n) for n in (rs.MANIFEST, rs.SHEET, rs.KEY)} + return out + + +def max_level(levels: Iterable[str]) -> str: + return max(levels, key=lambda x: ORDER[x], default="R0") + + +@dataclass +class Assessment: + cohort: str + item: int + provenance: str + repo_level: str + repo_level_core_only: str + repo_level_campaign_as_outcome: str + external_level: str + combined: str + disposition: str + occurrences: list[dict[str, Any]] = field(default_factory=list) + partial_files: int = 0 + identifiers_matched: dict[str, int] = field(default_factory=dict) + + +def _level(occs: Sequence[Occurrence], partial: bool, *, campaign_outcome: bool = False) -> str: + if occs: + roles = [ + "outcome" if campaign_outcome and o.kind == "campaign_expansion" else o.role + for o in occs + ] + return max_level(ROLE_LEVEL[r] for r in roles) + return "RU" if partial else "R0" + + +def assess( + item: Item, + head: Mapping[str, Sequence[Occurrence]], + history: Mapping[str, Mapping[str, Occurrence]], + partial: Mapping[str, Sequence[str]], +) -> Assessment: + def occurrences(idents: Iterable[str]) -> list[Occurrence]: + occs: list[Occurrence] = [] + for i in idents: + at_head = {o.path: o for o in head.get(i, ())} + hist = history.get(i, {}) + for path, o in at_head.items(): + first = hist[path].first_date if path in hist else None + occs.append(Occurrence(o.path, o.kind, o.role, "head", first)) + occs += [o for p, o in hist.items() if p not in at_head] + return occs + + every = item.core | item.context + occs = occurrences(every) + core_occs = occurrences(item.core) + has_partial = any(partial.get(i) for i in every) + repo = _level(occs, has_partial) + external = EXTERNAL_LEVEL[item.provenance] + combined = max_level((repo, external)) + matched = { + "core": sum(1 for i in item.core if head.get(i) or history.get(i)), + "context": sum(1 for i in item.context if head.get(i) or history.get(i)), + } + return Assessment( + cohort=item.cohort, + item=item.item, + provenance=item.provenance, + repo_level=repo, + repo_level_core_only=_level(core_occs, any(partial.get(i) for i in item.core)), + repo_level_campaign_as_outcome=_level(occs, has_partial, campaign_outcome=True), + external_level=external, + combined=combined, + disposition=DISPOSITION[combined], + occurrences=[ + { + "path": o.path, + "kind": o.kind, + "role": o.role, + "channel": o.channel, + "first_date": o.first_date, + } + for o in sorted(occs, key=lambda o: (o.path, o.channel)) + ], + partial_files=len({f for i in every for f in partial.get(i, ())}), + identifiers_matched=matched, + ) + + +def core_overlap_12_8( + head: Mapping[str, Sequence[Occurrence]], items: Sequence[Item] +) -> dict[str, int]: + """The Phase 12.8 measure: per tracked file, unique core identifiers; summed.""" + core = {i for it in items for i in it.core} + per_file: Counter[str] = Counter() + for i in core: + for o in head.get(i, ()): + per_file[o.path] += 1 + return {"files": len(per_file), "identifiers": sum(per_file.values())} + + +def summarize(assessments: Sequence[Assessment]) -> dict[str, Any]: + out: dict[str, Any] = {} + for cohort in COHORT_DIRS: + rows = [a for a in assessments if a.cohort == cohort] + files = {o["path"] for a in rows for o in a.occurrences} + dates = [o["first_date"] for a in rows for o in a.occurrences if o["first_date"]] + out[cohort] = { + "items": len(rows), + "provenance": dict(Counter(a.provenance for a in rows)), + "repo_level": dict(Counter(a.repo_level for a in rows)), + "repo_level_core_identifiers_only": dict(Counter(a.repo_level_core_only for a in rows)), + "repo_level_if_campaign_expansion_were_outcome": dict( + Counter(a.repo_level_campaign_as_outcome for a in rows) + ), + "external_level": dict(Counter(a.external_level for a in rows)), + "combined_level": dict(Counter(a.combined for a in rows)), + "disposition": dict(Counter(a.disposition for a in rows)), + "items_with_core_match": sum(a.identifiers_matched["core"] > 0 for a in rows), + "items_with_context_only_match": sum( + a.identifiers_matched["core"] == 0 and a.identifiers_matched["context"] > 0 + for a in rows + ), + "items_with_history_only_match": sum( + bool(a.occurrences) and all(o["channel"] == "history" for o in a.occurrences) + for a in rows + ), + "items_with_partial_match": sum(a.partial_files > 0 for a in rows), + "overlapping_files": len(files), + "overlapping_file_kinds": dict(Counter(artifact_kind(f) for f in files)), + "first_added": { + "earliest": min(dates, default=None), + "latest": max(dates, default=None), + "before_freeze": sum(d < FREEZE_DATE for d in dates), + "on_or_after_freeze": sum(d >= FREEZE_DATE for d in dates), + }, + "confirmatory_eligible_items": sum(ORDER[a.combined] <= ORDER["R1"] for a in rows), + } + return out + + +# --- prospective review workflow ------------------------------------------------------------- + +Answer = Literal["yes", "no", "unknown"] +PAYLOAD_FIELDS = ( + "item", + "chain_id", + "wallet", + "address_under_review", + "transaction", + "block", + "context", + "coverage_note", +) +CONTEXT_FIELDS = ("block", "counterparty", "direction", "value") +ALLOWED_KEYS = frozenset(PAYLOAD_FIELDS) | frozenset(CONTEXT_FIELDS) # values still checked +FORBIDDEN_KEY = re.compile( + r"(?i)label|status|verdict|outcome|payoff|attack|attribut|score|rank|predict|model|" + r"decision|review|subtype|source|conclu|cohort|stratum|purpose|victim|lookalike|imitat|" + r"intended|harm|key|exposure|description|warning" +) +FORBIDDEN_TEXT = re.compile( + r"(?i)poison|scam|attack|victim|lookalike|look-alike|payoff|malicious|phish|stolen|theft|" + r"exploit|drain|confirmed|verified|legitimate|benign|hard.?negative|positive|negative|" + r"suspicious|fraud" +) +GUIDANCE_LEAKS = re.compile( + r"(?i)payoff|confirmed (?:victim|attack|poison)|known (?:victim|attack|incident)|" + r"most (?:of these|items|cases)|majority|expected (?:answer|label|result)|ground truth|" + r"answer key|unblind|cohort|hard.?negative|\bpositives?\b|\bnegatives?\b|source label|" + r"dataset label|was paid|lost funds|later lost|the model (?:flag|rank|score)" +) + + +class PayloadLeakError(ValueError): + """A review payload would carry outcome-bearing information.""" + + +def assert_payload_clean(payload: Any, where: str = "payload") -> None: + """Raise if a key or a text value could carry a label, a verdict or an attribution. + The message names the location only, never the value.""" + if isinstance(payload, dict): + for k, v in payload.items(): + if str(k) not in ALLOWED_KEYS and FORBIDDEN_KEY.search(str(k)): + raise PayloadLeakError(f"forbidden key at {where}.{k}") + assert_payload_clean(v, f"{where}.{k}") + elif isinstance(payload, list): + for n, v in enumerate(payload): + assert_payload_clean(v, f"{where}[{n}]") + elif isinstance(payload, str) and FORBIDDEN_TEXT.search(payload): + raise PayloadLeakError(f"outcome-bearing wording at {where}") + + +def task_payload(row: Mapping[str, Any]) -> dict[str, Any]: + """The reviewer-visible payload: whitelisted sheet fields only.""" + out: dict[str, Any] = {} + for k in PAYLOAD_FIELDS: + if k not in row: + continue + if k == "context": + out[k] = [{f: c[f] for f in CONTEXT_FIELDS if f in c} for c in row[k]] + else: + out[k] = row[k] + assert_payload_clean(out) + return out + + +class ReviewerDeclaration(BaseModel): + """Given by the reviewer, per task. Nothing here is ever filled in for them.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + reviewer_id: str + task_id: str + prior_familiarity: Answer + external_sources_consulted: Answer + repository_consulted: Answer + model_output_seen: Answer + declared_at: str + + @field_validator("reviewer_id") + @classmethod + def _rid(cls, v: str) -> str: + from cryptoguard.ml.annotation import REVIEWER_ID + + if not REVIEWER_ID.match(v): + raise ValueError("reviewer id must be an opaque code") + return v + + +class ReviewTask(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + schema_version: str = TASK_VERSION + task_id: str + item_version: str # sheet SHA-256 + evidence_version: str + evidence_sha256: str + exposure_level: Level + payload: dict[str, Any] + + +def task_id(sheet_sha256: str, item: int) -> str: + """Opaque: names neither the cohort nor its purpose.""" + return hashlib.sha256(f"cg-12.9-task|{sheet_sha256}|{item}".encode()).hexdigest()[:20] + + +def build_task( + row: Mapping[str, Any], + *, + sheet_sha256: str, + evidence_version: str, + evidence_sha256: str, + exposure_level: str, +) -> ReviewTask: + if exposure_level not in ORDER or exposure_level == "R4": + raise ValueError("a task carries a computed item level; R4 comes only from a reviewer") + return ReviewTask( + task_id=task_id(sheet_sha256, int(row["item"])), + item_version=sheet_sha256, + evidence_version=evidence_version, + evidence_sha256=evidence_sha256, + exposure_level=exposure_level, + payload=task_payload(row), + ) + + +def review_exposure(item_level: str, declaration: ReviewerDeclaration | None) -> dict[str, Any]: + """The exposure of one review. A missing declaration is never defaulted (RU). R4 only + when the reviewer declares familiarity or a consultation on an outcome-exposed item.""" + if declaration is None: + return {"level": "RU", "reason": "no declaration", "model_output_seen": None} + answers = ( + declaration.prior_familiarity, + declaration.external_sources_consulted, + declaration.repository_consulted, + ) + model_seen = declaration.model_output_seen + if item_level == "R3" and "yes" in answers: + return {"level": "R4", "reason": "declared on an R3 item", "model_output_seen": model_seen} + if "unknown" in answers: + return {"level": "RU", "reason": "declaration incomplete", "model_output_seen": model_seen} + return {"level": item_level, "reason": "declared", "model_output_seen": model_seen} + + +@dataclass(frozen=True) +class SubmittedReview: + reviewer_id: str + decision: str + evidence_sha256: str + declaration: ReviewerDeclaration | None + + +def adjudication_readiness(task: ReviewTask, reviews: Sequence[SubmittedReview]) -> dict[str, Any]: + """Two independent decisions on the same evidence, each with a declaration.""" + problems: list[str] = [] + reviewers = {r.reviewer_id for r in reviews} + if len(reviewers) < MIN_REVIEWERS: + problems.append(f"fewer than {MIN_REVIEWERS} independent reviewers") + if len(reviewers) != len(reviews): + problems.append("a reviewer submitted more than once") + if any(r.evidence_sha256 != task.evidence_sha256 for r in reviews): + problems.append("a decision was made on different evidence") + levels = [review_exposure(task.exposure_level, r.declaration)["level"] for r in reviews] + if any(r.declaration is None for r in reviews): + problems.append("a declaration is missing") + elif any(r.declaration.task_id != task.task_id for r in reviews if r.declaration): + problems.append("a declaration names another task") + return { + "ready": not problems, + "problems": problems, + "review_levels": levels, + "confirmatory": not problems and all(ORDER[x] <= ORDER["R1"] for x in levels), + } + + +def guidance_findings(text: str) -> dict[str, int]: + """Counts of prevalence or source-verdict hints in reviewer guidance (no text).""" + return dict(Counter(m.group(0).lower() for m in GUIDANCE_LEAKS.finditer(text))) + + +# --- study ---------------------------------------------------------------------------------- + + +def main(root: Path, poisoning_dir: Path, out: Path, *, history: bool = True) -> dict[str, Any]: + before = verify_cohorts(poisoning_dir) + items = load_items(poisoning_dir) + idents = frozenset(i for it in items for i in it.core | it.context) + head = scan_head(root, idents) + hist = scan_history(root, idents) if history else {} + partial = scan_partial(root, idents) + rows = [assess(it, head, hist, partial) for it in items] + after = verify_cohorts(poisoning_dir) + out.mkdir(parents=True, exist_ok=True) + with (out / "item_exposure.local.jsonl").open("w", encoding="utf-8") as fh: + for a in rows: + fh.write(json.dumps(a.__dict__, sort_keys=True) + "\n") + kits = sorted((poisoning_dir / "outbox").glob("reviewer-*/*.md")) + guidance = { + "files": len(kits), + "files_with_findings": sum( + bool(guidance_findings(p.read_text(encoding="utf-8", errors="replace"))) for p in kits + ), + "findings": dict( + sum( + ( + Counter(guidance_findings(p.read_text(encoding="utf-8", errors="replace"))) + for p in kits + ), + Counter(), + ) + ), + } + sent = [] + for rec in sorted((poisoning_dir / "outbox").glob("reviewer-*.record.json")): + sent.append(json.loads(rec.read_text(encoding="utf-8")).get("sent") is not None) + return { + "study": STUDY_VERSION, + "protocol": "protocol-12.9", + "rpc_requests": 0, + "cohort_integrity": { + "unchanged": before == after, + "verified_against_committed_hashes": sorted(before), + }, + "identifiers_searched": len(idents), + "core_overlap_12_8_definition": core_overlap_12_8(head, items), + "history_scanned": history, + "cohorts": summarize(rows), + "reviewer_process": { + "kits_prepared": len(sent), + "kits_sent": sum(sent), + "submission_files_found": sum( + 1 for p in poisoning_dir.rglob("*submission*.json") if p.is_file() + ), + "declarations": 0, # the declaration form is introduced in this phase + }, + "existing_guidance_check": guidance, + "timing": { + "freeze": FREEZE_DATE, + "public_not_found": PUBLIC_NOT_FOUND, + "public_seen": PUBLIC_SEEN, + }, + } From 4fb217cbd9ec64cb09944594ffa93a9ef58dde24 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 11 Nov 2026 15:26:19 +0300 Subject: [PATCH 90/92] feat(ml): incident acquisition, pilot selection, collection gate and T5g (no RPC) Protocol 12.9 Parts II-III. `ml/incident_acquisition.py`: - Lead schema: verbatim identifiers must be full, truncated ones keep their ellipsis, and a role is recorded only when stated. - Identifiers live in a local vault. The public registry carries salted SHA-256 commitments and refuses any identifier, full or truncated. - Development-overlap search over fixtures, registries, campaign expansion, archive extracts (indexed sqlite lookups), review packets, cohort sheets, kits and research outputs; unblinding keys are never opened. - Union-find clusters; first-match eligibility rules; hash-ordered pilot selection with one lead per cluster, capped at 10. - Anchor and record jobs, with only CollectorRequest fields reaching the collector. - Budget caps (2,505 per window). - ApprovalRecord / check_approval bound to the manifest hash and caps; general encouragement is refused. - Pilot stop rules S1-S6. No network import and no runner. benchmark_eval: - T5g reference-group exposure, reported apart from T4; - the bucket map is kept outside the prediction digest, so 12.8 ledgers stay valid. CLI: `cryptoguard ml review-blinding` and `cryptoguard ml incident-acquisition [--write-public]`. Registry docs/ml/incident-benchmark/acquisition-12.9.json: 17 leads, 0 ready for recording, 5 needing identifiers, 12 rejected. Co-Authored-By: Claude Opus 5.5 --- .../incident-benchmark/acquisition-12.9.json | 600 ++++++++++++ src/cryptoguard/ml/benchmark_eval.py | 37 +- src/cryptoguard/ml/cli.py | 49 + src/cryptoguard/ml/incident_acquisition.py | 873 ++++++++++++++++++ 4 files changed, 1558 insertions(+), 1 deletion(-) create mode 100644 docs/ml/incident-benchmark/acquisition-12.9.json create mode 100644 src/cryptoguard/ml/incident_acquisition.py diff --git a/docs/ml/incident-benchmark/acquisition-12.9.json b/docs/ml/incident-benchmark/acquisition-12.9.json new file mode 100644 index 0000000..5d81dcb --- /dev/null +++ b/docs/ml/incident-benchmark/acquisition-12.9.json @@ -0,0 +1,600 @@ +{ + "schema_version": "incident-acquisition-registry/1", + "protocol": "protocol-12.9", + "discovery": { + "date": "2026-11-11", + "searches": 16, + "page_reads": 17, + "budget": { + "searches": 20, + "page_reads": 30 + }, + "explorer_or_rpc_requests": 0 + }, + "commitment": "sha256(salt|role|lower-case identifier); one secret salt per lead, kept locally and disclosed only at unblinding", + "development_duplicates": [ + { + "case": "usdt-50m-poisoning-2025-12-19", + "sources_seen": 3 + }, + { + "case": "eth-4556-poisoning-2026-01-30", + "sources_seen": 3 + }, + { + "case": "usdt-counterfeit-39890-2026-08-09", + "sources_seen": 1 + }, + { + "case": "wbtc-1155-poisoning-2024-05-03", + "sources_seen": 1 + }, + { + "case": "scamsniffer-763k-2025-02-20", + "sources_seen": 1 + } + ], + "leads": [ + { + "lead_id": "aethusdc-24m-2026-03", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "blockchain.news (flash citing PeckShieldAlert on X)", + "url": "https://blockchain.news/flashnews/peckshieldalert-reports-24m-crypto-theft-via-address-poisoning-attack", + "date": "2026-03", + "read": true + }, + { + "publisher": "CCN", + "url": "https://www.ccn.com/news/crypto/sillytuna-crypto-24m-poisoning-attack-how-it-happened/", + "date": "2026-03", + "read": false + }, + { + "publisher": "Coin-Turk", + "url": "https://en.coin-turk.com/hackers-drain-24-million-in-aethusdc-as-address-poisoning-strikes-defi-sector/", + "date": "2026-03", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-03-04/2026-03-05", + "amount": "about 23.6 million aEthUSDC", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "truncated", + "unassigned_address": "truncated", + "victim": "truncated" + }, + "commitments": {}, + "status": "NEEDS_IDENTIFIER_VERIFICATION", + "reasons": [ + "conflicting: event date: outlets give 4 March and 5 March 2026" + ], + "cluster": "aethusdc-24m-2026-03", + "conflicts": [ + "event date: outlets give 4 March and 5 March 2026" + ], + "campaign_notes": [] + }, + { + "lead_id": "amlbot-czech-50k-usdt", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "AMLBot blog (Honey Trap)", + "url": "https://blog.amlbot.com/honey-trap-how-address-poisoning-scammed-50k-and-how-it-was-recovered/", + "date": "2025-02-20", + "read": true + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2025", + "amount": "more than 50,000 USDT", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "amlbot-czech-50k-usdt", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "cyvers-1.2m-2025-03-aggregate", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "ForkLog (citing Cyvers)", + "url": "https://forklog.com/en/crypto-address-poisoning-nets-hackers-1-2-million-in-three-weeks/", + "date": "2025-03-19", + "read": true + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2025-03", + "amount": "more than 1.2 million USD across several victims", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "cyvers-1.2m-2025-03-aggregate", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "dea-usdt-55k-2023", + "origin": "registry:candidates.json", + "sources": [ + { + "publisher": "Cointelegraph / The Block (citing Forbes and an FBI search warrant)", + "url": "https://cointelegraph.com/news/dea-loses-tether-in-address-poisoning-scam", + "date": "2023-08-25", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2023", + "amount": "about 55,000 USDT", + "mechanism_claimed": "token_airdrop", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "dea-usdt-55k-2023", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "eth-636k-2025-08", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "Cointelegraph (search result only)", + "url": "", + "date": "2025-08", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2025-08", + "amount": "about 636,000-880,000 USD", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "eth-636k-2025-08", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "phantom-chat-wbtc-2026-02", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "Cointelegraph (search result only)", + "url": "https://cointelegraph.com/news/phantom-chat-address-poisoning-bitcoin-phishing", + "date": "2026-02", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-02", + "amount": "about 3.5 wBTC", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "phantom-chat-wbtc-2026-02", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "pink-drainer-10eth-2024-06-27", + "origin": "registry:stage2-candidates.json", + "sources": [ + { + "publisher": "ForkLog (citing MistTrack, X post of 2024-07-07)", + "url": "https://forklog.com/en/pink-drainer-hackers-fall-victim-to-address-poisoning-scam/", + "date": "2024-07-08", + "read": true + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2024-06-27", + "amount": "10 ETH", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "intended": "verbatim", + "lookalike": "truncated", + "victim": "verbatim" + }, + "commitments": { + "intended": "6838b47a6b4a299fb0c3312ade65184a64bc2f277079012b6cff1540020c2be5", + "victim": "9e20554c94d42ea9375934f3561fc175bdb2c828301b5702098b1484b2944138" + }, + "status": "NEEDS_IDENTIFIER_VERIFICATION", + "reasons": [ + "harm_tx absent" + ], + "cluster": "pink-drainer-10eth-2024-06-27", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-100k-2026-08", + "origin": "registry:candidates.json", + "sources": [ + { + "publisher": "crypto.news (citing a Cyvers alert on X)", + "url": "https://crypto.news/address-poisoning-attack-drains-100k-dollars-usdt/", + "date": "2026-08-11", + "read": true + }, + { + "publisher": "AMBCrypto (citing Lookonchain on X)", + "url": "https://ambcrypto.com/crypto-address-poisoning-costs-user-100k-usdt-how-the-trap-worked/", + "date": "2026-08-13", + "read": true + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-08", + "amount": "about 100,000 USDT", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "usdt-100k-2026-08", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-100k-2026-08-13", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "AMBCrypto (citing Lookonchain on X)", + "url": "https://ambcrypto.com/crypto-address-poisoning-costs-user-100k-usdt-how-the-trap-worked/", + "date": "2026-08-13", + "read": true + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-08", + "amount": "more than 100,000 USDT", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "usdt-100k-2026-08", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-509k-2026-01", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "news reports citing a Cyvers alert (search results only)", + "url": "", + "date": "2026-01-16", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-01", + "amount": "about 509,000-514,000 USDT", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "usdt-509k-2026-01", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-50k-2026-10", + "origin": "registry:candidates.json", + "sources": [ + { + "publisher": "crypto.news (citing a Scam Sniffer post on X)", + "url": "https://crypto.news/address-poisoning-user-loss-50000/", + "date": "2026-10-28", + "read": true + } + ], + "chain_stated": "ethereum", + "chain_name": null, + "event_date": "2026-10", + "amount": "about 50,000 USDT", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "usdt-50k-2026-10", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-600k-2026-02-17", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "CryptoRank feed (403); search results citing Cyvers", + "url": "https://cryptorank.io/news/feed/12343-victim-loses-600k-address-poisoning-attacks", + "date": "2026-02-17", + "read": false + } + ], + "chain_stated": "unstated", + "chain_name": null, + "event_date": "2026-02-17", + "amount": "about 600,000 USD", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "no identifier in any source read" + ], + "cluster": "usdt-600k-2026-02-17", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "usdt-700k-2025-04", + "origin": "registry:candidates.json", + "sources": [ + { + "publisher": "Decrypt (citing PeckShield, Cyvers, AMLBot, Bubblemaps)", + "url": "https://decrypt.co/316412/crypto-user-loses-700000-to-address-poisoning-scam-heres-what-happened", + "date": "2025-04-25", + "read": true + } + ], + "chain_stated": "ethereum", + "chain_name": null, + "event_date": "2025-04", + "amount": "699,990 USDT", + "mechanism_claimed": "zero_value_transfer", + "identifier_status": { + "harm_tx": "verbatim", + "intended": "absent", + "lookalike": "absent", + "planting_tx": "verbatim", + "test_transfer_tx": "verbatim", + "unassigned_address": "verbatim", + "victim": "absent" + }, + "commitments": { + "harm_tx": "29cc9c0e5ca7ad68122f44de767b2b5d249ec9de4aa42e7f0d9005cba255c94e", + "planting_tx": "6c2ccf4d83a896a137910bca74cc49b59892aaea19f4006f053fdd1d329fc19b", + "test_transfer_tx": "1ba65cfe36352e343cc255b9e3fc54ca1f86006cabf992a825ed386a0275a7b7", + "unassigned_address": "3e32195c1c8d0396ec6b77e80f28e42bc43078648e20fd0eb2f920530a5a2111" + }, + "status": "NEEDS_IDENTIFIER_VERIFICATION", + "reasons": [ + "victim absent" + ], + "cluster": "usdt-700k-2025-04", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "wbtc-2.38-2025-12-18", + "origin": "registry:candidates.json", + "sources": [ + { + "publisher": "Bitquery", + "url": "https://bitquery.io/investigations/address-poisoning-ethereum", + "date": "2026", + "read": true + } + ], + "chain_stated": "ethereum", + "chain_name": null, + "event_date": "2025-12-18", + "amount": "about 2.38 WBTC (page text: $205,900 of WBTC)", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "verbatim", + "lookalike": "truncated", + "post_harm_address_1": "truncated", + "post_harm_address_2": "truncated", + "post_harm_tx_1": "verbatim", + "post_harm_tx_2": "verbatim", + "victim": "absent" + }, + "commitments": { + "harm_tx": "94042e69cf1d1edc10027955b32cfe23bfdeb7658e8e56e5a51a683cecfcde3d", + "post_harm_tx_1": "4ec45162bcb73b70c8fbe011aae99af1a614498317ba7e76089f8cd7b8ebeee1", + "post_harm_tx_2": "22378de47a38f4608f734a72b19efae7108f9b3db3776e2999e5c24356409661" + }, + "status": "NEEDS_IDENTIFIER_VERIFICATION", + "reasons": [ + "victim absent" + ], + "cluster": "wbtc-2.38-2025-12-18", + "conflicts": [], + "campaign_notes": [ + "The page labels this theft 'Same crew' as another incident it documents (a case already used in development)." + ] + }, + { + "lead_id": "webacy-6.88m-usdt-2025-09", + "origin": "registry:stage2-candidates.json", + "sources": [ + { + "publisher": "Webacy (From the CTO's Desk, September 2025)", + "url": "https://www.webacy.com/blog/from-the-ctos-desk-september-2025", + "date": "page shows 2026-08-17; covers September 2025", + "read": true + } + ], + "chain_stated": "ethereum", + "chain_name": null, + "event_date": "2025-09-15/2025-09-18", + "amount": "about 6,880,000 USDT over two bursts", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike_1": "truncated", + "lookalike_2": "truncated", + "lookalike_3": "truncated", + "lookalike_4": "truncated", + "victim": "verbatim" + }, + "commitments": { + "victim": "46fa6f6872a25fe8a344f99b6f1627b4f4b6ba493e433b0f21330e59ae96460d" + }, + "status": "NEEDS_IDENTIFIER_VERIFICATION", + "reasons": [ + "harm_tx absent" + ], + "cluster": "webacy-6.88m-usdt-2025-09", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "webacy-base-25k-usdc-2026-04", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "Webacy blog (search result only)", + "url": "https://www.webacy.com/blog/25k-usdc-address-poisoning-attack-on-base-one-of-thousands-today", + "date": "2026-04", + "read": false + } + ], + "chain_stated": "other", + "chain_name": "Base", + "event_date": "2026-04", + "amount": "24,965 USDC", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "lookalike": "absent", + "victim": "absent" + }, + "commitments": {}, + "status": "REJECTED", + "reasons": [ + "not Ethereum mainnet (Base)" + ], + "cluster": "webacy-base-25k-usdc-2026-04", + "conflicts": [], + "campaign_notes": [] + }, + { + "lead_id": "webacy-polygon-792k-usdc-2025-09", + "origin": "new:phase12.9", + "sources": [ + { + "publisher": "Webacy (From the CTO's Desk, September 2025)", + "url": "https://www.webacy.com/blog/from-the-ctos-desk-september-2025", + "date": "page shows 2026-08-17", + "read": true + } + ], + "chain_stated": "other", + "chain_name": "Polygon", + "event_date": "2025-09-02", + "amount": "792,000 USDC (22 x 36,000)", + "mechanism_claimed": "unknown", + "identifier_status": { + "harm_tx": "absent", + "victim": "verbatim" + }, + "commitments": { + "victim": "4e3e6abdb7bd900573ccd8ee7bcf4b3b25dbf3c5562a0c7e0dd9f461e77b3cf2" + }, + "status": "REJECTED", + "reasons": [ + "not Ethereum mainnet (Polygon)" + ], + "cluster": "webacy-polygon-792k-usdc-2025-09", + "conflicts": [ + "the page lists the same address as victim and as scam recipient" + ], + "campaign_notes": [] + } + ] +} diff --git a/src/cryptoguard/ml/benchmark_eval.py b/src/cryptoguard/ml/benchmark_eval.py index 472c242..5cc1543 100644 --- a/src/cryptoguard/ml/benchmark_eval.py +++ b/src/cryptoguard/ml/benchmark_eval.py @@ -19,7 +19,7 @@ import hashlib import json from collections.abc import Mapping, Sequence -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any @@ -155,6 +155,10 @@ class Prediction: burden: dict[str, Any] fidelity: dict[str, Any] digest: str + # Best-reference bucket per candidate (protocol 12.9, T5g). A deterministic function of + # the observation and the cutoff, which the digest already binds; kept out of the digest + # so that Phase 12.8 ledgers stay valid. + buckets: dict[str, str] = field(default_factory=dict) def _digest(payload: Mapping[str, Any]) -> str: @@ -212,6 +216,7 @@ def predict(case: bc.BenchmarkCase, fixture: Any) -> Prediction: burden=burden, fidelity=fidelity, digest=_digest(body), + buckets={g.lookalike: ce.bucket_of(g) for g in groups}, ) @@ -313,6 +318,24 @@ def mechanism_identified(label: str, mechanisms: Sequence[str], kinds: Sequence[ raise ValueError(label) +def reference_group_exposure( + prediction: Prediction, outcome: bc.Outcome +) -> dict[str, dict[str, bool]] | None: + """T5g (protocol 12.9): within K, is there a candidate whose best-reference bucket is the + intended recipient? Reported apart from address exposure (T4); not assessable (None) + without an intended recipient.""" + if not outcome.intended_recipient: + return None + intended = outcome.intended_recipient.lower() + return { + m: { + str(k): any(prediction.buckets.get(c, "").lower() == intended for c in order[:k]) + for k in K_GRID + } + for m, order in prediction.orders.items() + } + + def score( case: bc.BenchmarkCase, prediction: Prediction, @@ -365,6 +388,7 @@ def score( "T4_exposed": { m: {str(k): r is not None and r <= k for k in K_GRID} for m, r in ranks.items() }, + "T5g_reference_group_exposed": reference_group_exposure(prediction, outcome), } if generated and mechanism in bc.MECHANISM_REQUIREMENTS: out["T5_mechanism_identified"] = mechanism_identified( @@ -451,6 +475,17 @@ def aggregate(results: Sequence[Mapping[str, Any]]) -> dict[str, Any]: "value": round(sum(rr) / len(rr), 4) if rr else None, "denominator": len(rr), } + grouped = [r for r in mech_ok if r.get("T5g_reference_group_exposed") is not None] + out["reference_group_exposure"] = { + m: { + k: _ratio( + sum(r["T5g_reference_group_exposed"][m][str(k)] for r in grouped), len(grouped) + ) + for k in K_GRID + } + for m in ORDERS + } + out["reference_group_not_assessable"] = len(mech_ok) - len(grouped) labelled = [r for r in generated if r["T5_mechanism_identified"] is not None] out["mechanism_identification"] = _ratio( sum(r["T5_mechanism_identified"] for r in labelled), len(labelled) diff --git a/src/cryptoguard/ml/cli.py b/src/cryptoguard/ml/cli.py index f875090..51ca950 100644 --- a/src/cryptoguard/ml/cli.py +++ b/src/cryptoguard/ml/cli.py @@ -136,6 +136,22 @@ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None brd.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.8") brd.add_argument("--no-archive", action="store_true", help="skip the archive tie analysis") brd.add_argument("--no-history", action="store_true", help="skip the git-history scan") + rbl = ml.add_parser( + "review-blinding", + help="Phase 12.9 exposure audit of the frozen review cohorts (offline; aggregates)", + ) + rbl.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.9" / "blinding") + rbl.add_argument("--no-history", action="store_true", help="skip the git-history channel") + iac = ml.add_parser( + "incident-acquisition", + help="Phase 12.9 lead eligibility, pilot selection and collection manifest (no RPC)", + ) + iac.add_argument("--out", type=Path, default=ML_DIR / "research" / "phase12.9" / "acquisition") + iac.add_argument( + "--write-public", + action="store_true", + help="write the public registry (citations, statuses, salted commitments only)", + ) bpw = ml.add_parser( "benchmark-power", help="sample-size planning for a paired exposure comparison (assumptions are inputs)", @@ -271,6 +287,39 @@ def run(args: argparse.Namespace) -> int: brief = {k: result[k] for k in ("eligibility_summary", "resources")} print(json.dumps(brief, indent=1, default=str)) return 0 + if args.ml_command in ("review-blinding", "incident-acquisition"): + import json + import subprocess + + try: + git = subprocess.run( + ["git", "rev-parse", "HEAD"], # noqa: S607 + capture_output=True, + text=True, + check=True, + timeout=10, + ).stdout.strip() + except (OSError, subprocess.SubprocessError): + git = None + if args.ml_command == "review-blinding": + from cryptoguard.ml import review_blinding + + summary = review_blinding.main( + Path(), ML_DIR / "poisoning", args.out, history=not args.no_history + ) + else: + from cryptoguard.ml import incident_acquisition + + summary = incident_acquisition.main( + Path(), ML_DIR / "poisoning", args.out, write_public=args.write_public, git=git + ) + summary["git"] = git + args.out.mkdir(parents=True, exist_ok=True) + (args.out / "summary.json").write_text( + json.dumps(summary, indent=1, sort_keys=True, default=str) + "\n", encoding="utf-8" + ) + print(json.dumps(summary, indent=1, sort_keys=True, default=str)) + return 0 if args.ml_command == "benchmark-power": import json diff --git a/src/cryptoguard/ml/incident_acquisition.py b/src/cryptoguard/ml/incident_acquisition.py new file mode 100644 index 0000000..3e4a105 --- /dev/null +++ b/src/cryptoguard/ml/incident_acquisition.py @@ -0,0 +1,873 @@ +"""Phase 12.9 independent incident acquisition (protocol 12.9, Part II). Offline only. + +A *lead* is a publicly described incident with whatever identifiers its sources give. This +module checks those identifiers, finds overlaps with every development artifact, groups +related leads, assigns one eligibility status per lead (first matching rule wins), selects a +pilot, and prepares - but never runs - the collection jobs and their budget. + +Two safety properties hold by construction: + +* **No network.** Nothing here imports an HTTP, RPC or socket client. Collection jobs are + data; a recorder that could run them is not called, and no batch runner exists. +* **No identifier is published.** Lead identifiers live in a git-ignored local vault. The + public registry carries source citations, statuses and *salted* SHA-256 commitments, so it + neither repeats the identifiers nor lets anyone test a guessed address against it. + +Approval is a separate record (``ApprovalRecord``) bound to the manifest's hash and caps; +``check_approval`` refuses anything else, including general encouragement. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import secrets +import sqlite3 +from collections import Counter +from collections.abc import Iterable, Mapping, Sequence +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, model_validator + +from cryptoguard.ml import benchmark_contract as bc + +STUDY_VERSION = "incident-acquisition/1" +LEADS_VERSION = "incident-leads-local/1" +REGISTRY_VERSION = "incident-acquisition-registry/1" +MANIFEST_VERSION = "collection-manifest/1" +VAULT = Path("data/ml/research/phase12.9/leads.local.json") +SALTS = Path("data/ml/research/phase12.9/commitment-salts.local.json") +PUBLIC_REGISTRY = Path("docs/ml/incident-benchmark/acquisition-12.9.json") + +PILOT_SEED = "cg-12.9-pilot|" +PILOT_CAP = 10 +ANCHOR_CAP = 5 +RECORD_CAP = 2_500 +WINDOW_BLOCKS = 21_600 +# Measured on the recorded 21,600-block windows (Stage 1 and Stage 2a ledgers). +ESTIMATES = {"low": 475, "typical": 1_299, "high": 1_433} +ANCHOR_ESTIMATE = 1 +RETRY_RESERVE = 0.20 +ARCHIVE_LAST_DATE = "2024-06-30" + +READY = "READY_FOR_BLIND_RECORDING" +STATUSES = ( + "DEVELOPMENT_ONLY", + "REJECTED", + "NEEDS_IDENTIFIER_VERIFICATION", + "NEEDS_CAMPAIGN_REVIEW", + "UNSUPPORTED_MECHANISM", + "NOT_EVALUABLE", + READY, +) +UNSUPPORTED = frozenset({"internal_transfer", "erc1155", "zero_value_native"}) +REQUIRED_FOR_READY = ("victim", "harm_tx") + +_FULL = re.compile(r"^0x(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$") +_TRUNC = re.compile(r"(…|\.\.\.)") +_HEX_IN_TEXT = re.compile(r"0x[0-9a-fA-F]{8,}") +GENERIC_APPROVALS = frozenset( + {"continue", "ok", "okay", "yes", "go", "go ahead", "proceed", "approved", "do it", "sure"} +) + + +class AcquisitionError(ValueError): + """The lead vault or a lead is malformed.""" + + +class ApprovalError(PermissionError): + """No valid approval for the collection manifest.""" + + +# --- leads ---------------------------------------------------------------------------------- + + +class Identifier(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + status: Literal["verbatim", "truncated", "absent"] + value: str | None = None + where: Literal["text", "hyperlink"] | None = None + + @model_validator(mode="after") + def _consistent(self) -> Identifier: + if self.status == "absent": + if self.value is not None: + raise ValueError("an absent identifier has no value") + elif self.value is None: + raise ValueError(f"a {self.status} identifier needs its value as shown") + elif self.status == "verbatim" and not _FULL.match(self.value): + raise ValueError("a verbatim identifier must be a full address or hash") + elif self.status == "truncated" and ( + _FULL.match(self.value) or not _TRUNC.search(self.value) + ): + raise ValueError("a truncated identifier keeps its ellipsis and is never completed") + return self + + +class LeadSource(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + publisher: str + url: str + date: str + read: bool # False: seen only in search results, not read in full + + +class Lead(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + lead_id: str + origin: str + sources: tuple[LeadSource, ...] + chain_stated: Literal["ethereum", "other", "unstated"] + chain_name: str | None = None + event_date: str | None = None + amount: str | None = None + mechanism_claimed: str = "unknown" + harm_claimed: bool = True + identifiers: dict[str, Identifier] + conflicts: tuple[str, ...] = () + campaign_notes: tuple[str, ...] = () + cluster_hint: str | None = None + notes: tuple[str, ...] = () + + def verbatim(self) -> dict[str, str]: + return { + r: i.value.lower() + for r, i in self.identifiers.items() + if i.status == "verbatim" and i.value + } + + def statuses(self) -> dict[str, str]: + return {r: i.status for r, i in sorted(self.identifiers.items())} + + def has_identifier(self) -> bool: + return any(i.status != "absent" for i in self.identifiers.values()) + + +def load_vault(path: Path) -> tuple[list[Lead], dict[str, Any]]: + raw = json.loads(path.read_text(encoding="utf-8")) + if raw.get("schema_version") != LEADS_VERSION: + raise AcquisitionError(f"{path}: unexpected schema {raw.get('schema_version')!r}") + leads = [Lead.model_validate(x) for x in raw["leads"]] + ids = [x.lead_id for x in leads] + if len(set(ids)) != len(ids): + raise AcquisitionError("duplicate lead ids") + meta = {k: v for k, v in raw.items() if k != "leads"} + return leads, meta + + +def identifier_problems(lead: Lead) -> list[str]: + """Internal consistency: one value in two roles, or a role contradiction.""" + seen: dict[str, str] = {} + out: list[str] = [] + for role, value in sorted(lead.verbatim().items()): + if value in seen: + out.append(f"same identifier in roles {seen[value]} and {role}") + seen[value] = role + v = lead.verbatim() + if "victim" in v and v["victim"] in {v.get("lookalike"), v.get("intended")}: + out.append("victim equals a counterparty role") + return out + + +# --- commitments ---------------------------------------------------------------------------- + + +def load_salts(path: Path, leads: Sequence[Lead], *, create: bool = True) -> dict[str, str]: + """One secret 128-bit salt per lead, generated once and kept locally. A salted commitment + binds the recorded identifier without letting anyone test a guessed one.""" + salts: dict[str, str] = {} + if path.is_file(): + salts = json.loads(path.read_text(encoding="utf-8")) + missing = [x.lead_id for x in leads if x.lead_id not in salts] + if missing and create: + for lead_id in missing: + salts[lead_id] = secrets.token_hex(16) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(salts, indent=1, sort_keys=True) + "\n", encoding="utf-8") + elif missing: + raise AcquisitionError(f"no salt for {len(missing)} lead(s)") + return salts + + +def commitment(salt: str, role: str, value: str) -> str: + return hashlib.sha256(f"{salt}|{role}|{value.lower()}".encode()).hexdigest() + + +def commitments(lead: Lead, salt: str) -> dict[str, str]: + return {r: commitment(salt, r, v) for r, v in sorted(lead.verbatim().items())} + + +# --- development overlap --------------------------------------------------------------------- + +TRACKED_DEVELOPMENT = ( + "src/cryptoguard/replay/cases", + "src/cryptoguard/replay/background_cases", + "src/cryptoguard/replay/campaign_cases", + "docs/ml/incident-benchmark/cases", +) +REGISTRIES = ( + Path("docs/ml/incident-benchmark/candidates.json"), + Path("docs/ml/incident-benchmark/stage2-candidates.json"), +) +TEXT_SUFFIXES = (".json", ".jsonl", ".md", ".csv", ".txt") +SQLITE_COLUMNS = frozenset( + { + "sender", + "receiver", + "tx", + "intended", + "victim", + "lookalike", + "address", + "counterparty", + "wallet", + "transaction_hash", + "planting_tx", + "imitated", + } +) + + +def _is_key_file(path: Path) -> bool: + return "unblinding" in path.name or path.name.endswith(".zip") + + +def _scan_text_file(path: Path, needles: frozenset[str], chunk: int = 1 << 24) -> set[str]: + """Lower-cased substring search, streamed in chunks with an overlap, so a large file is + never held in memory.""" + found: set[str] = set() + tail = "" + width = max((len(n) for n in needles), default=0) + with path.open(encoding="utf-8", errors="replace") as fh: + while True: + block = fh.read(chunk) + if not block: + break + text = (tail + block).lower() + found |= {n for n in needles if n not in found and n in text} + tail = text[-width:] if width else "" + if len(found) == len(needles): + break + return found + + +def _scan_sqlite(path: Path, needles: frozenset[str]) -> set[str]: + """Exact matches in address- and hash-like columns, read only. The local databases store + lower-case hex (checked in Phase 12.9), so an indexed column is searched by its index.""" + found: set[str] = set() + variants = sorted(needles) + marks = ",".join("?" * len(variants)) + con = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True) + try: + tables = [r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")] + for t in tables: + cols = [r[1] for r in con.execute(f'PRAGMA table_info("{t}")')] + for c in cols: + if c.lower() not in SQLITE_COLUMNS: + continue + q = f'SELECT DISTINCT "{c}" FROM "{t}" WHERE "{c}" IN ({marks})' # noqa: S608 + found |= {str(r[0]).lower() for r in con.execute(q, variants)} + finally: + con.close() + return found + + +def development_registry_entries(root: Path) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """(development entries, lead entries) of the committed registries. An entry is + development when it has a recorded fixture or a case directory.""" + dev: list[dict[str, Any]] = [] + leads: list[dict[str, Any]] = [] + for reg in REGISTRIES: + path = root / reg + if not path.is_file(): + continue + for c in json.loads(path.read_text(encoding="utf-8"))["candidates"]: + recorded = ( + bool(c.get("fixture_case_id")) + or (root / "docs/ml/incident-benchmark/cases" / c["case_id"]).exists() + ) + (dev if recorded else leads).append(c) + return dev, leads + + +def development_sources(root: Path, poisoning_dir: Path) -> dict[str, list[Path]]: + """Every development artifact, by class (protocol 12.9 section 8, rule 1).""" + research = root / "data/ml/research" + out: dict[str, list[Path]] = { + "recorded_fixtures_and_manifests": [], + "campaign_expansion": [], + "archive_episodes": [], + "archive_rows": [], + "review_packets": [], + "frozen_cohort_sheets": [], + "reviewer_kits": [], + "local_research_outputs": [], + "archive_databases": [], + } + for base in TRACKED_DEVELOPMENT: + for p in sorted((root / base).rglob("*.json")): + key = ( + "campaign_expansion" + if "campaign_cases" in p.parts + else ("recorded_fixtures_and_manifests") + ) + out[key].append(p) + episodes = research / "phase12.5/episodes.jsonl" + if episodes.is_file(): + out["archive_episodes"].append(episodes) + for p in sorted(poisoning_dir.rglob("*")): + if not p.is_file() or _is_key_file(p): + continue + rel = p.relative_to(poisoning_dir).as_posix() + if p.suffix == ".sqlite": + out["archive_databases"].append(p) + elif p.suffix not in TEXT_SUFFIXES: + continue + elif p.name == "reviewer_sheet.jsonl" and not rel.startswith("outbox"): + out["frozen_cohort_sheets"].append(p) + elif rel.startswith("outbox"): + out["reviewer_kits"].append(p) + elif "review_packets" in p.name or "/evidence/" in f"/{rel}" or rel.startswith("review"): + out["review_packets"].append(p) + elif p.name.endswith("rows.jsonl"): + out["archive_rows"].append(p) + else: + out["local_research_outputs"].append(p) + for p in sorted(research.rglob("*")): + if ( + p.is_file() + and p.suffix in TEXT_SUFFIXES + and "phase12.9" not in p.parts + and p != episodes + and not _is_key_file(p) + ): + out["local_research_outputs"].append(p) + return out + + +def development_hits( + leads: Sequence[Lead], root: Path, poisoning_dir: Path +) -> tuple[dict[str, dict[str, list[str]]], dict[str, int]]: + """Per lead: role -> the development source classes containing that verbatim identifier. + Also returns how many files of each class were searched.""" + needles = frozenset(v for x in leads for v in x.verbatim().values()) + hits: dict[str, set[str]] = {n: set() for n in needles} + searched: dict[str, int] = {} + if needles: + for klass, paths in development_sources(root, poisoning_dir).items(): + searched[klass] = len(paths) + for p in paths: + try: + found = ( + _scan_sqlite(p, needles) + if p.suffix == ".sqlite" + else _scan_text_file(p, needles) + ) + except (OSError, sqlite3.Error): + continue + for n in found: + hits[n].add(klass) + dev_entries, _ = development_registry_entries(root) + dev_values = { + str(v).lower() + for c in dev_entries + for v in (c.get("identifiers") or {}).values() + if isinstance(v, str) + } + searched["development_registry_entries"] = len(dev_entries) + for n in needles & dev_values: + hits[n].add("development_registry_entries") + out = { + x.lead_id: {r: sorted(hits[v]) for r, v in sorted(x.verbatim().items()) if hits[v]} + for x in leads + } + return out, searched + + +# --- clusters and eligibility ---------------------------------------------------------------- + + +def clusters(leads: Sequence[Lead]) -> dict[str, str]: + """Lead id -> cluster id (the smallest lead id in its group). Leads join when they share + a verbatim identifier in any role or carry the same cluster hint.""" + parent = {x.lead_id: x.lead_id for x in leads} + + def find(a: str) -> str: + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a: str, b: str) -> None: + ra, rb = find(a), find(b) + if ra != rb: + parent[max(ra, rb)] = min(ra, rb) + + owner: dict[str, str] = {} + for x in leads: + keys = [f"id:{v}" for v in x.verbatim().values()] + if x.cluster_hint: + keys.append(f"hint:{x.cluster_hint}") + for k in keys: + if k in owner: + union(owner[k], x.lead_id) + else: + owner[k] = x.lead_id + return {x.lead_id: find(x.lead_id) for x in leads} + + +def shared_attacker_identifiers(leads: Sequence[Lead]) -> dict[str, list[str]]: + """Lead id -> other leads sharing a lookalike, post-harm or unassigned identifier.""" + by_value: dict[str, set[str]] = {} + for x in leads: + for role, v in x.verbatim().items(): + if role.startswith(("lookalike", "post_harm", "unassigned")): + by_value.setdefault(v, set()).add(x.lead_id) + out: dict[str, set[str]] = {} + for ids in by_value.values(): + for a in ids: + out.setdefault(a, set()).update(ids - {a}) + return {k: sorted(v) for k, v in out.items() if v} + + +def classify( + lead: Lead, + dev: Mapping[str, Sequence[str]], + *, + shared: Sequence[str] = (), + same_cluster: Iterable[str] = (), +) -> tuple[str, list[str]]: + """Protocol 12.9 section 8: the first matching rule wins. Returns (status, reasons); + reasons never contain an identifier.""" + if dev: + roles = ", ".join(sorted(dev)) + return "DEVELOPMENT_ONLY", [f"identifier ({roles}) found in a development artifact"] + if lead.chain_stated == "other": + return "REJECTED", [f"not Ethereum mainnet ({lead.chain_name or 'other chain'})"] + if not lead.has_identifier(): + return "REJECTED", ["no identifier in any source read"] + problems = identifier_problems(lead) + if lead.conflicts or problems: + return "NEEDS_IDENTIFIER_VERIFICATION", [ + *(f"conflicting: {c}" for c in lead.conflicts), + *problems, + ] + status = lead.statuses() + missing = [r for r in REQUIRED_FOR_READY if status.get(r, "absent") != "verbatim"] + if missing: + return "NEEDS_IDENTIFIER_VERIFICATION", [f"{r} {status.get(r, 'absent')}" for r in missing] + if lead.chain_stated != "ethereum": + return "NEEDS_IDENTIFIER_VERIFICATION", ["chain not stated by any source read"] + unclustered = sorted(set(shared) - set(same_cluster)) + if lead.campaign_notes or unclustered: + return "NEEDS_CAMPAIGN_REVIEW", [ + *lead.campaign_notes, + *(f"shares an attacker identifier with {o}" for o in unclustered), + ] + if lead.mechanism_claimed in UNSUPPORTED: + return "UNSUPPORTED_MECHANISM", [f"{lead.mechanism_claimed} is not observable"] + if not lead.harm_claimed: + return "NOT_EVALUABLE", ["no harmful transfer claimed"] + return READY, [] + + +def classify_all( + leads: Sequence[Lead], dev_hits: Mapping[str, Mapping[str, Sequence[str]]] +) -> dict[str, dict[str, Any]]: + cl = clusters(leads) + shared = shared_attacker_identifiers(leads) + out: dict[str, dict[str, Any]] = {} + for x in leads: + mates = [o for o, c in cl.items() if c == cl[x.lead_id] and o != x.lead_id] + status, reasons = classify( + x, dev_hits.get(x.lead_id, {}), shared=shared.get(x.lead_id, ()), same_cluster=mates + ) + out[x.lead_id] = {"status": status, "reasons": reasons, "cluster": cl[x.lead_id]} + return out + + +# --- pilot, jobs and budget ------------------------------------------------------------------ + + +def pilot_rank(lead_id: str) -> str: + return hashlib.sha256((PILOT_SEED + lead_id).encode()).hexdigest() + + +def select_pilot(classified: Mapping[str, Mapping[str, Any]], cap: int = PILOT_CAP) -> list[str]: + """Every READY lead, at most one per cluster, in hash order, capped. Detectability, loss + size and ease of recording are never inputs.""" + ready = sorted((x for x, v in classified.items() if v["status"] == READY), key=pilot_rank) + taken: set[str] = set() + out: list[str] = [] + for lead_id in ready: + c = classified[lead_id]["cluster"] + if c in taken: + continue + taken.add(c) + out.append(lead_id) + if len(out) == cap: + break + return out + + +class AnchorJob(BaseModel): + """One receipt read of the harmful transaction. Its output to the collector is the block + number only; the receipt goes to the outcome vault.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + job_id: str + lead_id: str + kind: Literal["anchor"] = "anchor" + chain_id: Literal[1] = 1 + transaction: str + expected_sender: str + max_requests: int = ANCHOR_CAP + + +class RecordJob(BaseModel): + """A Phase 12.8 collector request, completed from the anchor's block number.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + job_id: str + lead_id: str + kind: Literal["record"] = "record" + depends_on: str + chain_id: Literal[1] = 1 + wallet: str + window_blocks: int = WINDOW_BLOCKS + observation: Literal[2] = 2 + max_requests: int = RECORD_CAP + + +def collection_jobs(selected: Sequence[Lead]) -> list[AnchorJob | RecordJob]: + jobs: list[AnchorJob | RecordJob] = [] + for x in selected: + v = x.verbatim() + anchor = AnchorJob( + job_id=f"{x.lead_id}:anchor", + lead_id=x.lead_id, + transaction=v["harm_tx"], + expected_sender=v["victim"], + ) + jobs += [ + anchor, + RecordJob( + job_id=f"{x.lead_id}:record", + lead_id=x.lead_id, + depends_on=anchor.job_id, + wallet=v["victim"], + ), + ] + return jobs + + +def record_request(job: RecordJob, harm_block: int) -> bc.CollectorRequest: + """The collector request once the anchor has produced the harmful block H: the window + ends at H and no outcome field can be passed.""" + if harm_block <= job.window_blocks: + raise ValueError("implausible harmful block") + return bc.CollectorRequest( + chain_id=job.chain_id, + wallet=job.wallet, + from_block=harm_block - job.window_blocks, + to_block=harm_block, + observation=job.observation, + max_requests=job.max_requests, + ) + + +def budget(n_leads: int) -> dict[str, Any]: + """Hard caps and planning estimates for ``n_leads`` selected leads.""" + per_window = ANCHOR_CAP + RECORD_CAP + est = { + k: { + "requests": n_leads * (ANCHOR_ESTIMATE + v), + "with_retry_reserve": round(n_leads * (ANCHOR_ESTIMATE + v) * (1 + RETRY_RESERVE)), + } + for k, v in ESTIMATES.items() + } + return { + "leads": n_leads, + "jobs": 2 * n_leads, + "anchor_cap": ANCHOR_CAP, + "record_cap": RECORD_CAP, + "per_window_cap": per_window, + "total_cap": n_leads * per_window, + "estimates": est, + "basis": "measured 21,600-block observation/1 and /2 recordings (475 / 1,299 / 1,433)", + "wallet_activity": "unknown without RPC", + } + + +def manifest(selected: Sequence[Lead], git: str | None) -> dict[str, Any]: + jobs = collection_jobs(selected) + b = budget(len(selected)) + return { + "schema_version": MANIFEST_VERSION, + "protocol": "protocol-12.9", + "code_revision": git, + "status": "planning only: not approved, not executed", + "jobs": [j.model_dump() for j in jobs], + "per_window_cap": b["per_window_cap"], + "total_cap": b["total_cap"], + "budget": b, + } + + +def manifest_bytes(m: Mapping[str, Any]) -> bytes: + return json.dumps(m, sort_keys=True, separators=(",", ":")).encode() + + +def manifest_sha256(m: Mapping[str, Any]) -> str: + return hashlib.sha256(manifest_bytes(m)).hexdigest() + + +# --- approval gate --------------------------------------------------------------------------- + + +class ApprovalRecord(BaseModel): + """The user's specific approval, quoted from chat. Never inferred from configuration.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + manifest_sha256: str + per_window_cap: int + total_cap: int + approver_statement: str + approved_at: str + + +def _mentions(statement: str, number: int) -> bool: + digits = re.sub(r"(?<=\d)[,\s_](?=\d{3}\b)", "", statement) + return re.search(rf"(? None: + """Raise ``ApprovalError`` unless ``record`` approves exactly this manifest and caps.""" + if record is None: + raise ApprovalError("no approval record: the manifest is planning only") + if not m.get("jobs"): + raise ApprovalError("the manifest has no jobs: there is nothing to approve") + problems = [] + sha = manifest_sha256(m) + if record.manifest_sha256 != sha: + problems.append("manifest hash differs") + if record.per_window_cap != m["per_window_cap"]: + problems.append("per-window cap differs") + if record.total_cap != m["total_cap"]: + problems.append("total cap differs") + text = record.approver_statement.strip() + if text.lower().strip(" .!") in GENERIC_APPROVALS: + problems.append("general encouragement is not approval of a specific cap") + if not _mentions(text, m["total_cap"]): + problems.append("the statement does not state the total cap") + if sha[:12] not in text.lower(): + problems.append("the statement does not name the manifest (first 12 hex characters)") + if problems: + raise ApprovalError("; ".join(problems)) + + +# --- pilot stop rules ------------------------------------------------------------------------ + + +def pilot_stop_rules(summary: Mapping[str, Any]) -> list[dict[str, Any]]: + """Protocol 12.9 section 13, in order, on a recorded pilot's summary: ``selected``, + ``provider_failures``, ``recorded``, ``mechanism_eligible``, ``discordant_top5``, + ``cluster_sizes`` (cluster -> recorded incidents), ``leakage_failures`` (case ids), + ``missing_categories``.""" + selected = int(summary["selected"]) + recorded = int(summary["recorded"]) + out: list[dict[str, Any]] = [] + failures = int(summary["provider_failures"]) + out.append( + { + "rule": "S1", + "triggered": selected > 0 and failures / selected > 0.30, + "action": "stop and report", + } + ) + eligible = int(summary["mechanism_eligible"]) + out.append( + { + "rule": "S2", + "triggered": eligible < min(5, -(-recorded // 2)) if recorded else True, + "action": "pause broader collection", + } + ) + out.append( + { + "rule": "S3", + "triggered": int(summary["discordant_top5"]) < 2, + "action": "no powered comparison on current assumptions", + } + ) + sizes: Mapping[str, int] = summary.get("cluster_sizes", {}) + biggest = max(sizes.values(), default=0) + out.append( + { + "rule": "S4", + "triggered": recorded > 0 and biggest > recorded / 2, + "action": "effective sample size is the cluster count", + "effective_n": len(sizes), + } + ) + leaks = list(summary.get("leakage_failures", ())) + out.append( + { + "rule": "S5", + "triggered": bool(leaks), + "action": "exclude from confirmatory metrics", + "excluded": len(leaks), + } + ) + out.append( + { + "rule": "S6", + "triggered": bool(summary.get("missing_categories")), + "action": "report every missing mechanism category", + "missing": sorted(summary.get("missing_categories", ())), + } + ) + return out + + +# --- public registry ------------------------------------------------------------------------- + + +def public_registry( + leads: Sequence[Lead], + classified: Mapping[str, Mapping[str, Any]], + salts: Mapping[str, str], + meta: Mapping[str, Any], +) -> dict[str, Any]: + """Citations, statuses and salted commitments only. No identifier, truncated or full.""" + rows = [] + for x in sorted(leads, key=lambda x: x.lead_id): + c = classified[x.lead_id] + rows.append( + { + "lead_id": x.lead_id, + "origin": x.origin, + "sources": [s.model_dump() for s in x.sources], + "chain_stated": x.chain_stated, + "chain_name": x.chain_name, + "event_date": x.event_date, + "amount": x.amount, + "mechanism_claimed": x.mechanism_claimed, + "identifier_status": x.statuses(), + "commitments": commitments(x, salts[x.lead_id]), + "status": c["status"], + "reasons": c["reasons"], + "cluster": c["cluster"], + "conflicts": list(x.conflicts), + "campaign_notes": list(x.campaign_notes), + } + ) + disc = meta.get("discovery", {}) + reg = { + "schema_version": REGISTRY_VERSION, + "protocol": "protocol-12.9", + "discovery": { + k: disc.get(k) + for k in ("date", "searches", "page_reads", "budget", "explorer_or_rpc_requests") + }, + "commitment": "sha256(salt|role|lower-case identifier); one secret salt per lead, kept " + "locally and disclosed only at unblinding", + "development_duplicates": [ + {"case": d["case"], "sources_seen": len(d.get("seen_in", []))} + for d in meta.get("development_duplicates", []) + ], + "leads": rows, + } + assert_no_identifiers(json.dumps(reg)) + return reg + + +def assert_no_identifiers(text: str) -> None: + """A public artifact must not carry an address or hash, even a truncated one.""" + if _HEX_IN_TEXT.search(text) or re.search(r"0x[0-9a-fA-F]{2,}\s*(…|\.\.\.)", text): + raise AcquisitionError("an identifier would be published") + + +# --- study ---------------------------------------------------------------------------------- + + +def selection_bias( + leads: Sequence[Lead], classified: Mapping[str, Mapping[str, Any]] +) -> dict[str, Any]: + def by(fn: Any) -> dict[str, dict[str, int]]: + out: dict[str, Counter[str]] = {} + for x in leads: + out.setdefault(str(fn(x)), Counter())[classified[x.lead_id]["status"]] += 1 + return {k: dict(sorted(v.items())) for k, v in sorted(out.items())} + + return { + "by_origin": by(lambda x: x.origin.split(":")[0]), + "by_any_source_read": by(lambda x: any(s.read for s in x.sources)), + "by_chain_stated": by(lambda x: x.chain_stated), + "by_victim_status": by(lambda x: x.statuses().get("victim", "absent")), + "by_harm_tx_status": by(lambda x: x.statuses().get("harm_tx", "absent")), + "within_archive_period": by( + lambda x: bool(x.event_date) and str(x.event_date)[:10] <= ARCHIVE_LAST_DATE + ), + } + + +def main( + root: Path, + poisoning_dir: Path, + out: Path, + *, + vault: Path | None = None, + write_public: bool = False, + git: str | None = None, +) -> dict[str, Any]: + vault = vault or root / VAULT + leads, meta = load_vault(vault) + salts = load_salts(root / SALTS, leads) + dev, searched = development_hits(leads, root, poisoning_dir) + classified = classify_all(leads, dev) + pilot_ids = select_pilot(classified) + by_id = {x.lead_id: x for x in leads} + m = manifest([by_id[i] for i in pilot_ids], git) + out.mkdir(parents=True, exist_ok=True) + local = { + "study": STUDY_VERSION, + "classified": classified, + "development_hits": dev, # roles and source classes only; identifiers stay in the vault + "pilot": pilot_ids, + } + (out / "acquisition.local.json").write_text( + json.dumps(local, indent=1, sort_keys=True) + "\n", encoding="utf-8" + ) + (out / "collection-manifest.local.json").write_bytes(manifest_bytes(m) + b"\n") + registry = public_registry(leads, classified, salts, meta) + if write_public: + (root / PUBLIC_REGISTRY).write_text( + json.dumps(registry, indent=1, ensure_ascii=False) + "\n", encoding="utf-8" + ) + statuses = Counter(v["status"] for v in classified.values()) + return { + "study": STUDY_VERSION, + "protocol": "protocol-12.9", + "rpc_requests": 0, + "leads": len(leads), + "new_leads": sum(x.origin.startswith("new") for x in leads), + "statuses": {s: statuses.get(s, 0) for s in STATUSES}, + "clusters": len(set(v["cluster"] for v in classified.values())), + "development_overlap_leads": sum(bool(v) for v in dev.values()), + "development_files_searched": searched, + "pilot_selected": len(pilot_ids), + "manifest_sha256": manifest_sha256(m), + "manifest_jobs": len(m["jobs"]), + "budget": m["budget"], + "selection_bias": selection_bias(leads, classified), + "discovery": meta.get("discovery", {}), + } From 6c929bf7cb1f7dfc0e05412148c9452c9b4e2211 Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 11 Nov 2026 15:26:20 +0300 Subject: [PATCH 91/92] docs(ml): Phase 12.9 report and tests - blinding integrity, incident acquisition (no RPC) - tests/test_ml_blinding_acquisition.py: 42 offline synthetic tests covering exposure levels, history dates, payload leaks, declarations, adjudication, eligibility rule order, duplicates and campaigns, pilot determinism, the overlap search, collector fields, caps, approval specificity, stop rules, the absence of network code and runners, identifier-free public files, and T5g. - ML_INDEPENDENT_INCIDENT_ACQUISITION.md: 35 sections and gates G1-G14. - Cohort A is 60 x R3 (external). - Cohort B is 4 x R3, 30 x R2 and 1 x R1. - Reviewer exposure is unknown: no kit was sent. - 0 of 17 leads are ready for recording, so no RPC approval is requested. - Independent validation is BLOCKED BY DATA. - CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + ML_INDEPENDENT_INCIDENT_ACQUISITION.md | 709 +++++++++++++++++++++++++ tests/test_ml_blinding_acquisition.py | 592 +++++++++++++++++++++ 3 files changed, 1310 insertions(+) create mode 100644 ML_INDEPENDENT_INCIDENT_ACQUISITION.md create mode 100644 tests/test_ml_blinding_acquisition.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d218844..78448e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,15 @@ All notable changes. Versions follow semantic versioning; 0.x means interfaces m LightGBM text serialization, wallet-history features (infrastructure, no accuracy claim). Report: ML_GENERALIZATION_AUDIT.md; tables: ML_AUDIT_TABLES.md. +### Phase 12.9: reviewer-blinding integrity, independent incident acquisition, pilot gate (no RPC requests) +- **Protocol 12.9** (`docs/ml/protocol-12.9.md`) was frozen before the audit, any search or any classification. +- **Exposure audit** (`cryptoguard ml review-blinding`) searches HEAD, git history, truncated prefixes and provenance. It reproduces the 12.8 overlap (54 identifiers, 17 files). Cohort A is 60 × R3 (public archive labels). Cohort B is 4 × R3, 30 × R2 and 1 × R1. Both cohorts are byte-identical; no reviewer kit was sent, so reviewer exposure is unknown. +- **Reviewer protocol** (`docs/ml/reviewer-blinding-protocol.md`): whitelisted, leak-checked task payloads, opaque task ids, declarations that are never defaulted (R4 only from a declaration), and an adjudication-readiness check. +- **Incident acquisition** (`cryptoguard ml incident-acquisition`): 7 existing and 10 new leads from a bounded search (16 searches, 17 page reads). **0 ready for recording:** 5 need identifiers, 12 rejected, and no overlap with development artifacts. Identifiers stay local; the public registry carries salted SHA-256 commitments only. +- **Collection gate:** the job manifest, caps (2,505 per window) and an `ApprovalRecord` bound to the manifest hash. General encouragement is refused and no runner exists. The manifest is empty, so no approval is requested. +- **Benchmark:** T5g (reference-group exposure) is added to the blind harness, separate from address exposure. Independent validation remains BLOCKED BY DATA. +- **Report:** `ML_INDEPENDENT_INCIDENT_ACQUISITION.md`. + ### Phase 12.8: independent benchmark contract, ground-truth quality, readiness (no RPC requests) - **Protocol 12.8** (`docs/ml/protocol-12.8.md`) was frozen before any harness code. The code was committed before the measured run. - **Contracts (research only):** a five-dimension label ontology with evidence rules; a case record separate from the sealed outcome; a collector request that cannot carry an answer; data-quality severities; per-mechanism observation eligibility; independence checks. diff --git a/ML_INDEPENDENT_INCIDENT_ACQUISITION.md b/ML_INDEPENDENT_INCIDENT_ACQUISITION.md new file mode 100644 index 0000000..224b00c --- /dev/null +++ b/ML_INDEPENDENT_INCIDENT_ACQUISITION.md @@ -0,0 +1,709 @@ +# Phase 12.9: independent incident acquisition, reviewer-blinding integrity and pilot gate + +**Protocol:** [`docs/ml/protocol-12.9.md`](docs/ml/protocol-12.9.md), frozen at `89aea4e` +before any audit, search or classification. + +**Branch:** `feature/ml-pipeline`. + +**RPC budget:** 0. No Ethereum JSON-RPC request, explorer page or explorer API was used in +this phase. + +**Public repository:** the repository is public by its owner's choice. This report carries +aggregates, rules and citations only: +- **kept locally:** per-item exposure mappings, cohort membership and incident identifiers + stay in the git-ignored `data/ml/research/phase12.9/`; +- **in the public registry:** salted SHA-256 commitments in + [`acquisition-12.9.json`](docs/ml/incident-benchmark/acquisition-12.9.json). + +## 1. Executive summary + +**Problem A, reviewer blinding.** +- **Cohort A (60 items) is not usable for confirmatory blinded evaluation.** It has no overlap + with the repository. But every item comes from the public archive's payoff-linked pool, whose + own labels disclose the outcome (external R3). +- **Cohort B (35 items):** + - 4 items are R3, through context counterparties that public incident manifests name in an + outcome role; + - 30 are R2, either archive context or recorded incident windows; + - 1 is R1. +- **The Phase 12.8 count is reproduced exactly:** 54 core identifiers in 17 tracked files. +- **No reviewer has been exposed through the project's process:** + - no kit was sent; + - there are no submissions and no declarations; + - actual reviewer exposure is therefore **unknown**, not demonstrated. +- **Both frozen cohorts are byte-identical** to their committed hashes before and after the + audit. +- **New safeguards** (a protocol, and code with tests): + - a whitelisted, leak-checked task payload; + - opaque task ids; + - a reviewer declaration that is never defaulted; + - R4 assigned only from a declaration; + - an adjudication-readiness check. +- **These safeguards do not restore blinding for publicly exposed items.** + +**Problem B, incident acquisition.** +- **Leads:** 7 existing leads re-examined and 10 new public leads recorded, within a bounded + search of 16 searches and 17 page reads (budget 20 / 30). +- **Statuses:** **no lead is ready for blind recording**: + - 5 need identifier verification; + - 12 are rejected: 10 because no identifier appears in any source read, 2 because they are + not on Ethereum mainnet. +- **No source read gives both a verbatim victim address and a verbatim harmful transaction** + for any incident outside development: + - two leads have a verbatim harmful transaction but no victim; + - two Ethereum leads have a verbatim victim but no transaction. +- **Independence:** no lead identifier overlaps any development artifact. Five development + incidents were re-encountered in the sources and excluded as duplicates. + +**Pilot.** +- **The pilot selection is empty:** 0 eligible incidents, 0 collection jobs, total cap 0. +- **No RPC approval is requested**, because the frozen protocol has nothing to approve. +- **Section 35 sets out what would change this:** an identifier source, or a pre-registered + protocol amendment. + +**ML.** +- **Methods and stop rules are frozen.** T5g (reference-group exposure) is added to the blind + harness and kept apart from address exposure. +- **Independent validation remains BLOCKED BY DATA.** No ML generalization claim is made. + +## 2. Phase 12.8 baseline + +**What Phase 12.8 left behind:** +- **Contracts:** `benchmark-labels/1`, `benchmark-case/1`, an outcome-free `CollectorRequest`, an + `OutcomeVault` that opens only for a sealed prediction, and a score-once `Ledger`. +- **Taxonomy and planning:** a failure taxonomy, metric denominators, group splits, paired + sign-test planning and a repository-safety scan. +- **Local data:** 16 recorded windows: + - 7 protected; + - 3 development incident windows from 2 incidents; + - 6 unlabelled background windows. + Of these, 15 use `observation/1` and 1 uses `observation/2`. +- **Gaps:** 0 independent incidents, 0 verified legitimate negatives, 0 reviewer submissions. +- **Prior negative result:** Phase 12.7.1 found P1b not supported (−0.018 against B4). +- **Exposure count:** 54 identifiers of the protected cohorts in 17 tracked files. + +## 3. Research objectives + +1. **Audit the public overlap.** Find which protected items may have outcome-disclosure risk, + without altering any frozen cohort. +2. **Separate the risk levels.** Distinguish public exposure risk from demonstrated reviewer + exposure, and design a review workflow that records what reviewers knew. +3. **Re-examine the leads.** Revisit the seven unrecorded leads and search public sources, + within a fixed budget, for independent incidents with verbatim identifiers. +4. **Classify and plan.** Classify every lead reproducibly, select a pilot of at most 10, and + prepare outcome-blind collection jobs and their caps without executing anything. +5. **Freeze the comparison.** Freeze the B0 vs B4 comparison and the pilot stop rules before + any recording. + +## 4. Public repository context + +- **Visibility timeline:** + - 2026-11-09: an anonymous API read returned Not Found; + - 2026-11-10: it returned `visibility: public`; + - since then, git history is public in full. +- **Both cohorts were frozen on 2026-11-02.** +- **Every artifact that overlaps Cohort B was first committed on 2026-10-24, 2026-10-28 or + 2026-11-03:** + - all while the repository was private; + - 134 of the 144 first additions predate the freeze; + - the other 10 are incident-registry lines of 2026-11-03. +- **The overlap is by construction.** Cohort B's recorded-window frames were drawn from windows + whose fixtures and manifests were already committed. +- **Nothing has been removed or rewritten:** no history rewrite was requested or done. + +## 5. Cohort B exposure audit + +**Method.** Identifiers come from the blinded sheet only: wallet, address under review, +transaction, and context counterparties. That is 310 identifiers across both cohorts. The +unblinding keys are hashed, never parsed. + +**Channels:** +- every tracked file at HEAD; +- every line ever added in any commit; +- truncated prefixes (at least 8 hex characters before an ellipsis); +- the item's documented provenance. + +| Cohort B | Items | +|---|---| +| provenance: archive "uncategorized" pool | 24 | +| provenance: recorded window | 11 | +| repo level R0 / R1 / R2 / R3 | 24 / 1 / 6 / 4 | +| repo level, core identifiers only (R0 / R1 / R2) | 24 / 1 / 10 | +| external level R2 (archive) / R0 (recorded) | 24 / 11 | +| **combined level R1 / R2 / R3** | **1 / 30 / 4** | +| recorded-window items with all three core identifiers in public files | 11 | +| items matched only through history (no longer at HEAD) | 0 | +| items with a truncated-prefix match | 1 (already R3) | + +**Where the exposure comes from:** +- **The 4 R3 items are R3 through a context counterparty.** The item's own wallet, address + and transaction reach R2 at most. The context list of each of these items includes an + identifier that a public incident manifest names in an outcome role: the harmful + transaction's recipient or hash. For three of them, the incident registry also names it. +- **A reviewer who reads the repository can learn that the wallet belongs to a documented + poisoning incident** and which counterparty received the harmful payment. +- **Sensitivity check:** if the campaign-expansion records, which carry a verification status, + were treated as outcome rather than context, the R3 count would rise from 4 to 8. The frozen + rule treats them as context. + +## 6. Public identifier overlap + +| Measure | Cohort A | Cohort B | +|---|---|---| +| tracked files with an item identifier (core or context) | 0 | 18 | +| of which incident manifests / fixtures / registry / campaign / neutral | — | 4 / 4 / 1 / 1 / 8 | +| core identifiers in tracked files (Phase 12.8 measure) | 0 | 54 in 17 files | +| first added (range) | — | 2026-10-24 to 2026-11-03 | + +- **The neutral files** are tests and earlier research reports that quote fixture data. +- **The per-item mapping is never committed.** It stays in + `data/ml/research/phase12.9/blinding/item_exposure.local.jsonl`, a git-ignored file that a + test checks. + +## 7. Outcome-disclosure risks + +1. **Repository, outcome role (R3).** 4 Cohort B items. +2. **Repository, context (R2).** + - 6 Cohort B recorded-window items: their wallet is a published incident victim, or their + identifiers sit in incident fixtures or campaign expansion. +3. **The public archive (external).** + - Cohort A: payoff-linked, so the dataset's own labels disclose the outcome (R3). + - Cohort B: 24 archive items come from its poisoning-attempt context (R2). + - The dataset is public and carries its source's labels. +4. **Block explorers (not auditable here).** + - The reviewer instructions for archive items point to a block explorer, which can display + public name tags and phishing warnings. + - Without explorer access this channel cannot be measured. It is handled by the declaration + (`external_sources_consulted`), not assumed absent. +5. **Pre-publication period.** All overlap was committed while the repository was private, but + it is public now through HEAD and history. + +## 8. Reviewer blinding model + +**Five conditions are kept separate and never conflated:** + +| Condition | Level | +|---|---| +| identifier visible | R1 or above | +| context discoverable | R2 or above | +| outcome discoverable | R3 | +| reviewer exposed | R4: only from the reviewer's declaration or independent evidence | +| reviewer exposure unknown | no declaration | + +**Today's status:** +- every item has a computed public-exposure level; +- **no reviewer has an exposure level**, because no review exists; +- R4 is never inferred from R3 (tested); +- an item's combined level is the maximum of its repository and external levels. + +## 9. Reviewer protocol + +[`docs/ml/reviewer-blinding-protocol.md`](docs/ml/reviewer-blinding-protocol.md) contains: +- **Neutral guidance**, given to reviewers verbatim. It contains no prevalence hints and no + source-verdict wording; the screen finds zero hits and a test enforces it. +- **A four-question declaration** (`yes`, `no` or `unknown`): + - prior familiarity; + - external sources consulted; + - repository consulted; + - model output seen. + +**Rules:** +- A missing or incomplete declaration makes the review's exposure RU. +- On an R3 item, any declared familiarity or consultation makes it R4. +- `model_output_seen` is reported separately. +- **Access separation is procedural.** The protocol states that it is not proof of blindness. + +## 10. Protected cohort disposition + +| Cohort | Disposition | +|---|---| +| A (60) | all **not eligible for confirmatory blinded evaluation**; exploratory or sensitivity use only | +| B (35) | 4 not eligible (R3); 30 **qualified blinding, sensitivity stratum** (R2); 1 eligible for an explicitly qualified blinded review (R1) | + +- **The frozen files are unchanged.** Their hashes were verified before and after the audit, + and the dispositions are a separate local record. +- **No replacement cohort was drawn.** The archive pools are externally labelled; the incident + windows are public context. +- **A new low-exposure cohort is blocked by data.** It could come only from the unlabelled + background windows (R1, small, already used in development) or from new recordings, which + need a separately approved RPC budget. + +## 11. Annotation-quality improvements + +**What `review_blinding` adds:** + +| Feature | What it does | +|---|---| +| `ReviewTask` | task id, item version (sheet hash), evidence version and SHA-256, exposure level, whitelisted payload | +| `assert_payload_clean` | refuses label, verdict, score, attribution, cohort or source keys and outcome-bearing wording; errors name the location, never the value | +| `ReviewerDeclaration` | strict schema; an opaque reviewer id; answers limited to yes / no / unknown | +| `review_exposure` | RU / R4 rules | +| `adjudication_readiness` | two or more distinct reviewers, the same evidence hash, declarations naming the task; "confirmatory" only when every review is R1 or below | +| `guidance_findings` | screens reviewer guidance for hints | + +**The prepared, unsent kits:** +- They gave 4 screen hits in 2 files. On reading, all are benign: two are a decision option's + name, one describes the evidence panel, one is a disclosure question. +- They predate the declaration form and must be rebuilt before use. + +## 12. Existing incident leads + +| Lead | Victim | Harmful tx | Other | Status | +|---|---|---|---|---| +| `usdt-700k-2025-04` (Decrypt) | absent | **verbatim** (hyperlink) | planting and test-transfer tx verbatim; one address with no stated role | NEEDS_IDENTIFIER_VERIFICATION | +| `wbtc-2.38-2025-12-18` (Bitquery) | absent | **verbatim** | lookalike truncated; post-harm tx verbatim; "same crew" as a development case | NEEDS_IDENTIFIER_VERIFICATION | +| `pink-drainer-10eth-2024-06-27` (ForkLog / MistTrack) | **verbatim** | absent | intended verbatim; chain not stated | NEEDS_IDENTIFIER_VERIFICATION | +| `webacy-6.88m-usdt-2025-09` (Webacy) | **verbatim** | absent | four lookalikes as 8-hex prefixes; two bursts | NEEDS_IDENTIFIER_VERIFICATION | +| `dea-usdt-55k-2023` | absent | absent | — | REJECTED (no identifier) | +| `usdt-100k-2026-08` (crypto.news / Cyvers) | absent | absent | re-read; none | REJECTED (no identifier) | +| `usdt-50k-2026-10` (crypto.news / Scam Sniffer) | absent | absent | re-read; none | REJECTED (no identifier) | + +- **The two Decrypt hashes match the Phase 12.3 registry.** The Decrypt page was re-read + independently, and its planting and harmful hashes equal the registry's values. + +## 13. New public incident leads + +| Lead | Source (read?) | Identifiers | Status | +|---|---|---|---| +| `aethusdc-24m-2026-03` | blockchain.news flash citing PeckShield (read); CCN, Coin-Turk (403) | victim and two addresses truncated; outlets disagree on 4 vs 5 March | NEEDS_IDENTIFIER_VERIFICATION (conflict) | +| `usdt-509k-2026-01` | search results citing Cyvers | none | REJECTED | +| `usdt-600k-2026-02-17` | CryptoRank (403) | none | REJECTED | +| `usdt-100k-2026-08-13` | AMBCrypto citing Lookonchain (read) | none | REJECTED | +| `webacy-polygon-792k-usdc-2025-09` | Webacy (read) | victim verbatim | REJECTED (Polygon) | +| `webacy-base-25k-usdc-2026-04` | Webacy (search result) | none | REJECTED (Base) | +| `amlbot-czech-50k-usdt` | AMLBot blog (read) | none; chain not stated | REJECTED | +| `phantom-chat-wbtc-2026-02` | Cointelegraph (search result) | none | REJECTED | +| `eth-636k-2025-08` | Cointelegraph (search result) | none | REJECTED | +| `cyvers-1.2m-2025-03-aggregate` | ForkLog citing Cyvers (read) | none; several victims | REJECTED | + +**Development incidents re-encountered, excluded as duplicates:** + +| Development case | Times seen in the sources | +|---|---| +| `usdt-50m` | 3 | +| `eth-4556` | 3 | +| `usdt-counterfeit-39890` | 1 | +| `wbtc-1155` | 1 | +| `scamsniffer-763k` | 1 | + +The source URLs for every lead are in the public registry. + +## 14. Source verification + +**Discovery rules (protocol section 7):** +- **Budget:** 20 searches and 30 page reads. Used: 16 and 17. Three reads returned 403 and one + PDF was unreadable. +- **Never fetched:** X posts and explorer pages. +- **Identifiers are copied verbatim with where they appeared** (text or hyperlink). Truncated + values keep their ellipsis; a schema validator refuses a completed or ellipsis-less + "truncated" value. +- **A role is recorded only when the page states it.** Two identifiers shown without a role are + kept as `unassigned` and never stand in for a victim (tested). + +**Result:** +- **6 of the 17 leads were seen only in search results.** No search summary was used as an + identifier source. +- **Corroboration:** no lead has two independent original sources that both give identifiers. + +## 15. Incident identity + +`identifier_problems` checks every verbatim identifier for: +- full-length format; +- the same value appearing in two roles; +- a victim equal to a counterparty. + +No lead has an internal inconsistency in its verbatim identifiers. The Polygon lead's page +lists one address as both victim and recipient; it is recorded as a conflict and the lead is +rejected (not Ethereum). + +## 16. Campaign overlap + +- **Clustering (union-find):** leads join on any shared verbatim identifier or a stated + narrative link. The 17 leads form **16 clusters**: the two August 2026 USDT reports are + joined by narrative. +- **Shared attacker identifiers:** no lead shares a verbatim attacker or lookalike identifier + with another. +- **Link to a development case:** Bitquery describes `wbtc-2.38` as the "same crew" as a + development incident. Once its victim is known it would go to NEEDS_CAMPAIGN_REVIEW. + +## 17. Independence assessment + +**What was searched:** every verbatim lead identifier, against every development artifact: + +| Artifact class | Files | +|---|---| +| recorded fixtures and manifests | 32 | +| campaign expansion | 1 | +| development registry entries | 6 | +| archive episodes | 1 | +| archive row files | 2 | +| archive databases (indexed lookups) | 5 | +| review packets and evidence | 9 | +| frozen cohort sheets (blinded) | 3 | +| reviewer kits | 86 | +| local research outputs | 58 | + +Unblinding keys are never opened. + +**Result:** +- **No lead identifier was found in any development artifact.** +- **The search works:** positive controls (a development victim and its harmful tx, and an + archive victim) are found. + +## 18. Eligibility decisions + +**The first matching rule wins (protocol section 8):** + +| Status | Leads | +|---|---| +| DEVELOPMENT_ONLY | 0 | +| REJECTED | 12 | +| NEEDS_IDENTIFIER_VERIFICATION | 5 | +| NEEDS_CAMPAIGN_REVIEW | 0 | +| UNSUPPORTED_MECHANISM | 0 | +| NOT_EVALUABLE | 0 | +| **READY_FOR_BLIND_RECORDING** | **0** | + +**The 5 leads that need verification:** +- 2 lack a victim address; +- 2 lack a harmful transaction; +- 1 has a truncated victim and conflicting dates. + +## 19. Rejected leads + +| Reason | Leads | +|---|---| +| no identifier in any source read | 10 | +| not Ethereum mainnet (Polygon, Base) | 2 | + +**A rejection records what the sources read gave.** It does not claim the incident did not +happen, and a lead can be reopened if a source with identifiers appears. + +## 20. Selection bias + +**Where the population comes from.** These are incidents that English-language crypto news +and security-firm blogs chose to write about, found by one general-purpose search engine: +- large losses dominate; +- most reports cite an X alert and give truncated identifiers; +- Chinese-language searches returned reprints of the same cases. + +| Breakdown | Ready | Verify | Rejected | +|---|---|---|---| +| origin: registry | 0 | 4 | 3 | +| origin: new | 0 | 1 | 9 | +| a source read in full | 0 | 5 | 6 | +| search results only | 0 | 0 | 6 | +| chain stated as Ethereum | 0 | 3 | 1 | +| inside the archive period (≤ 2024-06-30) | 0 | 1 | 1 | + +**Two consequences:** +- **Any future pilot from this channel over-represents some incidents:** large, widely + reported, stablecoin incidents whose reporters published full identifiers. Detectability is + never a selection input, but **reporting is not independent of the incident's + characteristics**. +- **The pilot cannot estimate a population rate.** + +## 21. Ten-case pilot readiness + +**Selection rule:** every READY lead, at most one per cluster, ordered by +`sha256("cg-12.9-pilot|" + lead_id)` and capped at 10. + +**Selected: 0.** +- **The pilot is not ready.** There is nothing to authorize. +- **Even a small pilot would hit stop rule S2.** S2 needs at least five mechanism-eligible + recordings, and the amendments discussed in section 35 would yield 1 to 3 leads. + +## 22. Outcome-blind collection requests + +**Per lead, two prepared jobs:** + +| Job | Contents | Cap | +|---|---|---| +| **anchor** | one receipt read of the harmful transaction; it confirms the sender is the stated victim and gives block H | 5 requests | +| **record** | `CollectorRequest(chain_id=1, wallet=victim, from_block=H−21,600, to_block=H, observation=2, max_requests=2,500)` | 2,500 requests | + +- **What reaches the collector:** the anchor passes the block number only; the receipt goes to + the outcome vault. +- **What cannot be passed:** `CollectorRequest` refuses extra fields, so no lookalike, harmful + transaction or label can be handed to it (tested). +- **What a job has no field for:** retries. No runner exists. +- **The manifest for this phase has 0 jobs.** + +## 23. RPC cost estimates + +**Planning basis:** the measured 21,600-block recordings (475 / 1,299 / 1,433 requests), plus 1 +request per anchor and a 20 % retry reserve. + +| Leads | Per-window cap | Total cap | Low | Typical | High | High + 20 % | +|---|---|---|---|---|---|---| +| 0 (this phase) | 2,505 | 0 | 0 | 0 | 0 | 0 | +| 1 (hypothetical) | 2,505 | 2,505 | 476 | 1,300 | 1,434 | 1,721 | +| 10 (full pilot) | 2,505 | 25,050 | 4,760 | 13,000 | 14,340 | 17,208 | + +- **Wallet activity is unknown without RPC**, so a busy wallet can exceed the high estimate. + The per-window cap is then the bound. +- **Every request would be counted in the durable run ledger.** It fails closed and carries + nothing over from earlier approvals. + +## 24. Proposed authorization gate + +**Recording requires an `ApprovalRecord` with:** +- the manifest's SHA-256; +- the per-window cap; +- the total cap; +- the approver's statement quoted from chat. + +**`check_approval` refuses:** +- a missing record; +- an empty manifest; +- any mismatch of hash or caps; +- general encouragement ("continue", "go ahead"); +- a statement that does not state the total cap and the manifest's first 12 hex characters. + +**Approvals do not travel:** an approval for one manifest is refused for another. No +configuration implies approval, and no batch runner exists (tested). + +## 25. Frozen ranking baselines + +**Unchanged from the Phase 12.8 registry:** + +| Kind | Methods | +|---|---| +| generators | C0, C1, C2 and `candidate-evidence/2` | +| orders | B0 (similarity → recency), B1 (recency), B4 (reference rotation), P1, P1b | + +- **P1b is comparison-only.** +- **The primary pair is B0 vs B4.** +- **Recorded at freeze:** the code revision, protocol 12.9, and the observation schema + (`observation/2`). +- **Missingness behaviour is per method,** as listed in `benchmark_eval.REGISTRY`. +- **Not used for tuning:** no incident lead was used to tune anything. + +## 26. Benchmark metrics + +**Tasks:** +- T1 observation; +- T2 generation; +- T3 conditional rank; +- T4 end-to-end Top-K; +- **T5g reference-group exposure (new);** +- T6 burden; +- T7 evidence fidelity. + +**T5g asks:** is there a candidate within K whose best-reference bucket is the intended +recipient? +- **It is reported separately from T4,** with its own denominator: mechanism-eligible cases + that have an intended recipient. +- **Without an intended recipient it is not assessable.** +- **The bucket map is added to the prediction outside its digest,** so Phase 12.8 ledgers stay + valid. It is a deterministic function of the observation and the cutoff, which the digest + binds. + +**Development check (not independent):** +- T5g is assessable on 1 of 2 mechanism-eligible development cases. +- In that case, B0 and B4 show the intended recipient's group at K = 1, while the paid address + ranks third. +- **Group exposure is not address detection.** + +## 27. Statistical design + +**Analysis plan:** +- **Primary readout:** End-to-End Top-5 for B0 and B4 over mechanism-eligible recorded cases. +- **Test:** the exact sign test on discordant incidents, with clusters counted once. +- **Reported alongside:** the failure-class distribution and T5g. Exact counts and effect sizes + are reported with their uncertainty. +- **Not reported from the pilot:** precision, recall or a false-positive rate. + +**Stop rules, frozen (protocol section 13):** + +| Rule | Condition | +|---|---| +| S1 | more than 30 % provider failures | +| S2 | fewer than 5 mechanism-eligible (or under half) | +| S3 | fewer than 2 discordant incidents | +| S4 | one cluster holds more than half: the effective n is the cluster count | +| S5 | a leakage failure: the case is excluded | +| S6 | report missing categories | + +**Sample size:** the Phase 12.8 planner gives sample sizes as a function of the discordance +rate, the effect size, power, cluster dependence and the eligibility rate. No fixed count is +claimed as sufficient. + +## 28. Future legitimate-negative requirements + +**What does not count as a legitimate negative:** +- background windows are not confirmed benign; +- the absence of a known theft is not legitimacy; +- `unknown` is never a negative. + +**A verified legitimate negative needs:** +- two independent reviews (`label_policy`), each with a declaration at R1 or below on an item + that is itself R1 or below; +- or an independent verification of the counterparty relationship, such as a documented + exchange deposit address. + +**There are none today.** The outcome-selected pilot cannot by itself estimate a false-positive +rate. + +## 29. Implementation + +**New and changed modules:** + +| Module | What it holds | +|---|---| +| `ml/review_blinding.py` (new) | exposure audit (HEAD, history, partial, external), levels, dispositions, payload whitelist, declarations, adjudication readiness, guidance screen | +| `ml/incident_acquisition.py` (new) | lead schema, local vault, salted commitments, development-overlap search, clusters, eligibility, pilot selection, jobs, budget, approval gate, stop rules, public registry; no network import | +| `ml/benchmark_eval.py` | T5g, prediction bucket map, aggregate | +| `ml/cli.py` | new commands `cryptoguard ml review-blinding` and `cryptoguard ml incident-acquisition [--write-public]` | + +**Documents:** +- [`docs/ml/reviewer-blinding-protocol.md`](docs/ml/reviewer-blinding-protocol.md); +- [`docs/ml/incident-benchmark/acquisition-12.9.json`](docs/ml/incident-benchmark/acquisition-12.9.json). + +**Unchanged:** the detector, the replay fixtures and the frozen cohorts. + +## 30. Test results + +**`tests/test_ml_blinding_acquisition.py` has 42 tests, all offline and synthetic.** They +cover: +- exposure levels; +- R4 never inferred; +- the history channel and its dates; +- partial matches; +- payload leaks, model scores and opaque ids; +- declarations never defaulted; +- adjudication; +- the guidance screen; +- cohort hashes; +- the identifier validator; +- every eligibility rule; +- duplicates and campaigns; +- deterministic, size-blind pilot selection; +- the development-overlap search, which never reads a key; +- the collector request carrying only its fields; +- caps; +- approval specificity; +- stop rules; +- the absence of network imports, runners and retries; +- salted commitments and an identifier-free registry; +- T5g separate from T4. + +The full-suite result is given in the delivery note, and the pull-request comment records it. + +## 31. CI + +CI runs on the pushed commit. Its result is recorded in the pull-request comment and the +delivery note. + +## 32. Reproducibility + +```bash +uv run cryptoguard ml review-blinding +``` + +```bash +uv run cryptoguard ml incident-acquisition --write-public +``` + +```bash +uv run cryptoguard ml benchmark-readiness --out data/ml/research/phase12.9/dev-regression --no-archive --no-history +``` + +**What each run depends on:** +- **Determinism:** both studies are deterministic given the local vault, the per-lead salts + (created once, kept locally) and the repository state. +- **Runtime:** + +| Study | Runtime | Peak RSS | +|---|---|---| +| blinding audit | 9–16 s | about 71 MiB | +| acquisition | 33–61 s | about 75 MiB | + + Large files are streamed in 16 MiB chunks, and the databases are queried by index. +- **Local data:** the frozen cohorts, the archive extracts and the lead vault are local and are + not in the repository. + +## 33. Public-repository safety + +**What this phase publishes:** +- **No incident identifier, full or truncated.** The registry carries salted commitments, and a + test enforces this on every new public file. +- **No per-item exposure mapping, no cohort membership and no key.** + +**What stays local (git-ignored):** +- the vault; +- the salts; +- the item mapping; +- the collection manifest. + +**The repository-safety scan is clean:** +- no secret patterns; +- no sensitive names; +- no tracked restricted paths. + +The repository stays public by its owner's choice. + +## 34. Remaining limitations + +- **The external channel is coarse.** External exposure is assigned by provenance class, not + measured per item. +- **Explorer name tags and warnings are not audited.** +- **Discovery was bounded and came from one engine.** X posts and explorers were not read. + Three pages returned 403 and one PDF was unreadable. +- **The role rules are frozen choices.** Treating campaign expansion as context, and assigning + roles to history lines by key, are conservative choices that could be argued. The + sensitivity count is reported in section 5. +- **No reviewer exists yet.** The declaration workflow is untested with real reviewers. +- **Two implementation choices that protocol 12.9 does not spell out:** + - a lead with complete identifiers but no stated chain is classed + NEEDS_IDENTIFIER_VERIFICATION, because READY requires a stated Ethereum chain; + - the development-artifact search also covers the reviewer kits and local research outputs. + That can only add DEVELOPMENT_ONLY results, and none occurred. +- **T5g has been exercised on one development case only.** +- **Independent validation remains BLOCKED BY DATA.** ML generalization is not established. + +## 35. Recommended next experimental step + +**Recording is not the bottleneck; identifiers are.** Without a lead that has a verbatim +victim and harmful transaction, no RPC budget can produce an independent pilot. Requesting one +now would only spend requests. + +**Options, in order of preference. Each must be pre-registered before any recording.** + +1. **User-sourced incidents.** Obtain incidents whose public source gives both identifiers in + full, for example a firm's write-up with explorer links. They would be added to the vault and + classified by the frozen rules. +2. **Amendment A1 (anchor-derived victim).** For a lead whose page states that the hyperlinked + harmful transaction is the victim's own transfer, the anchor receipt's sender becomes the + victim. The cross-check of the sender against a stated victim is lost. + - Today this would make 1 lead ready (`usdt-700k-2025-04`), with a cap of 2,505. + - `wbtc-2.38` would go to campaign review. +3. **Amendment A2 (date-window recording).** For a lead with a verbatim victim and a stated + event date but no transaction, record a wider window around the date. + - The harmful transfer would be identified afterwards, from the recording, by the page's + stated partial identifiers. + - Today this would add 1 to 2 leads (`webacy-6.88m`, and `pink-drainer` if its chain is + accepted). + - Larger windows need their own caps. + +**Even with both amendments, the pilot would be 2 or 3 incidents,** below stop rule S2. Such a +pilot can show feasibility, but it cannot inform the B0 vs B4 comparison. + +## Quality gates + +| Gate | Status | Basis | +|---|---|---| +| G1 Exposure audit | PASS WITH LIMITATIONS | repository channels exact and reproducible; external channel by provenance class; explorer tags not auditable | +| G2 Reviewer isolation | PASS WITH LIMITATIONS | whitelisted, leak-checked payloads (tested); existing kits must be rebuilt; explorers outside control | +| G3 Cohort integrity | PASS | committed hashes verified before and after; no file written | +| G4 Blinding credibility | PASS | R3 and R4 separated; R4 only from declarations; 0 declarations, so reviewer exposure unknown | +| G5 Lead provenance | PASS WITH LIMITATIONS | every identifier has a cited page and position; 6 leads seen only in search results | +| G6 Incident independence | PASS | overlap search with positive controls; 0 overlaps; 5 development duplicates excluded; campaign link flagged | +| G7 Eligibility | PASS | deterministic first-match rules, each tested | +| G8 Selection bias | PASS WITH LIMITATIONS | documented; the population is what news reports | +| G9 Collector blindness | PASS | outcome-free request with extra fields refused; the anchor passes the block only | +| G10 Resource planning | PASS WITH LIMITATIONS | explicit caps; estimates from measured windows; wallet activity unknown | +| G11 Authorization | PASS | 0 RPC requests; specific approval required; no runner | +| G12 ML benchmark readiness | PASS WITH LIMITATIONS | the harness accepts future cases unchanged, with T5g added; independent validation **BLOCKED BY DATA** | +| G13 Public safety | PASS | no identifiers, mappings or keys published; safety scan clean | +| G14 Production isolation | PASS | detector, fixtures and stable behaviour untouched; existing tests pass | diff --git a/tests/test_ml_blinding_acquisition.py b/tests/test_ml_blinding_acquisition.py new file mode 100644 index 0000000..515f770 --- /dev/null +++ b/tests/test_ml_blinding_acquisition.py @@ -0,0 +1,592 @@ +"""Protocol 12.9: reviewer-blinding exposure levels, review-task leakage, declarations, +incident eligibility, pilot selection, collection preparation and the approval gate. +Synthetic only; every expectation follows from a definition in the protocol.""" + +from __future__ import annotations + +import json +import re +import sqlite3 +import subprocess +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from cryptoguard.ml import benchmark_contract as bc +from cryptoguard.ml import benchmark_eval as be +from cryptoguard.ml import incident_acquisition as ia +from cryptoguard.ml import reliability_study as rs +from cryptoguard.ml import review_blinding as rb + +ROOT = Path(__file__).resolve().parents[1] +A1, A2, A3, A4 = ("0x" + c * 40 for c in "1234") +T1, T2 = ("0x" + c * 64 for c in "ab") + + +def git(cwd: Path, *args: str) -> str: + return subprocess.run( # noqa: S603 + ["git", "-C", str(cwd), *args], # noqa: S607 + capture_output=True, + text=True, + check=True, + ).stdout + + +def repo(tmp_path: Path) -> Path: + git(tmp_path, "init", "-q") + git(tmp_path, "config", "user.email", "t@example.invalid") + git(tmp_path, "config", "user.name", "t") + git(tmp_path, "config", "commit.gpgsign", "false") + return tmp_path + + +def commit(root: Path, files: dict[str, str], message: str, date: str) -> None: + for rel, text in files.items(): + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text, encoding="utf-8") + git(root, "add", "-A") + subprocess.run( # noqa: S603 + ["git", "-C", str(root), "commit", "-q", "-m", message], # noqa: S607 + check=True, + env={ + **__import__("os").environ, + "GIT_AUTHOR_DATE": f"{date}T12:00:00", + "GIT_COMMITTER_DATE": f"{date}T12:00:00", + }, + ) + + +# --- Part I: exposure levels ---------------------------------------------------------------- + + +def test_artifact_roles() -> None: + k = rb.artifact_kind + assert k("src/cryptoguard/replay/cases/x/manifest.json") == "incident_manifest" + assert k("docs/ml/incident-benchmark/cases/x/manifest.json") == "incident_manifest" + assert k("docs/ml/incident-benchmark/stage2-candidates.json") == "incident_registry" + assert k("src/cryptoguard/replay/cases/x/fixture.json") == "incident_fixture" + assert k("src/cryptoguard/replay/campaign_cases/expansion.json") == "campaign_expansion" + assert k("src/cryptoguard/replay/background_cases/bg/fixture.json") == "neutral" + assert k("tests/test_x.py") == "neutral" + manifest = { + "victim": A1, + "intended_recipient": A2, + "harm": {"recipient": A3, "transaction_hash": T1}, + } + assert rb.json_roles("incident_manifest", manifest) == { + A1: "context", A2: "context", A3: "outcome", T1: "outcome" + } # fmt: skip + registry = {"candidates": [{"identifiers": {"victim": A1, "lookalike": A3, "harm_tx": T1, + "etherscan_filter_fadd": A4}}]} # fmt: skip + assert rb.json_roles("incident_registry", registry) == { + A1: "context", A3: "outcome", T1: "outcome", A4: "outcome" + } # fmt: skip + assert rb.line_role("incident_registry", f' "harm_tx": "{T1}",') == "outcome" + assert rb.line_role("incident_manifest", f' "recipient": "{A3}",') == "outcome" + assert rb.line_role("incident_manifest", f' "victim": "{A1}",') == "context" + assert rb.line_role("neutral", f' "harm_tx": "{T1}",') == "neutral" + + +def item(**kw: object) -> rb.Item: + base: dict[str, object] = dict( + cohort="hard-negative-candidates/1", item=1, provenance="recorded_window", + core=frozenset({A1, A2, T1}), context=frozenset({A4}), sheet_sha256="s" * 64, + ) # fmt: skip + return rb.Item(**(base | kw)) # type: ignore[arg-type] + + +def occ(path: str, role: str, channel: str = "head") -> rb.Occurrence: + return rb.Occurrence(path, rb.artifact_kind(path), role, channel, "2026-10-28") + + +@pytest.mark.parametrize( + ("role", "level"), [("outcome", "R3"), ("context", "R2"), ("neutral", "R1")] +) +def test_levels_follow_the_strongest_role(role: str, level: str) -> None: + a = rb.assess(item(), {A1: [occ("f.json", role)]}, {}, {}) + assert (a.repo_level, a.external_level, a.combined) == (level, "R0", level) + assert a.disposition == rb.DISPOSITION[level] + + +def test_partial_only_is_unknown_and_nothing_is_r0() -> None: + assert rb.assess(item(), {}, {}, {A2: ["notes.md"]}).repo_level == "RU" + assert rb.assess(item(), {}, {}, {}).repo_level == "R0" + + +def test_external_provenance_and_context_counterparties() -> None: + a = rb.assess(item(provenance="archive_payoff_linked"), {}, {}, {}) + assert (a.repo_level, a.external_level, a.combined) == ("R0", "R3", "R3") + b = rb.assess(item(provenance="archive_uncategorized"), {}, {}, {}) + assert b.combined == "R2" + # a context counterparty in an outcome role exposes the item; the core-only view does not + c = rb.assess(item(), {A4: [occ("src/cryptoguard/replay/cases/x/manifest.json", "outcome")]}, + {}, {}) # fmt: skip + assert (c.repo_level, c.repo_level_core_only) == ("R3", "R0") + + +def test_r4_is_never_inferred_from_r3() -> None: + every = [ + rb.assess(item(provenance=p), {A1: [occ("f.json", r)]}, {}, {}) + for p in rb.EXTERNAL_LEVEL + for r in ("outcome", "context", "neutral") + ] + assert all(a.combined != "R4" for a in every) + + +def test_history_channel_dates_and_roles(tmp_path: Path) -> None: + root = repo(tmp_path) + reg = "docs/ml/incident-benchmark/candidates.json" + body = json.dumps({"candidates": [{"identifiers": {"lookalike": A3}}]}, indent=1) + commit(root, {reg: body, "notes.md": f"see {A2[:12]}... later"}, "add", "2026-10-24") + commit(root, {reg: "{}"}, "drop", "2026-11-05") + idents = frozenset({A3, A2}) + hist = rb.scan_history(root, idents) + o = hist[A3][reg] + assert (o.role, o.first_date, o.channel) == ("outcome", "2026-10-24", "history") + assert rb.scan_head(root, idents) == {} # gone at HEAD, still public through history + a = rb.assess(item(core=frozenset({A3})), {}, hist, {}) + assert a.repo_level == "R3" + assert a.occurrences[0]["channel"] == "history" + assert rb.scan_partial(root, idents) == {A2: ["notes.md"]} + + +# --- Part I: review tasks and declarations --------------------------------------------------- + +ROW = { + "schema_version": "review-sheet/2", "item": 7, "chain_id": 1, "wallet": A1, + "address_under_review": A2, "transaction": T1, "block": 100, + "context": [{"block": "99", "counterparty": A4, "direction": "in", "value": "1", + "label": "x"}], + "coverage_note": "No wallet history is included: use a block explorer, up to the block above.", + "description": "Candidate for independent security review", + "subtype": "fake_token", "source_label": "payoff", +} # fmt: skip + + +def test_payload_is_whitelisted_and_clean() -> None: + p = rb.task_payload(ROW) + assert set(p) == {"item", "chain_id", "wallet", "address_under_review", "transaction", + "block", "context", "coverage_note"} # fmt: skip + assert set(p["context"][0]) == {"block", "counterparty", "direction", "value"} + leaks = ( + {"subtype": "x"}, + {"model_score": 0.9}, + {"nested": {"verdict": "x"}}, + {"note": "confirmed poisoning victim"}, + {"items": ["looks like a scam"]}, + ) + for leak in leaks: + with pytest.raises(rb.PayloadLeakError) as e: + rb.assert_payload_clean(leak) + assert "poison" not in str(e.value) + assert "scam" not in str(e.value) + + +def test_task_ids_are_opaque_and_r4_is_not_a_task_level() -> None: + t = rb.build_task(ROW, sheet_sha256="a" * 64, evidence_version="evidence-packets/2", + evidence_sha256="e" * 64, exposure_level="R2") # fmt: skip + assert t.task_id == rb.task_id("a" * 64, 7) + assert len(t.task_id) == 20 + assert "hard" not in t.task_id + assert t.task_id != rb.task_id("a" * 64, 8) + with pytest.raises(ValueError, match="R4"): + rb.build_task(ROW, sheet_sha256="a" * 64, evidence_version="v", evidence_sha256="e", + exposure_level="R4") # fmt: skip + + +def declaration(task: str = "t1", rid: str = "rev-a", **kw: str) -> rb.ReviewerDeclaration: + base = dict(reviewer_id=rid, task_id=task, prior_familiarity="no", + external_sources_consulted="no", repository_consulted="no", + model_output_seen="no", declared_at="2026-11-12") # fmt: skip + return rb.ReviewerDeclaration(**(base | kw)) + + +def test_declarations_are_never_defaulted() -> None: + assert rb.review_exposure("R3", None)["level"] == "RU" + assert rb.review_exposure("R3", declaration())["level"] == "R3" + assert rb.review_exposure("R3", declaration(external_sources_consulted="yes"))["level"] == "R4" + assert rb.review_exposure("R3", declaration(prior_familiarity="yes"))["level"] == "R4" + assert rb.review_exposure("R2", declaration(repository_consulted="yes"))["level"] == "R2" + assert rb.review_exposure("R1", declaration(prior_familiarity="unknown"))["level"] == "RU" + seen = rb.review_exposure("R1", declaration(model_output_seen="yes")) + assert (seen["level"], seen["model_output_seen"]) == ("R1", "yes") # reported apart + with pytest.raises(ValidationError): + declaration(prior_familiarity="maybe") + with pytest.raises(ValidationError): + declaration(rid="name with spaces") + + +def test_adjudication_needs_two_declared_reviews_on_the_same_evidence() -> None: + t = rb.build_task(ROW, sheet_sha256="a" * 64, evidence_version="v", evidence_sha256="e" * 64, + exposure_level="R1") # fmt: skip + a = rb.SubmittedReview("rev-a", "insufficient_evidence", "e" * 64, declaration(t.task_id)) + b = rb.SubmittedReview("rev-b", "insufficient_evidence", "e" * 64, + declaration(t.task_id, "rev-b")) # fmt: skip + assert rb.adjudication_readiness(t, [a])["ready"] is False + ok = rb.adjudication_readiness(t, [a, b]) + assert ok["ready"] + assert ok["confirmatory"] + assert not rb.adjudication_readiness(t, [a, rb.SubmittedReview("rev-b", "x", "e" * 64, None)])[ + "ready" + ] + elsewhere = rb.SubmittedReview("rev-b", "x", "f" * 64, b.declaration) + assert not rb.adjudication_readiness(t, [a, elsewhere])["ready"] + other = rb.SubmittedReview("rev-b", "x", "e" * 64, declaration("another", "rev-b")) + assert not rb.adjudication_readiness(t, [a, other])["ready"] + t3 = t.model_copy(update={"exposure_level": "R3"}) + assert rb.adjudication_readiness(t3, [a, b])["confirmatory"] is False + + +def test_guidance_screen() -> None: + doc = (ROOT / "docs/ml/reviewer-blinding-protocol.md").read_text(encoding="utf-8") + section = doc.split("")[1].split( + "" + )[0] + assert rb.guidance_findings(section) == {} + for field in ("prior_familiarity", "external_sources_consulted", "repository_consulted", + "model_output_seen"): # fmt: skip + assert field in section + assert rb.guidance_findings("Most of these were confirmed victims (payoff).") + + +@pytest.mark.skipif( + not (ROOT / "data/ml/poisoning/review_sample/reviewer_sheet.jsonl").is_file(), + reason="frozen cohorts are local research data", +) +def test_frozen_cohorts_are_unchanged() -> None: + before = rb.verify_cohorts(ROOT / "data/ml/poisoning") + rb.load_items(ROOT / "data/ml/poisoning") + assert rb.verify_cohorts(ROOT / "data/ml/poisoning") == before + + +# --- Part II: leads and eligibility ---------------------------------------------------------- + + +def lead(lead_id: str = "L1", **kw: object) -> ia.Lead: + ids = { + "victim": ia.Identifier(status="verbatim", value=A1), + "harm_tx": ia.Identifier(status="verbatim", value=T1), + "lookalike": ia.Identifier(status="truncated", value="0x3333…3333"), + } + base: dict[str, object] = dict( + lead_id=lead_id, origin="new:test", chain_stated="ethereum", identifiers=ids, + sources=(ia.LeadSource(publisher="p", url="https://example.invalid", date="2026", + read=True),), + ) # fmt: skip + return ia.Lead(**(base | kw)) # type: ignore[arg-type] + + +def test_identifiers_are_verbatim_or_marked_truncated() -> None: + with pytest.raises(ValidationError): + ia.Identifier(status="verbatim", value="0x1234...abcd") # never completed + with pytest.raises(ValidationError): + ia.Identifier(status="truncated", value=A1) # a full value is not truncated + with pytest.raises(ValidationError): + ia.Identifier(status="truncated", value="0x1234abcd") # no ellipsis kept + with pytest.raises(ValidationError): + ia.Identifier(status="absent", value=A1) + assert ia.Identifier(status="truncated", value="0x5a5a5a5a…").status == "truncated" + + +def ids(**over: ia.Identifier) -> dict[str, ia.Identifier]: + return dict(lead().identifiers) | over + + +@pytest.mark.parametrize( + ("kw", "dev", "status"), + [ + ({}, {"victim": ["archive_databases"]}, "DEVELOPMENT_ONLY"), + ({"chain_stated": "other", "chain_name": "Base"}, {}, "REJECTED"), + ({"identifiers": {"victim": ia.Identifier(status="absent")}}, {}, "REJECTED"), + ({"conflicts": ("date differs",)}, {}, "NEEDS_IDENTIFIER_VERIFICATION"), + ({"identifiers": ids(victim=ia.Identifier(status="truncated", value="0x5b5b...5b5b"))}, + {}, "NEEDS_IDENTIFIER_VERIFICATION"), + ({"identifiers": ids(harm_tx=ia.Identifier(status="absent"))}, {}, + "NEEDS_IDENTIFIER_VERIFICATION"), + ({"chain_stated": "unstated"}, {}, "NEEDS_IDENTIFIER_VERIFICATION"), + ({"campaign_notes": ("same crew as a development case",)}, {}, "NEEDS_CAMPAIGN_REVIEW"), + ({"mechanism_claimed": "erc1155"}, {}, "UNSUPPORTED_MECHANISM"), + ({"harm_claimed": False}, {}, "NOT_EVALUABLE"), + ({}, {}, ia.READY), + ], +) # fmt: skip +def test_eligibility_rule_order(kw: dict, dev: dict, status: str) -> None: + got, reasons = ia.classify(lead(**kw), dev) + assert got == status + assert not any(re.search(r"0x[0-9a-f]{8}", r) for r in reasons) # no identifier in reasons + + +def test_shared_attacker_identifiers_need_a_cluster() -> None: + a = lead("La", identifiers=ids(lookalike=ia.Identifier(status="verbatim", value=A3))) + b = lead("Lb", identifiers=ids(victim=ia.Identifier(status="verbatim", value=A4), + harm_tx=ia.Identifier(status="verbatim", value=T2), + lookalike=ia.Identifier(status="verbatim", + value=A3))) # fmt: skip + assert ia.shared_attacker_identifiers([a, b]) == {"La": ["Lb"], "Lb": ["La"]} + assert ia.classify(a, {}, shared=["Lb"])[0] == "NEEDS_CAMPAIGN_REVIEW" + assert ia.classify(a, {}, shared=["Lb"], same_cluster=["Lb"])[0] == ia.READY + out = ia.classify_all([a, b], {}) + assert out["La"]["cluster"] == out["Lb"]["cluster"] == "La" + assert ia.select_pilot(out) == [min(["La", "Lb"], key=ia.pilot_rank)] # one per cluster + + +def test_pilot_selection_ignores_size_and_is_capped() -> None: + leads = [ + lead(f"L{i:02d}", amount=f"{i} USDT", + identifiers=ids(victim=ia.Identifier(status="verbatim", value="0x" + f"{i:040x}"), + harm_tx=ia.Identifier(status="verbatim", value="0x" + f"{i:064x}"))) + for i in range(1, 15) + ] # fmt: skip + chosen = ia.select_pilot(ia.classify_all(leads, {})) + assert len(chosen) == ia.PILOT_CAP + assert chosen == sorted((x.lead_id for x in leads), key=ia.pilot_rank)[:10] + bigger = [x.model_copy(update={"amount": "1,000,000 USDT"}) for x in leads] + assert ia.select_pilot(ia.classify_all(bigger, {})) == chosen + + +def test_hint_clusters_join_narrative_duplicates() -> None: + a = lead("La", cluster_hint="h") + other = ids( + victim=ia.Identifier(status="verbatim", value=A4), + harm_tx=ia.Identifier(status="verbatim", value=T2), + ) + b = lead("Lb", cluster_hint="h", identifiers=other) + assert ia.clusters([a, b]) == {"La": "La", "Lb": "La"} + + +def test_development_overlap_search(tmp_path: Path) -> None: + root, poison = tmp_path, tmp_path / "data/ml/poisoning" + fx = root / "src/cryptoguard/replay/cases/c1/fixture.json" + fx.parent.mkdir(parents=True) + fx.write_text(json.dumps({"wallet": A1.upper().replace("0X", "0x")}), encoding="utf-8") + poison.mkdir(parents=True) + con = sqlite3.connect(poison / "archive_subset.sqlite") + con.execute("CREATE TABLE transfers (tx TEXT, sender TEXT, receiver TEXT, value REAL)") + con.execute("INSERT INTO transfers VALUES (?, ?, ?, 1.0)", (T1, A2, A3)) + con.commit() + con.close() + (poison / "unblinding_key.jsonl").write_text(json.dumps({"x": A4}), encoding="utf-8") + probe = lead(identifiers={ + "victim": ia.Identifier(status="verbatim", value=A1), + "harm_tx": ia.Identifier(status="verbatim", value=T1), + "intended": ia.Identifier(status="verbatim", value=A4), + }) # fmt: skip + hits, searched = ia.development_hits([probe], root, poison) + assert hits["L1"] == { + "victim": ["recorded_fixtures_and_manifests"], + "harm_tx": ["archive_databases"], + } # the unblinding key is never read + assert searched["archive_databases"] == 1 + assert ia.classify(probe, hits["L1"])[0] == "DEVELOPMENT_ONLY" + + +# --- Part II: collection preparation and approval ------------------------------------------- + + +def test_jobs_carry_only_collector_fields() -> None: + jobs = ia.collection_jobs([lead()]) + anchor, record = jobs + assert isinstance(anchor, ia.AnchorJob) + assert isinstance(record, ia.RecordJob) + assert anchor.max_requests == 5 + assert record.max_requests == 2_500 + req = ia.record_request(record, 24_000_000) + assert req.model_dump() == { + "chain_id": 1, "wallet": A1, "from_block": 24_000_000 - 21_600, "to_block": 24_000_000, + "observation": 2, "max_requests": 2_500, + } # fmt: skip + with pytest.raises(ValidationError): + bc.CollectorRequest(**req.model_dump(), harm_tx=T1) # type: ignore[call-arg] + assert "harm" not in json.dumps(record.model_dump()) + + +def test_budget() -> None: + b = ia.budget(10) + assert (b["per_window_cap"], b["total_cap"], b["jobs"]) == (2_505, 25_050, 20) + assert b["estimates"]["high"]["requests"] == 10 * (1 + 1_433) + assert b["estimates"]["high"]["with_retry_reserve"] == round(10 * 1_434 * 1.2) + assert ia.budget(0)["total_cap"] == 0 + + +def approval(m: dict, **kw: object) -> ia.ApprovalRecord: + sha = ia.manifest_sha256(m) + base: dict[str, object] = dict( + manifest_sha256=sha, per_window_cap=m["per_window_cap"], total_cap=m["total_cap"], + approver_statement=f"I approve manifest {sha[:12]} with a total cap of " + f"{m['total_cap']:,} requests.", + approved_at="2026-11-12", + ) # fmt: skip + return ia.ApprovalRecord(**(base | kw)) # type: ignore[arg-type] + + +def test_approval_is_specific_and_never_inferred() -> None: + m = ia.manifest([lead()], git="abc") + ia.check_approval(approval(m), m) # exact approval passes + with pytest.raises(ia.ApprovalError, match="planning only"): + ia.check_approval(None, m) + for bad in ( + approval(m, approver_statement="continue"), + approval(m, approver_statement="Go ahead with the recording."), + approval(m, manifest_sha256="0" * 64), + approval(m, per_window_cap=5_000), + approval(m, total_cap=6_000), + approval(m, approver_statement=f"approve {ia.manifest_sha256(m)[:12]} up to 2,000"), + ): + with pytest.raises(ia.ApprovalError): + ia.check_approval(bad, m) + # an approval for one manifest is not reusable for another + second = lead("L2", identifiers=ids(victim=ia.Identifier(status="verbatim", value=A4))) + m2 = ia.manifest([lead(), second], git="abc") + with pytest.raises(ia.ApprovalError): + ia.check_approval(approval(m), m2) + empty = ia.manifest([], git="abc") + with pytest.raises(ia.ApprovalError, match="nothing to approve"): + ia.check_approval(approval(empty), empty) + + +def test_stop_rules() -> None: + base = dict(selected=10, provider_failures=0, recorded=10, mechanism_eligible=8, + discordant_top5=3, cluster_sizes={f"c{i}": 1 for i in range(10)}, + leakage_failures=[], missing_categories=[]) # fmt: skip + assert not any(r["triggered"] for r in ia.pilot_stop_rules(base)) + + def fired(**kw: object) -> list[str]: + return [r["rule"] for r in ia.pilot_stop_rules(base | kw) if r["triggered"]] + + assert fired(provider_failures=4) == ["S1"] + assert fired(mechanism_eligible=4) == ["S2"] + assert ( + fired(recorded=6, mechanism_eligible=3, cluster_sizes={f"c{i}": 1 for i in range(6)}) == [] + ) + assert fired(discordant_top5=1) == ["S3"] + assert fired(cluster_sizes={"c0": 6, "c1": 4}) == ["S4"] + assert fired(leakage_failures=["x"]) == ["S5"] + assert fired(missing_categories=["native_dust"]) == ["S6"] + + +def test_no_network_code() -> None: + for mod in (ia, rb): + src = Path(mod.__file__).read_text(encoding="utf-8") # type: ignore[arg-type] + imports = "\n".join( + line for line in src.splitlines() if re.match(r"\s*(from|import) ", line) + ) + for banned in ("requests", "httpx", "urllib", "socket", "aiohttp", "web3", "replay.record", + "ml.fetch", "ml.collect", "rpc"): # fmt: skip + assert banned not in imports, (mod.__name__, banned) + + +def test_commitments_are_salted_and_registry_is_identifier_free(tmp_path: Path) -> None: + x = lead() + salts = ia.load_salts(tmp_path / "s.json", [x]) + assert ia.load_salts(tmp_path / "s.json", [x]) == salts # created once + c = ia.commitments(x, salts["L1"]) + assert c == ia.commitments(x, salts["L1"]) != ia.commitments(x, "other-salt") + assert set(c) == {"victim", "harm_tx"} # verbatim identifiers only + reg = ia.public_registry([x], ia.classify_all([x], {}), salts, {}) + text = json.dumps(reg) + assert A1 not in text + assert T1 not in text + assert "0x3333" not in text + for leak in (f"x {A1}", "0x5a5a5a5a…", "0x5b5b...5b5b"): + with pytest.raises(ia.AcquisitionError): + ia.assert_no_identifiers(leak) + + +def test_public_phase_12_9_files_carry_no_identifiers() -> None: + for rel in ("docs/ml/incident-benchmark/acquisition-12.9.json", + "docs/ml/reviewer-blinding-protocol.md", "docs/ml/protocol-12.9.md", + "ML_INDEPENDENT_INCIDENT_ACQUISITION.md"): # fmt: skip + ia.assert_no_identifiers((ROOT / rel).read_text(encoding="utf-8")) + out = git(ROOT, "check-ignore", "data/ml/research/phase12.9/leads.local.json") + assert out.strip() + + +# --- T5g reference-group exposure ------------------------------------------------------------ + + +def test_reference_group_exposure() -> None: + fx = rs.wallet_fixture( + transfers=[], native=[(rs.lookalike(1), 1, 2_000, True)], + wallet_txs=[(rs.lookalike(1), 10**18, 5_000)], + ) # fmt: skip + c = bc.BenchmarkCase( + case_id="g", chain_id=1, victim=fx.wallet, from_block=fx.from_block, to_block=fx.to_block, + cutoff=(5_000, 0), cutoff_rule="x", observation_schema="observation/2", + source=bc.CaseSource(publisher="s", url="synthetic://"), cluster_id="g", + population="synthetic", + ) # fmt: skip + p = be.predict(c, fx) + assert set(p.buckets) == set(p.candidates) + o = bc.Outcome(case_id="g", verified=True, paid_address=rs.lookalike(1), + intended_recipient=p.buckets[rs.lookalike(1)]) # fmt: skip + g = be.reference_group_exposure(p, o) + assert g is not None + assert g["B0"]["1"] is True + assert be.reference_group_exposure(p, o.model_copy(update={"intended_recipient": A4})) == { + m: {str(k): False for k in be.K_GRID} for m in be.ORDERS + } + assert be.reference_group_exposure(p, o.model_copy(update={"intended_recipient": None})) is None + + +# --- protocol 12.9 D3 additions ------------------------------------------------------------- + + +def test_identity_cases() -> None: + truncated_tx = ids(harm_tx=ia.Identifier(status="truncated", value="0x5c5c5c5c...5c5c")) + assert ia.classify(lead(identifiers=truncated_tx), {})[0] == "NEEDS_IDENTIFIER_VERIFICATION" + # an identifier whose role the page does not state never stands in for the victim + unassigned = { + "unassigned_address": ia.Identifier(status="verbatim", value=A1), + "harm_tx": ia.Identifier(status="verbatim", value=T1), + } + status, reasons = ia.classify(lead(identifiers=unassigned), {}) + assert (status, reasons) == ("NEEDS_IDENTIFIER_VERIFICATION", ["victim absent"]) + # a missing intended recipient does not block recording (T5g is then not assessable) + no_intended = lead() + assert "intended" not in no_intended.identifiers + assert ia.classify(no_intended, {})[0] == ia.READY + + +def test_duplicate_reports_share_a_cluster() -> None: + a = lead("La") + same_tx = lead("Lb", identifiers=ids(victim=ia.Identifier(status="verbatim", value=A4))) + same_victim = lead("Lc", identifiers=ids(harm_tx=ia.Identifier(status="verbatim", value=T2))) + cl = ia.clusters([a, same_tx, same_victim]) + assert set(cl.values()) == {"La"} + assert len(ia.select_pilot(ia.classify_all([a, same_tx, same_victim], {}))) == 1 + + +def test_no_runner_no_retries_and_no_mapping_in_public_output() -> None: + names = {n for n in dir(ia) if callable(getattr(ia, n))} + assert not {n for n in names if re.search(r"(?i)^(run|execute|launch|submit|record_all)", n)} + job_fields = set(ia.AnchorJob.model_fields) | set(ia.RecordJob.model_fields) + assert not {f for f in job_fields if "retry" in f or "retries" in f} + a = rb.assess(item(), {A1: [occ("src/cryptoguard/replay/cases/x/manifest.json", "outcome")]}, + {}, {}) # fmt: skip + public = json.dumps(rb.summarize([a])) + assert "manifest.json" not in public + assert '"item"' not in public + assert A1 not in public + for rel in ("data/ml/research/phase12.9/blinding/item_exposure.local.jsonl", + "data/ml/research/phase12.9/commitment-salts.local.json"): # fmt: skip + assert git(ROOT, "check-ignore", rel).strip() + + +def test_group_exposure_is_reported_apart_from_address_exposure() -> None: + r = { + "eligible": True, "mechanism_eligible": True, "T1_assessable": True, "T1_observed": True, + "T2_generated": True, "cluster_id": "c", "failure": "ranked_below_k", + "T3_rank": {m: 7 for m in be.ORDERS}, + "T4_exposed": {m: {str(k): k >= 7 for k in be.K_GRID} for m in be.ORDERS}, + "T5g_reference_group_exposed": {m: {str(k): True for k in be.K_GRID} for m in be.ORDERS}, + "T5_mechanism_identified": None, "fidelity": {"records": 1, "resolved_pre_cutoff": 1}, + "burden": {"candidates": 9, "wallet_days": 3.0, "evidence_records": 9, "summary_bytes": 1}, + "candidates": 9, + } # fmt: skip + agg = be.aggregate([r, r | {"T5g_reference_group_exposed": None}]) + assert agg["end_to_end_topk"]["B0"][1]["value"] == 0.0 + assert agg["reference_group_exposure"]["B0"][1] == {"value": 1.0, "numerator": 1, + "denominator": 1} # fmt: skip + assert agg["reference_group_not_assessable"] == 1 From 310fe658d6b931bb81830ba1cf9e080e099e28dd Mon Sep 17 00:00:00 2001 From: Rostislav Date: Wed, 11 Nov 2026 15:27:25 +0300 Subject: [PATCH 92/92] fix(ml): write the public acquisition registry with LF line endings The registry is written as bytes, so regenerating it on Windows leaves the tracked file byte-identical. Content unchanged. Co-Authored-By: Claude Opus 5.5 --- src/cryptoguard/ml/incident_acquisition.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cryptoguard/ml/incident_acquisition.py b/src/cryptoguard/ml/incident_acquisition.py index 3e4a105..5f17ea6 100644 --- a/src/cryptoguard/ml/incident_acquisition.py +++ b/src/cryptoguard/ml/incident_acquisition.py @@ -850,8 +850,9 @@ def main( (out / "collection-manifest.local.json").write_bytes(manifest_bytes(m) + b"\n") registry = public_registry(leads, classified, salts, meta) if write_public: - (root / PUBLIC_REGISTRY).write_text( - json.dumps(registry, indent=1, ensure_ascii=False) + "\n", encoding="utf-8" + # bytes, so the tracked file has LF endings on every platform + (root / PUBLIC_REGISTRY).write_bytes( + (json.dumps(registry, indent=1, ensure_ascii=False) + "\n").encode() ) statuses = Counter(v["status"] for v in classified.values()) return {