#!/usr/bin/env python3
"""Check a Stamp receipt on your own machine.

  python3 verify.py st_0123456789abcdef            # checks the signature
  python3 verify.py st_0123456789abcdef my-file    # also checks that my-file has the stamped digest

It downloads the receipt and the public key, rebuilds the signed text itself and
verifies the Ed25519 signature (needs: pip install cryptography). The Bitcoin
proof is checked separately, with the standard OpenTimestamps client:
  ots verify -f my-file st_0123456789abcdef.ots
"""
import hashlib
import json
import sys
import urllib.request

BASE = "https://paywithprompt.com"


def fetch(path):
    with urllib.request.urlopen(BASE + path, timeout=20) as resp:
        return json.loads(resp.read().decode("utf-8"))


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return 2
    receipt = fetch("/stamp/api/v1/receipts/" + sys.argv[1])["receipt"]
    key = fetch("/stamp/api/v1/key")
    text = "\n".join([key["statement"], receipt["id"], receipt["sha256"], receipt["time"]])
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    except ImportError:
        print("pip install cryptography, then run again")
        return 2
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(key["public_key"])).verify(
            bytes.fromhex(receipt["signature"]), text.encode()
        )
    except Exception:
        print("BAD SIGNATURE")
        return 1
    print("signature ok:", receipt["sha256"], "seen at", receipt["time"])
    if len(sys.argv) > 2:
        digest = hashlib.sha256(open(sys.argv[2], "rb").read()).hexdigest()
        if digest != receipt["sha256"]:
            print("FILE DOES NOT MATCH: its digest is", digest)
            return 1
        print("file matches the receipt")
    print("bitcoin:", receipt["bitcoin"]["status"], receipt["bitcoin"].get("block") or "")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
