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
omega-mv / om / sha256 / om2-evidence / deskcheck / interp.py
| 1 | #!/usr/bin/env python3 |
| 2 | # L838 desk check (oracle, outside the delivered closure, NOT compiler evidence): a small interpreter |
| 3 | # of the OM-2 subset that om/sha256/sha256-om2.om uses, as the contract describes it, to check the |
| 4 | # unit's algorithm (schedule, rounds, buffering, padding) against hashlib before an OM-2 omc exists. |
| 5 | import sys, hashlib, random, os |
| 6 | LIMIT = int(os.environ.get("LIMIT", "1000000")) |
| 7 | W = {'uchar': 8, 'ushort': 16, 'uint': 32, 'ulong': 64} |
| 8 | BIN = {'add', 'sub', 'mul', 'shl', 'shr', 'and', 'or', 'xor', 'rotr', 'lt', 'le', 'gt', 'ge', 'eq', 'ne'} |
| 9 | class Trap(Exception): pass |
| 10 | |
| 11 | class Arr: |
| 12 | def __init__(s, t, n, v=0): s.t, s.a = t, [v] * n |
| 13 | class View: # a (possibly unsized) array argument |
| 14 | def __init__(s, arr): s.arr = arr |
| 15 | |
| 16 | def parse(src): |
| 17 | lines = src.split('\n'); fns = {}; layouts = {}; i = 0 |
| 18 | while i < len(lines): |
| 19 | w = lines[i].split() |
| 20 | if not w or w[0] == 'note' or w == ['om2']: i += 1; continue |
| 21 | if w[0] == 'layout': |
| 22 | name, size = w[1], int(w[2]); fields = {}; i += 1 |
| 23 | while lines[i].split()[0] != 'end': |
| 24 | f = lines[i].split() # field F T COUNT at OFF little |
| 25 | if f[3] == 'at': fields[f[1]] = (f[2], None, int(f[4])) # E5: no COUNT = scalar |
| 26 | else: fields[f[1]] = (f[2], int(f[3]), int(f[5])) |
| 27 | i += 1 |
| 28 | layouts[name] = (size, fields); i += 1; continue |
| 29 | exp = w[0] == 'export' |
| 30 | if exp: w = w[1:] |
| 31 | assert w[0] == 'fn', lines[i] |
| 32 | name = w[1]; params = []; j = 2 |
| 33 | while w[j] != 'to': |
| 34 | pn = w[j] |
| 35 | if w[j + 1] in W: |
| 36 | params.append((pn, 'scalar', w[j + 1])); j += 2 |
| 37 | elif w[j + 2] in layouts: |
| 38 | params.append((pn, w[j + 1], w[j + 2])); j += 3 |
| 39 | else: |
| 40 | params.append((pn, w[j + 1], w[j + 2], w[j + 3])); j += 4 |
| 41 | if j < len(w) and w[j] == 'fresh': j += 1 |
| 42 | body = []; i += 1; depth = 0 |
| 43 | while True: |
| 44 | t = lines[i].split() |
| 45 | if t and t[0] != 'note': |
| 46 | if t[0] == 'end' and depth == 0: break |
| 47 | if t[0] in ('for', 'if'): depth += 1 |
| 48 | if t[0] == 'end': depth -= 1 |
| 49 | body.append((i + 1, t)) |
| 50 | i += 1 |
| 51 | fns[name] = (params, body, w[j + 1]); i += 1 |
| 52 | return fns, layouts |
| 53 | |
| 54 | class VM: |
| 55 | def __init__(s, src): |
| 56 | s.fns, s.layouts = parse(src) |
| 57 | def call(s, name, args): |
| 58 | params, body, rt = s.fns[name] |
| 59 | env = {} |
| 60 | for p, a in zip(params, args): env[p[0]] = a |
| 61 | s.ret = False |
| 62 | s.block(body, 0, len(body), env) |
| 63 | s.ret = False |
| 64 | def block(s, body, a, b, env): |
| 65 | k = a |
| 66 | while k < b and not s.ret: |
| 67 | ln, t = body[k] |
| 68 | end = s.match(body, k) if t[0] in ('for', 'if') else k |
| 69 | if t[0] == 'for': |
| 70 | var, ty = t[1], t[2] |
| 71 | cnt, rest = s.expr(t[3:], env) |
| 72 | if rest != ['unroll'] and cnt[0] > LIMIT: raise Trap(4) # rolled loop pass limit |
| 73 | for it in range(cnt[0]): |
| 74 | env[var] = (it, ty) |
| 75 | s.block(body, k + 1, end, env) |
| 76 | if s.ret: return |
| 77 | k = end + 1; continue |
| 78 | if t[0] == 'if': |
| 79 | c, _ = s.expr(t[1:], env) |
| 80 | if c[0]: s.block(body, k + 1, end, env) |
| 81 | k = end + 1; continue |
| 82 | s.stmt(t, env) |
| 83 | k += 1 |
| 84 | def match(s, body, k): |
| 85 | d = 0 |
| 86 | for j in range(k, len(body)): |
| 87 | w = body[j][1][0] |
| 88 | if w in ('for', 'if'): d += 1 |
| 89 | elif w == 'end': |
| 90 | d -= 1 |
| 91 | if d == 0: return j |
| 92 | raise SyntaxError |
| 93 | def stmt(s, t, env): |
| 94 | if t[0] == 'ret': s.ret = True; return |
| 95 | if len(t) > 1 and t[1] == '=': |
| 96 | if t[2] == 'new': |
| 97 | env[t[0]] = Arr(t[3], int(t[4]), int(t[5])); return |
| 98 | v, rest = s.expr(t[2:], env); assert not rest, t |
| 99 | old = env.get(t[0]) |
| 100 | if old is not None and old[1] and v[1] is None: v = (v[0], old[1]) |
| 101 | env[t[0]] = v; return |
| 102 | if t[0] == 'put': |
| 103 | tgt = env[t[1]] |
| 104 | if isinstance(tgt, View): tgt = tgt.arr |
| 105 | if isinstance(tgt, Lay): |
| 106 | f = t[2]; r = t[3:] |
| 107 | if tgt.f[f][1] is None: i = (0, None) |
| 108 | else: i, r = s.expr(r, env) |
| 109 | v, r = s.expr(r, env); assert not r |
| 110 | tgt.put(f, i[0], v[0]); return |
| 111 | i, r = s.expr(t[2:], env); v, r = s.expr(r, env); assert not r, t |
| 112 | if not (0 <= i[0] < len(tgt.a)): raise Trap(3) |
| 113 | assert 0 <= v[0] < (1 << W[tgt.t]), (t, v) |
| 114 | tgt.a[i[0]] = v[0]; return |
| 115 | if t[0] in s.fns: |
| 116 | args, r = s.args(t[0], t[1:], env); assert not r, t |
| 117 | s.call(t[0], args); return |
| 118 | raise SyntaxError(t) |
| 119 | def args(s, fn, toks, env): |
| 120 | out = [] |
| 121 | for p in s.fns[fn][0]: |
| 122 | if p[1] == 'scalar': |
| 123 | v, toks = s.expr(toks, env); out.append(v) |
| 124 | else: |
| 125 | if toks[0] in ('view', 'edit'): toks = toks[1:] |
| 126 | if toks[0] == 'part': # section 6: checks o <= len, then k <= len - o; a view copy |
| 127 | b = env[toks[1]]; b = b.arr if isinstance(b, View) else b |
| 128 | o, toks = s.expr(toks[2:], env); k, toks = s.expr(toks, env) |
| 129 | if o[0] > len(b.a) or k[0] > len(b.a) - o[0]: raise Trap(3) |
| 130 | c = Arr(b.t, 0); c.a = b.a[o[0]:o[0] + k[0]]; out.append(View(c)); continue |
| 131 | a = env[toks[0]]; toks = toks[1:] |
| 132 | out.append(a) |
| 133 | return out, toks |
| 134 | def expr(s, t, env): |
| 135 | w = t[0]; r = t[1:] |
| 136 | if w.startswith('0x'): return (int(w, 16), None), r |
| 137 | if w.isdigit(): return (int(w), None), r |
| 138 | if w in W: |
| 139 | v, r = s.expr(r, env) |
| 140 | if not (0 <= v[0] < (1 << W[w])): raise Trap(5) |
| 141 | return (v[0], w), r |
| 142 | if w == 'not': |
| 143 | v, r = s.expr(r, env); return (v[0] ^ ((1 << W[v[1]]) - 1), v[1]), r |
| 144 | if w == 'len': |
| 145 | a = env[r[0]]; a = a.arr if isinstance(a, View) else a |
| 146 | return (len(a.a), 'ulong'), r[1:] |
| 147 | if w == 'get': |
| 148 | a = env[r[0]]; a = a.arr if isinstance(a, View) else a; r = r[1:] |
| 149 | if isinstance(a, Lay): |
| 150 | f = r[0]; r = r[1:] |
| 151 | if a.f[f][1] is None: return a.get(f, 0), r |
| 152 | i, r = s.expr(r, env); return a.get(f, i[0]), r |
| 153 | i, r = s.expr(r, env) |
| 154 | if not (0 <= i[0] < len(a.a)): raise Trap(3) |
| 155 | return (a.a[i[0]], a.t), r |
| 156 | if w in BIN: |
| 157 | x, r = s.expr(r, env); y, r = s.expr(r, env) |
| 158 | ty = x[1] or y[1] |
| 159 | assert not (x[1] and y[1] and x[1] != y[1]), (w, x, y) |
| 160 | m = (1 << W[ty]) - 1 if ty else None |
| 161 | a, b = x[0], y[0] |
| 162 | if w in ('lt', 'le', 'gt', 'ge', 'eq', 'ne'): |
| 163 | return (int({'lt': a < b, 'le': a <= b, 'gt': a > b, 'ge': a >= b, 'eq': a == b, 'ne': a != b}[w]), 'bool'), r |
| 164 | if w in ('shl', 'shr', 'rotr') and not (0 <= b < W[ty]): raise Trap(7) |
| 165 | if w == 'rotr': v = (a >> b) | (a << (W[ty] - b)) |
| 166 | else: |
| 167 | v = {'add': a + b, 'sub': a - b, 'mul': a * b, 'shl': a << b if b < 4096 else 0, 'shr': a >> b, |
| 168 | 'and': a & b, 'or': a | b, 'xor': a ^ b}[w] |
| 169 | return (v & m, ty), r |
| 170 | if w in env: return env[w], r |
| 171 | raise SyntaxError(t) |
| 172 | |
| 173 | class Lay: |
| 174 | def __init__(s, fields, size, data=None): |
| 175 | s.f, s.b = fields, bytearray(size) if data is None else data |
| 176 | def get(s, f, i): |
| 177 | t, n, off = s.f[f]; wb = W[t] // 8; n = 1 if n is None else n |
| 178 | if not (0 <= i < n): raise Trap(3) |
| 179 | return (int.from_bytes(s.b[off + i * wb: off + (i + 1) * wb], 'little'), t) |
| 180 | def put(s, f, i, v): |
| 181 | t, n, off = s.f[f]; wb = W[t] // 8; n = 1 if n is None else n |
| 182 | if not (0 <= i < n): raise Trap(3) |
| 183 | s.b[off + i * wb: off + (i + 1) * wb] = v.to_bytes(wb, 'little') |
| 184 | |
| 185 | def main(): |
| 186 | vm = VM(open(sys.argv[1]).read()) |
| 187 | size, fields = vm.layouts['shactx'] |
| 188 | def ctx(): return Lay(fields, size) |
| 189 | def view(bs): return View(_arr(bs)) |
| 190 | def _arr(bs): |
| 191 | a = Arr('uchar', len(bs)); a.a = list(bs); return a |
| 192 | def out(): return Arr('uchar', 32) |
| 193 | rng = random.Random(838); bad = 0; cases = 0 |
| 194 | lens = list(range(0, 260)) + [447, 448, 511, 512, 1000, 4095, 4096, 4097, 12345] |
| 195 | lens += [int(x) for x in os.environ.get('EXTRA', '').split(',') if x] |
| 196 | def one(n): |
| 197 | nonlocal cases, bad |
| 198 | msg = bytes(rng.randrange(256) for _ in range(n)); ref = hashlib.sha256(msg).digest() |
| 199 | o = out(); vm.call('sha256_hash', [view(msg), o]); cases += 1 |
| 200 | if bytes(o.a) != ref: bad += 1; print('hash FAIL', n) |
| 201 | c = ctx(); vm.call('sha256_init', [c]); p = 0 |
| 202 | while p < n: |
| 203 | k = rng.choice([0, 1, 3, 55, 56, 63, 64, 65, 200]); k = min(k, n - p) |
| 204 | vm.call('sha256_update', [c, view(msg[p:p + k])]); p += k |
| 205 | if k == 0: vm.call('sha256_update', [c, view(b'')]) |
| 206 | o = out(); vm.call('sha256_final', [c, o]); cases += 1 |
| 207 | if bytes(o.a) != ref: bad += 1; print('split FAIL', n) |
| 208 | # copy of a live context (erratum E3): copy after the first half, continue both |
| 209 | c1 = ctx(); vm.call('sha256_init', [c1]); vm.call('sha256_update', [c1, view(msg[:n // 2])]) |
| 210 | c2 = Lay(fields, size, bytearray(c1.b)); o1, o2 = out(), out() |
| 211 | vm.call('sha256_update', [c1, view(msg[n // 2:])]); vm.call('sha256_update', [c2, view(msg[n // 2:])]) |
| 212 | vm.call('sha256_final', [c1, o1]); vm.call('sha256_final', [c2, o2]); cases += 1 |
| 213 | if not (bytes(o1.a) == bytes(o2.a) == ref): bad += 1; print('copy FAIL', n) |
| 214 | # init/update/final after a final equals a fresh context |
| 215 | vm.call('sha256_init', [c1]); vm.call('sha256_update', [c1, view(msg)]); o3 = out() |
| 216 | vm.call('sha256_final', [c1, o3]); cases += 1 |
| 217 | if bytes(o3.a) != ref: bad += 1; print('reuse FAIL', n) |
| 218 | for n in lens: |
| 219 | try: one(n) |
| 220 | except Trap as e: bad += 1; print('TRAP', e.args[0], 'at length', n) |
| 221 | print(f'desk-check cases={cases} fail={bad}') |
| 222 | sys.exit(1 if bad else 0) |
| 223 | main() |