File size: 4,778 Bytes
6da4e64 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | from __future__ import annotations
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
def canonical_json(value: object) -> bytes:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
def sha256_bytes(value: bytes) -> str:
return hashlib.sha256(value).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def merkle_root(leaves: list[str]) -> str:
if not leaves:
return sha256_bytes(b"")
level = [bytes.fromhex(item) for item in leaves]
while len(level) > 1:
if len(level) % 2:
level.append(level[-1])
level = [hashlib.sha256(level[index] + level[index + 1]).digest() for index in range(0, len(level), 2)]
return level[0].hex()
def build(run_path: Path, output_path: Path) -> dict:
run = json.loads(run_path.read_text(encoding="utf-8"))
run_dir = run_path.parent
source = run["input"]["capture"]["source"]
world_seed = {
"capture_sha256": source["sha256"],
"frames": [item["sha256"] for item in run["input"]["files"]],
"model": run["model"],
"settings": run["settings"],
}
artifacts = []
artifact_candidates = (
"exports/npz/results.npz",
"prediction.npz",
"scene.glb",
"evidence.glb",
"evidence.ply",
)
for name in artifact_candidates:
path = run_dir / name
if path.is_file():
artifacts.append({"path": name, "bytes": path.stat().st_size, "sha256": sha256_file(path)})
leaves = [sha256_bytes(canonical_json(item)) for item in run["input"]["files"]]
leaves.extend(sha256_bytes(canonical_json(item)) for item in artifacts)
proof = {
"schema": "kineworld.spatial-lineage.proof.v1",
"created_at": datetime.now(timezone.utc).isoformat(),
"world_id": f"kw:world:{sha256_bytes(canonical_json(world_seed))}",
"mode_contract": {
"imagine": "same persistent world with evidence overlay hidden",
"verify": "same persistent world with lineage and confidence exposed",
"camera_and_state_preserved": True,
},
"capture_commitment": {
"name": source["name"],
"bytes": source["bytes"],
"sha256": source["sha256"],
"source_media_embedded": False,
},
"frame_commitments": run["input"]["files"],
"producer": {"model": run["model"], "settings": run["settings"]},
"provenance": run["provenance"],
"artifacts": artifacts,
"merkle": {"algorithm": "sha256-pair-duplicate-last", "leaf_count": len(leaves), "root": merkle_root(leaves)},
"limitations": [
"This bundle is content integrity evidence, not proof that model estimates are physically correct.",
"Confidence values are model scores and are not calibrated probabilities.",
"The reconstruction scale is model-relative unless separately calibrated.",
],
}
output_path.write_text(json.dumps(proof, ensure_ascii=False, indent=2), encoding="utf-8")
return proof
def verify(proof_path: Path, run_dir: Path) -> None:
proof = json.loads(proof_path.read_text(encoding="utf-8"))
for artifact in proof["artifacts"]:
path = run_dir / artifact["path"]
if not path.is_file() or sha256_file(path) != artifact["sha256"]:
raise SystemExit(f"verification failed: {artifact['path']}")
leaves = [sha256_bytes(canonical_json(item)) for item in proof["frame_commitments"]]
leaves.extend(sha256_bytes(canonical_json(item)) for item in proof["artifacts"])
if merkle_root(leaves) != proof["merkle"]["root"]:
raise SystemExit("verification failed: Merkle root")
print(f"verified {proof['world_id']} ({len(leaves)} commitments)")
def main() -> None:
parser = argparse.ArgumentParser(description="Build or verify a KineJing spatial-lineage proof")
parser.add_argument("run", type=Path, help="run.json when building; proof.json when verifying")
parser.add_argument("--output", type=Path)
parser.add_argument("--verify", action="store_true")
args = parser.parse_args()
if args.verify:
verify(args.run.resolve(), args.run.resolve().parent)
return
output = args.output.resolve() if args.output else args.run.resolve().with_name("proof.json")
proof = build(args.run.resolve(), output)
print(f"wrote {output}\n{proof['world_id']}\nmerkle {proof['merkle']['root']}")
if __name__ == "__main__":
main()
|