interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / turing / ty_qrecord.c

714 lines · 30254 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* TURING companion records for continuous-value evidence. See ty_qrecord.h. */
18#define _POSIX_C_SOURCE 200809L
19#include "turing/ty_qrecord.h"
20
21#include "omega_canonical.h"
22#include "sha256.h"
23
24#include <errno.h>
25#include <fcntl.h>
26#include <inttypes.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <unistd.h>
31
32/* ------------------------------------------------------------------------
33 * Builder helpers ob_new, ob_text, ob_u64, ob_i64, ob_digest and ob_finish
34 * are copied from src/turing/ty_record.c (same OMG0 layout rules as
35 * src/turing/field.c). Changes: the builder also carries a refusal reason,
36 * and ob_finish can hand back the canonical bytes. ty_record.c is unchanged.
37 * ---------------------------------------------------------------------- */
38typedef struct {
39 OmegaObject *o;
40 int err;
41 char why[160];
42} obj_b;
43
44static void ob_fail(obj_b *b, const char *fmt, const char *key) {
45 if (b->err) return;
46 b->err = 1;
47 snprintf(b->why, sizeof b->why, fmt, key);
48}
49
50static void ob_text(obj_b *b, const char *key, const char *val) {
51 if (b->err) return;
52 size_t kl = strlen(key), vl = strlen(val);
53 if (b->o->attr_count >= OMEGA_MAX_ATTRIBUTES || kl >= OMEGA_MAX_KEY_LEN || vl > OMEGA_MAX_VAL_LEN) {
54 ob_fail(b, "attribute %s: too many attributes, key >= 64 bytes or value > 512 bytes", key);
55 return;
56 }
57 OmegaAttribute *a = &b->o->attributes[b->o->attr_count++];
58 memcpy(a->key, key, kl + 1);
59 memcpy(a->value, val, vl);
60 a->val_len = (uint16_t)vl;
61}
62
63static void ob_u64(obj_b *b, const char *key, uint64_t v) {
64 char t[24];
65 snprintf(t, sizeof t, "%" PRIu64, v);
66 ob_text(b, key, t);
67}
68
69static void ob_i64(obj_b *b, const char *key, int64_t v) {
70 char t[24];
71 snprintf(t, sizeof t, "%" PRId64, v);
72 ob_text(b, key, t);
73}
74
75static void ob_digest(obj_b *b, const char *key, const ty_digest *d) {
76 char h[65];
77 ty_hex(d, h);
78 ob_text(b, key, h);
79}
80
81static int ob_new(obj_b *b, SemanticKind kind, const char *record) {
82 b->err = 0;
83 b->why[0] = 0;
84 b->o = calloc(1, sizeof(OmegaObject));
85 if (!b->o) return -1;
86 b->o->kind = kind;
87 ob_text(b, "record", record);
88 return 0;
89}
90
91/* bytes/blen may be NULL. */
92static int ob_finish(obj_b *b, const char *domain, ty_digest *out, uint8_t *bytes, size_t bcap, size_t *blen) {
93 int rc = TY_E_FORMAT;
94 uint8_t *buf = NULL;
95 size_t n = 0;
96 if (!b->o || b->err) goto done;
97 buf = malloc(TYQR_CANON_CAP);
98 if (!buf) goto done;
99 if (omega_canonical_encode(b->o, buf, TYQR_CANON_CAP, &n) != 0) {
100 snprintf(b->why, sizeof b->why, "canonical encoding failed");
101 goto done;
102 }
103 sha256_ctx c;
104 sha256_init(&c);
105 sha256_update(&c, (const uint8_t *)domain, strlen(domain) + 1); /* includes the 0x00 separator */
106 sha256_update(&c, buf, n);
107 sha256_final(&c, out->b);
108 if (bytes) {
109 if (n > bcap) goto done;
110 memcpy(bytes, buf, n);
111 *blen = n;
112 }
113 rc = TY_OK;
114done:
115 free(buf);
116 free(b->o);
117 b->o = NULL;
118 return rc;
119}
120
121/* ------------------------------------------------------- field validation */
122
123static int is_zero(const ty_digest *d) {
124 for (int i = 0; i < 32; ++i)
125 if (d->b[i]) return 0;
126 return 1;
127}
128
129/* NUL-terminated within `cap` bytes, length 1..512, printable ASCII. */
130static int text_ok(const char *s, size_t cap) {
131 const char *z = memchr(s, 0, cap);
132 if (!z) return 0;
133 size_t n = (size_t)(z - s);
134 if (n < 1 || n > OMEGA_MAX_VAL_LEN) return 0;
135 for (size_t i = 0; i < n; ++i)
136 if ((unsigned char)s[i] < 0x20 || (unsigned char)s[i] > 0x7e) return 0;
137 return 1;
138}
139
140static int list_ok(const char *s, size_t cap) {
141 if (!text_ok(s, cap)) return 0;
142 size_t n = strlen(s);
143 if (s[0] == ' ' || s[n - 1] == ' ') return 0;
144 for (size_t i = 1; i < n; ++i)
145 if (s[i] == ' ' && s[i - 1] == ' ') return 0;
146 return 1;
147}
148
149static int in_set(const char *s, const char *const *set) {
150 for (; *set; ++set)
151 if (strcmp(s, *set) == 0) return 1;
152 return 0;
153}
154
155static int hex40_ok(const char *s, size_t cap) {
156 if (!memchr(s, 0, cap) || strlen(s) != 40) return 0;
157 for (int i = 0; i < 40; ++i)
158 if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0;
159 return 1;
160}
161
162/* A cell or item name: printable ASCII without space. */
163static int name_ok(const char *s, size_t cap) {
164 if (!text_ok(s, cap)) return 0;
165 return strchr(s, ' ') == NULL;
166}
167
168#define REFUSE(b, ...) \
169 do { \
170 if (!(b)->err) { \
171 (b)->err = 1; \
172 snprintf((b)->why, sizeof (b)->why, __VA_ARGS__); \
173 } \
174 } while (0)
175
176static void t_text(obj_b *b, const char *key, const char *v, size_t cap) {
177 if (!text_ok(v, cap)) REFUSE(b, "field %s: not printable ASCII text of 1..512 bytes", key);
178 else ob_text(b, key, v);
179}
180static void t_list(obj_b *b, const char *key, const char *v, size_t cap) {
181 if (!list_ok(v, cap)) REFUSE(b, "field %s: not a one-space-separated list of 1..512 bytes", key);
182 else ob_text(b, key, v);
183}
184static void t_enum(obj_b *b, const char *key, const char *v, size_t cap, const char *const *set) {
185 if (!text_ok(v, cap) || !in_set(v, set)) REFUSE(b, "field %s: value outside its allowed set", key);
186 else ob_text(b, key, v);
187}
188static void t_name(obj_b *b, const char *key, const char *v, size_t cap) {
189 if (!name_ok(v, cap)) REFUSE(b, "field %s: not a space-free printable name", key);
190 else ob_text(b, key, v);
191}
192
193static const char *const SET_MODE_W[] = {"dev", "certification", "discovery", NULL};
194static const char *const SET_MODE_F[] = {"certification", "discovery", NULL};
195static const char *const SET_PARENT[] = {"dev", "sealed", NULL};
196static const char *const SET_LABEL[] = {"POSITIVE", "NEGATIVE", "AMBIGUOUS", NULL};
197static const char *const SET_CHECK[] = {"AGREE", "STOP", NULL};
198static const char *const SET_PF[] = {"PASS", "FAIL", NULL};
199static const char *const SET_LEAK[] = {"0", "1", "INCONCLUSIVE", NULL};
200static const char *const SET_CLASS[] = {"POSITIVE", "NEGATIVE", "AMBIGUOUS", "WEAK", "STOPPED", NULL};
201
202/* ----------------------------------------------------------------- qprofile */
203
204static int enc_profile(const tyqr_profile *r, ty_digest *out, uint8_t *by, size_t bc, size_t *bl, char *why, size_t wl) {
205 obj_b b;
206 if (!r || !out || ob_new(&b, KIND_CONSTRAINT, "turing.qprofile") != 0) return TY_E_ARG;
207 const size_t V = TYQR_VAL;
208 t_text(&b, "profile", r->profile, V);
209 ob_digest(&b, "spec", &r->spec);
210 ob_digest(&b, "packet", &r->packet);
211 t_text(&b, "protocol", r->protocol, V);
212 t_text(&b, "quantizer", r->quantizer, V);
213 ob_i64(&b, "delta_log2", r->delta_log2);
214 t_text(&b, "edge_rule", r->edge_rule, V);
215 ob_i64(&b, "sd_min_log2", r->sd_min_log2);
216 t_text(&b, "floor_rule", r->floor_rule, V);
217 t_list(&b, "families", r->families, V);
218 ob_u64(&b, "kmax", r->kmax);
219 ob_u64(&b, "n_points", r->n_points);
220 ob_u64(&b, "split", r->split);
221 ob_digest(&b, "cells", &r->cells);
222 t_text(&b, "rider", r->rider, V);
223 t_text(&b, "lm_rule", r->lm_rule, V);
224 t_list(&b, "baselines", r->baselines, V);
225 ob_digest(&b, "thresholds", &r->thresholds);
226 t_text(&b, "thresholds_format", r->thresholds_format, V);
227 t_text(&b, "gen_version", r->gen_version, V);
228 ob_u64(&b, "bootstrap_b", r->bootstrap_b);
229 t_text(&b, "unit", r->unit, V);
230 if (why && wl) snprintf(why, wl, "%s", b.why);
231 return ob_finish(&b, TYQR_DOMAIN_PROFILE, out, by, bc, bl);
232}
233
234/* ------------------------------------------------------------------- qworld */
235
236static int enc_world(const tyqr_world *r, ty_digest *out, uint8_t *by, size_t bc, size_t *bl, char *why, size_t wl) {
237 obj_b b;
238 if (!r || !out || ob_new(&b, KIND_EVIDENCE, "turing.qworld") != 0) return TY_E_ARG;
239 const size_t V = TYQR_VAL;
240 ob_digest(&b, "qprofile", &r->qprofile);
241 t_enum(&b, "mode", r->mode, V, SET_MODE_W);
242 t_enum(&b, "parent_kind", r->parent_kind, V, SET_PARENT);
243 if (!b.err) {
244 int dev_mode = strcmp(r->mode, "dev") == 0, dev_parent = strcmp(r->parent_kind, "dev") == 0;
245 if (dev_mode != dev_parent) REFUSE(&b, "mode and parent_kind disagree (dev iff dev)");
246 else if (dev_parent != is_zero(&r->qfreeze)) REFUSE(&b, "qfreeze must be all zero iff parent_kind is dev");
247 }
248 ob_digest(&b, "qfreeze", &r->qfreeze);
249 t_name(&b, "cell", r->cell, V);
250 ob_u64(&b, "block", r->block);
251 t_text(&b, "label", r->label, V);
252 t_text(&b, "gen_version", r->gen_version, V);
253 ob_digest(&b, "generator", &r->generator);
254 ob_u64(&b, "rep_first", r->rep_first);
255 ob_u64(&b, "rep_count", r->rep_count);
256 ob_digest(&b, "traj_manifest", &r->traj_manifest);
257 t_text(&b, "traj_format", r->traj_format, V);
258 if (why && wl) snprintf(why, wl, "%s", b.why);
259 return ob_finish(&b, TYQR_DOMAIN_WORLD, out, by, bc, bl);
260}
261
262/* ------------------------------------------------------------------ qfreeze */
263
264static int enc_freeze(const tyqr_freeze *r, ty_digest *out, uint8_t *by, size_t bc, size_t *bl, char *why, size_t wl) {
265 obj_b b;
266 if (!r || !out || ob_new(&b, KIND_EVIDENCE, "turing.qfreeze") != 0) return TY_E_ARG;
267 const size_t V = TYQR_VAL;
268 t_enum(&b, "mode", r->mode, V, SET_MODE_F);
269 int cert = !b.err && strcmp(r->mode, "certification") == 0;
270 ob_digest(&b, "artifact", &r->artifact);
271 t_text(&b, "artifact_kind", r->artifact_kind, V);
272 if (!b.err && cert != is_zero(&r->artifact_bin)) REFUSE(&b, "artifact_bin must be all zero iff certification");
273 ob_digest(&b, "artifact_bin", &r->artifact_bin);
274 ob_digest(&b, "qprofile", &r->qprofile);
275 ob_digest(&b, "dev_manifest", &r->dev_manifest);
276 t_enum(&b, "b2_emerging_label", r->b2_emerging_label, V, SET_LABEL);
277 t_enum(&b, "bayes_plugin_check", r->bayes_plugin_check, V, SET_CHECK);
278 t_list(&b, "diag_fw_rate_ppm", r->diag_fw_rate_ppm, V);
279 t_enum(&b, "lengthening_test", r->lengthening_test, V, SET_PF);
280 t_enum(&b, "stability_test", r->stability_test, V, SET_PF);
281 t_text(&b, "calibration_extra", r->calibration_extra, V);
282 if (!hex40_ok(r->run_commit, sizeof r->run_commit)) REFUSE(&b, "field run_commit: not 40 lowercase hex");
283 else ob_text(&b, "run_commit", r->run_commit);
284 if (r->tree_dirty > 1) REFUSE(&b, "field tree_dirty: not 0 or 1");
285 ob_u64(&b, "tree_dirty", r->tree_dirty);
286 t_list(&b, "base_commits", r->base_commits, V);
287 t_text(&b, "producer_tool", r->producer_tool, V);
288 t_text(&b, "producer_model", r->producer_model, V);
289 if (!b.err && cert) {
290 if (strcmp(r->producer_tool, "none") || strcmp(r->producer_model, "none") ||
291 !is_zero(&r->prompt_digest) || !is_zero(&r->transcript_digest))
292 REFUSE(&b, "certification: producer fields must be none and prompt/transcript all zero");
293 }
294 if (!b.err && !cert && (is_zero(&r->prompt_digest) || is_zero(&r->transcript_digest)))
295 REFUSE(&b, "discovery: prompt and transcript digests must be present");
296 ob_digest(&b, "prompt_digest", &r->prompt_digest);
297 ob_digest(&b, "transcript_digest", &r->transcript_digest);
298 if (r->n_lineage > TYQR_MAX_LINEAGE) REFUSE(&b, "field n_lineage: more than 8 predecessors (stop condition)");
299 ob_u64(&b, "n_lineage", r->n_lineage);
300 for (uint64_t i = 0; !b.err && i < r->n_lineage; ++i) {
301 char k[16];
302 snprintf(k, sizeof k, "lineage.%02u", (unsigned)i);
303 ob_digest(&b, k, &r->lineage[i]);
304 }
305 if (why && wl) snprintf(why, wl, "%s", b.why);
306 return ob_finish(&b, TYQR_DOMAIN_FREEZE, out, by, bc, bl);
307}
308
309/* -------------------------------------------------------------------- qgain */
310
311static void ob_list_i64(obj_b *b, const char *key, const int64_t *v, size_t n) {
312 char t[TYQR_VAL];
313 size_t o = 0;
314 for (size_t i = 0; i < n; ++i) {
315 int k = snprintf(t + o, sizeof t - o, i ? " %" PRId64 : "%" PRId64, v[i]);
316 if (k < 0 || (size_t)k >= sizeof t - o) {
317 REFUSE(b, "field %s: list too long", key);
318 return;
319 }
320 o += (size_t)k;
321 }
322 ob_text(b, key, t);
323}
324
325static int enc_gain(const tyqr_gain *r, ty_digest *out, uint8_t *by, size_t bc, size_t *bl, char *why, size_t wl) {
326 obj_b b;
327 if (!r || !out || ob_new(&b, KIND_EVIDENCE, "turing.qgain") != 0) return TY_E_ARG;
328 const size_t V = TYQR_VAL;
329 ob_digest(&b, "qprofile", &r->qprofile);
330 ob_digest(&b, "qworld", &r->qworld);
331 ob_digest(&b, "qfreeze", &r->qfreeze);
332 t_enum(&b, "mode", r->mode, V, SET_MODE_F);
333 t_name(&b, "cell", r->cell, V);
334 t_text(&b, "gen_version", r->gen_version, V);
335 if (r->baseline_opcode < 1 || r->baseline_opcode > 7) REFUSE(&b, "field baseline: opcode outside 1..7");
336 if (!b.err) {
337 char h[65], t[96];
338 ty_hex(&r->baseline_artifact, h);
339 snprintf(t, sizeof t, "%" PRIu64 " %s", r->baseline_opcode, h);
340 ob_text(&b, "baseline", t);
341 }
342 ob_digest(&b, "candidate", &r->candidate);
343 if (!b.err) {
344 int disc = strcmp(r->mode, "discovery") == 0;
345 int ok = disc ? r->candidate_opcode == 255 : (r->candidate_opcode >= 1 && r->candidate_opcode <= 7);
346 if (!ok) REFUSE(&b, "field candidate_opcode: 1..7 for certification, 255 for discovery");
347 }
348 ob_u64(&b, "candidate_opcode", r->candidate_opcode);
349 ob_digest(&b, "prd_b", &r->prd_b);
350 ob_digest(&b, "prd_m", &r->prd_m);
351 if (r->official > 1) REFUSE(&b, "field official: not 0 or 1");
352 ob_u64(&b, "official", r->official);
353 t_text(&b, "ladder_item", r->ladder_item, V);
354 if (!b.err && (r->official == 1) != (strcmp(r->ladder_item, "-") == 0))
355 REFUSE(&b, "ladder_item must be - iff official is 1");
356 ob_list_i64(&b, "lengths", r->lengths, 6);
357 if (!b.err) {
358 int64_t d;
359 if (ty_sub(r->lengths[4], r->lengths[5], &d) != TY_OK || d != r->t_ub)
360 REFUSE(&b, "t_ub is not DL(B,D) - DL(M,D)");
361 if (r->t_lo_ub > r->t_hi_ub) REFUSE(&b, "t_lo_ub exceeds t_hi_ub");
362 }
363 ob_i64(&b, "t_ub", r->t_ub);
364 ob_i64(&b, "t_lo_ub", r->t_lo_ub);
365 ob_i64(&b, "t_hi_ub", r->t_hi_ub);
366 ob_i64(&b, "numeric_bound_ub", r->numeric_bound_ub);
367 ob_i64(&b, "mc_err_ub", r->mc_err_ub);
368 if (!b.err) {
369 char t[TYQR_VAL];
370 snprintf(t, sizeof t, "%" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, r->counts[0], r->counts[1],
371 r->counts[2], r->counts[3]);
372 ob_text(&b, "counts", t);
373 }
374 ob_u64(&b, "floor_hits", r->floor_hits);
375 int stopped = 0;
376 if (!text_ok(r->status, V)) REFUSE(&b, "field status: not text");
377 else {
378 stopped = strcmp(r->status, "STOPPED") == 0;
379 if (!stopped && strcmp(r->status, "PASS") != 0 && strncmp(r->status, "FAIL_", 5) != 0)
380 REFUSE(&b, "field status: not PASS, FAIL_* or STOPPED");
381 else if (strchr(r->status, ' ')) REFUSE(&b, "field status: contains a space");
382 }
383 if (!b.err && !stopped && r->protocol_failures != 0) REFUSE(&b, "protocol_failures must be 0 for a scored gain");
384 ob_u64(&b, "protocol_failures", r->protocol_failures);
385 t_enum(&b, "leak_flag", r->leak_flag, V, SET_LEAK);
386 for (int i = 0; i < 3; ++i)
387 if (r->coverage[i] < -1) REFUSE(&b, "field coverage: below -1");
388 ob_list_i64(&b, "coverage", r->coverage, 3);
389 t_list(&b, "diag_warnings", r->diag_warnings, V);
390 t_enum(&b, "classification", r->classification, V, SET_CLASS);
391 ob_text(&b, "status", r->status);
392 t_text(&b, "unit", r->unit, V);
393 if (why && wl) snprintf(why, wl, "%s", b.why);
394 return ob_finish(&b, TYQR_DOMAIN_GAIN, out, by, bc, bl);
395}
396
397/* ------------------------------------------------- public digest / verify */
398
399int tyqr_profile_digest(const tyqr_profile *r, ty_digest *out) { return enc_profile(r, out, NULL, 0, NULL, NULL, 0); }
400int tyqr_world_digest(const tyqr_world *r, ty_digest *out) { return enc_world(r, out, NULL, 0, NULL, NULL, 0); }
401int tyqr_freeze_digest(const tyqr_freeze *r, ty_digest *out) { return enc_freeze(r, out, NULL, 0, NULL, NULL, 0); }
402int tyqr_gain_digest(const tyqr_gain *r, ty_digest *out) { return enc_gain(r, out, NULL, 0, NULL, NULL, 0); }
403
404static int verify_common(int rc, const ty_digest *got, const ty_digest *want, char *why, size_t wl) {
405 if (rc != TY_OK) return rc;
406 if (!want) return TY_E_ARG;
407 if (!ty_digest_eq(got, want)) {
408 if (why && wl) snprintf(why, wl, "recomputed digest differs from the recorded digest");
409 return TY_E_DIGEST;
410 }
411 return TY_OK;
412}
413
414#define VERIFY_FN(name, T, enc) \
415 int name(const T *r, const ty_digest *want, char *why, size_t wl) { \
416 ty_digest d; \
417 if (why && wl) why[0] = 0; \
418 int rc = enc(r, &d, NULL, 0, NULL, why, wl); \
419 return verify_common(rc, &d, want, why, wl); \
420 }
421VERIFY_FN(tyqr_profile_verify, tyqr_profile, enc_profile)
422VERIFY_FN(tyqr_world_verify, tyqr_world, enc_world)
423VERIFY_FN(tyqr_freeze_verify, tyqr_freeze, enc_freeze)
424VERIFY_FN(tyqr_gain_verify, tyqr_gain, enc_gain)
425
426int tyqr_gain_bind(const tyqr_gain *g, const ty_digest *gd, const tyqr_world *w, const ty_digest *wd,
427 const tyqr_freeze *f, const ty_digest *fd, const ty_digest *pd, char *why, size_t wl) {
428 int rc;
429 if (!g || !gd || !w || !wd || !f || !fd || !pd) return TY_E_ARG;
430 if ((rc = tyqr_gain_verify(g, gd, why, wl)) != TY_OK) return rc;
431 if ((rc = tyqr_world_verify(w, wd, why, wl)) != TY_OK) return rc;
432 if ((rc = tyqr_freeze_verify(f, fd, why, wl)) != TY_OK) return rc;
433 const char *bad = NULL;
434 if (!ty_digest_eq(&g->qprofile, pd)) bad = "gain qprofile differs from the profile digest";
435 else if (!ty_digest_eq(&w->qprofile, pd)) bad = "world qprofile differs from the profile digest";
436 else if (!ty_digest_eq(&f->qprofile, pd)) bad = "freeze qprofile differs from the profile digest";
437 else if (!ty_digest_eq(&g->qworld, wd)) bad = "gain does not name this world";
438 else if (!ty_digest_eq(&g->qfreeze, fd)) bad = "gain does not name this freeze";
439 else if (!ty_digest_eq(&w->qfreeze, fd)) bad = "world is not sealed by this freeze";
440 else if (strcmp(g->mode, w->mode) != 0) bad = "gain mode differs from the world's";
441 else if (strcmp(g->mode, f->mode) != 0) bad = "gain mode differs from the freeze's";
442 else if (strcmp(g->cell, w->cell) != 0) bad = "gain cell differs from the world's";
443 else if (strcmp(g->gen_version, w->gen_version) != 0) bad = "gain gen_version differs from the world's";
444 else if (!ty_digest_eq(&g->candidate, &f->artifact)) bad = "gain candidate is not the freeze artifact";
445 if (bad) {
446 if (why && wl) snprintf(why, wl, "%s", bad);
447 return TY_E_PROFILE;
448 }
449 return TY_OK;
450}
451
452/* ------------------------------------------------------------------ writer */
453
454static int write_once(const char *dir, const char *record, const ty_digest *d, const uint8_t *by, size_t n,
455 char *path, size_t pathlen) {
456 char h[65], p[1024];
457 ty_hex(d, h);
458 int k = snprintf(p, sizeof p, "%s/%s.%s.omg0", dir, record, h);
459 if (k < 0 || (size_t)k >= sizeof p) return TY_E_ARG;
460 if (path) {
461 if ((size_t)k >= pathlen) return TY_E_ARG;
462 memcpy(path, p, (size_t)k + 1);
463 }
464 int fd = open(p, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0444);
465 if (fd < 0) return errno == EEXIST ? TYQR_E_EXISTS : TY_E_IO;
466 const uint8_t *q = by;
467 size_t left = n;
468 while (left) {
469 ssize_t w = write(fd, q, left);
470 if (w < 0 && errno == EINTR) continue;
471 if (w <= 0) {
472 close(fd);
473 unlink(p);
474 return TY_E_IO;
475 }
476 q += w;
477 left -= (size_t)w;
478 }
479 if (close(fd) != 0) {
480 unlink(p);
481 return TY_E_IO;
482 }
483 return TY_OK;
484}
485
486#define WRITE_FN(name, T, enc, rec) \
487 int name(const char *dir, const T *r, ty_digest *d, char *path, size_t pl) { \
488 uint8_t *by = malloc(TYQR_CANON_CAP); \
489 size_t n = 0; \
490 ty_digest dd; \
491 if (!dir || !by) { \
492 free(by); \
493 return TY_E_ARG; \
494 } \
495 int rc = enc(r, &dd, by, TYQR_CANON_CAP, &n, NULL, 0); \
496 if (rc == TY_OK) { \
497 if (d) *d = dd; \
498 rc = write_once(dir, rec, &dd, by, n, path, pl); \
499 } \
500 free(by); \
501 return rc; \
502 }
503WRITE_FN(tyqr_profile_write, tyqr_profile, enc_profile, "turing.qprofile")
504WRITE_FN(tyqr_world_write, tyqr_world, enc_world, "turing.qworld")
505WRITE_FN(tyqr_freeze_write, tyqr_freeze, enc_freeze, "turing.qfreeze")
506WRITE_FN(tyqr_gain_write, tyqr_gain, enc_gain, "turing.qgain")
507
508int tyqr_file_verify(const char *path, const char *domain, const ty_digest *want) {
509 if (!path || !domain || !want) return TY_E_ARG;
510 FILE *f = fopen(path, "rb");
511 if (!f) return TY_E_IO;
512 uint8_t *buf = malloc(TYQR_CANON_CAP + 1);
513 if (!buf) {
514 fclose(f);
515 return TY_E_IO;
516 }
517 size_t n = fread(buf, 1, TYQR_CANON_CAP + 1, f);
518 int err = ferror(f);
519 fclose(f);
520 int rc;
521 if (err) rc = TY_E_IO;
522 else if (n > TYQR_CANON_CAP) rc = TY_E_FORMAT;
523 else {
524 sha256_ctx c;
525 ty_digest d;
526 sha256_init(&c);
527 sha256_update(&c, (const uint8_t *)domain, strlen(domain) + 1);
528 sha256_update(&c, buf, n);
529 sha256_final(&c, d.b);
530 rc = ty_digest_eq(&d, want) ? TY_OK : TY_E_DIGEST;
531 }
532 free(buf);
533 return rc;
534}
535
536/* --------------------------------------------------------------- sidecars */
537
538void tyqr_sidecar_digest(const char *buf, size_t len, ty_digest *out) {
539 sha256_hash((const uint8_t *)buf, len, out->b);
540}
541
542/* Parse a decimal with no sign, no leading zero (except "0"), fitting uint64. */
543static int parse_dec(const char *s, size_t n, uint64_t *out) {
544 if (n < 1 || n > 20 || (n > 1 && s[0] == '0')) return 0;
545 uint64_t v = 0;
546 for (size_t i = 0; i < n; ++i) {
547 if (s[i] < '0' || s[i] > '9') return 0;
548 uint64_t dg = (uint64_t)(s[i] - '0');
549 if (v > (UINT64_MAX - dg) / 10) return 0;
550 v = v * 10 + dg;
551 }
552 *out = v;
553 return 1;
554}
555
556static int parse_hex64(const char *s, size_t n, ty_digest *d) {
557 if (n != 64) return 0;
558 char t[65];
559 memcpy(t, s, 64);
560 t[64] = 0;
561 return ty_parse_hex(t, d) == TY_OK;
562}
563
564/* Split one line (without LF) into single-space separated fields. Returns
565 * the field count, or -1 if a field is empty or a byte is outside 0x21..0x7e
566 * (and not the separating space). At most `max` fields are stored. */
567static int split_line(const char *l, size_t n, const char **f, size_t *fl, int max) {
568 int c = 0;
569 size_t i = 0;
570 for (;;) {
571 size_t s = i;
572 while (i < n && l[i] != ' ') {
573 if ((unsigned char)l[i] < 0x21 || (unsigned char)l[i] > 0x7e) return -1;
574 ++i;
575 }
576 if (i == s) return -1;
577 if (c < max) {
578 f[c] = l + s;
579 fl[c] = i - s;
580 }
581 ++c;
582 if (i == n) return c;
583 ++i; /* skip the space; a trailing space leaves an empty field */
584 if (i == n) return -1;
585 }
586}
587
588/* Iterate lines; requires the buffer to be non-empty and end with LF. */
589static int next_line(const char *buf, size_t len, size_t *pos, const char **l, size_t *ln) {
590 if (*pos >= len) return 0;
591 const char *e = memchr(buf + *pos, '\n', len - *pos);
592 if (!e) return -1; /* last line lacks LF */
593 *l = buf + *pos;
594 *ln = (size_t)(e - *l);
595 *pos = (size_t)(e - buf) + 1;
596 return 1;
597}
598
599int tyqr_repman_build(const tyqr_repline *e, size_t n, char *out, size_t cap, size_t *len) {
600 if (!e || !out || !len || n == 0) return TY_E_ARG;
601 size_t o = 0;
602 for (size_t i = 0; i < n; ++i) {
603 if (i && e[i].rep <= e[i - 1].rep) return TY_E_FORMAT;
604 char h[65];
605 ty_hex(&e[i].d, h);
606 int k = snprintf(out + o, cap - o, "%" PRIu64 " %s\n", e[i].rep, h);
607 if (k < 0 || (size_t)k >= cap - o) return TY_E_FORMAT;
608 o += (size_t)k;
609 }
610 *len = o;
611 return TY_OK;
612}
613
614int tyqr_repman_parse(const char *buf, size_t len, tyqr_repline *out, size_t cap, size_t *n) {
615 if (!buf || !out || !n || len == 0) return TY_E_FORMAT;
616 size_t pos = 0, c = 0;
617 const char *l;
618 size_t ln;
619 int r;
620 while ((r = next_line(buf, len, &pos, &l, &ln)) == 1) {
621 const char *f[2];
622 size_t fl[2];
623 if (c >= cap || split_line(l, ln, f, fl, 2) != 2) return TY_E_FORMAT;
624 if (!parse_dec(f[0], fl[0], &out[c].rep) || !parse_hex64(f[1], fl[1], &out[c].d)) return TY_E_FORMAT;
625 if (c && out[c].rep <= out[c - 1].rep) return TY_E_FORMAT;
626 ++c;
627 }
628 if (r < 0 || c == 0) return TY_E_FORMAT;
629 *n = c;
630 return TY_OK;
631}
632
633static int devline_before(const tyqr_devline *a, const tyqr_devline *b) {
634 int c = strcmp(a->cell, b->cell);
635 return c < 0 || (c == 0 && a->block < b->block);
636}
637
638int tyqr_devman_build(const tyqr_devline *e, size_t n, char *out, size_t cap, size_t *len) {
639 if (!e || !out || !len || n == 0) return TY_E_ARG;
640 size_t o = 0;
641 for (size_t i = 0; i < n; ++i) {
642 if (!name_ok(e[i].cell, sizeof e[i].cell)) return TY_E_FORMAT;
643 if (i && !devline_before(&e[i - 1], &e[i])) return TY_E_FORMAT;
644 char h[65];
645 ty_hex(&e[i].d, h);
646 int k = snprintf(out + o, cap - o, "%s %" PRIu64 " %s\n", e[i].cell, e[i].block, h);
647 if (k < 0 || (size_t)k >= cap - o) return TY_E_FORMAT;
648 o += (size_t)k;
649 }
650 *len = o;
651 return TY_OK;
652}
653
654int tyqr_devman_parse(const char *buf, size_t len, tyqr_devline *out, size_t cap, size_t *n) {
655 if (!buf || !out || !n || len == 0) return TY_E_FORMAT;
656 size_t pos = 0, c = 0;
657 const char *l;
658 size_t ln;
659 int r;
660 while ((r = next_line(buf, len, &pos, &l, &ln)) == 1) {
661 const char *f[3];
662 size_t fl[3];
663 if (c >= cap || split_line(l, ln, f, fl, 3) != 3) return TY_E_FORMAT;
664 if (fl[0] >= TYQR_CELL_MAX) return TY_E_FORMAT;
665 memcpy(out[c].cell, f[0], fl[0]);
666 out[c].cell[fl[0]] = 0;
667 if (!parse_dec(f[1], fl[1], &out[c].block) || !parse_hex64(f[2], fl[2], &out[c].d)) return TY_E_FORMAT;
668 if (c && !devline_before(&out[c - 1], &out[c])) return TY_E_FORMAT;
669 ++c;
670 }
671 if (r < 0 || c == 0) return TY_E_FORMAT;
672 *n = c;
673 return TY_OK;
674}
675
676/* Lines strictly ascending by the given key length (whole line if cmp_key is 0). */
677static int table_check(const char *buf, size_t len, int min_fields, int max_fields, int by_cell, int kv) {
678 if (!buf || len == 0) return TY_E_FORMAT;
679 size_t pos = 0, pl = 0;
680 const char *l, *prev = NULL;
681 size_t ln;
682 int r;
683 while ((r = next_line(buf, len, &pos, &l, &ln)) == 1) {
684 const char *f[64];
685 size_t fl[64];
686 int nf = split_line(l, ln, f, fl, 64);
687 if (nf < min_fields || nf > 64 || (max_fields && nf > max_fields)) return TY_E_FORMAT;
688 if (kv) {
689 for (int i = 1; i < nf; ++i) {
690 const char *eq = memchr(f[i], '=', fl[i]);
691 if (!eq || eq == f[i] || eq == f[i] + fl[i] - 1) return TY_E_FORMAT;
692 }
693 }
694 if (prev) {
695 size_t a = pl, b = by_cell ? fl[0] : ln;
696 const char *ka = prev, *kb = l;
697 if (by_cell) {
698 size_t sp = 0;
699 while (sp < pl && prev[sp] != ' ') ++sp;
700 a = sp;
701 }
702 size_t m = a < b ? a : b;
703 int c = memcmp(ka, kb, m);
704 if (c == 0) c = a < b ? -1 : (a > b ? 1 : 0);
705 if (c >= 0) return TY_E_FORMAT;
706 }
707 prev = l;
708 pl = ln;
709 }
710 return (r < 0 || !prev) ? TY_E_FORMAT : TY_OK;
711}
712
713int tyqr_celltab_check(const char *buf, size_t len) { return table_check(buf, len, 2, 0, 1, 1); }
714int tyqr_thrtab_check(const char *buf, size_t len) { return table_check(buf, len, 3, 3, 0, 0); }