honesty-index / verify.py
Enerzy17's picture
Publish the Honesty Index: advertised versus realized APY for synthetic dollars
0eff826 verified
Raw
History Blame Contribute Delete
8.83 kB
#!/usr/bin/env python3
"""
Independently verify a Kerne Honesty Index snapshot.
The whole point of this dataset is that you do not have to take its word for
anything, so this script takes nothing on trust either. It checks, in order:
1. The attestation hash is really sha256 of the published canonical payload.
2. The EIP-191 signature really recovers to the published signer address.
3. The CSV in this repo really agrees with the snapshot JSON beside it.
4. Optionally, the live endpoint still verifies too.
Usage
-----
python verify.py # check the files in this repo
python verify.py --live # also fetch and check the live endpoint
Step 2 needs `eth_account` (`pip install eth-account`). Without it the script
still runs and reports step 2 as SKIPPED rather than silently passing, because
an unchecked signature reported as a tick is worse than no check at all.
Exit code is 0 only if every check that ran passed.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import os
import sys
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
SNAPSHOT = os.path.join(HERE, "snapshot", "honesty-index-api-response.json")
CURRENT_CSV = os.path.join(HERE, "data", "current.csv")
LIVE_URL = "https://kerne.fi/api/honesty-index"
OK, FAIL, SKIP = "PASS", "FAIL", "SKIP"
results: list[tuple[str, str, str]] = []
def report(name: str, status: str, detail: str = "") -> None:
results.append((name, status, detail))
print(" [%s] %s%s" % (status, name, (" " + detail) if detail else ""))
def fetch_live() -> dict | None:
"""Fetch the live snapshot, or explain why not and return None.
A verification script that dies with a traceback on a network hiccup has
told the reader nothing, so this reports and keeps going. The explicit
User-Agent matters: the default urllib one is refused by the edge in front
of the API, which looks exactly like the endpoint being down.
"""
req = urllib.request.Request(
LIVE_URL,
headers={"User-Agent": "kerne-honesty-index-verify/1.0 (+https://kerne.fi/honesty-index)",
"Accept": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode("utf-8"))
except Exception as exc: # noqa: BLE001 - any failure here is reportable, not fatal
print(" could not fetch the live endpoint: %s" % exc)
print(" the checks against the files in this repo above are unaffected.")
return None
def check_hash(snap: dict) -> bool:
"""attestation_hash == "0x" + sha256(utf8(signed_payload_canonical))."""
canonical = snap.get("signed_payload_canonical")
claimed = snap.get("attestation_hash")
if not canonical or not claimed:
report("attestation hash", FAIL, "snapshot carries no canonical payload or no hash")
return False
# Hash the PUBLISHED BYTES. Re-serializing the JSON would change key order
# or spacing and the hash would not match; that is not a bug, it is the
# check working.
computed = "0x" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()
if computed == claimed:
report("attestation hash", OK, claimed)
return True
report("attestation hash", FAIL, "computed %s, published %s" % (computed, claimed))
return False
def check_signature(snap: dict) -> bool:
"""EIP-191 personal_sign over the RAW 32 BYTES of the attestation hash."""
try:
from eth_account import Account
from eth_account.messages import encode_defunct
except ImportError:
report("signature -> signer", SKIP, "pip install eth-account to run this check")
return True
signature = snap.get("signature")
signer = snap.get("signer")
digest = snap.get("attestation_hash")
if not (signature and signer and digest):
report("signature -> signer", FAIL, "snapshot is missing signature, signer or hash")
return False
# Note the shape: the signed message is the 32 raw bytes of the hash, NOT
# the hex string of it. Signing the string instead is the usual mistake.
message = encode_defunct(primitive=bytes.fromhex(digest[2:]))
recovered = Account.recover_message(message, signature=signature)
if recovered.lower() == signer.lower():
report("signature -> signer", OK, recovered)
return True
report("signature -> signer", FAIL, "recovered %s, published %s" % (recovered, signer))
return False
def check_csv_matches(snap: dict) -> bool:
"""The CSV in this repo must describe the same snapshot as the JSON."""
if not os.path.exists(CURRENT_CSV):
report("csv agrees with snapshot", SKIP, "data/current.csv not found")
return True
with open(CURRENT_CSV, newline="", encoding="utf-8") as fh:
rows = list(csv.DictReader(fh))
snap_rows = {r["key"]: r for r in snap.get("rows", [])}
if len(rows) != len(snap_rows):
report("csv agrees with snapshot", FAIL, "%d csv rows vs %d snapshot rows" % (len(rows), len(snap_rows)))
return False
problems = []
for row in rows:
key = row["key"]
if key not in snap_rows:
problems.append("%s is in the csv but not the snapshot" % key)
continue
if row["snapshot_attestation_hash"] != snap.get("attestation_hash"):
problems.append("%s carries a different attestation hash" % key)
if row["snapshot_generated_at"] != snap.get("generated_at"):
problems.append("%s carries a different generated_at" % key)
realized = snap_rows[key].get("realized") or {}
if realized.get("ok") and row["realized_apy_pct"]:
if abs(float(row["realized_apy_pct"]) - float(realized["annualizedPct"])) > 1e-6:
problems.append("%s realized apy disagrees" % key)
# A blank must never have been written as a zero. This is the single
# most damaging thing this file could get wrong about a third party.
if row["comparability"] != "direct" and row["gap_pp"] != "":
problems.append("%s states a gap it is not entitled to state" % key)
if problems:
report("csv agrees with snapshot", FAIL, "; ".join(problems[:5]))
return False
report("csv agrees with snapshot", OK, "%d rows, hashes and gaps consistent" % len(rows))
return True
def check_blank_not_zero(snap: dict) -> bool:
"""No row may publish a gap of exactly 0 where it meant 'not comparable'."""
if not os.path.exists(CURRENT_CSV):
report("blanks are blank, not zero", SKIP, "data/current.csv not found")
return True
with open(CURRENT_CSV, newline="", encoding="utf-8") as fh:
rows = list(csv.DictReader(fh))
stated = [r for r in rows if r["gap_pp"] != ""]
blank = [r for r in rows if r["gap_pp"] == ""]
bad = [r["key"] for r in blank if r["comparability"] == "direct" and r["realized_ok"] == "true"]
if bad:
report("blanks are blank, not zero", FAIL, "comparable rows with no gap: %s" % ", ".join(bad))
return False
report("blanks are blank, not zero", OK, "%d rows state a gap, %d correctly do not" % (len(stated), len(blank)))
return True
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--live", action="store_true", help="also fetch and verify the live endpoint")
args = parser.parse_args()
if not os.path.exists(SNAPSHOT):
print("Cannot find %s" % SNAPSHOT, file=sys.stderr)
return 2
with open(SNAPSHOT, encoding="utf-8") as fh:
snap = json.load(fh)
print("Snapshot in this repo: %s" % snap.get("generated_at"))
check_hash(snap)
check_signature(snap)
check_csv_matches(snap)
check_blank_not_zero(snap)
if args.live:
print("\nLive endpoint: %s" % LIVE_URL)
live = fetch_live()
if live is None:
report("live endpoint", SKIP, "could not be fetched, see the message above")
else:
print("Live snapshot: %s" % live.get("generated_at"))
check_hash(live)
check_signature(live)
if live.get("generated_at") != snap.get("generated_at"):
print("\n NOTE: the live snapshot is newer than this repo's copy. That is expected.")
print(" The live endpoint is always correct; this repo is a lagging mirror.")
failed = [r for r in results if r[1] == FAIL]
skipped = [r for r in results if r[1] == SKIP]
print("\n%d checks, %d failed, %d skipped." % (len(results), len(failed), len(skipped)))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())