#!/usr/bin/env python3 """Checks a pillar's promise log (https://kamiforge.com/promises.html#verify) with Python's standard library alone. python3 promises-verify.py a # fetches https://promises.kamiforge.com/a/keys.json and log.jsonl python3 promises-verify.py d --hashes # prints each line's SHA-256 too (keep the last one to compare later) python3 promises-verify.py a --log log.jsonl --keys keys.json # files you saved For each line it checks, in order: 1. the signature: the line's body is the line with its last member ,"sig":"..." cut out (the text before it, then "}"); sig is the Ed25519 signature (base64) of the body's UTF-8 bytes by the key named in "key"; 2. "seq" counts 0, 1, 2, ... and "day" goes up by exactly one day per line; 3. "prev" is the SHA-256 (hex) of the previous line's bytes (without the newline); the first line's is 64 zeros. A changed, removed or inserted line fails at that line. It exits 0 when every line holds, 1 otherwise. """ import base64 import datetime import hashlib import json import sys import urllib.request BASE = 'https://promises.kamiforge.com' GENESIS = '0' * 64 # --- Ed25519 verification (RFC 8032, section 5.1.7) ----------------------------------------------------------------- P = 2 ** 255 - 19 L = 2 ** 252 + 27742317777372353535851937790883648493 D = -121665 * pow(121666, P - 2, P) % P SQRT_M1 = pow(2, (P - 1) // 4, P) def _recover_x(y, sign): xx = (y * y - 1) * pow(D * y * y + 1, P - 2, P) % P x = pow(xx, (P + 3) // 8, P) if (x * x - xx) % P: x = x * SQRT_M1 % P if (x * x - xx) % P: return None if x == 0 and sign: return None if x & 1 != sign: x = P - x return x def _add(a, b): x1, y1, z1, t1 = a x2, y2, z2, t2 = b aa = (y1 - x1) * (y2 - x2) % P bb = (y1 + x1) * (y2 + x2) % P cc = t1 * 2 * D * t2 % P dd = z1 * 2 * z2 % P e, f, g, h = bb - aa, dd - cc, dd + cc, bb + aa return (e * f % P, g * h % P, f * g % P, e * h % P) def _mul(s, pt): q = (0, 1, 1, 0) while s: if s & 1: q = _add(q, pt) pt = _add(pt, pt) s >>= 1 return q def _decode(b): if len(b) != 32: return None y = int.from_bytes(b, 'little') sign = y >> 255 y &= (1 << 255) - 1 if y >= P: return None x = _recover_x(y, sign) return None if x is None else (x, y, 1, x * y % P) def _encode(pt): x, y, z, _ = pt zi = pow(z, P - 2, P) x, y = x * zi % P, y * zi % P return (y | ((x & 1) << 255)).to_bytes(32, 'little') _BY = 4 * pow(5, P - 2, P) % P _BASE_POINT = (_recover_x(_BY, 0), _BY, 1, _recover_x(_BY, 0) * _BY % P) def ed25519_verify(public, msg, sig): if len(sig) != 64: return False a, r = _decode(public), _decode(sig[:32]) s = int.from_bytes(sig[32:], 'little') if a is None or r is None or s >= L: return False h = int.from_bytes(hashlib.sha512(sig[:32] + public + msg).digest(), 'little') % L return _encode(_mul(s, _BASE_POINT)) == _encode(_add(r, _mul(h, a))) # --- the log --------------------------------------------------------------------------------------------------------- def body_of(line): marker = ',"sig":"' if not line.endswith('"}') or marker not in line: return None, None at = line.rfind(marker) return line[:at] + '}', line[at + len(marker):-2] def verify(pillar, log_text, keys): prev, last_day, n, hashes = GENESIS, None, 0, [] lines = log_text[:-1].split('\n') if log_text.endswith('\n') else log_text.split('\n') if lines == ['']: lines = [] for i, line in enumerate(lines): where = f'line {i}' body, sig = body_of(line) if body is None: return False, f'{where}: no signature at the end', hashes try: o = json.loads(body) except ValueError as e: return False, f'{where}: not JSON ({e})', hashes if 'sig' in o or o.get('v') != 1 or o.get('pillar') != pillar: return False, f'{where}: not a version 1 line of pillar {pillar}', hashes public = keys.get(o.get('key')) if public is None: return False, f'{where}: unknown key {o.get("key")!r}', hashes if not ed25519_verify(base64.b64decode(public), body.encode('utf-8'), base64.b64decode(sig)): return False, f'{where}: the signature does not match', hashes if o.get('seq') != i: return False, f'{where}: seq out of order', hashes if o.get('prev') != prev: return False, f'{where}: prev is not the hash of the line before', hashes day = datetime.date.fromisoformat(o.get('day', '')) if last_day is not None and day != last_day + datetime.timedelta(days=1): return False, f'{where}: {day} does not follow {last_day}', hashes prev, last_day, n = hashlib.sha256(line.encode('utf-8')).hexdigest(), day, n + 1 s = o.get('summary', {}) hashes.append((o['day'], prev, s)) return True, f'{n} lines hold' + (f', the last is {last_day}' if last_day else ''), hashes def fetch(url): req = urllib.request.Request(url, headers={'User-Agent': 'promises-verify'}) with urllib.request.urlopen(req, timeout=30) as r: return r.read().decode('utf-8') def main(argv): if not argv or argv[0] not in ('a', 'd', 'e', 'f', 'g'): print(__doc__) return 2 pillar = argv[0] opt = lambda name: argv[argv.index(name) + 1] if name in argv else None log_text = open(opt('--log'), encoding='utf-8').read() if opt('--log') else fetch(f'{BASE}/{pillar}/log.jsonl') keys_text = open(opt('--keys'), encoding='utf-8').read() if opt('--keys') else fetch(f'{BASE}/{pillar}/keys.json') keys = {k['id']: k['public'] for k in json.loads(keys_text).get('keys', [])} # a key's id is the first 16 hex digits of SHA-256 of the raw public key for kid, public in keys.items(): if hashlib.sha256(base64.b64decode(public)).hexdigest()[:16] != kid: print(f'NG: keys.json: the id {kid} is not the hash of its public key') return 1 ok, why, hashes = verify(pillar, log_text, keys) if '--hashes' in argv: for day, h, s in hashes: print(f'{day} {h} kept {s.get("kept")} broken {s.get("broken")} unmeasured {s.get("unmeasured")}') print(('OK: ' if ok else 'NG: ') + why) return 0 if ok else 1 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))