interplane.Get Omega
Read in your language

omega-mv

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

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / omc / receipts-v1.py

174 lines · 7733 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent verifier for native omc canonical program-identity & effect receipts (OMC_RECEIPT=1)."""
3import hashlib
4import os
5from pathlib import Path
6import re
7import subprocess
8import sys
9import tempfile
10
11root = Path(__file__).resolve().parents[2]
12compiler = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else root / 'seed/out/omc'
13source = root / 'seed/omc/omc.om'
14text = source.read_text()
15pins = re.findall(r'^text d2pin "([0-9a-f]{64})"$', text, re.M)
16assert len(pins) == 1, 'source-pin-count'
17compiler_src_pin = pins[0]
18
19def canonical_body_bytes(data: bytes) -> bytes:
20 out = bytearray()
21 e = len(data)
22 p = 0
23 ht = 0
24 while p < e:
25 b = data[p]
26 if b in (32, 9, 13):
27 p += 1
28 elif b == 10:
29 if ht:
30 out.append(10)
31 ht = 0
32 p += 1
33 elif ht == 0 and data[p:p+4] == b'note' and (p + 4 == e or data[p+4] <= 32 or data[p+4] in (40, 41)):
34 nl = data.find(b'\n', p)
35 p = e if nl == -1 else nl + 1
36 else:
37 if ht:
38 out.append(32)
39 if b == 34:
40 out.append(34)
41 p += 1
42 while p < e:
43 sb = data[p]
44 out.append(sb)
45 p += 1
46 if sb == 92 and p < e:
47 out.append(data[p])
48 p += 1
49 elif sb in (34, 10):
50 break
51 elif b in (40, 41):
52 out.append(b)
53 p += 1
54 else:
55 while p < e and data[p] > 32 and data[p] not in (40, 41, 34):
56 out.append(data[p])
57 p += 1
58 ht = 1
59 if ht:
60 out.append(10)
61 return bytes(out)
62
63env = os.environ.copy()
64env.pop('OMC_DIAGNOSTICS', None)
65env.pop('OMC_MEMORY_MAX', None)
66env.pop('OMC_RECEIPT', None)
67
68def run_omc(c, data: bytes, receipt: bool = True, diag: bool = False):
69 e = env.copy()
70 if receipt:
71 e['OMC_RECEIPT'] = '1'
72 if diag:
73 e['OMC_DIAGNOSTICS'] = '2'
74 return subprocess.run([str(c)], input=data, capture_output=True, env=e, timeout=30)
75
76def parse_and_verify(c, data: bytes, expect_effects: int = None, expect_sites_min: int = None):
77 plain = run_omc(c, data, receipt=False)
78 rich = run_omc(c, data, receipt=True)
79 assert plain.returncode == 0, ('plain-fail', plain.returncode, plain.stderr)
80 assert rich.returncode == 0, ('rich-fail', rich.returncode, rich.stderr)
81 # stdout must be byte-identical whether OMC_RECEIPT=1 is set or not
82 assert plain.stdout == rich.stdout, 'stdout-parity'
83 assert plain.stderr == b'', ('plain-stderr-nonempty', plain.stderr)
84
85 lines = [ln for ln in rich.stderr.splitlines() if ln.startswith(b'omc-receipt 1 ')]
86 assert len(lines) == 1, ('receipt-line-count', rich.stderr)
87 line = lines[0]
88 marker = b' receipt_id='
89 idx = line.rfind(marker)
90 assert idx > 0, ('missing-receipt-id', line)
91 payload = line[:idx]
92 rid_hex = line[idx + len(marker):].decode()
93 expected_rid = hashlib.sha256(b'omega.effect.receipt.v1\x00' + payload).hexdigest()
94 assert rid_hex == expected_rid, ('receipt-id-mismatch', rid_hex, expected_rid)
95
96 fields = dict(tok.split(b'=', 1) for tok in payload[len(b'omc-receipt 1 '):].split())
97 assert fields[b'input_sha256'].decode() == hashlib.sha256(data).hexdigest(), 'input-sha256'
98 assert int(fields[b'input_bytes']) == len(data), 'input-bytes'
99 assert fields[b'output_sha256'].decode() == hashlib.sha256(rich.stdout).hexdigest(), 'output-sha256'
100 assert int(fields[b'output_bytes']) == len(rich.stdout), 'output-bytes'
101 assert fields[b'compiler_source_sha256'].decode() == compiler_src_pin, 'compiler-source-sha256'
102
103 exp_body = hashlib.sha256(canonical_body_bytes(data)).digest()
104 assert fields[b'body_id'].decode() == exp_body.hex(), ('body-id', fields[b'body_id'].decode(), exp_body.hex())
105
106 sig_bytes = bytes.fromhex(fields[b'sig_id'].decode())
107 con_bytes = bytes.fromhex(fields[b'contract_id'].decode())
108 exp_pid = hashlib.sha256(b'omega.program.v2\x00' + exp_body + sig_bytes + con_bytes).hexdigest()
109 assert fields[b'program_id'].decode() == exp_pid, ('program-id', fields[b'program_id'].decode(), exp_pid)
110
111 eff = int(fields[b'effects'])
112 sites = int(fields[b'effect_sites'])
113 if expect_effects is not None:
114 assert eff == expect_effects, ('effects-mask', eff, expect_effects)
115 if expect_sites_min is not None:
116 assert sites >= expect_sites_min, ('effect-sites', sites, expect_sites_min)
117 return fields
118
119# 1. Pure program: effects=0, effect_sites=0, contract_id=0..0
120pure_a = b'fn main to int\nret 7\nend\n'
121pure_b = b'note header comment\n\n fn main to int \n note inline comment\n\tret 7\n\nend\n'
122pure_c = b'fn main to int\nret 8\nend\n'
123
124fa = parse_and_verify(compiler, pure_a, expect_effects=0, expect_sites_min=0)
125fb = parse_and_verify(compiler, pure_b, expect_effects=0, expect_sites_min=0)
126fc = parse_and_verify(compiler, pure_c, expect_effects=0, expect_sites_min=0)
127
128assert fa[b'input_sha256'] != fb[b'input_sha256'], 'raw-inputs-should-differ'
129assert fa[b'body_id'] == fb[b'body_id'], 'whitespace-comment-invariance-body'
130assert fa[b'program_id'] == fb[b'program_id'], 'whitespace-comment-invariance-program-id'
131assert fa[b'program_id'] != fc[b'program_id'], 'mutation-separation'
132assert fa[b'contract_id'] == b'0' * 64, 'zero-contract-id'
133assert int(fa[b'effect_sites']) == 0, 'pure-zero-sites'
134assert fa[b'effect_words'] == b'0' * 64, 'pure-zero-words'
135
136# 2. Pure OM-2 function-mode unit
137om2_pure = b'om2\nexport fn add1 x ulong to ulong\nret add x 1\nend\n'
138f_om2 = parse_and_verify(compiler, om2_pure, expect_effects=0, expect_sites_min=0)
139assert f_om2[b'om2'] == b'1' and int(f_om2[b'effect_sites']) == 0
140
141# 3. Effectful IO program (write = keyword 54 -> cat bit 0 = 1)
142io_prog = b'text hi "hi\\n"\nfn main to int\nw = write 1 hi 0 len hi\nret 0\nend\n'
143f_io = parse_and_verify(compiler, io_prog, expect_effects=1, expect_sites_min=1)
144ew_io = int(f_io[b'effect_words'].decode(), 16)
145assert (ew_io & (1 << 54)) != 0, 'write-word-bit-set'
146
147# 4. Effectful PROC + TIME + MEM program (monons=109 -> cat 16, enlarge=244 -> cat 64, exit=82 -> cat 4)
148multi_eff = b'global pool uchar *\nfn main to int\nt = monons\nz = enlarge pool 64\nexit 0\nend\n'
149f_multi = parse_and_verify(compiler, multi_eff, expect_effects=16 | 64 | 4, expect_sites_min=3)
150ew_m = int(f_multi[b'effect_words'].decode(), 16)
151assert (ew_m & (1 << 109)) != 0 and (ew_m & (1 << 244)) != 0 and (ew_m & (1 << 82)) != 0
152
153# 5. Native object mode (object + om2)
154obj_unit = b'object\nom2\nexport fn inc x ulong to ulong\nret add x 1\nend\n'
155f_obj = parse_and_verify(compiler, obj_unit, expect_effects=0, expect_sites_min=0)
156assert f_obj[b'obj'] == b'1' and f_obj[b'om2'] == b'1'
157
158# 6. Compiler mutant control: skipping eff_rec must be caught by effect-mask check
159with tempfile.TemporaryDirectory(prefix='omc-rc-mut-') as td:
160 mut_src = text.replace('put rc_cat 0 or get rc_cat 0 cat\n', 'put rc_cat 0 0\n', 1)
161 assert mut_src != text, 'mutant-site-missing'
162 p = run_omc(compiler, mut_src.encode(), receipt=False)
163 assert p.returncode == 0, ('mutant-compile-failed', p.stderr)
164 mc = Path(td) / 'omc-no-eff'
165 mc.write_bytes(p.stdout)
166 mc.chmod(0o700)
167 try:
168 parse_and_verify(mc, io_prog, expect_effects=1, expect_sites_min=1)
169 except AssertionError as err:
170 assert 'effects-mask' in str(err), ('wrong-mutant-error', str(err))
171 else:
172 raise AssertionError('effect-mutant-survived')
173
174print('RECEIPTS_V1 PASS cases=7 invariants=5 mutants=1')