#!/usr/bin/env python3
"""Check the btc-signal public record. Needs only Python 3 and nothing else.

    python3 verify_record.py https://<site address>

It downloads the record, recomputes every fingerprint, and compares each sealed text with the
reading the site shows. To check the Bitcoin timestamps, download a head file and its proof from
the Record page and verify them with the OpenTimestamps tool or at https://opentimestamps.org.

    fingerprint = SHA-256( previous fingerprint + "\\n" + sealed text ); the first previous one is 64 zeros
"""
import hashlib
import json
import sys
import urllib.request

GENESIS = "0" * 64
FIELDS = ("timeframe", "bar_date", "published_at", "version", "score", "parts", "trend_label", "trend_position",
          "label", "position", "funding_f7", "funding_on")


def fingerprint(prev, text):
    return hashlib.sha256((prev + "\n" + text).encode()).hexdigest()


def check_chain(seals):
    """Problems in the chain of seals (dictionaries as the data feed gives them)."""
    problems, prev = [], GENESIS
    for n, s in enumerate(seals, start=1):
        if s["seq"] != n:
            problems.append("seal %s: expected number %s" % (s["seq"], n))
        if s["prev"] != prev:
            problems.append("seal %s: does not follow the seal before it" % s["seq"])
        if fingerprint(s["prev"], s["text"]) != s["fingerprint"]:
            problems.append("seal %s: fingerprint does not match its text" % s["seq"])
        prev = s["fingerprint"]
    return problems


def check_readings(seals, readings):
    """Problems between the sealed texts and the readings the site shows."""
    problems = []
    sealed = {(s["timeframe"], s["bar_date"]): json.loads(s["text"]) for s in seals}
    for r in readings:
        key = (r["timeframe"], r["bar_date"])
        if key not in sealed:
            problems.append("%s reading for %s has no seal" % key)
        elif sealed[key] != {k: r[k] for k in FIELDS}:
            problems.append("%s reading for %s differs from its sealed text" % key)
    return problems


def get(url):
    request = urllib.request.Request(url, headers={"User-Agent": "btc-signal-verify"})
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read().decode())


def main(base):
    base = base.rstrip("/")
    record = get(base + "/api/v1/record.json")
    readings = []
    for timeframe in ("daily", "weekly"):
        readings += get(base + "/api/v1/readings.json?timeframe=%s&limit=1000" % timeframe)["readings"]
    seals = record["seals"]
    problems = check_chain(seals) + check_readings(seals, readings)
    complete = [a for a in record["anchors"] if a["status"] == "complete"]
    print("%d seals, %d readings compared, %d of %d proofs complete" % (len(seals), len(readings), len(complete), len(record["anchors"])))
    if seals:
        print("newest fingerprint: %s (seal %s)" % (seals[-1]["fingerprint"], seals[-1]["seq"]))
    for p in problems:
        print("PROBLEM: " + p)
    print("The record is intact." if not problems else "The record does NOT check out.")
    return 1 if problems else 0


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    sys.exit(main(sys.argv[1]))
