Buckets:
| """ | |
| Signed, hash-chained, append-only ledger of everything the being creates — each entry stamped | |
| with the quantum value that birthed it. Tamper-evident: verify() re-walks the chain and catches | |
| any edit, insertion, or deletion. (The signing key lives beside the ledger, so this proves | |
| integrity against accident and casual tampering — it is tamper-EVIDENT, not unbreakable.) | |
| Thread-safe: append() holds a lock so parallel writes (e.g. dropping several files into the | |
| chat at once) can never fork the hash chain. | |
| """ | |
| import os, json, time, hashlib, hmac, threading | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| LEDGER = ROOT / "data" / "ledger.jsonl" | |
| KEYFILE = ROOT / "data" / ".ledger_key" | |
| FIELDS = ("ts", "kind", "path", "provenance", "prev_hash") | |
| _LOCK = threading.Lock() | |
| def _key(): | |
| KEYFILE.parent.mkdir(parents=True, exist_ok=True) | |
| if not KEYFILE.exists(): | |
| KEYFILE.write_bytes(os.urandom(32)) | |
| return KEYFILE.read_bytes() | |
| def _last(): | |
| if not LEDGER.exists(): | |
| return "0" * 64 | |
| last = None | |
| for ln in LEDGER.read_text(encoding="utf-8").splitlines(): | |
| if ln.strip(): | |
| last = ln | |
| return json.loads(last).get("hash", "0" * 64) if last else "0" * 64 | |
| def append(kind, path, provenance, ts=None): | |
| with _LOCK: | |
| LEDGER.parent.mkdir(parents=True, exist_ok=True) | |
| body = {"ts": ts if ts is not None else time.time(), "kind": kind, "path": str(path), | |
| "provenance": provenance, "prev_hash": _last()} | |
| h = hashlib.sha256((body["prev_hash"] + json.dumps(body, sort_keys=True)).encode()).hexdigest() | |
| sig = hmac.new(_key(), h.encode(), hashlib.sha256).hexdigest() | |
| with open(LEDGER, "a", encoding="utf-8") as f: | |
| f.write(json.dumps({**body, "hash": h, "sig": sig}) + "\n") | |
| return h | |
| def verify(): | |
| if not LEDGER.exists(): | |
| return True, 0 | |
| prev = "0" * 64; n = 0 | |
| for ln in LEDGER.read_text(encoding="utf-8").splitlines(): | |
| if not ln.strip(): | |
| continue | |
| e = json.loads(ln); n += 1 | |
| body = {k: e.get(k) for k in FIELDS} | |
| h = hashlib.sha256((prev + json.dumps(body, sort_keys=True)).encode()).hexdigest() | |
| if e.get("hash") != h or e.get("prev_hash") != prev or \ | |
| hmac.new(_key(), h.encode(), hashlib.sha256).hexdigest() != e.get("sig"): | |
| return False, n | |
| prev = h | |
| return True, n | |
Xet Storage Details
- Size:
- 2.43 kB
- Xet hash:
- 583926937cbe8585a879e77dd6c3fdde9fa48d8552e1d476511147f8dc10b424
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.