Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f711953
Create run_record.py
Nuruddeen61 Nov 22, 2026
a32886c
Add anchor functionality for run-record hashes
Nuruddeen61 Nov 22, 2026
3acd5f0
Add check_run.py for verifying record integrity
Nuruddeen61 Nov 22, 2026
5c1c752
Add run_analysis.py for data analysis and receipt generation
Nuruddeen61 Nov 22, 2026
bc325ad
Add README for reproducible run records with Nirium
Nuruddeen61 Nov 22, 2026
55854bb
Implement tests for build_record and check functions
Nuruddeen61 Nov 22, 2026
13891cf
Add run1.txt with sample data
Nuruddeen61 Nov 22, 2026
a03726d
Add run2.txt with sample data
Nuruddeen61 Nov 22, 2026
2f6682c
Refactor sdk_anchor to use asyncio for SDK calls
Nuruddeen61 Nov 22, 2026
198cf20
Add run1.json with results of notebook execution
Nuruddeen61 Nov 23, 2026
8b1d39b
Add run2.json with results data
Nuruddeen61 Nov 23, 2026
611f807
Add reproducible notebook JSON configuration
Nuruddeen61 Nov 23, 2026
c50ed92
Delete examples/build-reproducible-notebook/463b7d604aab.json
Nuruddeen61 Nov 23, 2026
f3ca485
Add JSON receipt for reproducible notebook
Nuruddeen61 Nov 23, 2026
d2714bc
Add JSON receipt for reproducible notebook
Nuruddeen61 Nov 23, 2026
6400c3d
Modify output format in run_analysis.py
Nuruddeen61 Nov 23, 2026
9c99e83
Add JSON receipt for reproducible notebook
Nuruddeen61 Nov 23, 2026
7fbb3e6
Add JSON receipt for reproducible notebook
Nuruddeen61 Nov 23, 2026
8b5c769
Delete examples/build-reproducible-notebook/receipts/463b7d604aab.json
Nuruddeen61 Nov 23, 2026
7b371b0
Delete examples/build-reproducible-notebook/receipts/8fb6bf393c1e.json
Nuruddeen61 Nov 23, 2026
4d21901
Revise README for usage and verification clarity
Nuruddeen61 Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions examples/build-reproducible-notebook/README.md
Original file line number Diff line number Diff line change
@@ -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:<sha256>` 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/<hash12>.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 <cid> --hash <sha256>`.

## 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.
33 changes: 33 additions & 0 deletions examples/build-reproducible-notebook/anchor.py
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions examples/build-reproducible-notebook/check_run.py
Original file line number Diff line number Diff line change
@@ -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())
1 change: 1 addition & 0 deletions examples/build-reproducible-notebook/data/run1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1 2 3 4 5
1 change: 1 addition & 0 deletions examples/build-reproducible-notebook/data/run2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
10 20 30
19 changes: 19 additions & 0 deletions examples/build-reproducible-notebook/receipts/c5f1ee188d91.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
}
19 changes: 19 additions & 0 deletions examples/build-reproducible-notebook/receipts/d8428bfa58dd.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
}
4 changes: 4 additions & 0 deletions examples/build-reproducible-notebook/results/run1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"n": 5,
"mean": 3.0
}
4 changes: 4 additions & 0 deletions examples/build-reproducible-notebook/results/run2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"n": 3,
"mean": 20.0
}
19 changes: 19 additions & 0 deletions examples/build-reproducible-notebook/run_analysis.py
Original file line number Diff line number Diff line change
@@ -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)))
31 changes: 31 additions & 0 deletions examples/build-reproducible-notebook/run_record.py
Original file line number Diff line number Diff line change
@@ -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)
33 changes: 33 additions & 0 deletions examples/build-reproducible-notebook/tests/test_all.py
Original file line number Diff line number Diff line change
@@ -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()