File size: 12,440 Bytes
5d12f8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Protocol Company
"""Recompute the cryptographic proof of every answer in the Edges dataset, from the dataset alone.

    python3 scripts/verify_rows.py                 # every row of data/cards.jsonl and data/solvers.jsonl
    python3 scripts/verify_rows.py data/cards.jsonl --id edge-0123456789ab

Nothing is sent anywhere and nothing but the Python standard library is used. For each row
the script recomputes, from the answer text the row holds:

  a run       link_0 from the request, the chain of recorded frames, the state digest,
              the run seal and the receipt;
  a solution  the six seal parts, the solution seal and the receipt;

and then holds the row's own columns to its two requests and two answers: the two requests
differ in the one input the row names, the values and their exact hex are the ones sent, the
width is their difference, and the stop name, the outcomes, the proofs and the engine version
are the ones the answers carry. An answer that is a sentence (a request stopped before any
computing) carries no proof; the script confirms the row claims none.

The rules are those of the engine's published reference, restated in VERIFY.md of
https://github.com/johnkruze/zero-trust-physics. Exit code 0: every row holds. 1: one does not.
"""
import hashlib
import json
import os
import re
import struct
import sys

NAME = re.compile(r"\(([A-Z][A-Za-z0-9]+)\)")


def sha(data):
    return hashlib.sha256(data if isinstance(data, bytes) else data.encode("utf-8")).hexdigest()


def fhex(x):
    return struct.pack(">d", float(x)).hex()


def string_text(s):
    return json.dumps(s, ensure_ascii=False)


def sealed_form(v):
    """The text a request is hashed in: keys sorted by their bytes, a number as x and its 64 bits."""
    if v is True:
        return "true"
    if v is False:
        return "false"
    if v is None:
        return "null"
    if isinstance(v, (int, float)):
        return "x" + fhex(v)
    if isinstance(v, str):
        return string_text(v)
    if isinstance(v, list):
        return "[" + ",".join(sealed_form(x) for x in v) + "]"
    if isinstance(v, dict):
        keys = sorted(v, key=lambda k: k.encode("utf-8"))
        return "{" + ",".join(string_text(k) + ":" + sealed_form(v[k]) for k in keys) + "}"
    raise ValueError("no sealed form for %r" % type(v))


def receipt_holds(text):
    marker = ',"receipt_sha256":"'
    at = text.rfind(marker)
    tail = text[at + len(marker):]
    if at < 0 or len(tail) != 66 or not tail.endswith('"}'):
        return False
    return tail[:64] == sha(text[:at] + "}")


def verify_run(text, request):
    """Returns a list of what does not hold in a run_trajectory answer; empty when all holds."""
    bad = []
    plain = json.loads(text)
    exact = json.loads(text, parse_int=float)
    sent = {k: v for k, v in json.loads(request, parse_int=float).items() if k not in ("readout", "from")}
    link = sha(sealed_form(exact["inputs"]))
    if sha(sealed_form(sent)) != link:
        bad.append("the answer's inputs are not the request sent")
    for frame in plain["frames"]:
        data = bytes.fromhex(frame["frame_hex"])
        if len(data) != 64 or data[48:64] != bytes.fromhex(link)[:16]:
            bad.append("proof slot of the frame of step %s" % frame["step"])
            break
        link = sha(data)
        if link != frame["link"]:
            bad.append("link of the frame of step %s" % frame["step"])
            break
    state, digest = plain["final_state"], None
    if plain["steps_landed"] and state is not None:
        lines = []
        for key in sorted(state, key=lambda k: k.encode("utf-8")):
            value = state[key]
            if isinstance(value, bool):
                lines.append("%s:%s\n" % (key, "true" if value else "false"))
            elif key.endswith("_hex"):
                lines.append("%s:%s\n" % (key, ",".join(value) if isinstance(value, list) else value))
        lines.append("final_residual_conservation_error_hex:%s\n" % plain["final_residual_conservation_error_hex"])
        lines.append("max_residual_conservation_error_hex:%s\n" % plain["max_residual_conservation_error_hex"])
        digest = sha("".join(lines))
    if digest != plain["state_digest"]:
        bad.append("state_digest")
    tail = json.dumps({"outcome": plain["outcome"], "steps_landed": plain["steps_landed"],
                       "reject": plain["reject"], "state_digest": digest}, separators=(",", ":"), ensure_ascii=False)
    if sha(link + tail) != plain["run_seal"]:
        bad.append("run_seal")
    if not receipt_holds(text):
        bad.append("receipt")
    return bad


def hex_item(v):
    return "[" + ",".join(hex_item(x) for x in v) + "]" if isinstance(v, list) else v


def hex_lines(section, name):
    if section is None:
        return ""
    return "".join("%s.%s:%s\n" % (name, k, hex_item(section[k]))
                   for k in sorted(section, key=lambda k: k.encode("utf-8")) if k.endswith("_hex"))


def verify_solution(text, request):
    """Returns a list of what does not hold in a solve answer; empty when all holds."""
    bad = []
    plain = json.loads(text)
    exact = json.loads(text, parse_int=float)
    sent = json.loads(request, parse_int=float)
    parts = [
        ("inputs", sealed_form(exact["inputs"])),
        ("engine_version", "engine_version:%s\n" % plain["engine_version"]),
        ("invariants", hex_lines(plain.get("invariants"), "invariants")),
        ("result", hex_lines(plain.get("result"), "result")),
        ("field_sha256", plain["field_sha256"] if plain.get("field_sha256") else "null"),
        ("outcome", json.dumps({"outcome": plain["outcome"], "iterations": plain["iterations"], "reject": plain["reject"]},
                               separators=(",", ":"), ensure_ascii=False)),
    ]
    if "parameters" in sent and sha(sealed_form(sent)) != sha(parts[0][1]):
        bad.append("the answer's inputs are not the request sent")
    for name, part in parts:
        if plain["seal_parts"].get(name) != sha(part):
            bad.append("seal part " + name)
    if sha("".join(part for _, part in parts)) != plain["solution_seal"]:
        bad.append("solution_seal")
    if not receipt_holds(text):
        bad.append("receipt")
    return bad


def leaves(node, path=""):
    if isinstance(node, dict):
        for k, v in node.items():
            yield from leaves(v, path + ("." if path else "") + k)
    elif isinstance(node, list):
        for i, v in enumerate(node):
            yield from leaves(v, "%s[%d]" % (path, i))
    else:
        yield path, node


def check_row(row):
    bad = []
    run = row["tool"] == "run_trajectory"
    verify = verify_run if run else verify_solution
    seal = "run_seal" if run else "solution_seal"
    if row["proof_kind"] != seal:
        bad.append("proof_kind")

    # the inside answer always stands and always carries a proof
    try:
        bad += ["inside: " + b for b in verify(row["inside_answer"], row["inside_request"])]
        inside = json.loads(row["inside_answer"])
    except (ValueError, KeyError, TypeError) as e:
        return bad + ["inside answer not read: %r" % e]
    if inside[seal] != row["inside_proof"] or inside["receipt_sha256"] != row["inside_receipt"]:
        bad.append("inside proof columns")
    if inside["outcome"] != row["inside_outcome"] or inside["outcome"] not in ("completed", "ended", "converged"):
        bad.append("inside_outcome")
    if inside["engine_version"] != row["engine_version"]:
        bad.append("engine_version")

    # the outside answer is a sealed result, or a sentence with no proof
    try:
        outside = json.loads(row["outside_answer"])
        outside = outside if isinstance(outside, dict) and "outcome" in outside else None
    except ValueError:
        outside = None
    if outside is None:
        names = NAME.findall(row["outside_answer"])
        if row["outside_proof"] is not None or row["outside_receipt"] is not None:
            bad.append("a proof is claimed for a request stopped before any computing")
        if row["stop_name"] != (names[-1] if names else None) or row["stop_sentence"] != row["outside_answer"]:
            bad.append("stop_name or stop_sentence is not the answer's")
        if not row["outside_answer_is_error"] or row["edge_kind"] != "declared_limit":
            bad.append("edge_kind")
    else:
        bad += ["outside: " + b for b in verify(row["outside_answer"], row["outside_request"])]
        if outside[seal] != row["outside_proof"] or outside["receipt_sha256"] != row["outside_receipt"]:
            bad.append("outside proof columns")
        if outside["outcome"] != row["outside_outcome"]:
            bad.append("outside_outcome")
        if row["edge_kind"] == "declared_limit":
            if outside["outcome"] != "refused" or outside["reject"] != row["stop_name"] or outside["reject_detail"] != row["stop_sentence"]:
                bad.append("stop columns")
        elif row["edge_kind"] == "declared_end":
            ended = outside if outside["outcome"] == "ended" else inside
            if ended["outcome"] != "ended" or ended["reject"] != row["stop_name"] or ended["reject_detail"] != row["stop_sentence"]:
                bad.append("stop columns")
        elif row["edge_kind"] == "outcome_flip":
            if (outside["outcome"], outside["reject"]) != (inside["outcome"], inside["reject"]) or not row["flip"]:
                bad.append("flip")
        else:
            bad.append("edge_kind")
    if run:
        if inside["steps_landed"] != row["inside_steps_landed"] or (outside["steps_landed"] if outside else None) != row["outside_steps_landed"]:
            bad.append("steps_landed columns")

    # the two requests differ in the one input the row names, by the values the row states
    a = dict(leaves(json.loads(row["inside_request"], parse_int=float)))
    b = dict(leaves(json.loads(row["outside_request"], parse_int=float)))
    differ = [k for k in a if a[k] != b.get(k) or (isinstance(a[k], float) and fhex(a[k]) != fhex(b[k]))]
    pattern = re.escape(row["input"]).replace(r"\[\*\]", r"\[\d+\]")
    if set(a) != set(b) or not differ or any(not re.fullmatch(pattern, k) for k in differ):
        bad.append("the requests do not differ in the named input alone: %s" % differ)
    else:
        if any(fhex(a[k]) != row["inside_value_hex"] or fhex(b[k]) != row["outside_value_hex"] for k in differ):
            bad.append("value hex")
    vi = struct.unpack(">d", bytes.fromhex(row["inside_value_hex"]))[0]
    vo = struct.unpack(">d", bytes.fromhex(row["outside_value_hex"]))[0]
    if vi != row["inside_value"] or vo != row["outside_value"] or abs(vo - vi) != row["width"]:
        bad.append("value decimals or width")
    if not row["whole_number_input"]:
        def order(h):
            n = int(h, 16)
            return n if n < 1 << 63 else -(n - (1 << 63)) - 1
        if (abs(order(row["inside_value_hex"]) - order(row["outside_value_hex"])) == 1) != row["adjacent_64_bit_numbers"]:
            bad.append("adjacent_64_bit_numbers")
    return bad


def main(argv):
    here = os.path.dirname(os.path.abspath(__file__))
    only = None
    if "--id" in argv:
        at = argv.index("--id")
        only = argv[at + 1]
        argv = argv[:at] + argv[at + 2:]
    files = argv or [os.path.join(here, "..", "data", "cards.jsonl"), os.path.join(here, "..", "data", "solvers.jsonl")]
    total = held = proofs = 0
    for path in files:
        n = ok = 0
        with open(path, encoding="utf-8") as f:
            for line in f:
                if not line.strip():
                    continue
                row = json.loads(line)
                if only and row["id"] != only:
                    continue
                n += 1
                bad = check_row(row)
                proofs += 1 + (row["outside_proof"] is not None)
                if bad:
                    print("%s  %s  %s: %s" % (row["id"], row["model"], row["input"], "; ".join(bad)))
                else:
                    ok += 1
        print("%s: %d of %d rows hold" % (os.path.basename(path), ok, n))
        total += n
        held += ok
    print("result: %d of %d rows hold; %d proofs recomputed" % (held, total, proofs))
    return 0 if held == total and total else 1


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