Hash-chained event log
Browse files- freestream/events.py +90 -0
freestream/events.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hash-chained, append-only session event log (see docs/SPEC-EVENTS.md).
|
| 2 |
+
|
| 3 |
+
Every session produces a verifiable artifact: each entry records the hash
|
| 4 |
+
of the previous entry, so any later tampering is detectable by
|
| 5 |
+
`freestream-log --verify` or `EventLog(path).verify()`.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
GENESIS_HASH = "0" * 64
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def canonical(obj) -> str:
|
| 18 |
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _hash_entry(seq: int, ts: float, etype: str, payload: dict, prev: str) -> str:
|
| 22 |
+
material = canonical({"seq": seq, "ts": ts, "type": etype,
|
| 23 |
+
"payload": payload, "prev": prev})
|
| 24 |
+
return hashlib.sha256(material.encode("utf-8")).hexdigest()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class EventLog:
|
| 28 |
+
"""Append-only JSONL log with SHA-256 hash chaining."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, path: str | Path):
|
| 31 |
+
self.path = Path(path)
|
| 32 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
self._seq = 0
|
| 34 |
+
self._prev = GENESIS_HASH
|
| 35 |
+
if self.path.exists():
|
| 36 |
+
self._load()
|
| 37 |
+
|
| 38 |
+
def _load(self) -> None:
|
| 39 |
+
ok, first_bad = self.verify()
|
| 40 |
+
if not ok:
|
| 41 |
+
raise ValueError(f"event log {self.path} fails hash-chain verification "
|
| 42 |
+
f"at seq {first_bad}; refusing to append")
|
| 43 |
+
with self.path.open("r", encoding="utf-8") as f:
|
| 44 |
+
last = None
|
| 45 |
+
for line in f:
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if line:
|
| 48 |
+
last = json.loads(line)
|
| 49 |
+
if last:
|
| 50 |
+
self._seq = last["seq"]
|
| 51 |
+
self._prev = last["hash"]
|
| 52 |
+
|
| 53 |
+
def append(self, etype: str, **payload) -> dict:
|
| 54 |
+
import time
|
| 55 |
+
entry = {
|
| 56 |
+
"seq": self._seq + 1,
|
| 57 |
+
"ts": time.time(),
|
| 58 |
+
"type": etype,
|
| 59 |
+
"payload": payload,
|
| 60 |
+
"prev": self._prev,
|
| 61 |
+
}
|
| 62 |
+
entry["hash"] = _hash_entry(entry["seq"], entry["ts"], etype, payload, self._prev)
|
| 63 |
+
with self.path.open("a", encoding="utf-8") as f:
|
| 64 |
+
f.write(json.dumps(entry, sort_keys=True) + "\n")
|
| 65 |
+
self._seq += 1
|
| 66 |
+
self._prev = entry["hash"]
|
| 67 |
+
return entry
|
| 68 |
+
|
| 69 |
+
def verify(self) -> tuple[bool, int | None]:
|
| 70 |
+
"""Returns (ok, first_bad_seq). ok=True means the whole chain holds."""
|
| 71 |
+
if not self.path.exists():
|
| 72 |
+
return True, None
|
| 73 |
+
prev = GENESIS_HASH
|
| 74 |
+
with self.path.open("r", encoding="utf-8") as f:
|
| 75 |
+
for line in f:
|
| 76 |
+
line = line.strip()
|
| 77 |
+
if not line:
|
| 78 |
+
continue
|
| 79 |
+
e = json.loads(line)
|
| 80 |
+
expected = _hash_entry(e["seq"], e["ts"], e["type"], e["payload"], e["prev"])
|
| 81 |
+
if e["prev"] != prev or e["hash"] != expected:
|
| 82 |
+
return False, e["seq"]
|
| 83 |
+
prev = e["hash"]
|
| 84 |
+
return True, None
|
| 85 |
+
|
| 86 |
+
def events(self) -> list[dict]:
|
| 87 |
+
if not self.path.exists():
|
| 88 |
+
return []
|
| 89 |
+
with self.path.open("r", encoding="utf-8") as f:
|
| 90 |
+
return [json.loads(line) for line in f if line.strip()]
|