diff --git a/examples/build-reproducible-notebook/README.md b/examples/build-reproducible-notebook/README.md new file mode 100644 index 0000000..da0c5e5 --- /dev/null +++ b/examples/build-reproducible-notebook/README.md @@ -0,0 +1,56 @@ +# Build with Nirium: reproducible run records + +Hashes a run's input files, code and output files into one run record, signs +`nirium-audit-v1:` with your own Stellar testnet key, and anchors the +hash via the Nirium Audit Trail (testnet). Large files are hashed locally and +never uploaded; only the record hash is public. + +## Usage +```bash +pip install stellar-sdk nirium +export STELLAR_TESTNET_SECRET=S... # your own testnet key, never committed +cd examples/build-reproducible-notebook +python run_analysis.py data/run1.txt --out results/run1.json +python run_analysis.py data/run2.txt --out results/run2.json +python check_run.py receipts/.json # recompute + nirium verify +python tests/test_all.py # offline, HTTP mocked +``` + +`check_run.py` recomputes the record from the files, compares its hash with the +receipt, then runs `npx nirium-cli verify --hash `. + +## Receipts +Signed by testnet key `GC3ADSZYQZWOQASTNZQ4PWA7GR6FAETSQBS4Q4EGZZXNZQYST3JXH5XT`, +tag `wave11-reproducible-notebook`. + +| Run | Input | CID | Record hash | +|-----|-------|-----|-------------| +| 1 | data/run1.txt | `QmdvnYaQEtqrQQ19hZ7hphbU6GAKknnvS9aMGezq5iMNVK` | `c5f1ee188d9180c8d63497d29c7f88f8798f722ed8212044264774dbd092809a` | +| 2 | data/run2.txt | `QmYgs3Ae89A7jFf9mkZYfk97UEg7gTBPB2E2TcDd5EyaYQ` | `d8428bfa58dd6b1879472dbf09d1c2577f449fcd949eafab0b3cc31d754334de` | + +Receipt files: `receipts/c5f1ee188d91.json`, `receipts/d8428bfa58dd.json`. + +### Verify output (fresh clone) +``` +--- RUN 1 --- +OK: record matches files and passes nirium verify +--- RUN 2 --- +OK: record matches files and passes nirium verify +``` + +### Tampered cases +Appending a line to `data/run1.txt`: +``` +FAIL: files changed (expected c5f1ee188d9180c8d63497d29c7f88f8798f722ed8212044264774dbd092809a, got bfeab19880fb8c89cd13f7021203ae468abbd5684cadaf13e6ead4fadb248c3b) +``` +Appending a line to `results/run2.json`: +``` +FAIL: files changed (expected d8428bfa58dd6b1879472dbf09d1c2577f449fcd949eafab0b3cc31d754334de, got fab65ab10426f471132c0820f4eca4d16275efc460af561c4273242a1349a2b9) +``` + +## What a receipt proves, and what it doesn't +Proves: the record has not changed since it was anchored, and which key signed it. +Does not prove: that the content is true or the analysis correct. `anchoredAt` +is the Nirium node's clock, not a ledger time. + +Do not edit `run_analysis.py` after anchoring: its hash is part of each record. diff --git a/examples/build-reproducible-notebook/anchor.py b/examples/build-reproducible-notebook/anchor.py new file mode 100644 index 0000000..7ab55da --- /dev/null +++ b/examples/build-reproducible-notebook/anchor.py @@ -0,0 +1,33 @@ +"""Sign and anchor a run-record hash through the Nirium Audit Trail (client only).""" +import asyncio, base64, json, os +from pathlib import Path + +NODE = "https://nirium-agent.fly.dev" # testnet node, POST /api/audit/log +PREFIX = "nirium-audit-v1:" + +def stellar_sign(secret, record_hash): + from stellar_sdk import Keypair # pip install stellar-sdk + kp = Keypair.from_secret(secret) + sig = kp.sign((PREFIX + record_hash).encode()) + return kp.public_key, base64.b64encode(sig).decode() + +def sdk_anchor(kwargs): + """Call the published SDK: Agent(...).anchor_audit_record(hash=, tag=, agent=).""" + from nirium import Agent + return asyncio.run(Agent(api_url=NODE).anchor_audit_record(**kwargs)) + +def anchor(record, record_hash, tag, secret=None, signer=stellar_sign, client=sdk_anchor): + if not tag.startswith("wave11-"): + raise ValueError("tag must start with 'wave11-'") + secret = secret or os.environ["STELLAR_TESTNET_SECRET"] # never commit keys + key, signature = signer(secret, record_hash) + resp = client({"hash": record_hash, "tag": tag, + "agent": {"key": key, "signature": signature}}) + return {"cid": resp["cid"], "hash": record_hash, "agent": key, "tag": tag, + "anchoredAt": resp.get("anchoredAt"), "record": record} + +def save_receipt(receipt, directory="receipts"): + Path(directory).mkdir(exist_ok=True) + path = Path(directory) / f"{receipt['hash'][:12]}.json" + path.write_text(json.dumps(receipt, indent=2)) + return path diff --git a/examples/build-reproducible-notebook/check_run.py b/examples/build-reproducible-notebook/check_run.py new file mode 100644 index 0000000..2a237fc --- /dev/null +++ b/examples/build-reproducible-notebook/check_run.py @@ -0,0 +1,25 @@ +"""check-run: recompute a record from local files, then run `nirium verify`.""" +import argparse, json, subprocess, sys +from run_record import rebuild, record_hash + +def check(receipt, root=".", verify=True, runner=subprocess.run): + recomputed = record_hash(rebuild(receipt["record"], root)) + if recomputed != receipt["hash"]: + return False, f"FAIL: files changed (expected {receipt['hash']}, got {recomputed})" + if verify: + r = runner(["npx", "nirium-cli", "verify", receipt["cid"], "--hash", receipt["hash"]], + capture_output=True, text=True) + if r.returncode != 0: + return False, "FAIL: nirium verify\n" + (r.stdout or "") + (r.stderr or "") + return True, "OK: record matches files" + (" and passes nirium verify" if verify else "") + +def main(argv=None): + ap = argparse.ArgumentParser() + ap.add_argument("receipt"); ap.add_argument("--root", default=".") + ap.add_argument("--skip-cli", action="store_true") + a = ap.parse_args(argv) + ok, msg = check(json.load(open(a.receipt)), a.root, not a.skip_cli) + print(msg); return 0 if ok else 1 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/build-reproducible-notebook/data/run1.txt b/examples/build-reproducible-notebook/data/run1.txt new file mode 100644 index 0000000..aacb595 --- /dev/null +++ b/examples/build-reproducible-notebook/data/run1.txt @@ -0,0 +1 @@ +1 2 3 4 5 diff --git a/examples/build-reproducible-notebook/data/run2.txt b/examples/build-reproducible-notebook/data/run2.txt new file mode 100644 index 0000000..659cfca --- /dev/null +++ b/examples/build-reproducible-notebook/data/run2.txt @@ -0,0 +1 @@ +10 20 30 diff --git a/examples/build-reproducible-notebook/receipts/c5f1ee188d91.json b/examples/build-reproducible-notebook/receipts/c5f1ee188d91.json new file mode 100644 index 0000000..582afca --- /dev/null +++ b/examples/build-reproducible-notebook/receipts/c5f1ee188d91.json @@ -0,0 +1,19 @@ +{ + "cid": "QmdvnYaQEtqrQQ19hZ7hphbU6GAKknnvS9aMGezq5iMNVK", + "hash": "c5f1ee188d9180c8d63497d29c7f88f8798f722ed8212044264774dbd092809a", + "agent": "GC3ADSZYQZWOQASTNZQ4PWA7GR6FAETSQBS4Q4EGZZXNZQYST3JXH5XT", + "tag": "wave11-reproducible-notebook", + "anchoredAt": "2026-11-23T00:48:18.540Z", + "record": { + "version": "nirium-run-record-v1", + "inputs": { + "data/run1.txt": "e7464530ec48c7398faea385c2e737c855ca15a7f9bb30f0cdc363b5d0f2e3d4" + }, + "code": { + "run_analysis.py": "a95d6b47948e2d2b52ef27143131cd4e8b0b10f3a1302ffcc3bb99fdf1576ac3" + }, + "outputs": { + "results/run1.json": "14ca05dda07329f2276571a7ffb8d1d74d190d414eeecc3a0ae7e304d414b26e" + } + } +} diff --git a/examples/build-reproducible-notebook/receipts/d8428bfa58dd.json b/examples/build-reproducible-notebook/receipts/d8428bfa58dd.json new file mode 100644 index 0000000..4443533 --- /dev/null +++ b/examples/build-reproducible-notebook/receipts/d8428bfa58dd.json @@ -0,0 +1,19 @@ +{ + "cid": "QmYgs3Ae89A7jFf9mkZYfk97UEg7gTBPB2E2TcDd5EyaYQ", + "hash": "d8428bfa58dd6b1879472dbf09d1c2577f449fcd949eafab0b3cc31d754334de", + "agent": "GC3ADSZYQZWOQASTNZQ4PWA7GR6FAETSQBS4Q4EGZZXNZQYST3JXH5XT", + "tag": "wave11-reproducible-notebook", + "anchoredAt": "2026-11-23T00:48:20.449Z", + "record": { + "version": "nirium-run-record-v1", + "inputs": { + "data/run2.txt": "0b2a04baf2fb45f9efd2e31510ab7e39fb025c310306add1783aa174e9e2881d" + }, + "code": { + "run_analysis.py": "a95d6b47948e2d2b52ef27143131cd4e8b0b10f3a1302ffcc3bb99fdf1576ac3" + }, + "outputs": { + "results/run2.json": "a66e586029dead095414f1feea320dd2a76da2502cce191b2e5aef72effae24c" + } + } +} diff --git a/examples/build-reproducible-notebook/results/run1.json b/examples/build-reproducible-notebook/results/run1.json new file mode 100644 index 0000000..d8bc0be --- /dev/null +++ b/examples/build-reproducible-notebook/results/run1.json @@ -0,0 +1,4 @@ +{ + "n": 5, + "mean": 3.0 +} diff --git a/examples/build-reproducible-notebook/results/run2.json b/examples/build-reproducible-notebook/results/run2.json new file mode 100644 index 0000000..e9a9f71 --- /dev/null +++ b/examples/build-reproducible-notebook/results/run2.json @@ -0,0 +1,4 @@ +{ + "n": 3, + "mean": 20.0 +} diff --git a/examples/build-reproducible-notebook/run_analysis.py b/examples/build-reproducible-notebook/run_analysis.py new file mode 100644 index 0000000..701fbb7 --- /dev/null +++ b/examples/build-reproducible-notebook/run_analysis.py @@ -0,0 +1,19 @@ +"""Run the analysis on an input file, write results, anchor a receipt.""" +import argparse, json, statistics +from pathlib import Path +from run_record import build_record, record_hash +from anchor import anchor, save_receipt + +def analyse(inp, out): + nums = [float(x) for x in Path(inp).read_text().split()] + result = {"n": len(nums), "mean": statistics.mean(nums)} + Path(out).write_text(json.dumps(result, indent=2) + "\n") + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("input"); ap.add_argument("--out", required=True) + ap.add_argument("--tag", default="wave11-reproducible-notebook") + a = ap.parse_args() + analyse(a.input, a.out) + rec = build_record([a.input], ["run_analysis.py"], [a.out]) + print(save_receipt(anchor(rec, record_hash(rec), a.tag))) diff --git a/examples/build-reproducible-notebook/run_record.py b/examples/build-reproducible-notebook/run_record.py new file mode 100644 index 0000000..0ca6d3b --- /dev/null +++ b/examples/build-reproducible-notebook/run_record.py @@ -0,0 +1,31 @@ +"""Build a canonical run record: hashes of inputs, code and outputs.""" +import hashlib, json +from pathlib import Path + +VERSION = "nirium-run-record-v1" + +def sha256_file(path, chunk=1 << 20): + h = hashlib.sha256() + with open(path, "rb") as f: # streamed: large files are hashed, never uploaded + while block := f.read(chunk): + h.update(block) + return h.hexdigest() + +def _entries(paths, root): + return {Path(p).as_posix(): sha256_file(Path(root) / p) for p in sorted(paths)} + +def build_record(inputs, code, outputs, root="."): + return {"version": VERSION, + "inputs": _entries(inputs, root), + "code": _entries(code, root), + "outputs": _entries(outputs, root)} + +def canonical(record): + return json.dumps(record, sort_keys=True, separators=(",", ":")) + +def record_hash(record): + return hashlib.sha256(canonical(record).encode()).hexdigest() + +def rebuild(record, root="."): + """Recompute a record from the files named in an existing one.""" + return build_record(record["inputs"], record["code"], record["outputs"], root) diff --git a/examples/build-reproducible-notebook/tests/test_all.py b/examples/build-reproducible-notebook/tests/test_all.py new file mode 100644 index 0000000..24e4337 --- /dev/null +++ b/examples/build-reproducible-notebook/tests/test_all.py @@ -0,0 +1,33 @@ +import shutil, sys, tempfile, unittest +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from run_record import build_record, record_hash +from anchor import anchor +from check_run import check + +fake_signer = lambda s, h: ("GFAKE", "c2ln") +fake_client = lambda p: {"cid": "bafyfake", "anchoredAt": "2026-11-22T00:00:00Z"} + +class T(unittest.TestCase): + def setUp(self): + self.d = Path(tempfile.mkdtemp()) + (self.d / "in.txt").write_text("1 2 3"); (self.d / "code.py").write_text("x") + (self.d / "out.json").write_text("{}") + self.rec = build_record(["in.txt"], ["code.py"], ["out.json"], self.d) + self.rcpt = anchor(self.rec, record_hash(self.rec), "wave11-test", "s", fake_signer, fake_client) + def tearDown(self): shutil.rmtree(self.d) + def test_ok(self): self.assertTrue(check(self.rcpt, self.d, verify=False)[0]) + def test_tampered_input(self): + (self.d / "in.txt").write_text("1 2 4"); self.assertFalse(check(self.rcpt, self.d, verify=False)[0]) + def test_tampered_output(self): + (self.d / "out.json").write_text("{1}"); self.assertFalse(check(self.rcpt, self.d, verify=False)[0]) + def test_different_inputs_different_hash(self): + (self.d / "in.txt").write_text("9"); r2 = build_record(["in.txt"], ["code.py"], ["out.json"], self.d) + self.assertNotEqual(record_hash(r2), self.rcpt["hash"]) + def test_tag_enforced(self): + with self.assertRaises(ValueError): anchor(self.rec, "h", "bad", "s", fake_signer, fake_client) + def test_cli_failure(self): + class R: returncode, stdout, stderr = 1, "", "bad" + self.assertFalse(check(self.rcpt, self.d, True, lambda *a, **k: R())[0]) + +if __name__ == "__main__": unittest.main()