idea70-narrativeweave-real-.../idea70_narrativeweave_real_.../ledger.py

36 lines
1.0 KiB
Python

import hashlib
import json
from typing import Optional
class SimpleLedger:
"""A minimal tamper-evident hash chain for blocks.
Each anchor is SHA256(prev_anchor || block_json). Stored externally (here we return the anchor).
"""
def __init__(self):
self.last_anchor = None
def anchor(self, block_json: str) -> str:
m = hashlib.sha256()
if self.last_anchor:
m.update(self.last_anchor.encode())
m.update(block_json.encode())
anchor = m.hexdigest()
self.last_anchor = anchor
return anchor
def verify_chain(self, block_jsons: list, anchors: list) -> bool:
"""Verify that anchors are consistent with the provided block_jsons sequence."""
prev = None
for bj, a in zip(block_jsons, anchors):
m = hashlib.sha256()
if prev:
m.update(prev.encode())
m.update(bj.encode())
if m.hexdigest() != a:
return False
prev = a
return True