gdp-wired 0.43.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +8 -3
  2. package/dist/core/c/reader.js +22 -7
  3. package/dist/core/check.js +3 -2
  4. package/dist/core/cli.d.ts +7 -0
  5. package/dist/core/cli.js +184 -12
  6. package/dist/core/counts.d.ts +1 -1
  7. package/dist/core/counts.js +30 -12
  8. package/dist/core/data.d.ts +6 -1
  9. package/dist/core/data.js +894 -152
  10. package/dist/core/dsl.d.ts +2 -0
  11. package/dist/core/dsl.js +88 -10
  12. package/dist/core/effect-prims.d.ts +60 -0
  13. package/dist/core/effect-prims.js +625 -0
  14. package/dist/core/effect.d.ts +17 -1
  15. package/dist/core/effect.js +108 -4
  16. package/dist/core/ex/harness.exs +2 -0
  17. package/dist/core/ex/reader.exs +17 -1
  18. package/dist/core/exists.d.ts +15 -1
  19. package/dist/core/exists.js +263 -41
  20. package/dist/core/extract-c.d.ts +2 -0
  21. package/dist/core/extract-c.js +22 -13
  22. package/dist/core/extract-check.d.ts +7 -0
  23. package/dist/core/extract-check.js +57 -4
  24. package/dist/core/extract-ex.js +5 -5
  25. package/dist/core/extract-go-check.js +22 -17
  26. package/dist/core/extract-go.d.ts +3 -0
  27. package/dist/core/extract-go.js +24 -9
  28. package/dist/core/extract-jvm.js +68 -16
  29. package/dist/core/extract-print.js +3 -0
  30. package/dist/core/extract-py.js +5 -5
  31. package/dist/core/extract-rb.js +5 -5
  32. package/dist/core/extract-read.d.ts +8 -0
  33. package/dist/core/extract-read.js +55 -0
  34. package/dist/core/extract-rs.js +28 -25
  35. package/dist/core/extract-shapes.js +20 -0
  36. package/dist/core/extract-sol.js +23 -12
  37. package/dist/core/extract-step.d.ts +59 -3
  38. package/dist/core/extract-step.js +334 -64
  39. package/dist/core/extract-swift.js +22 -15
  40. package/dist/core/extract.d.ts +1 -0
  41. package/dist/core/extract.js +27 -2
  42. package/dist/core/fresh.d.ts +2 -2
  43. package/dist/core/fresh.js +7 -3
  44. package/dist/core/go/reader.go +7 -1
  45. package/dist/core/infer.js +113 -40
  46. package/dist/core/jvm/Harness.java +8 -1
  47. package/dist/core/jvm/JavaReader.java +10 -2
  48. package/dist/core/jvm/Jvm.java +18 -2
  49. package/dist/core/jvm/KtReader.java +60 -5
  50. package/dist/core/machine.d.ts +2 -0
  51. package/dist/core/machine.js +32 -6
  52. package/dist/core/py/harness.py +128 -24
  53. package/dist/core/py/reader.py +50 -5
  54. package/dist/core/rb/reader.rb +52 -5
  55. package/dist/core/rs/src/main.rs +10 -0
  56. package/dist/core/sol/Replay.sol +52 -0
  57. package/dist/core/sol/harness.py +511 -0
  58. package/dist/core/solver.js +5 -4
  59. package/dist/core/system.d.ts +62 -1
  60. package/dist/core/system.js +274 -6
  61. package/dist/core/transfer.js +17 -0
  62. package/dist/core/watch.js +1 -1
  63. package/dist/interchange/check.d.ts +18 -1
  64. package/dist/interchange/check.js +19 -12
  65. package/dist/interchange/cli.d.ts +2 -0
  66. package/dist/interchange/cli.js +45 -0
  67. package/dist/interchange/format.d.ts +5 -1
  68. package/dist/interchange/format.js +25 -9
  69. package/dist/kernel/cdcl.js +65 -14
  70. package/dist/kernel/epr.js +35 -5
  71. package/dist/kernel/kernel.d.ts +2 -0
  72. package/dist/kernel/kernel.js +67 -40
  73. package/dist/kernel/prove.d.ts +22 -0
  74. package/dist/kernel/prove.js +156 -7
  75. package/dist/kernel/reader.js +3 -2
  76. package/dist/lean-kernel/emit.d.ts +9 -3
  77. package/dist/lean-kernel/emit.js +170 -29
  78. package/dist/lean-kernel/library.js +1 -1
  79. package/package.json +12 -3
@@ -0,0 +1,511 @@
1
+ """The Solidity front end's check harness (core/extract-sol.ts): the contract's bytecode, compiled by the same solc, run
2
+ on foundry's anvil (an EVM over JSON-RPC), spoken to in the step harness's JSON lines over two named pipes (hello, new,
3
+ at, get, call, coverage). The standard library only.
4
+
5
+ How the rule's values are the code's:
6
+ - an address is a natural below 2^26: n is the address BASE + n, 0 is address(0);
7
+ - a uint256 is a value below the rule's width W (the object's own, any W above the code's constants): v below
8
+ H = ceil(W/2) is v, any other is 2^256 - (W - v). Sums, differences, order and checked overflow are the same on both
9
+ sides wherever no value lands between the two bands; a code value there is outside what the rule compares (a value
10
+ string the step harness reads as outside the rule's numbers);
11
+ - a mapping's cell is held where it isn't zero; the cells read are those of every key the object was given or called
12
+ with (the rule's keys are the request's values);
13
+ - the contract's ether is `balance`.
14
+ """
15
+ import json
16
+ import os
17
+ import random
18
+ import socket
19
+ import subprocess
20
+ import sys
21
+ import time
22
+ import urllib.request
23
+
24
+ TWO256 = 1 << 256
25
+ BASE = 1 << 152
26
+ S = {}
27
+ OBJS = {}
28
+ PORT = [0]
29
+ RPC_ID = [0]
30
+ SHA = {}
31
+
32
+
33
+ def rpc(method, params):
34
+ RPC_ID[0] += 1
35
+ body = json.dumps({'jsonrpc': '2.0', 'id': RPC_ID[0], 'method': method, 'params': params}).encode()
36
+ req = urllib.request.Request(f'http://127.0.0.1:{PORT[0]}', data=body, headers={'content-type': 'application/json'})
37
+ with urllib.request.urlopen(req, timeout=60) as r:
38
+ out = json.loads(r.read())
39
+ if 'error' in out: raise RpcError(out['error'])
40
+ return out['result']
41
+
42
+
43
+ # Many calls in one request (JSON-RPC's batch): their results in order.
44
+ def rpc_batch(calls):
45
+ if not calls: return []
46
+ body = []
47
+ for m, p in calls:
48
+ RPC_ID[0] += 1
49
+ body.append({'jsonrpc': '2.0', 'id': RPC_ID[0], 'method': m, 'params': p})
50
+ req = urllib.request.Request(f'http://127.0.0.1:{PORT[0]}', data=json.dumps(body).encode(), headers={'content-type': 'application/json'})
51
+ with urllib.request.urlopen(req, timeout=120) as r:
52
+ out = {x['id']: x for x in json.loads(r.read())}
53
+ res = []
54
+ for b in body:
55
+ x = out[b['id']]
56
+ if 'error' in x: raise RpcError(x['error'])
57
+ res.append(x['result'])
58
+ return res
59
+
60
+
61
+ def keccak_many(hexes):
62
+ todo = [h for h in dict.fromkeys(hexes) if h not in SHA]
63
+ for h, r in zip(todo, rpc_batch([('web3_sha3', ['0x' + h]) for h in todo])): SHA[h] = r[2:]
64
+
65
+
66
+ class RpcError(Exception):
67
+ pass
68
+
69
+
70
+ def start_anvil():
71
+ exe = os.environ.get('GDP_ANVIL') or 'anvil'
72
+ for _ in range(20):
73
+ port = random.randint(20000, 60000)
74
+ with socket.socket() as s:
75
+ if s.connect_ex(('127.0.0.1', port)) == 0: continue
76
+ p = subprocess.Popen([exe, '--port', str(port), '--silent', '--gas-price', '0', '--base-fee', '0', '--disable-block-gas-limit', '--disable-code-size-limit', '--auto-impersonate', '--accounts', '1', '--hardfork', 'cancun'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
77
+ S['anvil'] = p
78
+ PORT[0] = port
79
+ for _ in range(100):
80
+ try:
81
+ rpc('web3_clientVersion', [])
82
+ return
83
+ except Exception:
84
+ if p.poll() is not None: break
85
+ time.sleep(0.05)
86
+ p.kill()
87
+ raise RuntimeError('anvil did not start (foundry\'s anvil on the PATH, or $GDP_ANVIL)')
88
+
89
+
90
+ def keccak(hexdata):
91
+ h = SHA.get(hexdata)
92
+ if h is None: h = SHA[hexdata] = rpc('web3_sha3', ['0x' + hexdata])[2:]
93
+ return h
94
+
95
+
96
+ def word(n): return format(n % TWO256, '064x')
97
+ def addr_of(n): return 0 if n == 0 else BASE + n
98
+ def addr_hex(n): return '0x' + format(addr_of(n), '040x')
99
+ def addr_limit(): return 1 << (S['addrBits'] or 152)
100
+ def n_of_addr(a):
101
+ if a == 0: return 0
102
+ n = a - BASE
103
+ if 0 < n < addr_limit(): return n
104
+ return None
105
+
106
+
107
+ def half(W): return (W + 1) // 2
108
+ def to_code(v, W):
109
+ return v if v < half(W) else TWO256 - (W - v)
110
+ def to_rule(c, W):
111
+ if c < half(W): return c
112
+ if c >= TWO256 - (W - half(W)): return W - (TWO256 - c)
113
+ return None
114
+
115
+
116
+ # A value of a kind, the rule's to the code's and back (None: outside what the rule compares).
117
+ def enc(kind, v, W):
118
+ if kind == 'u256': return to_code(int(v), W)
119
+ if kind == 'addr': return addr_of(int(v))
120
+ if kind == 'bool': return 1 if v is True or v == 'true' else 0
121
+ if kind.startswith('choice:'): return kind[7:].split('|').index(v)
122
+ if kind.startswith('i'): return int(v) % (1 << int(kind[1:]))
123
+ return int(v)
124
+
125
+
126
+ def dec(kind, c, W):
127
+ if kind == 'u256':
128
+ r = to_rule(c, W)
129
+ return 'outside' if r is None else str(r)
130
+ if kind == 'addr':
131
+ r = n_of_addr(c)
132
+ return 'outside' if r is None else str(r)
133
+ if kind == 'bool': return c != 0
134
+ if kind.startswith('choice:'):
135
+ vals = kind[7:].split('|')
136
+ return vals[c] if c < len(vals) else 'outside'
137
+ if kind.startswith('i'):
138
+ b = int(kind[1:])
139
+ return str(c - (1 << b) if c >= 1 << (b - 1) else c)
140
+ return str(c)
141
+
142
+
143
+ def fits(kind, v, W):
144
+ if kind == 'u256': return 0 <= int(v) < W
145
+ if kind == 'addr': return 0 <= int(v) < addr_limit()
146
+ if kind.startswith('u') and kind[1:].isdigit(): return 0 <= int(v) < (1 << int(kind[1:]))
147
+ if kind.startswith('i') and kind[1:].isdigit(): b = int(kind[1:]); return -(1 << (b - 1)) <= int(v) < (1 << (b - 1))
148
+ return True
149
+
150
+
151
+ # --- storage ------------------------------------------------------------------------------------------------------------
152
+ def slot_of(label):
153
+ return S['slots'][label]
154
+
155
+
156
+ def key_word(kind, k, W):
157
+ return word(enc(kind, k, W))
158
+
159
+
160
+ def cell_slot(label, key, W):
161
+ s = slot_of(label)
162
+ base = int(s['slot'])
163
+ kk = S['keys'][label]
164
+ return int(keccak(key_word(kk[0], key, W) + word(base)), 16)
165
+
166
+
167
+ # A mapping of mappings the rule reads as any value (an input of the request): every cell of the addresses the object
168
+ # has seen set to it before the call, as the code then reads it.
169
+ def set_havoc(o, label, v, W):
170
+ kk, base, cs = S['keys'][label], word(int(slot_of(label)['slot'])), sorted(c for c in o['cands'] if c >= 0)
171
+ outer = [key_word(kk[0], a, W) + base for a in cs if fits(kk[0], a, W)]
172
+ keccak_many(outer)
173
+ inner = [key_word(kk[1], b, W) + keccak(h) for h in outer for b in cs if fits(kk[1], b, W)]
174
+ keccak_many(inner)
175
+ rpc_batch([('anvil_setStorageAt', [o['addr'], '0x' + keccak(h), '0x' + word(v)]) for h in inner])
176
+
177
+
178
+ def read_slot(addr, slot):
179
+ return int(rpc('eth_getStorageAt', [addr, hex(slot), 'latest']), 16)
180
+
181
+
182
+ def write_slot(addr, slot, value):
183
+ rpc('anvil_setStorageAt', [addr, '0x' + word(slot), '0x' + word(value)])
184
+
185
+
186
+ def read_field(o, label):
187
+ s = slot_of(label)
188
+ w = read_slot(o['addr'], int(s['slot']))
189
+ return (w >> (8 * s['offset'])) & ((1 << (8 * s['bytes'])) - 1)
190
+
191
+
192
+ def write_field(o, label, value):
193
+ s = slot_of(label)
194
+ slot = int(s['slot'])
195
+ w = read_slot(o['addr'], slot)
196
+ mask = ((1 << (8 * s['bytes'])) - 1) << (8 * s['offset'])
197
+ write_slot(o['addr'], slot, (w & ~mask) | ((value << (8 * s['offset'])) & mask))
198
+
199
+
200
+ # --- requests -------------------------------------------------------------------------------------------------------------
201
+ def hello(req):
202
+ S.update(req['sol'])
203
+ S['leaves'] = req['leaves']
204
+ S['ctorSpec'] = req['ctor']
205
+ # Each mapping's key kinds (one, or two for a mapping of mappings) and value kind.
206
+ S['keys'] = {}
207
+ for label, k in S['kinds'].items():
208
+ if k.startswith('map:'): S['keys'][label] = S['mapKeys'][label]
209
+ start_anvil()
210
+ return {'ok': True}
211
+
212
+
213
+ def fund(a, value):
214
+ # (exactly the value: gas costs nothing here, and an account that receives a value near 2^256 must have room for it)
215
+ rpc('anvil_setBalance', [a, hex(value)])
216
+
217
+
218
+ def arg_value(spec):
219
+ if 'in' in spec: return spec['in']
220
+ return 0
221
+
222
+
223
+ def send(frm, to, data, value, deploy=False):
224
+ tx = {'from': frm, 'data': '0x' + data, 'value': hex(value), 'gas': hex(30_000_000), 'gasPrice': '0x0'}
225
+ if not deploy: tx['to'] = to
226
+ fund(frm, value)
227
+ try:
228
+ h = rpc('eth_sendTransaction', [tx])
229
+ except RpcError as e:
230
+ return None, str(e)[:300]
231
+ r = None
232
+ for i in range(200):
233
+ r = rpc('eth_getTransactionReceipt', [h])
234
+ if r is not None: break
235
+ time.sleep(0.002 * (i + 1))
236
+ if r is None: raise TimeoutError('no receipt for a transaction anvil was sent')
237
+ if int(r['status'], 16) != 1: return None, 'reverted'
238
+ return r, None
239
+
240
+
241
+ def abi_args(types, vals, W):
242
+ return ''.join(word(enc(kind_of_type(t), v, W)) for t, v in zip(types, vals))
243
+
244
+
245
+ def kind_of_type(t):
246
+ t = t.split(' ')[0] if not t.startswith('enum ') else t
247
+ if t == 'uint256': return 'u256'
248
+ if t.startswith('address'): return 'addr'
249
+ if t == 'bool': return 'bool'
250
+ if t.startswith('enum '): return 'u8'
251
+ if t.startswith('uint'): return 'u' + t[4:]
252
+ if t.startswith('int'): return 'i' + t[3:]
253
+ raise ValueError(f'an argument of {t}')
254
+
255
+
256
+ def make(args):
257
+ a = dict((n, arg_value(s)) for n, s in args)
258
+ W = int(a.get(S['mod'], 0))
259
+ if W < S['minW']: raise ValueError(f'a width below {S["minW"]}')
260
+ # (a width the bands can't hold apart: sums of small values would land between them)
261
+ if W < (1 << 40): raise ValueError('a width below 2^40 (the check compares the code at 2^52 and at the prover\'s witnesses from 2^40)')
262
+ sender = int(a.get('msg.sender', 1))
263
+ if not 0 < sender < addr_limit(): raise ValueError('msg.sender outside the addresses')
264
+ params = [n for n, _ in args if n not in (S['mod'], 'msg.sender', 'msg.value')]
265
+ for n, t in zip(params, S['ctor']['inputs']):
266
+ if not fits(kind_of_type(t), a[n], W): raise ValueError(f'{n} outside its type')
267
+ if not fits('u256', a.get('msg.value', 0), W): raise ValueError('msg.value outside its type')
268
+ data = S['creation'] + abi_args(S['ctor']['inputs'], [a[n] for n in params], W)
269
+ r, err = send(addr_hex(sender), None, data, to_code(int(a.get('msg.value', 0)), W), deploy=True)
270
+ if err: raise ValueError(err)
271
+ i = len(OBJS) + 1
272
+ OBJS[i] = {'addr': r['contractAddress'], 'W': W, 'cands': {0, sender} | set(int(a[n]) for n, t in zip(params, S['ctor']['inputs']) if kind_of_type(t) in ('addr', 'u256')), 'held': {}}
273
+ return i
274
+
275
+
276
+ FRESH = [0]
277
+ def at(args, state):
278
+ i = make(args)
279
+ o = OBJS[i]
280
+ W = o['W']
281
+ # A fresh address with the contract's code, its storage only what the state says.
282
+ FRESH[0] += 1
283
+ fresh = '0x' + format(0xC0DE << 140 | FRESH[0], '040x')
284
+ rpc('anvil_setCode', [fresh, rpc('eth_getCode', [o['addr'], 'latest'])])
285
+ o['addr'] = fresh
286
+ for l in S['leaves']:
287
+ if l['kind'] == 'frame': continue
288
+ label = l['path'][0]
289
+ v = state.get(l['name'])
290
+ if label == S['mod']:
291
+ if int(v) != W: raise ValueError('a width other than the object\'s')
292
+ continue
293
+ if label == 'balance':
294
+ if not fits('u256', v, W): raise ValueError('a balance outside its type')
295
+ rpc('anvil_setBalance', [fresh, hex(to_code(int(v), W))])
296
+ continue
297
+ k = S['kinds'][label]
298
+ if l['kind'] == 'map':
299
+ vk = k[4:]
300
+ for key, c in (v or {}).items():
301
+ key = int(key)
302
+ x = c['value']
303
+ if x in (0, '0', False): raise ValueError('a cell held at zero (no state of a mapping)')
304
+ if not fits(vk, x, W): raise ValueError('a cell outside its type')
305
+ if not key_fits(label, key, W): raise ValueError('a key outside its type')
306
+ write_slot(fresh, cell_slot(label, key, W), enc(vk, x, W))
307
+ o['held'].setdefault(label, set()).add(key)
308
+ note_key(o, label, key)
309
+ continue
310
+ if not fits(k, v, W): raise ValueError(f'{label} outside its type')
311
+ write_field(o, label, enc(k, v, W))
312
+ if k in ('addr', 'u256'): o['cands'].add(int(v))
313
+ return i
314
+
315
+
316
+ def key_fits(label, key, W): return fits(S['keys'][label][0], key, W)
317
+ def note_key(o, label, key): o['cands'].add(key)
318
+ def keys_of(o, label, W): return [c for c in sorted(o['cands']) if c >= 0 and key_fits(label, c, W)]
319
+
320
+
321
+ def state_of(i):
322
+ o = OBJS[i]
323
+ W = o['W']
324
+ s = {}
325
+ # (every slot the state reads, hashed and read in two batches)
326
+ cells = [(l, key) for l in S['leaves'] if l['kind'] == 'map' for key in keys_of(o, l['path'][0], W)]
327
+ keccak_many([key_word(S['keys'][l['path'][0]][0], key, W) + word(int(slot_of(l['path'][0])['slot'])) for l, key in cells])
328
+ slots = [cell_slot(l['path'][0], key, W) for l, key in cells]
329
+ vals = dict(zip([(l['name'], key) for l, key in cells], [int(x, 16) for x in rpc_batch([('eth_getStorageAt', [o['addr'], hex(sl), 'latest']) for sl in slots])]))
330
+ for l in S['leaves']:
331
+ if l['kind'] == 'frame': continue
332
+ label = l['path'][0]
333
+ if label == S['mod']: s[l['name']] = str(W); continue
334
+ if label == 'balance':
335
+ s[l['name']] = dec('u256', int(rpc('eth_getBalance', [o['addr'], 'latest']), 16), W)
336
+ continue
337
+ k = S['kinds'][label]
338
+ if l['kind'] == 'map':
339
+ vk = k[4:]
340
+ cells = {}
341
+ for key in keys_of(o, label, W):
342
+ c = vals[(l['name'], key)]
343
+ if c != 0: cells[str(key)] = {'value': dec(vk, c, W)}
344
+ s[l['name']] = cells
345
+ continue
346
+ s[l['name']] = dec(k, read_field(o, label), W)
347
+ return s
348
+
349
+
350
+ def call(req):
351
+ o = OBJS[req['id']]
352
+ W = o['W']
353
+ m = req['m']
354
+ e = S['entries'][m]
355
+ a = dict((n, arg_value(s)) for n, s in req['a'])
356
+ sender = int(a.get('msg.sender', 0))
357
+ if not 0 < sender < addr_limit(): return {'err': 'msg.sender outside the addresses'}
358
+ if req.get('now'):
359
+ try: rpc('evm_setNextBlockTimestamp', [int(req['now'])])
360
+ except RpcError as x: return {'bad': f'the time {req["now"]}: {x}'}
361
+ data, value, bad = calldata(o, m, req['a'], W)
362
+ if bad: return {'err': bad}
363
+ bad = havoc(o, req.get('answers') or {}, W, m)
364
+ if bad: return {'err': bad}
365
+ frm = addr_hex(sender)
366
+ fund(frm, value)
367
+ tx = {'from': frm, 'to': o['addr'], 'data': '0x' + data, 'value': hex(value), 'gas': hex(30_000_000), 'gasPrice': '0x0'}
368
+ try:
369
+ ret = rpc('eth_call', [tx, 'latest'])
370
+ except RpcError as x:
371
+ return {'err': f'reverted: {str(x)[:200]}'}
372
+ r, err = send(frm, o['addr'], data, value)
373
+ if err: return {'err': err}
374
+ out = None
375
+ if e.get('out'):
376
+ c = int(ret[2:66] or '0', 16)
377
+ k = kind_of_type(e['out'])
378
+ v = dec(k, c, W)
379
+ out = v if isinstance(v, bool) else {'n': v}
380
+ return {'out': out}
381
+
382
+
383
+ # A call's data and value (the rule's arguments as the code's), or why it can't be made.
384
+ def calldata(o, m, args, W):
385
+ e = S['entries'][m]
386
+ a = dict((n, arg_value(s)) for n, s in args)
387
+ params = [n for n, _ in args if n not in ('msg.sender', 'msg.value')]
388
+ for n, t in zip(params, e['inputs']):
389
+ if not fits(kind_of_type(t), a[n], W): return None, None, f'{n} outside its type'
390
+ if kind_of_type(t) in ('addr', 'u256'): o['cands'].add(int(a[n]))
391
+ o['cands'].add(int(a.get('msg.sender', 0)))
392
+ if not fits('u256', a.get('msg.value', 0), W): return None, None, 'msg.value outside its type'
393
+ data = '' if m in ('receive', 'fallback') else S['ids'][e['sig']] + abi_args(e['inputs'], [a[n] for n in params], W)
394
+ return data, to_code(int(a.get('msg.value', 0)), W), None
395
+
396
+
397
+ # The answers of the mappings of mappings read (the rule's inputs): each set in the code's cells.
398
+ def havoc(o, answers, W, m):
399
+ # (a value below 0 is no natural: the rule's input kind refuses it at every request)
400
+ for label in S.get('havoc') or []:
401
+ a = answers.get(label)
402
+ if a is not None and isinstance(a.get('in'), (int, float)) and not isinstance(a.get('in'), bool) and a['in'] < 0: return f'{label} answers {a["in"]}, below 0'
403
+ for label in (S.get('havocBy') or {}).get(m, []):
404
+ if label not in (S.get('havoc') or []): continue
405
+ a = answers.get(label)
406
+ if a is None: continue
407
+ v = a.get('in', 0)
408
+ kind = S['kinds'][label][4:]
409
+ if not fits(kind, v, W): return f'{label} answers {v}, outside its type'
410
+ set_havoc(o, label, enc(kind, v, W), W)
411
+ return None
412
+
413
+
414
+ # --- re-entrant runs replayed: an Agent at every address, a Director with the run's script --------------------------------
415
+ DIRECTOR = 0xD1EC70
416
+
417
+
418
+ def abi_dyn(t, kinds, froms, values, rets, datas):
419
+ def arr(xs): return word(len(xs)) + ''.join(word(x) for x in xs)
420
+ def barr(bs):
421
+ heads, tails, off = [], [], 32 * len(bs)
422
+ for b in bs:
423
+ raw = bytes.fromhex(b)
424
+ body = word(len(raw)) + raw.hex() + '00' * ((32 - len(raw) % 32) % 32)
425
+ heads.append(word(off)); tails.append(body); off += len(body) // 2
426
+ return word(len(bs)) + ''.join(heads) + ''.join(tails)
427
+ parts = [arr(kinds), arr(froms), arr(values), arr([1 if r else 0 for r in rets]), barr(datas)]
428
+ head, off, tail = word(t), 32 * 6, ''
429
+ for p in parts:
430
+ head += word(off); tail += p; off += len(p) // 2
431
+ return head + tail
432
+
433
+
434
+ def replay(req):
435
+ hello({'sol': req['sol'], 'leaves': req['leaves'], 'ctor': req['ctorSpec']})
436
+ i = make(req['ctor'])
437
+ o = OBJS[i]
438
+ W = o['W']
439
+ d = '0x' + format(DIRECTOR, '040x')
440
+ rpc('anvil_setCode', [d, '0x' + req['director']])
441
+ run_sel = keccak('run(address,uint8[],address[],uint256[],bool[],bytes[])'.encode().hex())[:8]
442
+ oks_sel, count_sel = keccak('oks(uint256)'.encode().hex())[:8], keccak('count()'.encode().hex())[:8]
443
+ agents = set()
444
+ out = {'states': [], 'oks': []}
445
+ for g in req['groups']:
446
+ kinds, froms, values, rets, datas = [], [], [], [], []
447
+ for e in g:
448
+ if e['kind'] == 'ret':
449
+ kinds.append(1); froms.append(0); values.append(0); rets.append(bool(e['ok'])); datas.append('')
450
+ continue
451
+ a = dict((n, arg_value(s)) for n, s in e['a'])
452
+ data, value, bad = calldata(o, e['m'], e['a'], W)
453
+ if bad: return {'error': f'a call the code can\'t be given: {bad}'}
454
+ sender = int(a.get('msg.sender', 0))
455
+ if not 0 < sender < addr_limit(): return {'error': 'msg.sender outside the addresses'}
456
+ if sender not in agents:
457
+ rpc('anvil_setCode', [addr_hex(sender), '0x' + req['agent']])
458
+ agents.add(sender)
459
+ rpc('anvil_setBalance', [addr_hex(sender), hex(min(value + (1 << 128), TWO256 - 1))])
460
+ if e.get('answers'):
461
+ if len(g) > 1: return {'error': 'a mapping of mappings read inside a call of another (the replay sets its cells before a transaction)'}
462
+ bad = havoc(o, e['answers'], W, e['m'])
463
+ if bad: return {'error': bad}
464
+ kinds.append(0); froms.append(addr_of(sender)); values.append(value); rets.append(False); datas.append(data)
465
+ frm = '0x' + format(0xBEEF << 140, '040x')
466
+ r, err = send(frm, d, run_sel + abi_dyn(int(o['addr'], 16), kinds, froms, values, rets, datas), 0)
467
+ if err: return {'error': f'transaction {len(out["states"]) + 1} reverts: {err}', **out}
468
+ n = int(rpc('eth_call', [{'to': d, 'data': '0x' + count_sel}, 'latest']), 16)
469
+ out['oks'].append([int(rpc('eth_call', [{'to': d, 'data': '0x' + oks_sel + word(k)}, 'latest']), 16) == 1 for k in range(n)])
470
+ out['states'].append(state_of(i))
471
+ return out
472
+
473
+
474
+ def main():
475
+ if sys.argv[1] == '--replay':
476
+ req = json.load(open(sys.argv[2]))
477
+ try: res = replay(req)
478
+ except Exception as e: res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
479
+ finally:
480
+ if S.get('anvil'): S['anvil'].kill()
481
+ print(json.dumps(res))
482
+ return
483
+ fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
484
+ try:
485
+ for line in fin:
486
+ req = json.loads(line)
487
+ op = req['op']
488
+ try:
489
+ if op == 'hello': res = hello(req)
490
+ elif op == 'new':
491
+ try: res = {'id': make(req['a'])}
492
+ except OSError: raise
493
+ except Exception as e: res = {'err': f'{type(e).__name__}: {e}'[:300]}
494
+ elif op == 'at':
495
+ try: res = {'id': at(req['a'], req['state'])}
496
+ except OSError: raise
497
+ except Exception as e: res = {'bad': f'{type(e).__name__}: {e}'[:300]}
498
+ elif op == 'get': res = {'state': state_of(req['id'])}
499
+ elif op == 'call': res = call(req)
500
+ elif op == 'coverage': res = {'hit': []}
501
+ else: res = {'error': f'no op {op}'}
502
+ except Exception as e:
503
+ # (anvil's transport failing, a request past its time: the check's failure, never the code's)
504
+ res = {'error': f'{type(e).__name__}: {e}'[:500], **({'transport': True} if isinstance(e, OSError) else {})}
505
+ fout.write(json.dumps(res) + '\n'); fout.flush()
506
+ finally:
507
+ if S.get('anvil'): S['anvil'].kill()
508
+
509
+
510
+ if __name__ == '__main__':
511
+ main()
@@ -16,9 +16,10 @@ export const env = globalThis.process?.env ?? {};
16
16
  export const v = (name) => ({ [name]: 1 });
17
17
  export const k = (value) => (value === 0 ? {} : { 1: value });
18
18
  // (Plain loops, no intermediate arrays: these run millions of times in a proof. Each keeps the keys in the order they
19
- // first appear, as a sum over the entries would.)
19
+ // first appear, as a sum over the entries would. Each builds on an object with no prototype, so a variable
20
+ // named __proto__ is a key like any other and one named constructor or toString reads 0 until set.)
20
21
  export function add(...xs) {
21
- const out = {};
22
+ const out = Object.create(null);
22
23
  for (const x of xs)
23
24
  for (const key in x)
24
25
  out[key] = (out[key] ?? 0) + x[key];
@@ -28,7 +29,7 @@ export function add(...xs) {
28
29
  return out;
29
30
  }
30
31
  export const scale = (x, f) => {
31
- const out = {};
32
+ const out = Object.create(null);
32
33
  for (const key in x) {
33
34
  const value = x[key] * f;
34
35
  if (value !== 0)
@@ -37,7 +38,7 @@ export const scale = (x, f) => {
37
38
  return out;
38
39
  };
39
40
  export const sub = (a, b) => {
40
- const out = {};
41
+ const out = Object.create(null);
41
42
  for (const key in a)
42
43
  out[key] = a[key];
43
44
  for (const key in b)
@@ -1,4 +1,5 @@
1
- import { type Machine } from './machine.js';
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type StepLaw } from '../kernel/kernel.js';
2
3
  import { type Kind, type Rule } from './dsl.js';
3
4
  export type Model = {
4
5
  name: string;
@@ -21,6 +22,7 @@ export declare function asRule(m: Machine, kinds?: Record<string, Kind<unknown>>
21
22
  export type Level = 'atomic' | 'read committed' | 'snapshot';
22
23
  export declare const ISOLATION: Record<Level, Model>;
23
24
  export declare function isolation(m: Machine, level: Level): Machine;
25
+ export declare const readsOf: WeakMap<Machine, string[]>;
24
26
  export type Delivery = 'exactly-once' | 'at-least-once';
25
27
  export declare const DELIVERY: Record<Delivery, Model>;
26
28
  export declare function delivery(m: Machine, pool: string, fields: string[], mode: Delivery, opts?: {
@@ -42,3 +44,62 @@ export declare function expires(cells: Record<string, number>, at: string, opts?
42
44
  key?: string;
43
45
  now?: string;
44
46
  }): Machine;
47
+ export type Env = {
48
+ isolation?: Level;
49
+ expiry?: boolean;
50
+ retries?: boolean;
51
+ flow?: string[];
52
+ apart?: boolean;
53
+ };
54
+ export declare function envOf(text: string | string[]): Env;
55
+ export declare const envText: (e: Env) => string;
56
+ export type InEnv = {
57
+ rule: Rule;
58
+ models: Model[];
59
+ reads: string[];
60
+ part: string;
61
+ act: string;
62
+ id?: string;
63
+ commit?: number;
64
+ level: Level;
65
+ flow?: string[];
66
+ method?: string;
67
+ methods?: number;
68
+ law: (l: Law) => Law;
69
+ step: (s: StepLaw) => StepLaw;
70
+ between: (name: string, a: string, b: string) => Law;
71
+ };
72
+ export type EnvOpts = {
73
+ stores?: string[][];
74
+ own?: string[];
75
+ method?: {
76
+ name: string;
77
+ values: string[];
78
+ };
79
+ failed?: string;
80
+ args?: {
81
+ method: string;
82
+ code: string;
83
+ rule: string;
84
+ }[];
85
+ oks?: {
86
+ method: string;
87
+ rule: string;
88
+ }[];
89
+ };
90
+ export declare function inEnv(r: Rule | Machine, env: Env, o?: EnvOpts): InEnv;
91
+ export declare function shrinkRun<T extends {
92
+ params: Record<string, number>;
93
+ trace: Record<string, unknown>[];
94
+ }>(r: Rule | Machine, w: Law | StepLaw, run: T): T;
95
+ export declare function contend(e: InEnv, w: Law | StepLaw, opts?: {
96
+ bases?: number;
97
+ depth?: number;
98
+ bound?: number;
99
+ seed?: number;
100
+ ms?: number;
101
+ calls?: number;
102
+ }): {
103
+ params: Record<string, number>;
104
+ trace: Record<string, unknown>[];
105
+ } | undefined;