interplane.Get Omega
Read in your language

aien-train

AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.

Brought by drakestapleton

branch main Branches Tags History

aien-train / eval / omegese45 / oe_an0.py

350 lines · 13077 bytes Raw Blame History
1"""Eval-owned readers for the Aienet-0 job path artifacts (aien-train #45).
2
3Written from aien-protocols e705fdc9, not from any #45 lane's code:
4 specs/microjob/SPEC.md sections 4 and 5 (MJB1 document, MJR1 receipt),
5 specs/aienet/jobpath/PROFILE.md (AN0B bundle, AN0V countersignature,
6 matmul_u32 payload and digest), crates/aien-microjob/src/{lib.rs,aienet0.rs}
7 (byte offsets, domains), crates/aien-provenance/src/lib.rs:215-248
8 (ECDSA P-256 / SHA-256, raw r||s, low-S only, SEC1 compressed keys).
9
10Python standard library only. P-256 verification is implemented here from the
11SEC 1 / FIPS 186 definitions; tests cross-check it against real Rust-signed
12artifacts and, when importable, the `cryptography` package.
13"""
14
15import hashlib
16import struct
17
18# ---------------------------------------------------------------- P-256
19P = 2**256 - 2**224 + 2**192 + 2**96 - 1
20A = P - 3
21B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
22GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
23GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
24N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
25
26
27def _on_curve(pt):
28 if pt is None:
29 return True
30 x, y = pt
31 return (y * y - (x * x * x + A * x + B)) % P == 0
32
33
34def _add(p1, p2):
35 if p1 is None:
36 return p2
37 if p2 is None:
38 return p1
39 x1, y1 = p1
40 x2, y2 = p2
41 if x1 == x2:
42 if (y1 + y2) % P == 0:
43 return None
44 lam = (3 * x1 * x1 + A) * pow(2 * y1, -1, P) % P
45 else:
46 lam = (y2 - y1) * pow(x2 - x1, -1, P) % P
47 x3 = (lam * lam - x1 - x2) % P
48 return (x3, (lam * (x1 - x3) - y1) % P)
49
50
51def _mul(k, pt):
52 acc = None
53 while k:
54 if k & 1:
55 acc = _add(acc, pt)
56 pt = _add(pt, pt)
57 k >>= 1
58 return acc
59
60
61G = (GX, GY)
62
63
64def curve_self_test():
65 """G on the curve and of order N (catches a mistyped constant)."""
66 return _on_curve(G) and _mul(N, G) is None and _mul(N - 1, G) == (GX, P - GY)
67
68
69def decompress(key33):
70 if len(key33) != 33 or key33[0] not in (2, 3):
71 raise ValueError("public key is not SEC1 compressed")
72 x = int.from_bytes(key33[1:], "big")
73 if x >= P:
74 raise ValueError("x out of range")
75 y2 = (x * x * x + A * x + B) % P
76 y = pow(y2, (P + 1) // 4, P) # P = 3 mod 4
77 if y * y % P != y2:
78 raise ValueError("x not on curve")
79 if (y & 1) != (key33[0] & 1):
80 y = P - y
81 return (x, y)
82
83
84def verify_low_s(key33, message, sig64):
85 """(ok, reason). Mirrors p256_verify_low_s: high-S is refused."""
86 try:
87 q = decompress(bytes(key33))
88 except ValueError as e:
89 return False, "bad key: %s" % e
90 if len(sig64) != 64:
91 return False, "signature length"
92 r = int.from_bytes(sig64[:32], "big")
93 s = int.from_bytes(sig64[32:], "big")
94 if not (1 <= r < N and 1 <= s < N):
95 return False, "r or s out of range"
96 if s > N // 2:
97 return False, "high-S signature"
98 e = int.from_bytes(hashlib.sha256(message).digest(), "big")
99 w = pow(s, -1, N)
100 pt = _add(_mul(e * w % N, G), _mul(r * w % N, q))
101 if pt is None:
102 return False, "point at infinity"
103 if pt[0] % N != r:
104 return False, "signature does not verify"
105 return True, "ok"
106
107
108def crypto_crosscheck(key33, message, sig64):
109 """Optional cross-check with the `cryptography` package: True/False, or
110 None when the package is not importable."""
111 try:
112 from cryptography.exceptions import InvalidSignature
113 from cryptography.hazmat.primitives import hashes
114 from cryptography.hazmat.primitives.asymmetric import ec
115 from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
116 except ImportError:
117 return None
118 try:
119 pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), bytes(key33))
120 der = encode_dss_signature(int.from_bytes(sig64[:32], "big"), int.from_bytes(sig64[32:], "big"))
121 pub.verify(der, bytes(message), ec.ECDSA(hashes.SHA256()))
122 return True
123 except (InvalidSignature, ValueError):
124 return False
125
126
127# ---------------------------------------------------------------- matmul_u32
128MATMUL_DOMAIN = b"AIEN-HETJOB-MATMUL-U32-V1"
129MASK64 = (1 << 64) - 1
130MASK32 = (1 << 32) - 1
131
132
133def matmul_u32_digest(m, k, n, seed):
134 """PROFILE.md 'The job': A (m x k) then B (k x n) from splitmix64(seed),
135 each truncated to u32; C = A x B mod 2^32; SHA-256(domain || m || k || n
136 || seed || C as u32 BE row-major)."""
137 s = seed & MASK64
138 vals = []
139 for _ in range(m * k + k * n):
140 s = (s + 0x9E3779B97F4A7C15) & MASK64
141 z = s
142 z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK64
143 z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK64
144 vals.append((z ^ (z >> 31)) & MASK32)
145 a = vals[: m * k]
146 b = vals[m * k:]
147 cols = [b[q::n] for q in range(n)]
148 h = hashlib.sha256()
149 h.update(MATMUL_DOMAIN + struct.pack(">HHHQ", m, k, n, seed & MASK64))
150 out = bytearray()
151 for i in range(m):
152 row = a[i * k:(i + 1) * k]
153 for col in cols:
154 out += (sum(map(int.__mul__, row, col)) & MASK32).to_bytes(4, "big")
155 h.update(bytes(out))
156 return h.digest()
157
158
159# ---------------------------------------------------------------- records
160def sha(*parts):
161 h = hashlib.sha256()
162 for p in parts:
163 h.update(p)
164 return h.digest()
165
166
167class Bad(Exception):
168 pass
169
170
171def need(cond, msg):
172 if not cond:
173 raise Bad(msg)
174
175
176BUNDLE_HEAD = 4 + 1 + 1 + 2 + 4 + 33 + 64
177SUBMIT_DOMAIN = b"AIENET0-MJB1-SUBMIT-V1\x00"
178VERIFY_DOMAIN = b"AIENET0-MJR1-VERIFY-V1\x00"
179VERDICT_DOMAIN = b"AIENET0-RECOMPUTE-MATCH-V1\x00"
180HEADER_LEN = 192
181NODE_LEN = 448
182RECEIPT_LEN = 404
183RECEIPT_SIGNED_LEN = 340
184VERDICT_SIGNED_LEN = 172
185VERDICT_LEN = 236
186
187
188def parse_bundle(b):
189 need(len(b) >= BUNDLE_HEAD and b[:4] == b"AN0B", "AN0B magic/length")
190 need(b[4] == 1 and b[5] == 0, "AN0B version/reserved")
191 plen, dlen = struct.unpack(">HI", b[6:12])
192 need(plen <= 256 and BUNDLE_HEAD + plen + dlen == len(b), "AN0B lengths")
193 payload = b[BUNDLE_HEAD:BUNDLE_HEAD + plen]
194 return {"key": b[12:45], "sig": b[45:109], "payload": payload, "document": b[BUNDLE_HEAD + plen:]}
195
196
197def parse_payload(p):
198 need(len(p) == 15 and p[0] == 1, "payload is not matmul_u32 (kind 1, 15 bytes)")
199 m, k, n, seed = struct.unpack(">HHHQ", p[1:15])
200 return m, k, n, seed
201
202
203def parse_document(d):
204 """The fields of SPEC.md 4.1/4.2 that bind a profile document to its job."""
205 need(len(d) >= HEADER_LEN and d[:4] == b"MJB1" and d[4] == 1, "MJB1 magic/version")
206 (count,) = struct.unpack(">H", d[6:8])
207 need(len(d) == HEADER_LEN + count * NODE_LEN, "MJB1 length")
208 need(count == 1, "profile document has exactly one node")
209 nd = d[HEADER_LEN:HEADER_LEN + NODE_LEN]
210 ops = []
211 for s in range(nd[55]):
212 at = 288 + 40 * s
213 ops.append({"kind": nd[at], "generation": struct.unpack(">I", nd[at + 4:at + 8])[0], "digest": nd[at + 8:at + 40]})
214 return {
215 "expires_at": struct.unpack(">Q", d[144:152])[0],
216 "job_id": nd[0:16],
217 "idem": nd[16:32],
218 "generation": struct.unpack(">I", nd[32:36])[0],
219 "kind": nd[36],
220 "op": nd[37],
221 "verifier_kind": nd[48],
222 "dep_count": nd[54],
223 "work": struct.unpack(">Q", nd[80:88])[0],
224 "operands": ops,
225 }
226
227
228def parse_receipt(r):
229 need(len(r) == RECEIPT_LEN and r[:4] == b"MJR1" and r[4] == 1, "MJR1 length/magic/version")
230 need(r[7] == 0 and r[84:88] == b"\0" * 4 and r[337:340] == b"\0" * 3, "MJR1 reserved bytes")
231 need(1 <= r[5] <= 5 and r[6] != 0, "MJR1 outcome/attempt")
232 need(r[304] in (2, 3), "MJR1 signer key prefix")
233 completed = r[5] == 1
234 zero = lambda x: x == b"\0" * len(x)
235 need(completed != zero(r[144:176]), "MJR1 output_digest zero rule")
236 need(not (completed and zero(r[272:304])), "MJR1 verifier_verdict zero rule")
237 need(not zero(r[176:208]) and not zero(r[240:272]), "MJR1 source/policy hash zero")
238 return {
239 "outcome": r[5],
240 "attempt": r[6],
241 "dag_digest": r[8:40],
242 "job_id": r[40:56],
243 "idem": r[56:72],
244 "generation": struct.unpack(">I", r[72:76])[0],
245 "used_work": struct.unpack(">Q", r[104:112])[0],
246 "input_binding": r[112:144],
247 "output_digest": r[144:176],
248 "verdict": r[272:304],
249 "signer": r[304:337],
250 "sig": r[340:404],
251 }
252
253
254def parse_countersign(v):
255 need(len(v) == VERDICT_LEN and v[:4] == b"AN0V" and v[4] == 1, "AN0V length/magic/version")
256 need(v[5:8] == b"\0\0\0" and v[169:172] == b"\0\0\0", "AN0V reserved bytes")
257 return {
258 "receipt_sha": v[8:40],
259 "dag_digest": v[40:72],
260 "recomputed": v[72:104],
261 "commit": v[104:136],
262 "key": v[136:169],
263 "sig": v[172:236],
264 }
265
266
267def input_binding(operands):
268 h = hashlib.sha256(b"MJR1-BIND")
269 for o in operands:
270 h.update(bytes([o["kind"]]) + struct.pack(">I", o["generation"]) + o["digest"])
271 return h.digest()
272
273
274def check_triple(an0b, mjr1, mjv, submitter, executor, verifier, crosscheck=True):
275 """Independent re-check of one stored (bundle, receipt, countersignature).
276
277 Returns a list of (name, status, detail) with status PASS/FAIL/NOT_RUN and
278 the job (m, k, n, seed) or None. `mjv` may be None (no countersignature
279 written, e.g. a failed verification); then the AN0V checks are NOT_RUN.
280 """
281 out = []
282
283 def rec(name, ok, detail=""):
284 out.append((name, "PASS" if ok else "FAIL", detail))
285 return ok
286
287 job = None
288 try:
289 bd = parse_bundle(an0b)
290 job = parse_payload(bd["payload"])
291 doc = parse_document(bd["document"])
292 except Bad as e:
293 rec("an0b.parse", False, str(e))
294 return out, None
295 rec("an0b.parse", True, "m=%d k=%d n=%d seed=%d" % job)
296 dag = sha(bd["document"])
297 rec("an0b.submitter_pin", bd["key"] == submitter, bd["key"].hex())
298 ok, why = verify_low_s(bd["key"], SUBMIT_DOMAIN + dag + sha(bd["payload"]), bd["sig"])
299 rec("an0b.submitter_sig", ok, why)
300 rec("mjb1.allowlisted_shape", doc["kind"] == 1 and doc["op"] == 2 and doc["verifier_kind"] == 1
301 and doc["dep_count"] == 0 and len(doc["operands"]) == 1, "kind=%d op=%d" % (doc["kind"], doc["op"]))
302 rec("mjb1.payload_binding", len(doc["operands"]) == 1 and doc["operands"][0]["kind"] == 3
303 and doc["operands"][0]["digest"] == sha(bd["payload"])) # operand::CONTENT = 3 (lib.rs:98)
304 m, k, n, seed = job
305 rec("mjb1.work_cap", doc["work"] >= m * k * n, "work=%d" % doc["work"])
306 if mjr1 is None:
307 out.append(("mjr1.present", "FAIL", "no receipt file"))
308 return out, job
309 try:
310 r = parse_receipt(mjr1)
311 except Bad as e:
312 rec("mjr1.parse", False, str(e))
313 return out, job
314 rec("mjr1.parse", True, "outcome=%d attempt=%d" % (r["outcome"], r["attempt"]))
315 rec("mjr1.dag_binding", r["dag_digest"] == dag, dag.hex())
316 rec("mjr1.node_binding", r["job_id"] == doc["job_id"] and r["idem"] == doc["idem"]
317 and r["generation"] == doc["generation"])
318 rec("mjr1.input_binding", r["input_binding"] == input_binding(doc["operands"]))
319 rec("mjr1.executor_pin", r["signer"] == executor, r["signer"].hex())
320 ok, why = verify_low_s(r["signer"], mjr1[:RECEIPT_SIGNED_LEN], r["sig"])
321 rec("mjr1.signature", ok, why)
322 if crosscheck:
323 cc = crypto_crosscheck(r["signer"], mjr1[:RECEIPT_SIGNED_LEN], r["sig"])
324 if cc is None:
325 out.append(("mjr1.signature_crosscheck", "NOT_RUN", "cryptography not importable"))
326 else:
327 rec("mjr1.signature_crosscheck", cc == ok, "cryptography=%s" % cc)
328 rec("mjr1.completed", r["outcome"] == 1, "outcome=%d" % r["outcome"])
329 want = matmul_u32_digest(m, k, n, seed)
330 rec("recompute.output_digest", r["output_digest"] == want, "eval=%s" % want.hex())
331 # Internal bindings use the receipt's own digest; the independent recompute above
332 # is the single comparison against the truth. Conjoined with it this accepts
333 # exactly what binding to `want` would, and a forged-but-consistent receipt
334 # fails one check only: recompute.output_digest.
335 commit = sha(VERDICT_DOMAIN, dag, r["job_id"], r["output_digest"])
336 rec("mjr1.verdict_commitment", r["verdict"] == commit)
337 if mjv is None:
338 out.append(("an0v.present", "NOT_RUN", "no countersignature file"))
339 return out, job
340 try:
341 v = parse_countersign(mjv)
342 except Bad as e:
343 rec("an0v.parse", False, str(e))
344 return out, job
345 rec("an0v.receipt_binding", v["receipt_sha"] == sha(mjr1) and v["dag_digest"] == dag)
346 rec("an0v.recompute_binding", v["recomputed"] == r["output_digest"] and v["commit"] == commit)
347 rec("an0v.verifier_pin", v["key"] == verifier, v["key"].hex())
348 ok, why = verify_low_s(v["key"], VERIFY_DOMAIN + mjv[:VERDICT_SIGNED_LEN], v["sig"])
349 rec("an0v.signature", ok, why)
350 return out, job