Datasets:
Download verify.py from gemmozero/mcp-tool-change-events: direct link, hf CLI and curl.
- Browser
- Download file 6.32 kB
-
https://huggingface.co/datasets/gemmozero/mcp-tool-change-events/resolve/main/verify.py
- Command line
-
hf download hf://datasets/gemmozero/mcp-tool-change-events/verify.py
-
curl -L -o verify.py https://huggingface.co/datasets/gemmozero/mcp-tool-change-events/resolve/main/verify.py
6.32 kB
| #!/usr/bin/env python3 | |
| """Validation du dataset construit (aucun statut écrit à la main). | |
| 1. schéma : toutes les lignes d'une config ont les mêmes clés ; 2. doublons ; 3. signature Ed25519 de CHAQUE record d'événement | |
| (clé publique du /keyring public, épinglée par key_id = sha256(clé)) ; 4. intégrité des tools/list archivés (sha256(JCS) == haché signé) ; | |
| 5. preuves d'inclusion Merkle (RFC 9162) pour un échantillon aléatoire d'événements contre la tête signée épinglée + signature de la tête ; | |
| 6. balayage secrets (motifs de jetons) + aucun champ hors API publique. Écrit validation.json. Statut : DATASET_OK seulement si tout passe. | |
| Usage : python3 verify.py [--sample 40]""" | |
| import base64, glob, hashlib, json, os, random, re, sys, urllib.request | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| from build import SECRET, canon, BASE # noqa: E402 | |
| from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # noqa: E402 | |
| def has(cfg): | |
| return os.path.exists(os.path.join(HERE, "data", cfg, "train.jsonl")) or os.path.exists(os.path.join(HERE, "data", cfg, "train.parquet")) | |
| def _read(path): | |
| if os.path.exists(path + ".jsonl"): | |
| return [json.loads(l) for l in open(path + ".jsonl")] | |
| import pandas as pd # paquet publié : parquet seulement | |
| return json.loads(pd.read_parquet(path + ".parquet").to_json(orient="records")) | |
| def meta_dir(): | |
| for d in (os.path.join(HERE, "meta"), os.path.join(HERE, "cache", "meta")): | |
| if os.path.isdir(d): | |
| return d | |
| raise SystemExit("meta/ (keyring + tête signée) introuvable") | |
| def rows(cfg): | |
| out = [] | |
| for sp in ("train", "test"): | |
| out += _read(os.path.join(HERE, "data", cfg, sp)) | |
| return out | |
| def leaf_hash(b): | |
| return hashlib.sha256(b"\x00" + b).digest() | |
| def node(l, r): | |
| return hashlib.sha256(b"\x01" + l + r).digest() | |
| def root_from_path(index, size, leaf, path): | |
| fn, sn, r = index, size - 1, leaf | |
| for p in path: | |
| if sn == 0: | |
| return None | |
| if fn & 1 or fn == sn: | |
| r = node(p, r) | |
| while not fn & 1 and fn != 0: | |
| fn >>= 1 | |
| sn >>= 1 | |
| else: | |
| r = node(r, p) | |
| fn >>= 1 | |
| sn >>= 1 | |
| return r if sn == 0 else None | |
| def main(): | |
| k = int(sys.argv[sys.argv.index("--sample") + 1]) if "--sample" in sys.argv else 40 | |
| v = {"checks": {}} | |
| ev, bm = rows("events"), (rows("benchmark") if has("benchmark") else None) | |
| v["checks"]["schema_events_uniform"] = len({tuple(sorted(x)) for x in ev}) == 1 | |
| if bm is not None: | |
| v["checks"]["schema_benchmark_uniform"] = len({tuple(sorted(x)) for x in bm}) == 1 | |
| v["checks"]["no_duplicate_events"] = len({x["leaf_index"] for x in ev}) == len(ev) | |
| if bm is not None: | |
| v["checks"]["no_duplicate_benchmark_ids"] = len({x["id"] for x in bm}) == len(bm) | |
| v["checks"]["no_train_test_server_overlap_benchmark"] = not ({x["server_id"] for x in rows_split("benchmark", "train")} & {x["server_id"] for x in rows_split("benchmark", "test")}) | |
| keys = {} | |
| for l in open(os.path.join(meta_dir(), "keyring.bin"), encoding="utf-8"): | |
| if l.strip(): | |
| kk = json.loads(l) | |
| if kk.get("public_key_b64"): | |
| keys[hashlib.sha256(base64.b64decode(kk["public_key_b64"])).hexdigest()] = kk["public_key_b64"] | |
| bad = 0 | |
| for x in ev: | |
| r = json.loads(x["signed_record"]) | |
| sig = r.pop("signature_ed25519") | |
| try: | |
| Ed25519PublicKey.from_public_bytes(base64.b64decode(keys[r["key_id"]])).verify(base64.b64decode(sig), canon(r).encode()) | |
| except Exception: | |
| bad += 1 | |
| v["records_signature_checked"], v["records_signature_bad"] = len(ev), bad | |
| v["checks"]["all_event_record_signatures_valid"] = bad == 0 and len(ev) > 0 | |
| tbad = tn = 0 | |
| for p in glob.glob(os.path.join(HERE, "cache", "tools", "*.json")): # vide dans le paquet publié -> contrôle N/A | |
| d = json.load(open(p)) | |
| tn += 1 | |
| tbad += hashlib.sha256(canon(d["tools"]).encode()).hexdigest() != d["tools_sha256"] | |
| v["tools_lists_checked"], v["tools_lists_hash_mismatch"] = tn, tbad | |
| if tn: | |
| v["checks"]["archived_tools_lists_hash_ok"] = tbad == 0 | |
| else: | |
| v["not_applicable"] = ["archived_tools_lists_hash_ok (no cache/tools in this copy: re-fetch with collect.py --tools to run it)"] | |
| head = json.load(open(sorted(glob.glob(os.path.join(meta_dir(), "head_*.json")))[-1])) | |
| th = head["sth"]["tree_head"] | |
| try: | |
| Ed25519PublicKey.from_public_bytes(base64.b64decode(keys[th["issuer_pin_sha256"]])).verify(base64.b64decode(head["sth"]["signature_ed25519"]), canon(th).encode()) | |
| v["checks"]["pinned_head_signature_valid"] = True | |
| except Exception: | |
| v["checks"]["pinned_head_signature_valid"] = False | |
| random.seed(20261029) | |
| smp = random.sample(ev, min(k, len(ev))) | |
| ok = 0 | |
| for x in smp: | |
| pr = json.load(urllib.request.urlopen(urllib.request.Request(x["inclusion_proof_url"], headers={"User-Agent": "legion-hf-dataset-verify/0.1"}), timeout=60)) | |
| rt = root_from_path(x["leaf_index"], th["tree_size"], leaf_hash(x["signed_record"].encode()), [bytes.fromhex(h) for h in pr["audit_path"]]) | |
| ok += bool(rt and rt.hex() == th["root_sha256"]) | |
| v["inclusion_proofs_sampled"], v["inclusion_proofs_ok"] = len(smp), ok | |
| v["checks"]["inclusion_proofs_sample_ok"] = ok == len(smp) and len(smp) > 0 | |
| blob = "\n".join(json.dumps(x, ensure_ascii=False) for x in ev + (bm or [])) | |
| v["secret_like_patterns_found"] = len(SECRET.findall(blob)) | |
| v["checks"]["no_secret_like_patterns"] = v["secret_like_patterns_found"] == 0 | |
| if bm is not None: | |
| v["checks"]["benchmark_labels_consistent_with_signed_records"] = all(x["label_matches_signed_record"] for x in bm) | |
| v["status"] = "DATASET_OK" if all(v["checks"].values()) else "REVIEW_REQUIRED" | |
| out = os.path.join(HERE, "validation.json") if os.path.isdir(os.path.join(HERE, "cache")) else os.path.join(HERE, "validation_local_rerun.json") | |
| json.dump(v, open(out, "w"), indent=1) | |
| print(json.dumps(v, indent=1)) | |
| def rows_split(cfg, sp): | |
| return _read(os.path.join(HERE, "data", cfg, sp)) | |
| if __name__ == "__main__": | |
| main() | |