diff --git a/.crumb b/.crumb index 81f377ee2..9edc79e89 100644 --- a/.crumb +++ b/.crumb @@ -47,8 +47,8 @@ "purpose": "Directory calibration. Purpose not yet described by a human." }, { - "digest": "d2eb8967a939ebdb0b54e15fe5d849dd5af71c23b812941e4ba86ad2b0f21d39", - "last_commit": "4870b0a4", + "digest": "7f9297f3bc19305f0856ecbe5568a2cdeaa8ee8f1656ea9dfde3cce978153188", + "last_commit": "91c12358", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -59,8 +59,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "e7d38c87a51c3c0ee6e3b18419ef4a01d95029de12ac9bf69eb672654f0ace55", - "last_commit": "ae4ad9c0", + "digest": "ebe6e92b7cc148589120442365bfcc64f73e3fe764fdab5b5700c6d4698db84d", + "last_commit": "91c12358", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -83,27 +83,27 @@ "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "4eb9d4d76234448c0ed691f0aeb9c90d785f8a47b1b1291d728bbe3e1509dc10", - "last_commit": "88e24bdd", + "digest": "2e95b8364a0573b0c66178eed301749a15410bbe0f3b1541ac6a933081dd15e2", + "last_commit": "0241e846", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { - "digest": "566a123ba248da906e3c42430b73decd7c3ec030a4fd26c909d265aa9bf67db9", - "last_commit": "88e24bdd", + "digest": "bf664d513e2780b3af8ec0509be5732d2313467f5bbd98c58b9b24a0b0be49f1", + "last_commit": "0241e846", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:e1a8c008214ad5dbc33a3e184d7e882dc56d1d50f9bd14c58f8773992961557e", - "compiled_at": "2026-10-16T19:04:20Z", + "children_root": "sha256:eeb38ac82e70ac93c355ab28235238bed6017edc94103e1fd022427a7d5ef408", + "compiled_at": "2026-10-18T14:41:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:32086cfe6b319e0c0229bec39553d1b32f7460aa660ad888d5eb5990522e705a", + "digest": "sha256:736c385d61192d9086871091cc4595b63b30b98bcb6a6e12273fb9a9ef666d14", "evidence_files": 11127, "evidence_root": "sha256:4528085ec1661c442b64fb5dc8def65067ea2620ff88e42bcf52d58b7642ea6e", - "files": 14109, - "generated_at_commit": "88e24bdd57b27817d030d0ad95f62c3f3eacf426", - "source_tree": "sha256:e01c9caa38757306582443fe69f52cb061c3d27250f8ad0b9f4b4f43b009dc14" + "files": 14124, + "generated_at_commit": "0241e846f21daf2e91ae97dcd3f68e6b94372e36", + "source_tree": "sha256:b285e501beccd8895ba6adbd5a4544ddbbc10e9984689eae3cb619f253e038ac" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index ca5d5ec00..7469b3a98 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -124,14 +124,14 @@ } ], "children_root": "sha256:ac7f7ea4b00d4620a993c6dd88a0267f2d49008d415162976e45fa4341e43407", - "compiled_at": "2026-10-16T09:04:56Z", + "compiled_at": "2026-10-16T19:51:16Z", "compiler": "crumb-compile/1", - "digest": "sha256:d2eb8967a939ebdb0b54e15fe5d849dd5af71c23b812941e4ba86ad2b0f21d39", + "digest": "sha256:7f9297f3bc19305f0856ecbe5568a2cdeaa8ee8f1656ea9dfde3cce978153188", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", - "files": 127, - "generated_at_commit": "9d368679f13ea58c46bf7580899aee92e39f5885", - "source_tree": "sha256:29d159b6950500f96de859834fd2c5a9e9ba037f9bc88fd97a8ed47a1688233b" + "files": 128, + "generated_at_commit": "91c12358a0a215f63b2e9c6486861ced3982f2dd", + "source_tree": "sha256:6317a1f779f2ee5eeee9fb418ef93184925c0b7725ead9cdc0375c65fd79f72a" }, "owner_lane": "", "provenance": { diff --git a/docs/one_layer/VERIFIED_PROGRAM.md b/docs/one_layer/VERIFIED_PROGRAM.md new file mode 100644 index 000000000..d0db5b3ef --- /dev/null +++ b/docs/one_layer/VERIFIED_PROGRAM.md @@ -0,0 +1,149 @@ +# Verified program: objective-bound Omegese to executable result with an independent receipt + +**Status**: v1, host CPU only (omega#505, lane F of aien-dev/aien-architecture-mv#231). +**Code**: `tools/verified_program/vp.c` (runner), `tools/verified_program/vp_verify.c` (verifier), +`mk/verified-program.mk`, gate `tests/gates/omega-verified-program.gate`. + +## 1. What it does + +One request goes through the existing chain and nothing else: + +``` +program (Omegese, op list or OSC IR) + -> omegese emit -> omega_emit emit -> canonical OSC IR + -> checker2 check (ACCEPT or a named rule) + -> grant check (objective, tier, epoch window, effects, call limit) + -> code image (osc_cg_compile) -> checker2 receipt issue (TEST class: binds IR, code, binding, inputs) + -> preflight on the exact bytes to run + -> execution in a child under seccomp strict mode + -> execution receipt, content-addressed store, measurements +``` + +`verified_program run` says only that the program ran under its grant. Whether the result is right is +decided separately by `vp_verify`, which believes nothing the runner wrote and recomputes every answer +with its own reference function for the task (the oracle). Syntax acceptance and checker2 acceptance +never count as "correct": the negative controls include programs that pass both and are still wrong. + +## 2. Authority + +- The **objective id** is SHA-256 of `AIEN_E2E_OBJECTIVE_V1`, one newline byte, and the objective text + (the same rule as aien-sovereign-core `objective.rs`). Both tools recompute it. +- The **grant** is written by the runtime authority (AIENOS / sovereign-core approval desk). Omega does not + mint, widen or authenticate grants. The runner checks that the grant names the same objective and tier, + that the epoch is inside its window, that the call count is within its limit and that its effects cover + what the checked IR needs. The verifier repeats every one of these checks from the stored grant. +- **checker2** judges the IR bytes. It grants nothing. +- Model output never authorizes anything (PST1 section 8 item 5). + +## 3. Request (`omega.verified_program.request.v1`) + +Text, one `key value` line per key, exactly this order, newline-terminated. Relative paths are resolved +against the request file's directory. + +| key | value | +|---|---| +| `schema` | `omega.verified_program.request.v1` (anything else: `UNKNOWN_VERSION`) | +| `objective_id` | 64 lowercase hex | +| `objective_text` | the text, printable, one line | +| `program_format` | `omegese-v1`, `oplist-v1` or `oscir-v1` | +| `program` | path to the program bytes (at most 1 MiB) | +| `entry` | function name | +| `params` | space-separated scalar kinds (`bool u8 u16 u32 u64 i8 i16 i32 i64`), at most 6, may be empty | +| `ret` | scalar kind | +| `inputs` | path: one call per line, decimal values separated by single spaces | +| `tier` | `host-cpu-aarch64` (anything else: `TIER_UNSUPPORTED`) | +| `grant` | path to the grant | +| `epoch` | positive integer | +| `pin_checker2_id` | checker2 `checker_id`, or `-` for no pin | +| `pin_omegese_sha256` | SHA-256 of the omegese binary, or `-` | +| `pin_omega_emit_sha256` | SHA-256 of the omega_emit binary, or `-` | + +Only scalar signatures are accepted: the entry function takes and returns plain values, so the inputs +and the result are fully described by the input and output text. + +## 4. Grant (`aien.verified_program.grant.v1`) + +Same text layout: `schema`, `objective_id`, `tier`, `effects` (space-separated, from `pure`, `heap`, +`caller_memory`; `pure` is required), `epoch_first`, `epoch_last`, `max_calls` (1 to 4096). + +Effects are recomputed from the IR, never declared by the program: + +| effect | needed when the IR contains | +|---|---| +| `pure` | always | +| `heap` | any runtime-managed memory: `alloc`/`release` arrays, arenas, pools, handles | +| `caller_memory` | `sload`/`sstore`, or any register of the bytes or cells kind | + +## 5. Outputs + +`/` (one run per directory): + +- `store/`: every artifact by the SHA-256 of its bytes, read-only: objective text, program + bytes, op list, IR, code image, canonical inputs, grant, binding object, checker2 receipt, outputs. +- `receipts/.vpr`: the execution receipt; `id` is the SHA-256 of the file. Written only on EXECUTED. +- `result.txt`: `verdict` (EXECUTED or REFUSED), `rejection`, `stage`, `detail`, digests. +- `measure.txt`: `wall_ns`, `user_us`, `sys_us`, `maxrss_kb`, `calls`, `ir_bytes`, `code_bytes`. Kept + out of the receipt so the receipt is deterministic: the same request gives the same receipt id. + +Outputs text: one line per call, `R ` (the return value, decimal in the `ret` kind) or `T ` +(the call stopped with that OSC trap code, for example 1 for arithmetic overflow). + +The **binding object** (`omega.verified_program.binding.v1`: objective id, grant digest, entry, params, +ret, tier, epoch) is passed to `checker2 receipt issue --requirements`, and the canonical inputs to +`--input`, so the signed checker2 receipt covers the IR, the code image, the objective binding and the +inputs. The execution receipt (`omega.verified_program.receipt.v1`) records, in fixed order: objective, +grant, binding, program, op list, IR, code, inputs and outputs digests; entry and signature; call count; +effects required and granted; checker2 verdict, identity, receipt id and signer class; digests of the +omegese, omega_emit, checker2 and runner binaries; commit; tier; host CPU identity (architecture plus the +distinct `implementer:variant:part:revision` core kinds from `/proc/cpuinfo`); `machine_id=absent` (no +provisioned machine identity on this host); `gpu_used=no`; `sandbox=seccomp-strict`; epoch. + +## 6. Refusals + +Runner (`verified_program run`, exit 1, no receipt): `UNKNOWN_VERSION`, `REQUEST_MALFORMED`, +`TIER_UNSUPPORTED`, `TIER_UNAVAILABLE`, `OBJECTIVE_MISMATCH`, `GRANT_MISSING`, `GRANT_MALFORMED`, +`GRANT_OBJECTIVE`, `GRANT_TIER`, `GRANT_EPOCH`, `PIN_MISMATCH`, `PROGRAM_MISSING`, `EMIT_REFUSED`, +`LOWER_REFUSED`, `CHECKER_REJECT` (detail names the checker2 rule), `DECODE_REFUSED`, +`SIGNATURE_MISMATCH`, `UNAUTHORIZED_EFFECT`, `INPUT_MALFORMED`, `INPUT_RANGE`, `INPUT_LIMIT`, +`BACKEND_REFUSED`, `PREFLIGHT_IR_CHANGED`, `PREFLIGHT_CODE_CHANGED`, `PREFLIGHT_CODE_INVALID`, +`EXEC_FAILED`. + +Preflight, immediately before execution: the IR and code bytes are read back from the store and +re-hashed, checker2 runs again on the IR file, every code word is decoded and re-encoded +(`osc_cg_verify`), and the IR is recompiled independently of the first compile; the result must be the +same bytes and entry offset. Execution then maps exactly those bytes. + +Verifier (`vp_verify`, exit 1, first failure only), in check order: `RECEIPT_MISSING`, +`RECEIPT_ID_MISMATCH`, `UNKNOWN_VERSION`, `RECEIPT_MALFORMED`, `OBJECTIVE_MISMATCH`, `STORE_MISSING`, +`STORE_TAMPERED`, `GRANT_MALFORMED`, `GRANT_OBJECTIVE`, `GRANT_TIER`, `GRANT_EPOCH`, `GRANT_LIMIT`, +`CHECKER_REJECT`, `UNAUTHORIZED_EFFECT`, `BINDING_MISMATCH`, `CHECKER_ID`, `C2_RECEIPT_INVALID`, +`C2_BINDING`, `C2_INPUT`, `HOST_MISMATCH`, `ORACLE_SIGNATURE`, `ORACLE_DOMAIN`, `OUTPUT_MALFORMED`, +`WRONG_RESULT`. + +`vp_verify` links checker2's own decoder and `src/sha256.c`; it links nothing from `src/compiler`. It +calls the checker2 binary for `check`, `version` and `receipt verify`, and reads the requirements +(offset 16) and input (offset 272) fields of the 416-byte checker2 receipt itself, because `receipt +verify` does not compare them. + +## 7. Mapping to PST1 (aien-dev/aien-protocols-mv#34, draft) + +| PST1 | here | +|---|---| +| `objective_id` header field | `objective_id` (same derivation) | +| `completed` payload (32-byte result digest) | `outputs_sha256` | +| `receipt_reference` payload (32-byte receipt digest) | the execution receipt id | +| `effect_class` (a claim) | not trusted: effects are recomputed from the IR and checked against the grant | + +## 8. Limits (not covered by v1) + +- **Host CPU only.** A GPU tier is refused (`TIER_UNSUPPORTED`); `gpu_used=no` in every receipt. +- **TEST-class signature.** The checker2 receipt is signed with the TEST key. OWNER signing (the offline + key) is not exercised. The execution receipt itself is unsigned text bound by its hash. +- **Grants are not authenticated here.** A signed grant from the runtime authority is future work; v1 + checks the grant's binding and records its digest. +- **Oracles** exist for three public dev tasks (`gcd_u32`, `collatz_steps_u32`, `checked_mul_i16`). A + new task needs its own reference function in `vp_verify.c`. +- **No fresh model program yet.** The model generation lane (lane E) is not wired in; the model-written + program in the test is a kept fixture (`tests/one_layer/omegese/trial2/dev08.omegese`). +- **No provisioned machine identity** on this host (`machine_id=absent`); the host is identified by CPU + kind only. diff --git a/mk/.crumb b/mk/.crumb index cd51a1c73..285a6a714 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T02:24:36Z", + "compiled_at": "2026-10-16T19:51:16Z", "compiler": "crumb-compile/1", - "digest": "sha256:e7d38c87a51c3c0ee6e3b18419ef4a01d95029de12ac9bf69eb672654f0ace55", + "digest": "sha256:ebe6e92b7cc148589120442365bfcc64f73e3fe764fdab5b5700c6d4698db84d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 71, - "generated_at_commit": "ccf021b944b0128a537dfd3dd301e6d83eefa311", - "source_tree": "sha256:e7a2b37daa8149cb73da719737df82c74a61685b4076bf2c5b4e0c26bee61dc7" + "files": 72, + "generated_at_commit": "91c12358a0a215f63b2e9c6486861ced3982f2dd", + "source_tree": "sha256:2fc1599388deca8182084de39a9dd66523b2b5dcee8069b1a170d5d9c627db7c" }, "owner_lane": "", "provenance": { diff --git a/mk/verified-program.mk b/mk/verified-program.mk new file mode 100644 index 000000000..188af4956 --- /dev/null +++ b/mk/verified-program.mk @@ -0,0 +1,38 @@ +# tools/verified_program (omega#505): objective-bound Omegese -> OSC IR -> checker2 -> authorized +# execution with an independent receipt (docs/one_layer/VERIFIED_PROGRAM.md). Host CPU only. +# Picked up by `-include mk/*.mk`; not part of `all` or `test`. +# +# verified-program build/verified_program/{verified_program,vp_verify} and the two canary +# runners (IR or code bytes changed between the check and the execution; +# a forbidden system call inside the sandbox) +# test-verified-program tools/verified_program/test_verified_program.sh: positives verified by the +# independent oracle, then every negative control with its named reason +# +# vp_verify links checker2's core (C2_CORE, from mk/checker2.mk) and src/sha256.c only, never +# src/compiler: it judges the runner, so it shares none of the runner's lowering, back end or runtime. +ifndef VERIFIED_PROGRAM_MK +VERIFIED_PROGRAM_MK := 1 +.PHONY: verified-program test-verified-program +VP_DIR = $(OUT_DIR)/verified_program +VP_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Isrc/compiler +VP_OSC_LIB = $(filter-out src/compiler/oscc_main.c,$(wildcard src/compiler/*.c)) src/sha256.c +VPV_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Isrc/checker2 + +$(VP_DIR)/verified_program: tools/verified_program/vp.c $(VP_OSC_LIB) $(wildcard src/compiler/*.h) + @mkdir -p $(VP_DIR) + $(CC) $(VP_CFLAGS) -o $@ tools/verified_program/vp.c $(VP_OSC_LIB) + +$(VP_DIR)/verified_program_tamper%: tools/verified_program/vp.c $(VP_OSC_LIB) $(wildcard src/compiler/*.h) + @mkdir -p $(VP_DIR) + $(CC) $(VP_CFLAGS) -DVP_TAMPER=$* -o $@ tools/verified_program/vp.c $(VP_OSC_LIB) + +$(VP_DIR)/vp_verify: tools/verified_program/vp_verify.c $(C2_CORE) $(wildcard src/checker2/*.h) src/sha256.c src/sha256.h + @mkdir -p $(VP_DIR) + $(CC) $(VPV_CFLAGS) -o $@ tools/verified_program/vp_verify.c $(C2_CORE) src/sha256.c + +verified-program: $(VP_DIR)/verified_program $(VP_DIR)/vp_verify $(VP_DIR)/verified_program_tamper1 $(VP_DIR)/verified_program_tamper2 $(VP_DIR)/verified_program_tamper3 + +test-verified-program: verified-program omegese omega-emit checker2 + bash tools/verified_program/test_verified_program.sh $(abspath $(VP_DIR)) $(abspath $(OUT_DIR)/omegese/omegese) \ + $(abspath $(OUT_DIR)/omega_emit/omega_emit) $(abspath $(C2_DIR)/checker2) +endif diff --git a/tests/.crumb b/tests/.crumb index bd5535a8b..bde6ea940 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -296,14 +296,14 @@ } ], "children_root": "sha256:ddc3618190458bc5073e3bee67ffccc68a2ee9f065f2cb0d86545386a29fddf8", - "compiled_at": "2026-10-16T19:04:20Z", + "compiled_at": "2026-10-18T14:41:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:4eb9d4d76234448c0ed691f0aeb9c90d785f8a47b1b1291d728bbe3e1509dc10", + "digest": "sha256:2e95b8364a0573b0c66178eed301749a15410bbe0f3b1541ac6a933081dd15e2", "evidence_files": 16, "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a", - "files": 1270, - "generated_at_commit": "88e24bdd57b27817d030d0ad95f62c3f3eacf426", - "source_tree": "sha256:e6c4f0021d383ba2e59da0d85d06a0b98170f6d188289c891b5745200548e6fc" + "files": 1271, + "generated_at_commit": "0241e846f21daf2e91ae97dcd3f68e6b94372e36", + "source_tree": "sha256:902fd69e800e8f24ad6d71cb85c6c5f568a1cc173ee8a078062f72d707d61139" }, "owner_lane": "", "provenance": { diff --git a/tests/gates/omega-verified-program.gate b/tests/gates/omega-verified-program.gate new file mode 100644 index 000000000..70989c62d --- /dev/null +++ b/tests/gates/omega-verified-program.gate @@ -0,0 +1,35 @@ +# tests/gates/omega-verified-program.gate +# Objective-bound Omegese -> OSC IR -> checker2 -> authorized execution with an independent receipt +# (omega#505, docs/one_layer/VERIFIED_PROGRAM.md). Host CPU only: no model, no GPU, no held-out data. +# Positives are recomputed by vp_verify's own oracles; every negative control must give its named +# refusal (checker2 rejection, emit refusal, wrong but parseable program, tampered store, stale +# objective or grant, unauthorized effect, bytes changed before execution, sandbox breach canary). +gate: OMEGA-VERIFIED-PROGRAM +manifest_version: 2 +owner: omega +requires: + - host +inputs: + - Makefile + - mk/verified-program.mk + - mk/omegese.mk + - mk/omega-emit.mk + - mk/checker2.mk + - tools/verified_program/ + - tools/omegese/ + - tools/omega_emit/ + - src/compiler/ + - src/checker2/ + - src/searchtrace/sig/ + - src/sha256.c + - src/sha256.h + - tests/one_layer/omegese/ + - tests/gates/omega-verified-program.gate +run: + exec: tools/verified_program/gate.sh +expects: + exit: 0 + verdict: PASS +timeout: 10m +exactness: EXACT +cache_scope: machine diff --git a/tools/.crumb b/tools/.crumb index 8cf70bcac..1d98dab01 100644 --- a/tools/.crumb +++ b/tools/.crumb @@ -62,14 +62,14 @@ } ], "children_root": "sha256:e1f826c2beb8604bb0dcba49575f7c6b48cf5488c40b616b212fda2ed70c62ee", - "compiled_at": "2026-10-16T19:04:20Z", + "compiled_at": "2026-10-18T14:41:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:566a123ba248da906e3c42430b73decd7c3ec030a4fd26c909d265aa9bf67db9", + "digest": "sha256:bf664d513e2780b3af8ec0509be5732d2313467f5bbd98c58b9b24a0b0be49f1", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 284, - "generated_at_commit": "88e24bdd57b27817d030d0ad95f62c3f3eacf426", - "source_tree": "sha256:eee0218ae5c8d003fa0a585291551799e81e6c329a7f5db1295e771a75aee167" + "files": 296, + "generated_at_commit": "0241e846f21daf2e91ae97dcd3f68e6b94372e36", + "source_tree": "sha256:ed45994db0cd9e532c80d02578dbc297df988a364e4dce91f0091ad67ab66437" }, "owner_lane": "", "provenance": { diff --git a/tools/verified_program/fixtures/collatz.in b/tools/verified_program/fixtures/collatz.in new file mode 100644 index 000000000..cb322f141 --- /dev/null +++ b/tools/verified_program/fixtures/collatz.in @@ -0,0 +1,10 @@ +1 +2 +3 +6 +7 +9 +27 +97 +871 +77031 diff --git a/tools/verified_program/fixtures/collatz_big.in b/tools/verified_program/fixtures/collatz_big.in new file mode 100644 index 000000000..5e362163f --- /dev/null +++ b/tools/verified_program/fixtures/collatz_big.in @@ -0,0 +1 @@ +159487 diff --git a/tools/verified_program/fixtures/gcd.in b/tools/verified_program/fixtures/gcd.in new file mode 100644 index 000000000..50aa543e2 --- /dev/null +++ b/tools/verified_program/fixtures/gcd.in @@ -0,0 +1,12 @@ +84 36 +0 0 +0 7 +9 0 +17 5 +4294967295 3 +4294967295 4294967295 +1071 462 +12 18 +100 75 +2147483648 65536 +123456789 987654321 diff --git a/tools/verified_program/fixtures/gcd_arity.omegese b/tools/verified_program/fixtures/gcd_arity.omegese new file mode 100644 index 000000000..08334fc02 --- /dev/null +++ b/tools/verified_program/fixtures/gcd_arity.omegese @@ -0,0 +1,8 @@ +fn gcd a uint b uint to uint +while ne b 0 0 bound 100 +t = rem a b +a = b +b = t +end +ret a +end diff --git a/tools/verified_program/fixtures/gcd_heap.omegese b/tools/verified_program/fixtures/gcd_heap.omegese new file mode 100644 index 000000000..14da4a88a --- /dev/null +++ b/tools/verified_program/fixtures/gcd_heap.omegese @@ -0,0 +1,13 @@ +fn gcd a uint b uint to uint +s = new uint 2 0 +put s 0 a +put s 1 b +while ne get s 1 0 bound 100 +t = rem get s 0 get s 1 +put s 0 get s 1 +put s 1 t +end +r = get s 0 +free s +ret r +end diff --git a/tools/verified_program/fixtures/gcd_unbounded.json b/tools/verified_program/fixtures/gcd_unbounded.json new file mode 100644 index 000000000..e345abbfb --- /dev/null +++ b/tools/verified_program/fixtures/gcd_unbounded.json @@ -0,0 +1,11 @@ +{"functions": [ + {"name": "gcd", "params": ["u32", "u32"], "ret": "u32", "locals": ["u64", "u64", "u64", "u32", "bool", "u64", "bool", "u32"], + "blocks": [ + [{"op": "const", "dst": 2, "value": 0}, {"op": "const", "dst": 3, "value": 1}, {"op": "const", "dst": 5, "value": 0}, {"op": "const", "dst": 7, "value": 100}, {"op": "mov", "dst": 4, "a": 2}, {"op": "br", "to": 1}], + [{"op": "ne", "dst": 6, "a": 1, "b": 5}, {"op": "cbr", "cond": 6, "then": 2, "else": 5}], + [{"op": "ge", "dst": 8, "a": 4, "b": 7}, {"op": "cbr", "cond": 8, "then": 3, "else": 4}], + [{"op": "trap", "code": 4}, {"op": "br", "to": 5}], + [{"op": "rem", "dst": 9, "a": 0, "b": 1}, {"op": "mov", "dst": 0, "a": 1}, {"op": "mov", "dst": 1, "a": 9}, {"op": "br", "to": 1}], + [{"op": "ret", "a": 0}] + ]} +]} diff --git a/tools/verified_program/fixtures/gcd_wrong.omegese b/tools/verified_program/fixtures/gcd_wrong.omegese new file mode 100644 index 000000000..7e1eac767 --- /dev/null +++ b/tools/verified_program/fixtures/gcd_wrong.omegese @@ -0,0 +1,8 @@ +fn gcd a uint b uint to uint +while ne b 0 bound 100 +t = rem a b +a = b +b = t +end +ret b +end diff --git a/tools/verified_program/fixtures/mul.in b/tools/verified_program/fixtures/mul.in new file mode 100644 index 000000000..5deb30c5d --- /dev/null +++ b/tools/verified_program/fixtures/mul.in @@ -0,0 +1,9 @@ +3 4 +-7 6 +200 200 +-32768 1 +-32768 -1 +181 181 +182 181 +0 -32768 +-1 -1 diff --git a/tools/verified_program/gate.sh b/tools/verified_program/gate.sh new file mode 100755 index 000000000..4c94ea4cf --- /dev/null +++ b/tools/verified_program/gate.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# tools/verified_program/gate.sh: the gate entry for tests/gates/omega-verified-program.gate (omega#505). +# Same command as `make test-verified-program`, with the physics sibling switched off like the other +# host steps of tests/gates/run.sh. It lives here, not as a run.sh step, because run.sh is being +# changed by open pull requests at the time of writing; it can move into run.sh once those land. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT" +make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-verified-program diff --git a/tools/verified_program/test_verified_program.sh b/tools/verified_program/test_verified_program.sh new file mode 100755 index 000000000..81d70ddb0 --- /dev/null +++ b/tools/verified_program/test_verified_program.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# tools/verified_program/test_verified_program.sh +# Checks for the verified-program entrypoint and its independent verifier (omega#505, +# docs/one_layer/VERIFIED_PROGRAM.md). Host CPU only: no model, no GPU, no held-out data. +# +# 1. positives: fixed reference functions (public dev tasks gcd, collatz_steps, checked_mul with its +# overflow traps) and one model-written answer kept verbatim (tests/one_layer/omegese/trial2/dev08) +# run through omegese -> omega_emit -> checker2 -> authorized execution, and vp_verify recomputes +# every result with its own oracle: VERIFIED. Two runs of one request give the same receipt id. +# 2. negatives, each with the exit and the named reason it must give: +# incorrect but parseable programs (a wrong gcd; the model's collatz on an input past 32 bits), +# checker2 rejection, emit refusal, tampered IR / code / output, stale or mismatched objective, +# stale grant, unauthorized effect, bytes changed between check and execution and a forbidden +# system call inside the sandbox (canary builds), +# unknown versions, pin mismatch, signature mismatch, unbounded inputs, a GPU tier request. +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/../.." && pwd)" +[ $# -eq 4 ] || { echo "usage: test_verified_program.sh " >&2; exit 2; } +VPD="$1" G="$2" OME="$3" C2="$4" +VP="$VPD/verified_program" VV="$VPD/vp_verify" +FX="$HERE/fixtures" DEV="$ROOT/tests/one_layer/omegese" +T="$(mktemp -d "${TMPDIR:-/tmp}/vp-test.XXXXXXXX")"; trap 'rm -rf "$T"' EXIT +fails=0 passes=0 +bad() { echo "FAIL $*"; fails=$((fails + 1)); } +ok() { echo "ok $*"; passes=$((passes + 1)); } + +oid() { printf 'AIEN_E2E_OBJECTIVE_V1\n%s' "$1" | sha256sum | cut -c1-64; } +TXT_GCD="Pi asks: the greatest common divisor of each pair of numbers" +TXT_COL="Pi asks: how many Collatz steps each number takes to reach 1" +TXT_MUL="Pi asks: multiply each pair of 16-bit signed numbers, refusing overflow" +TXT_OTHER="Pi asks: something else entirely" +C2ID="$("$C2" version | sed -n 's/^checker_id=//p')" +GSHA="$(sha256sum "$G" | cut -c1-64)" OSHA="$(sha256sum "$OME" | cut -c1-64)" + +# grant [epoch_first epoch_last max_calls tier] +grant() { + printf 'schema aien.verified_program.grant.v1\nobjective_id %s\ntier %s\neffects %s\nepoch_first %s\nepoch_last %s\nmax_calls %s\n' \ + "$(oid "$2")" "${7:-host-cpu-aarch64}" "$3" "${4:-1}" "${5:-10}" "${6:-64}" > "$1" +} +# req [key=value overrides] +req() { + local f="$1" text="$2" fmt="$3" prog="$4" entry="$5" params="$6" ret="$7" in="$8" gr="$9"; shift 9 + local schema="omega.verified_program.request.v1" id; id="$(oid "$text")" tier="host-cpu-aarch64" epoch=1 + local pc="$C2ID" pg="$GSHA" po="$OSHA" kv + for kv in "$@"; do case "$kv" in + schema=*) schema="${kv#*=}" ;; objective_id=*) id="${kv#*=}" ;; tier=*) tier="${kv#*=}" ;; + epoch=*) epoch="${kv#*=}" ;; pin_checker2_id=*) pc="${kv#*=}" ;; esac; done + printf 'schema %s\nobjective_id %s\nobjective_text %s\nprogram_format %s\nprogram %s\nentry %s\nparams %s\nret %s\ninputs %s\ntier %s\ngrant %s\nepoch %s\npin_checker2_id %s\npin_omegese_sha256 %s\npin_omega_emit_sha256 %s\n' \ + "$schema" "$id" "$text" "$fmt" "$prog" "$entry" "$params" "$ret" "$in" "$tier" "$gr" "$epoch" "$pc" "$pg" "$po" > "$f" +} +# run [runner]: runs into $T/; sets RC and leaves result.txt there +run() { + RC=0; "${3:-$VP}" run "$2" "$T/$1" --omegese "$G" --omega-emit "$OME" --checker2 "$C2" --commit test > "$T/$1.out" 2>&1 || RC=$? +} +field() { sed -n "s/^$2=//p" "$T/$1/result.txt" 2>/dev/null | head -1; } +# expect_exec : run exit 0 and verdict EXECUTED +expect_exec() { + if [ "$RC" -eq 0 ] && [ "$(field "$1" verdict)" = EXECUTED ]; then return 0; fi + bad "$1: want EXECUTED, got exit $RC: $(cat "$T/$1.out") $(cat "$T/$1/result.txt" 2>/dev/null | tr '\n' ' ')"; return 1 +} +# expect_refused : run exit 1, verdict REFUSED with that rejection, and no receipt written +expect_refused() { + local got; got="$(field "$1" rejection)" + if [ "$RC" -eq 1 ] && [ "$(field "$1" verdict)" = REFUSED ] && [ "$got" = "$2" ] && [ -z "$(ls "$T/$1/receipts" 2>/dev/null)" ]; then + ok "$1: REFUSED $2 ($(field "$1" stage): $(field "$1" detail))" + else bad "$1: want REFUSED $2, got exit $RC rejection=$got: $(cat "$T/$1.out")"; fi +} +# verify [receipt id] [extra args]: sets VRC and VOUT +verify() { + local id="$4"; [ -n "$id" ] || id="$(field "$1" receipt_id)" + VRC=0; VOUT="$("$VV" --receipt-id "$id" --store "$T/$1" --objective-text "$2" --oracle "$3" --checker2 "$C2" --epoch 1 --host-check 2>&1)" || VRC=$? +} +expect_verified() { + verify "$1" "$2" "$3" "${4:-}" + if [ "$VRC" -eq 0 ] && [ "${VOUT%% *}" = VERIFIED ]; then ok "$1: $VOUT"; else bad "$1: want VERIFIED, got exit $VRC: $VOUT"; fi +} +expect_fail() { # [receipt id] + verify "$1" "$2" "$3" "${5:-}" + case "$VOUT" in "FAIL $4"*) [ "$VRC" -eq 1 ] && { ok "$1: verifier $VOUT"; return; } ;; esac + bad "$1: want verifier FAIL $4, got exit $VRC: $VOUT" +} + +[ -x "$VP" ] && [ -x "$VV" ] || { echo "FAIL tools missing: $VP $VV"; exit 1; } + +# ---- 1. positives ---------------------------------------------------------------------------------- +grant "$T/g_gcd" "$TXT_GCD" pure +grant "$T/g_col" "$TXT_COL" pure +grant "$T/g_mul" "$TXT_MUL" pure +req "$T/r_gcd" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run gcd "$T/r_gcd"; expect_exec gcd && expect_verified gcd "$TXT_GCD" gcd_u32 +run gcd2 "$T/r_gcd"; expect_exec gcd2 +if [ -n "$(field gcd receipt_id)" ] && [ "$(field gcd receipt_id)" = "$(field gcd2 receipt_id)" ]; then + ok "determinism: two runs, one receipt id $(field gcd receipt_id)"; else bad "determinism: receipt ids differ"; fi +r="$(field gcd receipt_id)" +if [ -f "$T/gcd/receipts/$r.vpr" ] && [ "$(sha256sum < "$T/gcd/receipts/$r.vpr" | cut -c1-64)" = "$r" ] && + grep -qx "outputs_sha256=$(field gcd outputs_sha256)" "$T/gcd/receipts/$r.vpr" && + grep -qx "objective_id=$(oid "$TXT_GCD")" "$T/gcd/receipts/$r.vpr" && grep -qx 'gpu_used=no' "$T/gcd/receipts/$r.vpr"; then + ok "receipt: content-addressed, bound to the objective and the result, gpu_used=no" +else bad "receipt layout"; fi +if grep -Eq '^wall_ns=[0-9]+$' "$T/gcd/measure.txt" && grep -Eq '^maxrss_kb=[0-9]+$' "$T/gcd/measure.txt" && + grep -qx "receipt_id=$r" "$T/gcd/measure.txt"; then ok "measurements recorded beside the receipt"; else bad "measure.txt"; fi + +req "$T/r_col" "$TXT_COL" omegese-v1 "$DEV/dev/dev08.omegese" collatz_steps u32 u32 "$FX/collatz.in" "$T/g_col" +run col "$T/r_col"; expect_exec col && expect_verified col "$TXT_COL" collatz_steps_u32 +req "$T/r_colm" "$TXT_COL" omegese-v1 "$DEV/trial2/dev08.omegese" collatz_steps u32 u32 "$FX/collatz.in" "$T/g_col" +run colm "$T/r_colm"; expect_exec colm && expect_verified colm "$TXT_COL" collatz_steps_u32 +req "$T/r_mul" "$TXT_MUL" omegese-v1 "$DEV/dev/dev05.omegese" checked_mul "i16 i16" i16 "$FX/mul.in" "$T/g_mul" +run mul "$T/r_mul"; expect_exec mul && expect_verified mul "$TXT_MUL" checked_mul_i16 +if grep -qx 'T 1' "$T/mul/store/$(field mul outputs_sha256)" 2>/dev/null; then ok "mul: overflow traps recorded as T 1"; else bad "mul: no trap line"; fi +# the op-list form of the same gcd (control for the checker2 rejection below) +"$G" emit "$DEV/dev/dev04.omegese" "$T/dev04.json" > /dev/null +req "$T/r_gcdop" "$TXT_GCD" oplist-v1 "$T/dev04.json" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run gcdop "$T/r_gcdop"; expect_exec gcdop && expect_verified gcdop "$TXT_GCD" gcd_u32 +# heap effect granted (control for the unauthorized-effect refusal below) +grant "$T/g_gcdh" "$TXT_GCD" "pure heap" +req "$T/r_heapok" "$TXT_GCD" omegese-v1 "$FX/gcd_heap.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcdh" +run heapok "$T/r_heapok"; expect_exec heapok && expect_verified heapok "$TXT_GCD" gcd_u32 +# a designer collatz on the input past 32 bits (control for the model answer below) +req "$T/r_colbig" "$TXT_COL" omegese-v1 "$DEV/dev/dev08.omegese" collatz_steps u32 u32 "$FX/collatz_big.in" "$T/g_col" +run colbig "$T/r_colbig"; expect_exec colbig && expect_verified colbig "$TXT_COL" collatz_steps_u32 + +# ---- 2. negatives ---------------------------------------------------------------------------------- +# incorrect but parseable: accepted by emit and checker2, executed, and caught only by the verifier +req "$T/r_wrong" "$TXT_GCD" omegese-v1 "$FX/gcd_wrong.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run wrong "$T/r_wrong"; expect_exec wrong && expect_fail wrong "$TXT_GCD" gcd_u32 WRONG_RESULT +req "$T/r_colmbig" "$TXT_COL" omegese-v1 "$DEV/trial2/dev08.omegese" collatz_steps u32 u32 "$FX/collatz_big.in" "$T/g_col" +run colmbig "$T/r_colmbig"; expect_exec colmbig && expect_fail colmbig "$TXT_COL" collatz_steps_u32 WRONG_RESULT +# checker2 rejection (the op list passes omega_emit), and an emit refusal +req "$T/r_unb" "$TXT_GCD" oplist-v1 "$FX/gcd_unbounded.json" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run unb "$T/r_unb"; expect_refused unb CHECKER_REJECT +case "$(field unb detail)" in *C2-LOOP-UNBOUNDED*) ok "unb: rule C2-LOOP-UNBOUNDED named" ;; *) bad "unb: rule not named: $(field unb detail)" ;; esac +req "$T/r_arity" "$TXT_GCD" omegese-v1 "$FX/gcd_arity.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run arity "$T/r_arity"; expect_refused arity EMIT_REFUSED +# tampered artifacts in the store after a good run +for what in ir_sha256 code_sha256 outputs_sha256; do + rm -rf "$T/tam_$what"; cp -r "$T/gcd" "$T/tam_$what" + h="$(sed -n "s/^$what=//p" "$T/gcd/receipts/$r.vpr")"; f="$T/tam_$what/store/$h" + b="$(od -An -tu1 -j8 -N1 "$f" | tr -d ' ')" # flip the low bit of byte 8 (a real change, whatever it held) + chmod u+w "$f"; printf "\\$(printf '%03o' $(( b ^ 1 )))" | dd of="$f" bs=1 seek=8 conv=notrunc status=none + cmp -s "$f" "$T/gcd/store/$h" && bad "tam_$what: the tamper changed nothing" + expect_fail "tam_$what" "$TXT_GCD" gcd_u32 STORE_TAMPERED "$r" +done +# a forged result stored under its own hash, with the receipt rewritten to name it: new receipt id +rm -rf "$T/forge"; cp -r "$T/gcd" "$T/forge"; o="$(field gcd outputs_sha256)" +sed '1s/.*/R 13/' "$T/gcd/store/$o" > "$T/forged.out"; fo="$(sha256sum < "$T/forged.out" | cut -c1-64)" +cp "$T/forged.out" "$T/forge/store/$fo" +sed "s/^outputs_sha256=$o\$/outputs_sha256=$fo/" "$T/gcd/receipts/$r.vpr" > "$T/forged.vpr"; fr="$(sha256sum < "$T/forged.vpr" | cut -c1-64)" +rm "$T/forge/receipts/$r.vpr"; cp "$T/forged.vpr" "$T/forge/receipts/$fr.vpr" +expect_fail forge "$TXT_GCD" gcd_u32 RECEIPT_MISSING "$r" # the Pi holds the original id: the forged receipt is not it +cp "$T/forged.vpr" "$T/forge/receipts/$r.vpr" +expect_fail forge "$TXT_GCD" gcd_u32 RECEIPT_ID_MISMATCH "$r" +rm "$T/forge/receipts/$r.vpr" +expect_fail forge "$TXT_GCD" gcd_u32 WRONG_RESULT "$fr" # even with the forged id, the oracle refuses it +# stale or mismatched objective, stale grant +req "$T/r_oid" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" objective_id="$(oid "$TXT_OTHER")" +run oid "$T/r_oid"; expect_refused oid OBJECTIVE_MISMATCH +grant "$T/g_other" "$TXT_OTHER" pure +req "$T/r_gobj" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_other" +run gobj "$T/r_gobj"; expect_refused gobj GRANT_OBJECTIVE +grant "$T/g_old" "$TXT_GCD" pure 1 3 +req "$T/r_gold" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_old" epoch=4 +run gold "$T/r_gold"; expect_refused gold GRANT_EPOCH +expect_fail gcd "$TXT_OTHER" gcd_u32 OBJECTIVE_MISMATCH # the Pi asked something else +# unauthorized effect: the heap program under a grant for pure compute only +req "$T/r_heap" "$TXT_GCD" omegese-v1 "$FX/gcd_heap.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run heap "$T/r_heap"; expect_refused heap UNAUTHORIZED_EFFECT +# a tampered grant after a good heap run: the verifier recomputes the effects from the IR +rm -rf "$T/tgr"; cp -r "$T/heapok" "$T/tgr"; hr="$(field heapok receipt_id)" +gh="$(sed -n 's/^grant_sha256=//p' "$T/heapok/receipts/$hr.vpr")" +sed 's/^effects .*/effects pure/' "$T/heapok/store/$gh" > "$T/g_forged"; gf="$(sha256sum < "$T/g_forged" | cut -c1-64)" +cp "$T/g_forged" "$T/tgr/store/$gf" +sed "s/^grant_sha256=$gh\$/grant_sha256=$gf/; s/^effects_granted=.*/effects_granted=pure/" "$T/heapok/receipts/$hr.vpr" > "$T/tgr.vpr" +tr="$(sha256sum < "$T/tgr.vpr" | cut -c1-64)"; cp "$T/tgr.vpr" "$T/tgr/receipts/$tr.vpr" +expect_fail tgr "$TXT_GCD" gcd_u32 UNAUTHORIZED_EFFECT "$tr" +# bytes changed between the check and the execution (canary builds of the runner) +for k in 1 2; do + want=PREFLIGHT_IR_CHANGED; [ "$k" = 2 ] && want=PREFLIGHT_CODE_CHANGED + if [ -x "$VPD/verified_program_tamper$k" ]; then run "tamper$k" "$T/r_gcd" "$VPD/verified_program_tamper$k"; expect_refused "tamper$k" "$want" + else bad "canary build verified_program_tamper$k missing"; fi +done +# the sandbox is live: a canary child that makes one forbidden system call is killed by the kernel +if [ -x "$VPD/verified_program_tamper3" ]; then + run tamper3 "$T/r_gcd" "$VPD/verified_program_tamper3"; expect_refused tamper3 EXEC_FAILED + case "$(field tamper3 detail)" in *signal_9*) ok "tamper3: killed by SIGKILL (seccomp strict)" ;; *) bad "tamper3: not a seccomp kill: $(field tamper3 detail)" ;; esac +else bad "canary build verified_program_tamper3 missing"; fi +# unknown versions +req "$T/r_v2" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" schema=omega.verified_program.request.v2 +run v2 "$T/r_v2"; expect_refused v2 UNKNOWN_VERSION +"$OME" emit "$T/dev04.json" "$T/dev04.oscir" > /dev/null +cp "$T/dev04.oscir" "$T/dev04v9.oscir"; printf '\011' | dd of="$T/dev04v9.oscir" bs=1 seek=7 conv=notrunc status=none +req "$T/r_irv" "$TXT_GCD" oscir-v1 "$T/dev04v9.oscir" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run irv "$T/r_irv"; expect_refused irv CHECKER_REJECT +req "$T/r_irok" "$TXT_GCD" oscir-v1 "$T/dev04.oscir" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" +run irok "$T/r_irok"; expect_exec irok && expect_verified irok "$TXT_GCD" gcd_u32 +# pins, signature, inputs, tier +req "$T/r_pin" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gcd" pin_checker2_id="$(printf '0%.0s' $(seq 64))" +run pin "$T/r_pin"; expect_refused pin PIN_MISMATCH +req "$T/r_sig" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u64 "$FX/gcd.in" "$T/g_gcd" +run sig "$T/r_sig"; expect_refused sig SIGNATURE_MISMATCH +printf '4294967296 1\n' > "$T/range.in" +req "$T/r_range" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$T/range.in" "$T/g_gcd" +run range "$T/r_range"; expect_refused range INPUT_RANGE +grant "$T/g_few" "$TXT_GCD" pure 1 10 4 +req "$T/r_many" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_few" +run many "$T/r_many"; expect_refused many INPUT_LIMIT +grant "$T/g_gpu" "$TXT_GCD" pure 1 10 64 gb10-gpu +req "$T/r_gpu" "$TXT_GCD" omegese-v1 "$DEV/dev/dev04.omegese" gcd "u32 u32" u32 "$FX/gcd.in" "$T/g_gpu" tier=gb10-gpu +run gpu "$T/r_gpu"; expect_refused gpu TIER_UNSUPPORTED +# the verifier refuses an oracle for another signature +expect_fail gcd "$TXT_GCD" collatz_steps_u32 ORACLE_SIGNATURE + +echo "verified-program: $passes checks passed, $fails failed" +[ "$fails" -eq 0 ] && echo "VERIFIED_PROGRAM_PASS" || { echo "VERIFIED_PROGRAM_FAIL"; exit 1; } diff --git a/tools/verified_program/vp.c b/tools/verified_program/vp.c new file mode 100644 index 000000000..76341cc5f --- /dev/null +++ b/tools/verified_program/vp.c @@ -0,0 +1,857 @@ +/* + * vp.c -- the verified-program entrypoint (omega#505, docs/one_layer/VERIFIED_PROGRAM.md). + * + * verified_program run --omegese P --omega-emit P --checker2 P [--commit SHA] + * + * One request (program bytes, declared signature, bounded inputs, objective, grant, pins, tier) goes + * through the existing chain and nothing else: + * omegese emit -> omega_emit emit -> canonical OSC IR -> checker2 check -> checker2 receipt issue + * (TEST class, binds IR, code image, objective binding and inputs) -> preflight (IR and code bytes + * re-read and re-hashed, checker2 run again on the exact bytes, code image word self-check and an + * independent recompile that must give the same bytes) -> execution in a child under seccomp strict + * mode -> an execution receipt that names every artifact by its SHA-256 in a content-addressed store. + * + * Authority. The grant is an input written by the runtime authority (AIENOS / sovereign-core). This tool + * only checks that the grant names the same objective, tier and epoch window and covers the effects + * the checked IR needs; it never mints or widens a grant. checker2 judges the IR; it grants nothing. + * + * Exit: 0 EXECUTED (result.txt verdict=EXECUTED), 1 REFUSED (result.txt names one rejection code), + * 2 usage or I/O error. A refusal writes no receipt. EXECUTED says the program ran under its grant; it + * does NOT say the result is right: that is the independent verifier's job (vp_verify.c). + * + * Canary builds (negative controls only): -DVP_TAMPER=1 changes one IR byte in the store after the + * receipt is issued and before the preflight; -DVP_TAMPER=2 does the same to the code image. The + * preflight must refuse both. -DVP_TAMPER=3 makes one forbidden system call inside the sandbox; the + * kernel must kill the child and the run must be refused (EXEC_FAILED). + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "osc_cg.h" +#include "osc_ir.h" +#include "osc_native.h" +#include "osc_rt.h" +#include "sha256.h" + +/* Every path is built from an outdir and request path checked to be at most 1024 bytes (main), so the + * 4096-byte path buffers cannot truncate; GCC cannot see that bound. */ +#pragma GCC diagnostic ignored "-Wformat-truncation" + +#ifndef VP_TAMPER +#define VP_TAMPER 0 +#endif + +#define REQ_SCHEMA "omega.verified_program.request.v1" +#define GRANT_SCHEMA "aien.verified_program.grant.v1" +#define TIER_HOST "host-cpu-aarch64" +#define OBJ_TAG "AIEN_E2E_OBJECTIVE_V1" +#define MAX_CALLS 4096u +#define MAX_FILE (1u << 20) + +/* ---- small helpers ---------------------------------------------------------------------------- */ + +static const char *g_out; /* outdir */ +static char g_objective_id[65] = "-"; +static char g_ir_sha[65] = "-"; + +static void hex32(const uint8_t d[32], char out[65]) +{ + static const char *x = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = x[d[i] >> 4]; out[2 * i + 1] = x[d[i] & 15]; } + out[64] = 0; +} + +static void sha_hex(const uint8_t *b, size_t n, char out[65]) +{ + uint8_t d[32]; + sha256_hash(b, n, d); + hex32(d, out); +} + +static int is_hex64(const char *s) +{ + if (strlen(s) != 64) return 0; + for (; *s; s++) if (!((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'f'))) return 0; + return 1; +} + +static void die_io(const char *what) +{ + fprintf(stderr, "verified_program: %s: %s\n", what, strerror(errno)); + exit(2); +} + +static uint8_t *read_file(const char *path, size_t max, size_t *len) +{ + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + size_t cap = 4096, n = 0; + uint8_t *b = malloc(cap + 1); + if (!b) { close(fd); return NULL; } + for (;;) { + if (n == cap) { + if (cap > max) { free(b); close(fd); errno = EFBIG; return NULL; } + uint8_t *nb = realloc(b, cap * 2 + 1); + if (!nb) { free(b); close(fd); return NULL; } + b = nb; cap *= 2; + } + ssize_t r = read(fd, b + n, cap - n); + if (r < 0) { if (errno == EINTR) continue; free(b); close(fd); return NULL; } + if (r == 0) break; + n += (size_t)r; + } + close(fd); + if (n > max) { free(b); errno = EFBIG; return NULL; } + b[n] = 0; + *len = n; + return b; +} + +static int write_all(int fd, const void *p, size_t n) +{ + const uint8_t *b = p; + while (n) { + ssize_t w = write(fd, b, n); + if (w < 0) { if (errno == EINTR) continue; return -1; } + b += w; n -= (size_t)w; + } + return 0; +} + +/* Exclusive create; identical bytes already there is a no-op, any other content is an error. */ +static int put_file(const char *path, const void *p, size_t n, mode_t mode) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode); + if (fd < 0) { + if (errno != EEXIST) return -1; + size_t ol = 0; + uint8_t *old = read_file(path, MAX_FILE * 4u, &ol); + int same = old && ol == n && !memcmp(old, p, n); + free(old); + if (same) return 0; + errno = EEXIST; + return -1; + } + int rc = write_all(fd, p, n); + if (close(fd) || rc) return -1; + return 0; +} + +/* The content-addressed store: /store/, read-only files. */ +static void store_put(const void *p, size_t n, char hex[65]) +{ + char path[4096]; + sha_hex(p, n, hex); + snprintf(path, sizeof path, "%s/store/%s", g_out, hex); + if (put_file(path, p, n, 0444)) die_io(path); +} + +/* One space-free token for result fields (key=value lines). */ +static void token(char *s) +{ + for (; *s; s++) if ((unsigned char)*s <= ' ' || (unsigned char)*s >= 127 || *s == '=') *s = '_'; +} + +static void write_result(const char *verdict, const char *rejection, const char *stage, const char *detail, + const char *outputs, const char *receipt, const char *c2r) +{ + char d[256], path[4096], buf[2048]; + snprintf(d, sizeof d, "%s", detail && *detail ? detail : "-"); + token(d); + int n = snprintf(buf, sizeof buf, + "schema=omega.verified_program.result.v1\nverdict=%s\nrejection=%s\nstage=%s\ndetail=%s\n" + "objective_id=%s\nir_sha256=%s\noutputs_sha256=%s\nreceipt_id=%s\nchecker2_receipt_id=%s\n", + verdict, rejection, stage, d, g_objective_id, g_ir_sha, outputs, receipt, c2r); + snprintf(path, sizeof path, "%s/result.txt", g_out); + if (put_file(path, buf, (size_t)n, 0644)) die_io(path); +} + +static void refuse(const char *code, const char *stage, const char *fmt, ...) +{ + char detail[256]; + va_list ap; + va_start(ap, fmt); + vsnprintf(detail, sizeof detail, fmt, ap); + va_end(ap); + write_result("REFUSED", code, stage, detail, "-", "-", "-"); + printf("REFUSED %s %s: %s\n", code, stage, detail); + exit(1); +} + +/* Run argv; capture stdout and stderr together (at most cap-1 bytes, NUL-terminated). Exit code, or + * 128+signal; -1 when it could not start. */ +static int run_capture(char *const argv[], char *out, size_t cap) +{ + int p[2]; + if (pipe2(p, O_CLOEXEC)) return -1; + pid_t c = fork(); + if (c < 0) { close(p[0]); close(p[1]); return -1; } + if (c == 0) { + dup2(p[1], 1); + dup2(p[1], 2); + execv(argv[0], argv); + _exit(127); + } + close(p[1]); + size_t n = 0; + for (;;) { + char tmp[4096]; + ssize_t r = read(p[0], tmp, sizeof tmp); + if (r < 0) { if (errno == EINTR) continue; break; } + if (r == 0) break; + size_t k = (size_t)r; + if (n + k > cap - 1) k = cap - 1 - n; + memcpy(out + n, tmp, k); + n += k; + } + out[n] = 0; + close(p[0]); + int st = 0; + while (waitpid(c, &st, 0) < 0) if (errno != EINTR) return -1; + return WIFEXITED(st) ? WEXITSTATUS(st) : 128 + WTERMSIG(st); +} + +static void first_line(char *s) +{ + char *nl = strchr(s, '\n'); + if (nl) *nl = 0; +} + +static int file_sha(const char *path, char hex[65]) +{ + size_t n = 0; + uint8_t *b = read_file(path, 256u << 20, &n); + if (!b) return -1; + sha_hex(b, n, hex); + free(b); + return 0; +} + +/* ---- request and grant ------------------------------------------------------------------------ */ + +static const char *const REQ_KEYS[] = {"schema", "objective_id", "objective_text", "program_format", "program", + "entry", "params", "ret", "inputs", "tier", "grant", "epoch", + "pin_checker2_id", "pin_omegese_sha256", "pin_omega_emit_sha256"}; +#define NREQ (sizeof REQ_KEYS / sizeof REQ_KEYS[0]) +static const char *const GRANT_KEYS[] = {"schema", "objective_id", "tier", "effects", "epoch_first", "epoch_last", + "max_calls"}; +#define NGRANT (sizeof GRANT_KEYS / sizeof GRANT_KEYS[0]) + +/* Split text into exactly nk lines "key value" in the fixed key order. vals[i] points into text. A + * value is everything after the first space (may be empty only where allowed by the caller). Returns + * 0, or -1 with why filled. The schema line is checked by the caller (unknown version first). */ +static int parse_kv(char *text, size_t len, const char *const *keys, size_t nk, char **vals, char *why, size_t wn) +{ + if (memchr(text, 0, len)) { snprintf(why, wn, "NUL byte"); return -1; } + if (len == 0 || text[len - 1] != '\n') { snprintf(why, wn, "must end with a newline"); return -1; } + char *p = text; + for (size_t i = 0; i < nk; i++) { + char *nl = strchr(p, '\n'); + if (!nl) { snprintf(why, wn, "missing line %s", keys[i]); return -1; } + *nl = 0; + if (strchr(p, '\r')) { snprintf(why, wn, "carriage return in line %zu", i + 1); return -1; } + size_t kl = strlen(keys[i]); + if (strncmp(p, keys[i], kl) || (p[kl] != ' ' && p[kl] != 0)) { + snprintf(why, wn, "line %zu: want key %s", i + 1, keys[i]); + return -1; + } + vals[i] = p[kl] ? p + kl + 1 : p + kl; + p = nl + 1; + } + if (*p) { snprintf(why, wn, "extra lines after %s", keys[nk - 1]); return -1; } + return 0; +} + +static int parse_u64(const char *s, uint64_t *v) +{ + if (!*s || (*s == '0' && s[1])) return -1; + uint64_t x = 0; + for (; *s; s++) { + if (*s < '0' || *s > '9') return -1; + unsigned d = (unsigned)(*s - '0'); + if (x > (UINT64_MAX - d) / 10) return -1; + x = x * 10 + d; + } + *v = x; + return 0; +} + +static int kind_of(const char *s) +{ + static const char *const nm[] = {"bool", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"}; + static const int k[] = {OSC_T_BOOL, OSC_T_U8, OSC_T_U16, OSC_T_U32, OSC_T_U64, OSC_T_I8, OSC_T_I16, OSC_T_I32, OSC_T_I64}; + for (int i = 0; i < 9; i++) if (!strcmp(s, nm[i])) return k[i]; + return -1; +} + +enum { EFF_PURE = 1, EFF_HEAP = 2, EFF_CALLER = 4 }; + +static void effects_text(unsigned e, char *out, size_t n) +{ + snprintf(out, n, "%s%s%s", e & EFF_PURE ? "pure" : "", e & EFF_HEAP ? ",heap" : "", e & EFF_CALLER ? ",caller_memory" : ""); +} + +/* What the checked IR needs, read from every instruction and register type of every function. */ +static unsigned effects_of(const OscUnit *u) +{ + unsigned e = EFF_PURE; + for (unsigned f = 0; f < u->nfuncs; f++) { + const OscFunc *fn = &u->funcs[f]; + for (unsigned v = 0; v < fn->nvregs; v++) + if (fn->vtype[v].s == OSC_T_BYTES || fn->vtype[v].s == OSC_T_CELLS) e |= EFF_CALLER; + for (uint32_t i = 0; i < fn->ninsns; i++) switch (fn->insns[i].op) { + case OSC_I_ALLOC: case OSC_I_RELEASE: case OSC_I_AOPEN: case OSC_I_AALLOC: case OSC_I_ADESTROY: + case OSC_I_POPEN: case OSC_I_PCLOSE: case OSC_I_HALLOC: case OSC_I_HGEN: case OSC_I_HFREE: + case OSC_I_HLOAD: case OSC_I_HSTORE: + e |= EFF_HEAP; break; + case OSC_I_SLOAD: case OSC_I_SSTORE: + e |= EFF_CALLER; break; + default: break; + } + } + return e; +} + +/* ---- hardware --------------------------------------------------------------------------------- */ + +/* "aarch64/:::,..." over the distinct core kinds, sorted. */ +static void host_cpu(char *out, size_t n) +{ + struct utsname un; + char kinds[16][64]; + int nk = 0; + char imp[16] = "?", var[16] = "?", part[16] = "?", rev[16] = "?"; + FILE *f = fopen("/proc/cpuinfo", "re"); + if (uname(&un)) snprintf(un.machine, sizeof un.machine, "unknown"); + if (f) { + char line[256]; + int more = 1; + while (more) { + more = fgets(line, sizeof line, f) != NULL; + char *c = more ? strchr(line, ':') : NULL; + if (c) { + char *v = c + 1; + while (*v == ' ' || *v == '\t') v++; + v[strcspn(v, "\n")] = 0; + if (!strncmp(line, "CPU implementer", 15)) snprintf(imp, sizeof imp, "%s", v); + else if (!strncmp(line, "CPU variant", 11)) snprintf(var, sizeof var, "%s", v); + else if (!strncmp(line, "CPU part", 8)) snprintf(part, sizeof part, "%s", v); + else if (!strncmp(line, "CPU revision", 12)) snprintf(rev, sizeof rev, "%s", v); + } + if ((!more || line[0] == '\n') && strcmp(part, "?")) { + char k[64]; + snprintf(k, sizeof k, "%s:%s:%s:%s", imp, var, part, rev); + int seen = 0; + for (int i = 0; i < nk; i++) if (!strcmp(kinds[i], k)) seen = 1; + if (!seen && nk < 16) snprintf(kinds[nk++], sizeof kinds[0], "%s", k); + snprintf(part, sizeof part, "?"); + } + } + fclose(f); + } + for (int i = 0; i < nk; i++) + for (int j = i + 1; j < nk; j++) + if (strcmp(kinds[j], kinds[i]) < 0) { char t[64]; memcpy(t, kinds[i], 64); memcpy(kinds[i], kinds[j], 64); memcpy(kinds[j], t, 64); } + size_t o = (size_t)snprintf(out, n, "%s/", un.machine); + for (int i = 0; i < nk && o < n; i++) o += (size_t)snprintf(out + o, n - o, "%s%s", i ? "," : "", kinds[i]); + if (!nk && o < n) snprintf(out + o, n - o, "unknown"); +} + +/* ---- execution -------------------------------------------------------------------------------- */ + +typedef struct { + uint64_t wall_ns, user_us, sys_us; + long maxrss_kb; +} Measure; + +static uint64_t now_ns(void) +{ + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000u + (uint64_t)t.tv_nsec; +} + +static uint64_t canon(uint64_t v, int kind) +{ + unsigned w = osc_scalar_width((OscScalar)kind); + if (kind == OSC_T_BOOL) return v & 1; + if (w >= 64) return v; + uint64_t m = (1ull << w) - 1; + v &= m; + if (osc_scalar_signed((OscScalar)kind) && (v >> (w - 1)) & 1) v |= ~m; + return v; +} + +static void fmt_value(char *o, size_t n, uint64_t v, int kind) +{ + if (osc_scalar_signed((OscScalar)kind)) snprintf(o, n, "%" PRId64, (int64_t)v); + else snprintf(o, n, "%" PRIu64, v); +} + +/* Child: map the exact code bytes, enter seccomp strict mode (read, write, _exit, sigreturn only), + * run every call, write the transcript to fd w, _exit. Native code that tries anything else is killed + * by the kernel. The transcript is formatted without stdio (no hidden syscalls). */ +static void child_exec(int w, const OscUnit *u, int fi, const uint8_t *code, size_t clen, uint32_t entry, + const uint64_t *in, uint32_t ncalls, unsigned np, int ret_kind) +{ + struct rlimit cpu = {10, 10}; + setrlimit(RLIMIT_CPU, &cpu); + OscNative nm; + OscRt *rt = malloc(sizeof *rt); + size_t cap = (size_t)ncalls * 32u + 16u; + char *buf = malloc(cap); + if (!rt || !buf || osc_native_map(&nm, code, clen)) _exit(3); + osc_rt_init(rt); + if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0, 0, 0)) _exit(4); +#if VP_TAMPER == 3 + syscall(SYS_getpid); /* canary: any call outside read, write, _exit, sigreturn must kill the child */ +#endif + size_t o = 0; + for (uint32_t i = 0; i < ncalls; i++) { + uint64_t r = 0; + osc_rt_reset(rt); + int t = osc_native_call(u, fi, &nm, entry, rt, in + (size_t)i * np, np, &r); + if (t < 0) syscall(SYS_exit, 5); + char v[32]; + if (t > 0) snprintf(v, sizeof v, "%d", t); + else fmt_value(v, sizeof v, canon(r, ret_kind), ret_kind); + o += (size_t)snprintf(buf + o, cap - o, "%s %s\n", t > 0 ? "T" : "R", v); + } + size_t k = 0; + while (k < o) { + long r = syscall(SYS_write, w, buf + k, o - k); + if (r <= 0) syscall(SYS_exit, 6); + k += (size_t)r; + } + syscall(SYS_exit, 0); +} + +/* ---- main ------------------------------------------------------------------------------------- */ + +static const char *opt(int argc, char **argv, const char *name) +{ + for (int i = 4; i + 1 < argc; i++) if (!strcmp(argv[i], name)) return argv[i + 1]; + return NULL; +} + +static void resolve(const char *base_dir, const char *p, char *out, size_t n) +{ + if (p[0] == '/') snprintf(out, n, "%s", p); + else snprintf(out, n, "%s/%s", base_dir, p); +} + +int main(int argc, char **argv) +{ + if (argc < 4 || strcmp(argv[1], "run") || (argc - 4) % 2) { + fprintf(stderr, "usage: verified_program run --omegese P --omega-emit P --checker2 P [--commit SHA]\n"); + return 2; + } + const char *reqp = argv[2]; + const char *t_omegese = opt(argc, argv, "--omegese"), *t_ome = opt(argc, argv, "--omega-emit"), + *t_c2 = opt(argc, argv, "--checker2"), *commit = opt(argc, argv, "--commit"); + if (!t_omegese || !t_ome || !t_c2) { fprintf(stderr, "verified_program: --omegese, --omega-emit and --checker2 are required\n"); return 2; } + if (!commit) commit = "-"; + g_out = argv[3]; + char path[4096]; + if (strlen(g_out) > 1024 || strlen(reqp) > 1024) { fprintf(stderr, "verified_program: paths longer than 1024 bytes\n"); return 2; } + if (mkdir(g_out, 0755) && errno != EEXIST) die_io(g_out); + snprintf(path, sizeof path, "%s/result.txt", g_out); + if (access(path, F_OK) == 0) { fprintf(stderr, "verified_program: %s exists; one run per outdir\n", path); return 2; } + snprintf(path, sizeof path, "%s/store", g_out); + if (mkdir(path, 0755) && errno != EEXIST) die_io(path); + snprintf(path, sizeof path, "%s/receipts", g_out); + if (mkdir(path, 0755) && errno != EEXIST) die_io(path); + snprintf(path, sizeof path, "%s/work", g_out); + if (mkdir(path, 0755) && errno != EEXIST) die_io(path); + + /* 1. request: schema first (an unknown version is refused as such), then the fixed layout */ + size_t rlen = 0; + char *rtext = (char *)read_file(reqp, 65536, &rlen); + if (!rtext) die_io(reqp); + if (strncmp(rtext, "schema ", 7) == 0) { + size_t sl = strcspn(rtext + 7, "\n"); + if (sl != strlen(REQ_SCHEMA) || strncmp(rtext + 7, REQ_SCHEMA, sl)) + refuse("UNKNOWN_VERSION", "request", "request schema is not %s", REQ_SCHEMA); + } + char *rv[NREQ], why[160]; + if (parse_kv(rtext, rlen, REQ_KEYS, NREQ, rv, why, sizeof why)) refuse("REQUEST_MALFORMED", "request", "%s", why); + const char *objective_id = rv[1], *objective_text = rv[2], *fmt = rv[3], *entry = rv[5], *tier = rv[9]; + char req_dir[4096]; + snprintf(req_dir, sizeof req_dir, "%s", reqp); + char *slash = strrchr(req_dir, '/'); + if (slash) *slash = 0; else snprintf(req_dir, sizeof req_dir, "."); + char prog_path[4096], in_path[4096], grant_path[4096]; + resolve(req_dir, rv[4], prog_path, sizeof prog_path); + resolve(req_dir, rv[8], in_path, sizeof in_path); + resolve(req_dir, rv[10], grant_path, sizeof grant_path); + uint64_t epoch = 0; + if (parse_u64(rv[11], &epoch) || epoch == 0) refuse("REQUEST_MALFORMED", "request", "epoch is not a positive integer"); + int fmt_k = !strcmp(fmt, "omegese-v1") ? 0 : !strcmp(fmt, "oplist-v1") ? 1 : !strcmp(fmt, "oscir-v1") ? 2 : -1; + if (fmt_k < 0) refuse("UNKNOWN_VERSION", "request", "program_format %s", fmt); + if (strcmp(tier, TIER_HOST)) + refuse("TIER_UNSUPPORTED", "request", "tier %s: only %s executes here; a GPU tier needs its own lowering and device receipt", tier, TIER_HOST); + struct utsname un; + if (uname(&un) || strcmp(un.machine, "aarch64")) refuse("TIER_UNAVAILABLE", "request", "this host is not aarch64"); + unsigned np = 0; + int pk[OSC_MAX_PARAMS], ret_kind = kind_of(rv[7]); + { + char ptxt[256]; + snprintf(ptxt, sizeof ptxt, "%s", rv[6]); + for (char *s = strtok(ptxt, " "); s; s = strtok(NULL, " ")) { + if (np == OSC_MAX_PARAMS || (pk[np] = kind_of(s)) < 0) refuse("REQUEST_MALFORMED", "request", "params: bad kind or more than 6"); + np++; + } + } + if (ret_kind < 0) refuse("REQUEST_MALFORMED", "request", "ret: bad kind"); + + /* 2. objective: the id is SHA-256 of the tag, LF, the text (sovereign-core objective.rs) */ + if (!*objective_text) refuse("REQUEST_MALFORMED", "objective", "empty objective text"); + for (const char *c = objective_text; *c; c++) + if ((unsigned char)*c < 0x20 || *c == 0x7f) refuse("REQUEST_MALFORMED", "objective", "control byte in the objective text"); + char obj_buf[70000]; + int obl = snprintf(obj_buf, sizeof obj_buf, "%s\n%s", OBJ_TAG, objective_text); + char want_id[65]; + sha_hex((const uint8_t *)obj_buf, (size_t)obl, want_id); + if (!is_hex64(objective_id) || strcmp(objective_id, want_id)) + refuse("OBJECTIVE_MISMATCH", "objective", "objective_id is not SHA-256 of the tag and this objective text"); + snprintf(g_objective_id, sizeof g_objective_id, "%s", objective_id); + + /* 3. grant (the runtime authority's record; checked, never minted here) */ + size_t glen = 0; + char *gbytes = (char *)read_file(grant_path, 4096, &glen); + if (!gbytes) refuse("GRANT_MISSING", "grant", "no readable grant"); + char *gcopy = malloc(glen + 1); + if (!gcopy) die_io("malloc"); + memcpy(gcopy, gbytes, glen + 1); + char *gv[NGRANT]; + if (strncmp(gcopy, "schema ", 7) == 0 && strncmp(gcopy + 7, GRANT_SCHEMA "\n", strlen(GRANT_SCHEMA) + 1)) + refuse("UNKNOWN_VERSION", "grant", "grant schema is not %s", GRANT_SCHEMA); + if (parse_kv(gcopy, glen, GRANT_KEYS, NGRANT, gv, why, sizeof why)) refuse("GRANT_MALFORMED", "grant", "%s", why); + uint64_t e_first = 0, e_last = 0, max_calls = 0; + if (parse_u64(gv[4], &e_first) || parse_u64(gv[5], &e_last) || parse_u64(gv[6], &max_calls) || e_first > e_last || + max_calls == 0 || max_calls > MAX_CALLS) + refuse("GRANT_MALFORMED", "grant", "epochs or max_calls"); + unsigned granted = 0; + { + char etxt[128]; + snprintf(etxt, sizeof etxt, "%s", gv[3]); + for (char *s = strtok(etxt, " "); s; s = strtok(NULL, " ")) { + if (!strcmp(s, "pure")) granted |= EFF_PURE; + else if (!strcmp(s, "heap")) granted |= EFF_HEAP; + else if (!strcmp(s, "caller_memory")) granted |= EFF_CALLER; + else refuse("GRANT_MALFORMED", "grant", "unknown effect %s", s); + } + } + if (strcmp(gv[1], objective_id)) refuse("GRANT_OBJECTIVE", "grant", "the grant names another objective"); + if (strcmp(gv[2], tier)) refuse("GRANT_TIER", "grant", "the grant is for tier %s", gv[2]); + if (epoch < e_first || epoch > e_last) refuse("GRANT_EPOCH", "grant", "epoch %" PRIu64 " outside the grant window", epoch); + + /* 4. pins: the tool builds this run uses */ + char sha_omegese[65], sha_ome[65], sha_c2bin[65], sha_runner[65], c2id[65] = ""; + if (file_sha(t_omegese, sha_omegese) || file_sha(t_ome, sha_ome) || file_sha(t_c2, sha_c2bin) || + file_sha("/proc/self/exe", sha_runner)) + die_io("tool digest"); + static char cap[1u << 16]; + { + char *av[] = {(char *)t_c2, "version", NULL}; + if (run_capture(av, cap, sizeof cap)) refuse("PIN_MISMATCH", "pin", "checker2 version failed"); + char *p = strstr(cap, "checker_id="); + if (!p) refuse("PIN_MISMATCH", "pin", "checker2 printed no checker_id"); + snprintf(c2id, sizeof c2id, "%.64s", p + 11); + } + if (strcmp(rv[12], "-") && strcmp(rv[12], c2id)) refuse("PIN_MISMATCH", "pin", "checker2 identity %s is not the pinned one", c2id); + if (strcmp(rv[13], "-") && strcmp(rv[13], sha_omegese)) refuse("PIN_MISMATCH", "pin", "omegese binary is not the pinned one"); + if (strcmp(rv[14], "-") && strcmp(rv[14], sha_ome)) refuse("PIN_MISMATCH", "pin", "omega_emit binary is not the pinned one"); + + /* 5. program bytes -> op list -> canonical IR */ + size_t plen = 0; + uint8_t *pbytes = read_file(prog_path, MAX_FILE, &plen); + if (!pbytes) refuse("PROGRAM_MISSING", "program", "no readable program (max 1 MiB)"); + char sha_prog[65], sha_oplist[65] = "-"; + store_put(pbytes, plen, sha_prog); + char json_path[4096], ir_path[4096]; + snprintf(json_path, sizeof json_path, "%s/work/program.json", g_out); + snprintf(ir_path, sizeof ir_path, "%s/work/program.oscir", g_out); + if (fmt_k == 0) { + char sp[4096]; + snprintf(sp, sizeof sp, "%s/store/%s", g_out, sha_prog); + char *av[] = {(char *)t_omegese, "emit", sp, json_path, NULL}; + int rc = run_capture(av, cap, sizeof cap); + first_line(cap); + if (rc == 1) refuse("EMIT_REFUSED", "emit", "%s", cap); + if (rc) refuse("EMIT_REFUSED", "emit", "omegese exit %d", rc); + } else if (fmt_k == 1) { + if (put_file(json_path, pbytes, plen, 0644)) die_io(json_path); + } else if (put_file(ir_path, pbytes, plen, 0644)) die_io(ir_path); + if (fmt_k <= 1) { + size_t jl = 0; + uint8_t *jb = read_file(json_path, MAX_FILE, &jl); + if (!jb) die_io(json_path); + store_put(jb, jl, sha_oplist); + free(jb); + char *av[] = {(char *)t_ome, "emit", json_path, ir_path, NULL}; + int rc = run_capture(av, cap, sizeof cap); + first_line(cap); + if (rc) refuse("LOWER_REFUSED", "lower", "%s", cap); + } + size_t irlen = 0; + uint8_t *ir = read_file(ir_path, MAX_FILE, &irlen); + if (!ir) die_io(ir_path); + store_put(ir, irlen, g_ir_sha); + char ir_store[4096]; + snprintf(ir_store, sizeof ir_store, "%s/store/%s", g_out, g_ir_sha); + + /* 6. checker2 on the exact bytes in the store */ + { + char *av[] = {(char *)t_c2, "check", ir_store, NULL}; + int rc = run_capture(av, cap, sizeof cap); + first_line(cap); + char want[128]; + snprintf(want, sizeof want, "checker2=ACCEPT ir_sha256=%s", g_ir_sha); + if (rc || strcmp(cap, want)) refuse("CHECKER_REJECT", "checker2", "%s", cap); + } + OscUnit *u = calloc(1, sizeof *u); + if (!u) die_io("malloc"); + int drc = osc_ir_decode(ir, irlen, u); + if (drc) refuse("DECODE_REFUSED", "decode", "class=%s", osc_ir_refusal_name(drc)); + + /* 7. signature and effects */ + int fi = -1; + for (unsigned i = 0; i < u->nfuncs; i++) if (!strcmp(u->funcs[i].name, entry)) { fi = (int)i; break; } + if (fi < 0) refuse("SIGNATURE_MISMATCH", "signature", "no function %s", entry); + const OscFunc *fn = &u->funcs[fi]; + if (fn->nparams != np) refuse("SIGNATURE_MISMATCH", "signature", "param count %u, declared %u", fn->nparams, np); + for (unsigned i = 0; i < np; i++) + if ((int)fn->vtype[i].s != pk[i] || fn->vtype[i].ref != OSC_REF_NONE) refuse("SIGNATURE_MISMATCH", "signature", "param %u kind", i); + if ((int)fn->ret.s != ret_kind || fn->ret.ref != OSC_REF_NONE) refuse("SIGNATURE_MISMATCH", "signature", "ret kind"); + unsigned need = effects_of(u); + char need_txt[64], granted_txt[64]; + effects_text(need, need_txt, sizeof need_txt); + effects_text(granted, granted_txt, sizeof granted_txt); + if ((need & ~granted) || !(granted & EFF_PURE)) + refuse("UNAUTHORIZED_EFFECT", "effects", "program needs %s, grant allows %s", need_txt, granted_txt); + + /* 8. bounded inputs, canonical text */ + size_t ilen = 0; + char *itext = (char *)read_file(in_path, 1u << 20, &ilen); + if (!itext) refuse("INPUT_MALFORMED", "inputs", "no readable inputs"); + uint64_t *in = malloc(sizeof *in * (MAX_CALLS * OSC_MAX_PARAMS + 1)); + char *canon_in = malloc(MAX_CALLS * OSC_MAX_PARAMS * 24u + 16u); + if (!in || !canon_in) die_io("malloc"); + uint32_t ncalls = 0; + size_t co = 0; + for (char *line = itext; *line;) { + char *nl = strchr(line, '\n'); + if (!nl) refuse("INPUT_MALFORMED", "inputs", "last line has no newline"); + *nl = 0; + if (ncalls == MAX_CALLS || ncalls >= max_calls) refuse("INPUT_LIMIT", "inputs", "more than %" PRIu64 " calls", max_calls); + unsigned k = 0; + for (char *s = strtok(line, " "); s; s = strtok(NULL, " ")) { + if (k == np) refuse("INPUT_MALFORMED", "inputs", "line %u: more than %u values", ncalls + 1, np); + int neg = *s == '-'; + uint64_t mag = 0; + if (parse_u64(s + neg, &mag) || (neg && mag == 0)) refuse("INPUT_MALFORMED", "inputs", "line %u: not a decimal", ncalls + 1); + unsigned wbits = osc_scalar_width((OscScalar)pk[k]); + uint64_t v; + if (pk[k] == OSC_T_BOOL) { + if (neg || mag > 1) refuse("INPUT_RANGE", "inputs", "line %u: bool is 0 or 1", ncalls + 1); + v = mag; + } else if (osc_scalar_signed((OscScalar)pk[k])) { + uint64_t lim = 1ull << (wbits - 1); + if ((!neg && mag > lim - 1) || (neg && mag > lim)) refuse("INPUT_RANGE", "inputs", "line %u: value %u out of range", ncalls + 1, k + 1); + v = neg ? (uint64_t)0 - mag : mag; + } else { + if (neg || (wbits < 64 && mag >> wbits)) refuse("INPUT_RANGE", "inputs", "line %u: value %u out of range", ncalls + 1, k + 1); + v = mag; + } + in[(size_t)ncalls * np + k] = v; + char t[32]; + fmt_value(t, sizeof t, v, pk[k]); + co += (size_t)sprintf(canon_in + co, "%s%s", k ? " " : "", t); + k++; + } + if (k != np) refuse("INPUT_MALFORMED", "inputs", "line %u: %u values, want %u", ncalls + 1, k, np); + canon_in[co++] = '\n'; + ncalls++; + line = nl + 1; + } + if (ncalls == 0) refuse("INPUT_LIMIT", "inputs", "no calls"); + char sha_in[65]; + store_put(canon_in, co, sha_in); + + /* 9. code image */ + OscCode code; + memset(&code, 0, sizeof code); + char err[200]; + if (osc_cg_compile(u, &code, err, sizeof err)) refuse("BACKEND_REFUSED", "backend", "%s", err); + char sha_code[65]; + store_put(code.code, code.len, sha_code); + uint32_t entry_off = code.entry[fi]; + + /* 10. objective binding, grant, objective text into the store; checker2 signed receipt */ + char sha_obj[65], sha_grant[65], sha_bind[65], params_txt[128] = ""; + store_put(objective_text, strlen(objective_text), sha_obj); + store_put(gbytes, glen, sha_grant); + for (unsigned i = 0; i < np; i++) { + size_t l = strlen(params_txt); + snprintf(params_txt + l, sizeof params_txt - l, "%s%s", i ? "," : "", osc_scalar_name((OscScalar)pk[i])); + } + if (!np) snprintf(params_txt, sizeof params_txt, "-"); + char bind[1024]; + int bl = snprintf(bind, sizeof bind, + "schema=omega.verified_program.binding.v1\nobjective_id=%s\ngrant_sha256=%s\nentry=%s\nparams=%s\n" + "ret=%s\ntier=%s\nepoch=%" PRIu64 "\n", + objective_id, sha_grant, entry, params_txt, osc_scalar_name((OscScalar)ret_kind), tier, epoch); + store_put(bind, (size_t)bl, sha_bind); + char c2_id[65] = ""; + { + char rdir[4096], exe[4096], bindp[4096], inp[4096], ep[32], ex[32]; + snprintf(rdir, sizeof rdir, "%s/work/c2r", g_out); + if (mkdir(rdir, 0755) && errno != EEXIST) die_io(rdir); + snprintf(exe, sizeof exe, "%s/store/%s", g_out, sha_code); + snprintf(bindp, sizeof bindp, "%s/store/%s", g_out, sha_bind); + snprintf(inp, sizeof inp, "%s/store/%s", g_out, sha_in); + snprintf(ep, sizeof ep, "%" PRIu64, epoch); + snprintf(ex, sizeof ex, "%" PRIu64, e_last); + char *av[] = {(char *)t_c2, "receipt", "issue", ir_store, exe, "--target", (char *)tier, "--epoch", ep, + "--expiry", ex, "--out-dir", rdir, "--requirements", bindp, "--input", inp, NULL}; + int rc = run_capture(av, cap, sizeof cap); + first_line(cap); + if (rc) refuse("CHECKER_REJECT", "checker2-receipt", "%s", cap); + /* checker2 prints "receipt=/.rcpt" (id = SHA-256 of the 416 receipt bytes) */ + char *p = strncmp(cap, "receipt=", 8) ? NULL : strrchr(cap, '/'); + if (!p || strlen(p + 1) < 69 || strncmp(p + 65, ".rcpt", 5)) refuse("CHECKER_REJECT", "checker2-receipt", "unexpected output: %s", cap); + snprintf(c2_id, sizeof c2_id, "%.64s", p + 1); + if (!is_hex64(c2_id)) refuse("CHECKER_REJECT", "checker2-receipt", "unexpected output: %s", cap); + snprintf(path, sizeof path, "%s/%s.rcpt", rdir, c2_id); + size_t cl = 0; + uint8_t *cr = read_file(path, 4096, &cl); + if (!cr) die_io(path); + char h[65]; + store_put(cr, cl, h); + if (strcmp(h, c2_id)) refuse("CHECKER_REJECT", "checker2-receipt", "receipt id is not the hash of its bytes"); + free(cr); + } + + /* 11. preflight, immediately before execution */ +#if VP_TAMPER == 1 || VP_TAMPER == 2 + { + snprintf(path, sizeof path, "%s/store/%s", g_out, VP_TAMPER == 1 ? g_ir_sha : sha_code); + chmod(path, 0644); + int fd = open(path, O_WRONLY | O_CLOEXEC); + uint8_t x = 0x5a; + if (fd < 0 || pwrite(fd, &x, 1, VP_TAMPER == 1 ? 12 : 4) != 1) die_io("tamper"); + close(fd); + } +#endif + size_t ir2len = 0, code2len = 0; + uint8_t *ir2 = read_file(ir_store, MAX_FILE, &ir2len); + snprintf(path, sizeof path, "%s/store/%s", g_out, sha_code); + uint8_t *code2 = read_file(path, MAX_FILE * 4u, &code2len); + if (!ir2 || !code2) die_io("preflight read"); + char h[65]; + sha_hex(ir2, ir2len, h); + if (strcmp(h, g_ir_sha)) refuse("PREFLIGHT_IR_CHANGED", "preflight", "IR bytes in the store changed after the check"); + { + char *av[] = {(char *)t_c2, "check", ir_store, NULL}; + int rc = run_capture(av, cap, sizeof cap); + first_line(cap); + char want[128]; + snprintf(want, sizeof want, "checker2=ACCEPT ir_sha256=%s", g_ir_sha); + if (rc || strcmp(cap, want)) refuse("PREFLIGHT_IR_CHANGED", "preflight", "checker2 on the bytes to run: %s", cap); + } + sha_hex(code2, code2len, h); + if (strcmp(h, sha_code)) refuse("PREFLIGHT_CODE_CHANGED", "preflight", "code image in the store changed after the receipt"); + OscCode chk; + memset(&chk, 0, sizeof chk); + chk.code = code2; chk.len = code2len; chk.nfuncs = code.nfuncs; + if (osc_cg_verify(&chk, err, sizeof err)) refuse("PREFLIGHT_CODE_INVALID", "preflight", "%s", err); + OscUnit *u2 = calloc(1, sizeof *u2); + OscCode code3; + memset(&code3, 0, sizeof code3); + if (!u2 || osc_ir_decode(ir2, ir2len, u2) || osc_cg_compile(u2, &code3, err, sizeof err) || code3.len != code2len || + memcmp(code3.code, code2, code2len) || code3.entry[fi] != entry_off) + refuse("PREFLIGHT_CODE_CHANGED", "preflight", "the code image is not what the back end gives for the checked IR"); + + /* 12. execution */ + int p[2]; + if (pipe2(p, O_CLOEXEC)) die_io("pipe"); + fflush(NULL); + Measure m = {0, 0, 0, 0}; + uint64_t t0 = now_ns(); + pid_t c = fork(); + if (c < 0) die_io("fork"); + if (c == 0) { + close(p[0]); + child_exec(p[1], u2, fi, code2, code2len, entry_off, in, ncalls, np, ret_kind); + } + close(p[1]); + size_t ocap = (size_t)ncalls * 32u + 16u, on = 0; + char *outb = malloc(ocap + 1); + if (!outb) die_io("malloc"); + for (;;) { + ssize_t r = read(p[0], outb + on, ocap - on); + if (r < 0) { if (errno == EINTR) continue; break; } + if (r == 0 || (on += (size_t)r) == ocap) break; + } + close(p[0]); + int st = 0; + struct rusage ru; + while (wait4(c, &st, 0, &ru) < 0) if (errno != EINTR) die_io("wait4"); + m.wall_ns = now_ns() - t0; + m.user_us = (uint64_t)ru.ru_utime.tv_sec * 1000000u + (uint64_t)ru.ru_utime.tv_usec; + m.sys_us = (uint64_t)ru.ru_stime.tv_sec * 1000000u + (uint64_t)ru.ru_stime.tv_usec; + m.maxrss_kb = ru.ru_maxrss; + if (WIFSIGNALED(st)) refuse("EXEC_FAILED", "execute", "killed by signal %d (seccomp or CPU limit)", WTERMSIG(st)); + if (!WIFEXITED(st) || WEXITSTATUS(st)) refuse("EXEC_FAILED", "execute", "executor exit %d", WEXITSTATUS(st)); + outb[on] = 0; + uint32_t lines = 0; + for (size_t i = 0; i < on; i++) if (outb[i] == '\n') lines++; + if (lines != ncalls) refuse("EXEC_FAILED", "execute", "%u result lines for %u calls", lines, ncalls); + char sha_out[65]; + store_put(outb, on, sha_out); + + /* 13. the execution receipt (deterministic: no time, no pid, no path) */ + char cpu[512], rbuf[8192], rid[65]; + host_cpu(cpu, sizeof cpu); + int rn = snprintf(rbuf, sizeof rbuf, + "schema=omega.verified_program.receipt.v1\nverdict=EXECUTED\nobjective_id=%s\nobjective_text_sha256=%s\n" + "grant_sha256=%s\nbinding_sha256=%s\nprogram_format=%s\nprogram_sha256=%s\noplist_sha256=%s\n" + "ir_sha256=%s\ncode_sha256=%s\nentry=%s\nparams=%s\nret=%s\ninputs_sha256=%s\noutputs_sha256=%s\n" + "calls=%u\neffects_required=%s\neffects_granted=%s\nchecker2_verdict=ACCEPT\nchecker2_id=%s\n" + "checker2_receipt_id=%s\nchecker2_signer=TEST\nomegese_sha256=%s\nomega_emit_sha256=%s\n" + "checker2_bin_sha256=%s\nrunner_sha256=%s\ncommit=%s\ntier=%s\nhost_cpu=%s\nmachine_id=absent\n" + "gpu_used=no\nsandbox=seccomp-strict\nepoch=%" PRIu64 "\n", + objective_id, sha_obj, sha_grant, sha_bind, fmt, sha_prog, sha_oplist, g_ir_sha, sha_code, entry, + params_txt, osc_scalar_name((OscScalar)ret_kind), sha_in, sha_out, ncalls, need_txt, granted_txt, + c2id, c2_id, fmt_k == 0 ? sha_omegese : "-", fmt_k <= 1 ? sha_ome : "-", sha_c2bin, sha_runner, + commit, tier, cpu, epoch); + sha_hex((const uint8_t *)rbuf, (size_t)rn, rid); + snprintf(path, sizeof path, "%s/receipts/%s.vpr", g_out, rid); + if (put_file(path, rbuf, (size_t)rn, 0444)) die_io(path); + char mbuf[1024]; + int mn = snprintf(mbuf, sizeof mbuf, + "schema=omega.verified_program.measure.v1\nreceipt_id=%s\nwall_ns=%" PRIu64 "\nuser_us=%" PRIu64 + "\nsys_us=%" PRIu64 "\nmaxrss_kb=%ld\ncalls=%u\nir_bytes=%zu\ncode_bytes=%zu\n", + rid, m.wall_ns, m.user_us, m.sys_us, m.maxrss_kb, ncalls, irlen, code2len); + snprintf(path, sizeof path, "%s/measure.txt", g_out); + if (put_file(path, mbuf, (size_t)mn, 0644)) die_io(path); + write_result("EXECUTED", "-", "-", "-", sha_out, rid, c2_id); + printf("EXECUTED receipt=%s outputs_sha256=%s calls=%u\n", rid, sha_out, ncalls); + return 0; +} diff --git a/tools/verified_program/vp_verify.c b/tools/verified_program/vp_verify.c new file mode 100644 index 000000000..b684e100f --- /dev/null +++ b/tools/verified_program/vp_verify.c @@ -0,0 +1,510 @@ +/* + * vp_verify.c -- the independent verifier for verified-program receipts (omega#505, + * docs/one_layer/VERIFIED_PROGRAM.md section 6). + * + * vp_verify --receipt-id HEX --store DIR --objective-text TEXT --oracle NAME --checker2 PATH + * --epoch N [--host-check] + * + * The caller (the Pi, or anyone holding the receipt id it was told) states what it asked and which + * receipt it was given. This program believes nothing the runner wrote down. It re-hashes every + * artifact in the content-addressed store, recomputes the objective id from the text, recomputes the + * effects the IR needs with checker2's own decoder (no compiler code is linked), rebuilds the binding + * object, runs checker2 again on the stored IR and verifies the signed checker2 receipt with the + * checker2 binary, reads the receipt's requirements and input fields itself, compares the host, and + * finally recomputes every result with its own reference function (the oracle) for the task. + * + * Output: "VERIFIED receipt= result_sha256= oracle= calls=" and exit 0, or + * "FAIL " and exit 1 (2 on usage error). The first failing check is reported. + * + * Linked: src/sha256.c and checker2's decoder (src/checker2/c2_ir.c). Not linked: src/compiler. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "c2_ir.h" +#include "sha256.h" + +/* Paths come from a store directory checked to be at most 1024 bytes (main), so the 4096-byte path + * buffers cannot truncate; GCC cannot see that bound. */ +#pragma GCC diagnostic ignored "-Wformat-truncation" + +#define RCPT_SCHEMA "omega.verified_program.receipt.v1" +#define GRANT_SCHEMA "aien.verified_program.grant.v1" +#define OBJ_TAG "AIEN_E2E_OBJECTIVE_V1" +#define TIER_HOST "host-cpu-aarch64" + +static void fail(const char *code, const char *fmt, ...) +{ + va_list ap; + printf("FAIL %s ", code); + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + printf("\n"); + exit(1); +} + +static void hex32(const uint8_t d[32], char out[65]) +{ + static const char *x = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = x[d[i] >> 4]; out[2 * i + 1] = x[d[i] & 15]; } + out[64] = 0; +} + +static void sha_hex(const void *b, size_t n, char out[65]) +{ + uint8_t d[32]; + sha256_hash(b, n, d); + hex32(d, out); +} + +static int is_hex64(const char *s) +{ + if (strlen(s) != 64) return 0; + for (; *s; s++) if (!((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'f'))) return 0; + return 1; +} + +static uint8_t *slurp(const char *path, size_t max, size_t *len) +{ + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + size_t cap = 4096, n = 0; + uint8_t *b = malloc(cap + 1); + while (b) { + if (n == cap) { + if (cap > max) break; + uint8_t *nb = realloc(b, cap * 2 + 1); + if (!nb) break; + b = nb; cap *= 2; + } + ssize_t r = read(fd, b + n, cap - n); + if (r < 0 && errno == EINTR) continue; + if (r < 0) break; + if (r == 0) { + close(fd); + if (n > max) { free(b); return NULL; } + b[n] = 0; + *len = n; + return b; + } + n += (size_t)r; + } + free(b); + close(fd); + return NULL; +} + +/* argv run with stdout+stderr captured in full. Exit code or 128+signal, -1 if not started. */ +static int run_all(char *const argv[], char *out, size_t cap) +{ + int p[2]; + if (pipe2(p, O_CLOEXEC)) return -1; + pid_t c = fork(); + if (c < 0) return -1; + if (c == 0) { dup2(p[1], 1); dup2(p[1], 2); execv(argv[0], argv); _exit(127); } + close(p[1]); + size_t n = 0; + for (;;) { + char t[4096]; + ssize_t r = read(p[0], t, sizeof t); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + size_t k = (size_t)r; + if (n + k > cap - 1) k = cap - 1 - n; + memcpy(out + n, t, k); + n += k; + } + out[n] = 0; + close(p[0]); + int st = 0; + while (waitpid(c, &st, 0) < 0) if (errno != EINTR) return -1; + return WIFEXITED(st) ? WEXITSTATUS(st) : 128 + WTERMSIG(st); +} + +/* the same, first line only */ +static int run_line(char *const argv[], char *out, size_t cap) +{ + int rc = run_all(argv, out, cap); + out[strcspn(out, "\n")] = 0; + return rc; +} + +/* ---- the receipt ------------------------------------------------------------------------------ */ + +static const char *const RK[] = { + "schema", "verdict", "objective_id", "objective_text_sha256", "grant_sha256", "binding_sha256", "program_format", + "program_sha256", "oplist_sha256", "ir_sha256", "code_sha256", "entry", "params", "ret", "inputs_sha256", + "outputs_sha256", "calls", "effects_required", "effects_granted", "checker2_verdict", "checker2_id", + "checker2_receipt_id", "checker2_signer", "omegese_sha256", "omega_emit_sha256", "checker2_bin_sha256", + "runner_sha256", "commit", "tier", "host_cpu", "machine_id", "gpu_used", "sandbox", "epoch"}; +enum { + R_SCHEMA, R_VERDICT, R_OBJ, R_OBJTXT, R_GRANT, R_BIND, R_FMT, R_PROG, R_OPLIST, R_IR, R_CODE, R_ENTRY, R_PARAMS, + R_RET, R_IN, R_OUT, R_CALLS, R_EREQ, R_EGRANT, R_C2V, R_C2ID, R_C2R, R_C2SIGNER, R_OMEGESE, R_OME, R_C2BIN, + R_RUNNER, R_COMMIT, R_TIER, R_HOST, R_MACHINE, R_GPU, R_SANDBOX, R_EPOCH, NR +}; + +static char *rv[NR]; + +static void parse_receipt(char *t, size_t n) +{ + if (strncmp(t, "schema=", 7) == 0 && strncmp(t + 7, RCPT_SCHEMA "\n", strlen(RCPT_SCHEMA) + 1)) + fail("UNKNOWN_VERSION", "receipt schema is not %s", RCPT_SCHEMA); + if (memchr(t, 0, n) || !n || t[n - 1] != '\n') fail("RECEIPT_MALFORMED", "not newline-terminated text"); + char *p = t; + for (int i = 0; i < NR; i++) { + char *nl = strchr(p, '\n'); + size_t kl = strlen(RK[i]); + if (!nl || strncmp(p, RK[i], kl) || p[kl] != '=') fail("RECEIPT_MALFORMED", "line %d: want %s=", i + 1, RK[i]); + *nl = 0; + rv[i] = p + kl + 1; + p = nl + 1; + } + if (*p) fail("RECEIPT_MALFORMED", "extra lines"); + if (strcmp(rv[R_VERDICT], "EXECUTED") || strcmp(rv[R_C2V], "ACCEPT")) fail("RECEIPT_MALFORMED", "verdict"); +} + +/* ---- store ------------------------------------------------------------------------------------ */ + +static const char *g_store; + +static uint8_t *store_get(const char *hex, size_t *len, const char *what) +{ + char path[4096]; + if (!is_hex64(hex)) fail("RECEIPT_MALFORMED", "%s is not a digest", what); + snprintf(path, sizeof path, "%s/store/%s", g_store, hex); + uint8_t *b = slurp(path, 64u << 20, len); + if (!b) fail("STORE_MISSING", "%s %s", what, hex); + char h[65]; + sha_hex(b, *len, h); + if (strcmp(h, hex)) fail("STORE_TAMPERED", "%s: the bytes stored under %s hash to %s", what, hex, h); + return b; +} + +/* ---- grant and effects ------------------------------------------------------------------------ */ + +enum { EFF_PURE = 1, EFF_HEAP = 2, EFF_CALLER = 4 }; + +static void effects_text(unsigned e, char *out, size_t n) +{ + snprintf(out, n, "%s%s%s", e & EFF_PURE ? "pure" : "", e & EFF_HEAP ? ",heap" : "", e & EFF_CALLER ? ",caller_memory" : ""); +} + +/* What the IR needs, recomputed from checker2's decoding of the stored bytes. */ +static unsigned effects_of(const C2Unit *u) +{ + unsigned e = EFF_PURE; + for (unsigned f = 0; f < u->nfuncs; f++) { + const C2Func *fn = &u->fn[f]; + for (unsigned v = 0; v < fn->nvregs; v++) + if (fn->vt[v].s == S_BYTES || fn->vt[v].s == S_CELLS) e |= EFF_CALLER; + for (uint32_t i = 0; i < fn->ninsns; i++) { + unsigned op = fn->in[i].op; + if (op == C2_ALLOC || op == C2_RELEASE || (op >= C2_AOPEN && op <= C2_HSTORE)) e |= EFF_HEAP; + if (op == C2_SLOAD || op == C2_SSTORE) e |= EFF_CALLER; + } + } + return e; +} + +static int parse_u64(const char *s, uint64_t *v) +{ + if (!*s || (*s == '0' && s[1])) return -1; + uint64_t x = 0; + for (; *s; s++) { + if (*s < '0' || *s > '9') return -1; + unsigned d = (unsigned)(*s - '0'); + if (x > (UINT64_MAX - d) / 10) return -1; + x = x * 10 + d; + } + *v = x; + return 0; +} + +/* ---- host ------------------------------------------------------------------------------------- */ + +static void host_cpu(char *out, size_t n) +{ + struct utsname un; + char kinds[16][64], imp[16] = "?", var[16] = "?", part[16] = "?", rev[16] = "?", line[256]; + int nk = 0, more = 1; + if (uname(&un)) snprintf(un.machine, sizeof un.machine, "unknown"); + FILE *f = fopen("/proc/cpuinfo", "re"); + while (f && more) { + more = fgets(line, sizeof line, f) != NULL; + char *c = more ? strchr(line, ':') : NULL; + if (c) { + char *v = c + 1; + while (*v == ' ' || *v == '\t') v++; + v[strcspn(v, "\n")] = 0; + if (!strncmp(line, "CPU implementer", 15)) snprintf(imp, sizeof imp, "%s", v); + else if (!strncmp(line, "CPU variant", 11)) snprintf(var, sizeof var, "%s", v); + else if (!strncmp(line, "CPU part", 8)) snprintf(part, sizeof part, "%s", v); + else if (!strncmp(line, "CPU revision", 12)) snprintf(rev, sizeof rev, "%s", v); + } + if ((!more || line[0] == '\n') && strcmp(part, "?")) { + char k[64]; + int seen = 0; + snprintf(k, sizeof k, "%s:%s:%s:%s", imp, var, part, rev); + for (int i = 0; i < nk; i++) seen |= !strcmp(kinds[i], k); + if (!seen && nk < 16) snprintf(kinds[nk++], sizeof kinds[0], "%s", k); + snprintf(part, sizeof part, "?"); + } + } + if (f) fclose(f); + for (int i = 0; i < nk; i++) + for (int j = i + 1; j < nk; j++) + if (strcmp(kinds[j], kinds[i]) < 0) { char t[64]; memcpy(t, kinds[i], 64); memcpy(kinds[i], kinds[j], 64); memcpy(kinds[j], t, 64); } + size_t o = (size_t)snprintf(out, n, "%s/", un.machine); + for (int i = 0; i < nk && o < n; i++) o += (size_t)snprintf(out + o, n - o, "%s%s", i ? "," : "", kinds[i]); + if (!nk && o < n) snprintf(out + o, n - o, "unknown"); +} + +/* ---- oracles: reference functions written here, from the task statements ----------------------- */ + +typedef struct { + const char *name, *params, *ret; + unsigned np; + /* 0: expected line written; -1: input outside the oracle's domain */ + int (*f)(const int64_t *a, char *out, size_t n); +} Oracle; + +static int o_gcd(const int64_t *a, char *out, size_t n) +{ + uint64_t x = (uint64_t)a[0], y = (uint64_t)a[1]; + while (y) { uint64_t t = x % y; x = y; y = t; } + snprintf(out, n, "R %" PRIu64, x); + return 0; +} + +static int o_collatz(const int64_t *a, char *out, size_t n) +{ + uint64_t x = (uint64_t)a[0], steps = 0; + if (x == 0) return -1; + while (x != 1) { + if (steps >= 999 || x > (UINT64_MAX - 1) / 3) return -1; + x = (x & 1) ? 3 * x + 1 : x / 2; + steps++; + } + snprintf(out, n, "R %" PRIu64, steps); + return 0; +} + +/* overflow of the 16-bit signed product is refused: trap code 1 (OSC arithmetic overflow) */ +static int o_mul16(const int64_t *a, char *out, size_t n) +{ + int64_t p = a[0] * a[1]; + if (p < -32768 || p > 32767) snprintf(out, n, "T 1"); + else snprintf(out, n, "R %" PRId64, p); + return 0; +} + +static const Oracle ORACLES[] = { + {"gcd_u32", "u32,u32", "u32", 2, o_gcd}, + {"collatz_steps_u32", "u32", "u32", 1, o_collatz}, + {"checked_mul_i16", "i16,i16", "i16", 2, o_mul16}, +}; + +/* ---- main ------------------------------------------------------------------------------------- */ + +static const char *opt(int argc, char **argv, const char *name) +{ + for (int i = 1; i + 1 < argc; i++) if (!strcmp(argv[i], name)) return argv[i + 1]; + return NULL; +} + +int main(int argc, char **argv) +{ + const char *rid = opt(argc, argv, "--receipt-id"), *text = opt(argc, argv, "--objective-text"), + *oname = opt(argc, argv, "--oracle"), *c2 = opt(argc, argv, "--checker2"), *ep = opt(argc, argv, "--epoch"); + int host_check = 0; + for (int i = 1; i < argc; i++) host_check |= !strcmp(argv[i], "--host-check"); + g_store = opt(argc, argv, "--store"); + uint64_t now = 0; + if (!rid || !text || !oname || !c2 || !ep || !g_store || parse_u64(ep, &now)) { + fprintf(stderr, "usage: vp_verify --receipt-id HEX --store DIR --objective-text TEXT --oracle NAME --checker2 PATH --epoch N [--host-check]\n"); + return 2; + } + const Oracle *orc = NULL; + for (size_t i = 0; i < sizeof ORACLES / sizeof ORACLES[0]; i++) if (!strcmp(ORACLES[i].name, oname)) orc = &ORACLES[i]; + if (!orc) { fprintf(stderr, "vp_verify: unknown oracle %s\n", oname); return 2; } + if (strlen(g_store) > 1024) { fprintf(stderr, "vp_verify: store path longer than 1024 bytes\n"); return 2; } + + /* 1. the receipt the caller was given, by id */ + char path[4096], h[65]; + if (!is_hex64(rid)) fail("RECEIPT_MISSING", "not a receipt id"); + snprintf(path, sizeof path, "%s/receipts/%s.vpr", g_store, rid); + size_t rn = 0; + char *rt = (char *)slurp(path, 65536, &rn); + if (!rt) fail("RECEIPT_MISSING", "no receipt %s", rid); + sha_hex(rt, rn, h); + if (strcmp(h, rid)) fail("RECEIPT_ID_MISMATCH", "the receipt stored as %s hashes to %s", rid, h); + parse_receipt(rt, rn); + + /* 2. the objective the caller asked */ + char *ob = malloc(strlen(text) + 32); + if (!ob) return 2; + int obl = sprintf(ob, "%s\n%s", OBJ_TAG, text); + sha_hex(ob, (size_t)obl, h); + if (strcmp(h, rv[R_OBJ])) fail("OBJECTIVE_MISMATCH", "receipt is for objective %.16s..., the asked objective is %.16s...", rv[R_OBJ], h); + sha_hex(text, strlen(text), h); + if (strcmp(h, rv[R_OBJTXT])) fail("OBJECTIVE_MISMATCH", "objective text digest"); + + /* 3. every artifact, re-hashed */ + size_t n_obj, n_grant, n_bind, n_prog, n_ir, n_code, n_in, n_out, n_c2r, n_ol = 0; + free(store_get(rv[R_OBJTXT], &n_obj, "objective_text")); + char *grant = (char *)store_get(rv[R_GRANT], &n_grant, "grant"); + char *bind = (char *)store_get(rv[R_BIND], &n_bind, "binding"); + free(store_get(rv[R_PROG], &n_prog, "program")); + if (strcmp(rv[R_OPLIST], "-")) free(store_get(rv[R_OPLIST], &n_ol, "oplist")); + uint8_t *ir = store_get(rv[R_IR], &n_ir, "ir"); + free(store_get(rv[R_CODE], &n_code, "code")); + char *inputs = (char *)store_get(rv[R_IN], &n_in, "inputs"); + char *outputs = (char *)store_get(rv[R_OUT], &n_out, "outputs"); + uint8_t *c2r = store_get(rv[R_C2R], &n_c2r, "checker2_receipt"); + + /* 4. the grant: same objective, tier, epoch window, call limit; effects recomputed from the IR */ + static const char *const GK[] = {"schema", "objective_id", "tier", "effects", "epoch_first", "epoch_last", "max_calls"}; + char *gv[7], *p = grant; + for (int i = 0; i < 7; i++) { + char *nl = strchr(p, '\n'); + size_t kl = strlen(GK[i]); + if (!nl || strncmp(p, GK[i], kl) || p[kl] != ' ') fail("GRANT_MALFORMED", "line %d", i + 1); + *nl = 0; + gv[i] = p + kl + 1; + p = nl + 1; + } + uint64_t e_first, e_last, max_calls, calls, epoch; + if (*p || strcmp(gv[0], GRANT_SCHEMA) || parse_u64(gv[4], &e_first) || parse_u64(gv[5], &e_last) || + parse_u64(gv[6], &max_calls) || parse_u64(rv[R_CALLS], &calls) || parse_u64(rv[R_EPOCH], &epoch)) + fail("GRANT_MALFORMED", "grant or receipt numbers"); + if (strcmp(gv[1], rv[R_OBJ])) fail("GRANT_OBJECTIVE", "the grant names another objective"); + if (strcmp(gv[2], rv[R_TIER])) fail("GRANT_TIER", "grant tier %s, receipt tier %s", gv[2], rv[R_TIER]); + if (epoch < e_first || epoch > e_last || now < e_first || now > e_last) + fail("GRANT_EPOCH", "epoch %" PRIu64 " (now %" PRIu64 ") outside %" PRIu64 "..%" PRIu64, epoch, now, e_first, e_last); + if (calls == 0 || calls > max_calls) fail("GRANT_LIMIT", "%" PRIu64 " calls, grant allows %" PRIu64, calls, max_calls); + unsigned granted = 0; + for (char *s = strtok(gv[3], " "); s; s = strtok(NULL, " ")) { + if (!strcmp(s, "pure")) granted |= EFF_PURE; + else if (!strcmp(s, "heap")) granted |= EFF_HEAP; + else if (!strcmp(s, "caller_memory")) granted |= EFF_CALLER; + else fail("GRANT_MALFORMED", "effect %s", s); + } + C2Unit *u = calloc(1, sizeof *u); + C2Verdict cv; + if (!u) return 2; + if (c2_decode(ir, n_ir, u, &cv)) fail("CHECKER_REJECT", "checker2 decoder: rule=%s %s", cv.rule, cv.detail); + unsigned need = effects_of(u); + char need_t[64], grant_t[64]; + effects_text(need, need_t, sizeof need_t); + effects_text(granted, grant_t, sizeof grant_t); + if ((need & ~granted) || !(granted & EFF_PURE)) fail("UNAUTHORIZED_EFFECT", "the IR needs %s, the grant allows %s", need_t, grant_t); + if (strcmp(need_t, rv[R_EREQ]) || strcmp(grant_t, rv[R_EGRANT])) fail("BINDING_MISMATCH", "effects recorded in the receipt"); + + /* 5. the binding object (what checker2's receipt signed as requirements) and the signature */ + char want_bind[1024]; + int bl = snprintf(want_bind, sizeof want_bind, + "schema=omega.verified_program.binding.v1\nobjective_id=%s\ngrant_sha256=%s\nentry=%s\nparams=%s\n" + "ret=%s\ntier=%s\nepoch=%s\n", + rv[R_OBJ], rv[R_GRANT], rv[R_ENTRY], rv[R_PARAMS], rv[R_RET], rv[R_TIER], rv[R_EPOCH]); + if ((size_t)bl != n_bind || memcmp(bind, want_bind, n_bind)) fail("BINDING_MISMATCH", "binding object"); + static const char *const SN[] = {"void", "bool", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"}; + int fi = -1; + for (unsigned i = 0; i < u->nfuncs; i++) if (!strcmp(u->fn[i].name, rv[R_ENTRY])) fi = (int)i; + if (fi < 0) fail("BINDING_MISMATCH", "no function %s in the IR", rv[R_ENTRY]); + const C2Func *fn = &u->fn[fi]; + char sig[128] = ""; + for (unsigned i = 0; i < fn->nparams; i++) { + unsigned s = fn->vt[i].s; + size_t l = strlen(sig); + snprintf(sig + l, sizeof sig - l, "%s%s", i ? "," : "", s >= S_BOOL && s <= S_I64 && fn->vt[i].kind == K_NONE ? SN[s] : "ref"); + } + if (!fn->nparams) snprintf(sig, sizeof sig, "-"); + if (strcmp(sig, rv[R_PARAMS]) || fn->ret.s < S_BOOL || fn->ret.s > S_I64 || strcmp(SN[fn->ret.s], rv[R_RET])) + fail("BINDING_MISMATCH", "the IR entry signature is %s -> %s", sig, fn->ret.s <= S_I64 ? SN[fn->ret.s] : "ref"); + c2_unit_free(u); + + /* 6. checker2, again, on the stored bytes; and its identity */ + char out[8192], irp[4096], codep[4096], c2rp[4096], want[128]; + snprintf(irp, sizeof irp, "%s/store/%s", g_store, rv[R_IR]); + snprintf(codep, sizeof codep, "%s/store/%s", g_store, rv[R_CODE]); + snprintf(c2rp, sizeof c2rp, "%s/store/%s", g_store, rv[R_C2R]); + { + char *av[] = {(char *)c2, "check", irp, NULL}; + int rc = run_line(av, out, sizeof out); + snprintf(want, sizeof want, "checker2=ACCEPT ir_sha256=%s", rv[R_IR]); + if (rc || strcmp(out, want)) fail("CHECKER_REJECT", "%s", out); + char *av2[] = {(char *)c2, "version", NULL}; + rc = run_all(av2, out, sizeof out); + char *idp = strstr(out, "checker_id="); + if (rc || !idp || strncmp(idp + 11, rv[R_C2ID], 64)) fail("CHECKER_ID", "this checker2 is not the one named in the receipt"); + } + + /* 7. the signed checker2 receipt: signature, program, executable, target, epoch (checker2), then + * the requirements and input fields, read here from the 416 bytes */ + { + char *av[] = {(char *)c2, "receipt", "verify", c2rp, irp, codep, "--target", rv[R_TIER], "--epoch", (char *)ep, + "--allow-test-key", NULL}; + int rc = run_line(av, out, sizeof out); + if (rc || strcmp(out, "receipt=VALID")) fail("C2_RECEIPT_INVALID", "%s", out); + if (n_c2r != 416) fail("C2_RECEIPT_INVALID", "size %zu", n_c2r); + hex32(c2r + 16, h); + if (strcmp(h, rv[R_BIND])) fail("C2_BINDING", "the signed requirements digest is not this binding"); + hex32(c2r + 272, h); + if (strcmp(h, rv[R_IN])) fail("C2_INPUT", "the signed input digest is not these inputs"); + uint16_t signer = (uint16_t)(c2r[10] | c2r[11] << 8); + if ((signer == 1 && strcmp(rv[R_C2SIGNER], "TEST")) || (signer == 2 && strcmp(rv[R_C2SIGNER], "OWNER")) || signer < 1 || signer > 2) + fail("C2_RECEIPT_INVALID", "signer class"); + } + + /* 8. tier and host */ + if (strcmp(rv[R_TIER], TIER_HOST) || strcmp(rv[R_GPU], "no")) fail("HOST_MISMATCH", "tier %s gpu_used %s", rv[R_TIER], rv[R_GPU]); + if (host_check) { + char cpu[512]; + host_cpu(cpu, sizeof cpu); + if (strcmp(cpu, rv[R_HOST])) fail("HOST_MISMATCH", "receipt host %s, this host %s", rv[R_HOST], cpu); + } + + /* 9. the results, recomputed */ + if (strcmp(orc->params, rv[R_PARAMS]) || strcmp(orc->ret, rv[R_RET])) + fail("ORACLE_SIGNATURE", "oracle %s is for (%s) -> %s, the receipt is for (%s) -> %s", orc->name, orc->params, orc->ret, + rv[R_PARAMS], rv[R_RET]); + if (!n_out || outputs[n_out - 1] != '\n' || memchr(outputs, 0, n_out)) fail("OUTPUT_MALFORMED", "outputs text"); + char *ip = inputs, *op = outputs; + uint64_t line = 0; + while (*ip) { + char *inl = strchr(ip, '\n'), *onl = strchr(op, '\n'); + if (!inl) fail("OUTPUT_MALFORMED", "inputs text"); + if (!onl) fail("OUTPUT_MALFORMED", "fewer result lines than calls"); + *inl = 0; + *onl = 0; + line++; + int64_t a[6]; + unsigned k = 0; + for (char *s = strtok(ip, " "); s; s = strtok(NULL, " ")) { + if (k == orc->np) fail("OUTPUT_MALFORMED", "input line %" PRIu64, line); + char *end; + errno = 0; + a[k++] = strtoll(s, &end, 10); + if (errno || *end) fail("OUTPUT_MALFORMED", "input line %" PRIu64, line); + } + if (k != orc->np) fail("OUTPUT_MALFORMED", "input line %" PRIu64, line); + char exp[64]; + if (orc->f(a, exp, sizeof exp)) fail("ORACLE_DOMAIN", "call %" PRIu64 " is outside what oracle %s decides", line, orc->name); + if (strcmp(exp, op)) fail("WRONG_RESULT", "call %" PRIu64 ": got \"%s\", the task's answer is \"%s\"", line, op, exp); + ip = inl + 1; + op = onl + 1; + } + if (*op) fail("OUTPUT_MALFORMED", "more result lines than calls"); + if (line != calls) fail("OUTPUT_MALFORMED", "%" PRIu64 " calls, receipt says %" PRIu64, line, calls); + printf("VERIFIED receipt=%s result_sha256=%s oracle=%s calls=%" PRIu64 "\n", rid, rv[R_OUT], orc->name, calls); + return 0; +}