#!/usr/bin/env python3
# SPDX-License-Identifier: CC0-1.0
"""Recomputes the identifiers, hashes and arithmetic of the Test Cases from the files next to it.

Uses the Python standard library only (Keccak-256 is implemented below; hashlib's sha3_256 is a different
function). Run from anywhere:

    python3 vectors/verify.py

It checks, against the vector files of this directory and the documents under ../examples:

- Keccak-256 itself (known answers for "" and "abc");
- the canonicalization vector (JCS string and boundaryHash);
- profile, interest, descriptor-kind and denomination identifiers, and the methodId of every method descriptor;
- the elementId and relationId vectors, and the relationId of every identity relation of the examples;
- the interface identifiers of Section 15 (XOR of the function selectors), with each function name found in the
  interface source;
- the EIP-712 type hash, domain type hash, struct hash, example domain separator and digest, and the payload hash
  of the example valuation core;
- the boundaryHash of every example Unit Definition and the contentHash of every example assertion document;
- the five valuation vectors with the 18-decimal truncating arithmetic of AUFValuationLib.sol.

JCS (RFC 8785) is applied in the restricted form that these documents need: no floating-point numbers, integers
within 2^53 and object keys within the Basic Multilingual Plane, for which RFC 8785 coincides with sorted-key,
whitespace-free JSON with RFC 8259 string escaping. The script refuses documents outside that form.
"""

import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)  # the asset directory of the proposal

# ----------------------------------------------------------------------------- Keccak-256

_RC = [
    0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
    0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
    0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
    0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
    0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
    0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
]
_ROT = [
    [0, 36, 3, 41, 18],
    [1, 44, 10, 45, 2],
    [62, 6, 43, 15, 61],
    [28, 55, 25, 21, 56],
    [27, 20, 39, 8, 14],
]
_MASK = (1 << 64) - 1


def _rol(x, n):
    return ((x << n) | (x >> (64 - n))) & _MASK if n else x


def _keccak_f(a):
    for rc in _RC:
        c = [a[x][0] ^ a[x][1] ^ a[x][2] ^ a[x][3] ^ a[x][4] for x in range(5)]
        d = [c[(x - 1) % 5] ^ _rol(c[(x + 1) % 5], 1) for x in range(5)]
        a = [[a[x][y] ^ d[x] for y in range(5)] for x in range(5)]
        b = [[0] * 5 for _ in range(5)]
        for x in range(5):
            for y in range(5):
                b[y][(2 * x + 3 * y) % 5] = _rol(a[x][y], _ROT[x][y])
        a = [[b[x][y] ^ ((~b[(x + 1) % 5][y]) & b[(x + 2) % 5][y]) for y in range(5)] for x in range(5)]
        a[0][0] ^= rc
    return a


def keccak256(data):
    rate = 136
    msg = bytearray(data) + b"\x01"
    while len(msg) % rate:
        msg += b"\x00"
    msg[-1] |= 0x80
    a = [[0] * 5 for _ in range(5)]
    for off in range(0, len(msg), rate):
        block = msg[off:off + rate]
        for i in range(rate // 8):
            a[i % 5][i // 5] ^= int.from_bytes(block[8 * i:8 * i + 8], "little")
        a = _keccak_f(a)
    return b"".join(a[i % 5][i // 5].to_bytes(8, "little") for i in range(4))


def h(data):
    if isinstance(data, str):
        data = data.encode("utf-8")
    return "0x" + keccak256(data).hex()


# ----------------------------------------------------------------------------- JCS (restricted, see module docstring)

def _check_jcs(o):
    if o is None or isinstance(o, (bool, str)):
        return
    if isinstance(o, float):
        raise ValueError("floating-point number outside the restricted JCS form")
    if isinstance(o, int):
        if abs(o) > 2 ** 53:
            raise ValueError("integer outside the IEEE 754 safe range")
        return
    if isinstance(o, list):
        for x in o:
            _check_jcs(x)
        return
    if isinstance(o, dict):
        for k, v in o.items():
            if any(ord(ch) > 0xFFFF for ch in k):
                raise ValueError("object key outside the Basic Multilingual Plane")
            _check_jcs(v)
        return
    raise TypeError("unsupported JSON value")


def jcs(o):
    _check_jcs(o)
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def canonical_hash(o):
    return h(jcs(o))


# ----------------------------------------------------------------------------- ABI words (static types only)

def word(v):
    if isinstance(v, str) and v.startswith("0x"):
        b = bytes.fromhex(v[2:])
        return b.rjust(32, b"\x00") if len(b) < 32 else b
    n = int(v)
    return (n % (1 << 256)).to_bytes(32, "big")


def address_word(addr):
    return bytes.fromhex(addr[2:].lower()).rjust(32, b"\x00")


# ----------------------------------------------------------------------------- checks

FAILURES = []
COUNT = [0]


def check(label, got, want):
    COUNT[0] += 1
    if str(got).lower() != str(want).lower():
        FAILURES.append(f"{label}: computed {got}, file says {want}")


def load(*parts):
    with open(os.path.join(ROOT, *parts), "r", encoding="utf-8") as f:
        return json.load(f)


def sdiv(a, b):
    """Integer division truncating toward zero, as Solidity's signed division."""
    q = abs(a) // abs(b)
    return q if (a >= 0) == (b > 0) else -q


def two_decimals(wad):
    """Round an 18-decimal value half away from zero to two decimals, as the Test Cases display it."""
    cents = sdiv(abs(wad) * 100 + 5 * 10 ** 17, 10 ** 18) * (1 if wad >= 0 else -1)
    sign = "-" if cents < 0 else ""
    return f"{sign}{abs(cents) // 100}.{abs(cents) % 100:02d}"


# Canonical signatures of the functions of the two interfaces (Section 4 and Section 11), excluding
# supportsInterface. Enums and structs appear as their ABI types (uint8 and tuples).
INTERFACES = {
    "IAUFUnitRegistry": (
        "interfaces/IAUFUnitRegistry.sol",
        [
            "registerUnit(address,bytes32,string,(uint256,uint32)[])",
            "publishVersion(uint256,bytes32,string,(uint256,uint32)[])",
            "setController(uint256,address)",
            "acknowledge(uint256,uint32,bytes32,uint8)",
            "withdrawAcknowledgment(uint256,uint32,bytes32,uint8)",
            "unitCount()",
            "latestVersion(uint256)",
            "controllerOf(uint256)",
            "isFrozen(uint256)",
            "versionOf(uint256,uint32)",
            "containedAt(uint256,uint32,uint256)",
            "acknowledgedAt(uint256,uint32,bytes32,uint8,address)",
        ],
    ),
    "IAUFAssertionRegistry": (
        "interfaces/IAUFAssertionRegistry.sol",
        [
            "unitRegistry()",
            "registerDescriptor(bytes32,bytes32,string)",
            "descriptorOf(bytes32)",
            "assertStatement((uint8,uint256,uint32,bytes32,bytes32,string,uint64,uint64,bytes32,bytes))",
            "assertStatementBySig((uint8,uint256,uint32,bytes32,bytes32,string,uint64,uint64,bytes32,bytes),address,uint256,bytes)",
            "revoke(bytes32)",
            "assertionOf(bytes32)",
            "assertionCount(uint256,uint32)",
            "assertionAt(uint256,uint32,uint256)",
            "valuationCoreOf(bytes32)",
            "observationCoreOf(bytes32)",
            "nonces(address)",
            "DOMAIN_SEPARATOR()",
        ],
    ),
}


def main():
    # Keccak-256 known answers
    check("keccak256('')", h(b""), "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
    check("keccak256('abc')", h(b"abc"), "0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")

    # canonicalization vector
    c = load("vectors", "canonicalization.json")
    check("canonicalization: JCS string", jcs(c["input"]), c["canonical"])
    check("canonicalization: boundaryHash", canonical_hash(c["input"]), c["boundaryHash"])

    # identifiers
    ids = load("vectors", "identifiers.json")
    for name, value in ids["profileIds"].items():
        check(f"profileId {name}", h(name), value)
    for name, value in ids["descriptorKinds"].items():
        check(f"descriptorKind {name}", h(name), value)
    for name, value in ids["denominationIds"].items():
        check(f"denominationId {name}", h(name), value)
    for name, entry in ids["methodIds"].items():
        doc = load("vectors", entry["file"])
        check(f"methodId {name} (name in descriptor)", doc["name"], name)
        check(f"methodId {name}", canonical_hash(doc), entry["methodId"])
    ex = ids["elementIdExample"]
    check("elementId vector: preimage", f"{ex['kind']}:{ex['ref']}", ex["preimage"])
    check("elementId vector", h(f"{ex['kind']}:{ex['ref']}"), ex["elementId"])
    rx = ids["relationIdExample"]
    check("relationId vector: JCS string", jcs(rx["relation"]), rx["jcs"])
    check("relationId vector", canonical_hash(rx["relation"]), rx["relationId"])

    # interface identifiers
    iids = load("vectors", "interface-ids.json")
    for name, (src, sigs) in INTERFACES.items():
        with open(os.path.join(ROOT, "contracts", src), "r", encoding="utf-8") as f:
            source = f.read()
        acc = 0
        for sig in sigs:
            fn = sig.split("(")[0]
            if f"function {fn}(" not in source:
                FAILURES.append(f"{name}: function {fn} not found in contracts/{src}")
            acc ^= int.from_bytes(keccak256(sig.encode())[:4], "big")
        check(f"interface id {name}", f"0x{acc:08x}", iids[name])
    check("interface id IERC165", "0x" + keccak256(b"supportsInterface(bytes4)")[:4].hex(), iids["IERC165"])

    # EIP-712
    e = load("vectors", "eip712.json")
    check("EIP-712 typeHash", h(e["typeString"]), e["typeHash"])
    check("EIP-712 domainTypeHash", h("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), e["domainTypeHash"])
    check("EIP-712 nameHash", h("AUFAssertionRegistry"), e["nameHash"])
    check("EIP-712 versionHash", h("1"), e["versionHash"])
    core = e["valuationCore"]
    payload = b"".join(word(core[k]) for k in ("methodId", "interestId", "assessmentBoundaryHash", "snapshotHash", "resultKind", "decimals", "value", "denominationId", "asOf", "horizonEnd"))
    check("EIP-712 example payload (abi.encode(ValuationCore))", "0x" + payload.hex(), e["payload"])
    i = e["input"]
    check("EIP-712 example payloadHash", h(payload), i["payloadHash"])
    struct = keccak256(
        bytes.fromhex(e["typeHash"][2:])
        + word(i["kind"]) + word(i["unitId"]) + word(i["version"]) + word(i["profileId"]) + word(i["contentHash"])
        + keccak256(i["contentURI"].encode()) + word(i["validFrom"]) + word(i["validUntil"]) + word(i["supersedes"])
        + word(i["payloadHash"]) + word(i["nonce"]) + word(i["deadline"])
    )
    check("EIP-712 structHash", "0x" + struct.hex(), e["structHash"])
    d = e["exampleDomain"]
    ds = keccak256(
        bytes.fromhex(e["domainTypeHash"][2:]) + keccak256(d["name"].encode()) + keccak256(d["version"].encode())
        + word(d["chainId"]) + address_word(d["verifyingContract"])
    )
    check("EIP-712 example domain separator", "0x" + ds.hex(), e["exampleDomainSeparator"])
    check("EIP-712 example digest", h(b"\x19\x01" + ds + struct), e["exampleDigest"])

    # worked examples
    exm = load("vectors", "examples.json")
    for u in exm["units"]:
        doc = load(u["file"])
        check(f"boundaryHash unit {u['unitId']} ({u['file']})", canonical_hash(doc), u["boundaryHash"])
        rels = [r for r in doc.get("relations", []) if r.get("type") in ("same-claim", "distinct-claim")]
        found = {canonical_hash(r) for r in rels}
        for dcl in u.get("declarations", []):
            check(f"relationId in unit {u['unitId']}", dcl["relationId"] in found, True)
        if "v2" in u:
            check(f"boundaryHash unit {u['unitId']} v2", canonical_hash(load(u["v2"]["file"])), u["v2"]["boundaryHash"])
            for dcl in u["v2"].get("declarations", []):
                v2rels = {canonical_hash(r) for r in load(u["v2"]["file"]).get("relations", []) if r.get("type") in ("same-claim", "distinct-claim")}
                check(f"relationId in unit {u['unitId']} v2", dcl["relationId"] in v2rels, True)
        for comp in u.get("companions", []):
            cdoc = load("examples", comp["file"])
            check(f"contentHash {comp['file']}", canonical_hash(cdoc), comp["contentHash"])
            if comp["kind"] == "valuation":
                co = comp["core"]
                check(f"methodId of {comp['file']}", cdoc["method"]["id"], co["methodId"])
                check(f"interestId of {comp['file']}", h(cdoc["interest"]["id"]), co["interestId"])
                if cdoc["result"].get("denomination"):
                    check(f"denominationId of {comp['file']}", h(cdoc["result"]["denomination"]), co["denominationId"])

    # valuation vectors (18 decimals, truncating division, as AUFValuationLib.sol)
    wad = 10 ** 18
    vv = {v["name"]: v for v in load("vectors", "valuation-vectors.json")["vectors"]}
    fp = vv["net-equity"]["fixedPoint"]
    r = sum(int(x) for x in fp["assetsWad"]) - sum(int(x) for x in fp["liabilitiesWad"])
    check("net equity (wad)", r, vv["net-equity"]["expected"]["valueWad"])
    check("net equity", two_decimals(r), vv["net-equity"]["expected"]["value"])
    fp = vv["realized-net-cash-flow"]["fixedPoint"]
    r = sum(int(x) for x in fp["inflowsWad"]) - sum(int(x) for x in fp["outflowsWad"])
    check("realized net cash flow (wad)", r, vv["realized-net-cash-flow"]["expected"]["valueWad"])
    check("realized net cash flow", two_decimals(r), vv["realized-net-cash-flow"]["expected"]["value"])
    fp = vv["finite-horizon-dcf"]["fixedPoint"]
    factor, r = wad, 0
    for cf in fp["cashflowsWad"]:
        factor = factor * wad // (wad + int(fp["rateWad"]))
        r += sdiv(int(cf) * factor, wad)
    r += sdiv(int(fp["terminalValueWad"]) * factor, wad)
    check("finite-horizon DCF (wad)", r, vv["finite-horizon-dcf"]["expected"]["valueWad"])
    check("finite-horizon DCF", two_decimals(r), vv["finite-horizon-dcf"]["expected"]["value"])
    for name in ("conditional-payoff", "conditional-payoff-obligation"):
        fp = vv[name]["fixedPoint"]
        expectation = sum(sdiv(int(x) * int(p), wad) for x, p in zip(fp["payoffsWad"], fp["probabilitiesWad"]))
        check(f"{name}: probabilities sum to one", sum(int(p) for p in fp["probabilitiesWad"]), wad)
        factor = wad
        for _ in range(int(fp["periods"])):
            factor = factor * wad // (wad + int(fp["rateWad"]))
        r = sdiv(expectation * factor, wad)
        check(f"{name} (wad)", r, vv[name]["expected"]["valueWad"])
        check(name, two_decimals(r), vv[name]["expected"]["value"])

    if FAILURES:
        for line in FAILURES:
            print("FAIL " + line)
        print(f"{len(FAILURES)} of {COUNT[0]} checks failed")
        return 1
    print(f"all {COUNT[0]} checks passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())
