File size: 8,543 Bytes
ad19be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""node65 - MANY PLACES (Oracle7 6.5): parts move between places, and no place takes another's word for one. No language model.

A PACKET (what a place publishes for one admitted part)
  the part's signature (inputs, output), the formula it was solved into, the system it came from with its source (a Wikidata
  defining-formula entry), the place it was built at, and a hash over all of it.
RECEIVING (every check runs at the receiving place, on its own copy of the operation library)
  1. HASH        the packet's hash must match its contents
  2. SOURCE      the system must be the one the receiver's own library holds for that Wikidata entry, symbol for symbol
  3. RE-DERIVE   the receiver's maths organ solves that system itself; one of its parts must have the packet's signature,
                 and its formula must equal the packet's at 12 points across three orders of magnitude (1e-9)
  4. FRESH EXAM  12 questions at values the receiver draws (its own seed), each answered with the PACKET's formula and
                 checked against the system re-solved numerically (SymPy nsolve) - not the formula itself
  A part that fails any check is refused, with the reason; one that passes is admitted at the receiving place.
DELIVERY       before an answer leaves a place, every step of its plan is re-solved from that step's own system at the
               values used; an answer whose step disagrees (1e-6) is withheld and declined.
usage (a receiving place): node65.py verify <library derived.json> <packets.jsonl> <seed> <out.json>"""
from __future__ import annotations

import hashlib
import json
import math
import random
import sys
from pathlib import Path

import sympy as sp

import systems


def _canon(x):
    return json.dumps(x, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def packet_hash(body):
    return hashlib.sha256(_canon(body).encode("utf-8")).hexdigest()


def make_packet(local, pid, place):
    """a published packet for an admitted maths-organ part of a workspace"""
    d = Path(local) / "specialists" / pid
    spec = json.loads((d / "spec.json").read_text(encoding="utf-8"))
    sysd = spec["system"]
    src = (spec.get("composer"), json.loads((d / "manifest.json").read_text(encoding="utf-8")).get("sources", [{}])[0].get("name", ""))
    title = spec["title"]
    import re
    m = re.search(r"\(Wikidata (Q\d+)\)", title)
    wid = m.group(1) if m else None
    body = {"place": place, "part": pid, "wikidata": wid, "inputs": spec["inputs"], "output": spec["output"],
            "symbols": sysd["symbols"], "out_symbol": sysd["out_symbol"], "expression": spec["expression"],
            "system": {"equations": sysd["equations"], "quantities": sysd["quantities"], "constants": sysd.get("constants") or {}},
            "built_by": src[0]}
    return {"body": body, "hash": packet_hash(body)}


def _fn(symbols, expr):
    syms = [sp.Symbol(n, positive=True) for n in symbols]
    e = sp.sympify(expr, locals=dict(zip(symbols, syms)))
    return sp.lambdify(syms, e, "math")


def verify(packet, library, seed):
    """-> {"admit": bool, "why": str or None, "checks": {...}} at the receiving place"""
    body, checks = packet.get("body") or {}, {}
    # 1. hash
    checks["hash"] = packet_hash(body) == packet.get("hash")
    if not checks["hash"]:
        return {"admit": False, "why": "the hash does not match the packet's contents", "checks": checks}
    # 2. source: the receiver's own library entry for that Wikidata formula
    lib = library.get(body.get("wikidata"))
    if lib is None:
        return {"admit": False, "why": "no entry %s in this place's library" % body.get("wikidata"), "checks": checks}
    mine = {"equations": lib["equations"], "quantities": lib["quantities"], "constants": lib.get("constants") or {}}
    checks["source"] = _canon(mine) == _canon(body["system"])
    if not checks["source"]:
        return {"admit": False, "why": "the system differs from this place's copy of Wikidata %s" % body["wikidata"], "checks": checks}
    # 3. re-derive here
    r = systems.derive(dict(mine, title="re-derive"))
    match = [p for p in r.get("parts", []) if not p.get("why") and p["output"] == body["output"]
             and sorted(p["inputs"]) == sorted(body["inputs"])]
    if not match:
        return {"admit": False, "why": "this place's maths organ derives no part with that signature", "checks": checks}
    p = match[0]
    order = [body["inputs"].index(x) for x in p["inputs"]]
    mine_fn, theirs = _fn(p["symbols"], p["expression"]), _fn(body["symbols"], body["expression"])
    rng = random.Random(seed)
    agree = real = 0
    for _ in range(24):                                    # points where both formulas give a real value; at least 8
        if real >= 12:
            break
        xs = [10 ** rng.uniform(-0.5, 2.5) for _ in body["inputs"]]
        try:
            a, b = mine_fn(*[xs[i] for i in order]), theirs(*xs)
        except (ValueError, ZeroDivisionError, OverflowError, TypeError):
            continue
        if isinstance(a, complex) or isinstance(b, complex) or not math.isfinite(a):
            continue                                       # outside the quantities' domain (all positive): not a point
        real += 1
        agree += int(abs(a - b) <= 1e-9 * max(1.0, abs(a)))
    checks["re_derived_agree"] = [agree, real]
    if real < 8 or agree < real:
        return {"admit": False, "why": "the formula differs from this place's own derivation (%d of %d points agree)" % (agree, real), "checks": checks}
    # 4. a fresh exam: the packet's formula against the system re-solved numerically, at this place's values
    S = systems.System(dict(mine, title="exam"))
    out = S.sym[body["out_symbol"]]
    ok = n = 0
    for _ in range(24):
        if n >= 12:
            break
        xs = [float("%.4g" % 10 ** rng.uniform(-0.5, 2.5)) for _ in body["inputs"]]
        try:
            y = theirs(*xs)
        except (ValueError, ZeroDivisionError, OverflowError, TypeError):
            continue
        if isinstance(y, complex) or not math.isfinite(y):
            continue
        sub = {S.sym[s]: x * S.scale[S.sym[s]] for s, x in zip(body["symbols"], xs)}
        eq = [e.xreplace(sub) for e in S.si]
        try:
            root = float(sp.nsolve(eq[0], out, y * S.scale[out] if y > 0 else 1.0, tol=1e-20, prec=40))
        except Exception:  # noqa: BLE001
            continue
        n += 1
        ok += int(abs(root / S.scale[out] - y) <= 1e-6 * max(1e-300, abs(y)))
    checks["exam"] = [ok, n]
    if n < 8 or ok < n:
        return {"admit": False, "why": "the fresh exam: %d of %d right" % (ok, n), "checks": checks}
    return {"admit": True, "why": None, "checks": checks}


def library_index(derived):
    return {s["wikidata"]: s for s in derived["systems"] if not s.get("refused")}


def deliver_check(step_records, library):
    """re-solve every step of a plan at the values it used, from the step's own system: [(packet body, args, y)] -> ok, why"""
    for body, args, y in step_records:
        lib = library.get(body.get("wikidata"))
        if lib is None:
            return False, "no system for a step"
        S = systems.System({"title": "deliver", "equations": lib["equations"], "quantities": lib["quantities"],
                            "constants": lib.get("constants") or {}})
        out = S.sym[body["out_symbol"]]
        sub = {S.sym[s]: x * S.scale[S.sym[s]] for s, x in zip(body["symbols"], args)}
        resid = [e.xreplace(dict(sub, **{out: y * S.scale[out]})) for e in S.si]
        for e, r in zip(S.si, resid):
            terms = [abs(float(t.xreplace(dict(sub, **{out: y * S.scale[out]})))) for t in sp.Add.make_args(sp.expand(e))]
            if abs(float(r)) > 1e-6 * max(1.0, max(terms or [1.0])):
                return False, "a step does not satisfy its own equation at the values used"
    return True, None


if __name__ == "__main__" and sys.argv[1] == "verify":
    lib = library_index(json.load(open(sys.argv[2], encoding="utf-8")))
    seed = int(sys.argv[4])
    out = []
    for k, line in enumerate(open(sys.argv[3], encoding="utf-8")):
        pk = json.loads(line)
        v = verify(pk, lib, seed + k)
        out.append({"hash": pk.get("hash"), "part": (pk.get("body") or {}).get("part"), "place": (pk.get("body") or {}).get("place"),
                    "tamper": pk.get("tamper"), **v})
    json.dump(out, open(sys.argv[5], "w", encoding="utf-8"), indent=1)
    print("verified", len(out), "admitted", sum(1 for x in out if x["admit"]))