gdp-wired 0.43.0 → 0.44.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.
- package/README.md +8 -3
- package/dist/core/cli.d.ts +6 -0
- package/dist/core/cli.js +48 -6
- package/dist/core/data.js +2 -2
- package/dist/core/effect-prims.d.ts +60 -0
- package/dist/core/effect-prims.js +625 -0
- package/dist/core/effect.d.ts +17 -1
- package/dist/core/effect.js +108 -4
- package/dist/core/ex/harness.exs +2 -0
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +5 -3
- package/dist/core/extract-check.d.ts +1 -0
- package/dist/core/extract-check.js +8 -1
- package/dist/core/extract-ex.js +2 -2
- package/dist/core/extract-go-check.js +4 -6
- package/dist/core/extract-go.d.ts +3 -0
- package/dist/core/extract-go.js +4 -4
- package/dist/core/extract-jvm.js +6 -3
- package/dist/core/extract-py.js +2 -2
- package/dist/core/extract-rb.js +2 -2
- package/dist/core/extract-rs.js +12 -7
- package/dist/core/extract-sol.js +4 -4
- package/dist/core/extract-step.d.ts +9 -0
- package/dist/core/extract-step.js +48 -9
- package/dist/core/extract-swift.js +3 -3
- package/dist/core/infer.js +3 -3
- package/dist/core/jvm/Harness.java +8 -1
- package/dist/core/jvm/Jvm.java +1 -1
- package/dist/core/jvm/KtReader.java +3 -0
- package/dist/core/machine.d.ts +3 -0
- package/dist/core/machine.js +15 -1
- package/dist/core/py/harness.py +51 -13
- package/dist/core/sol/Replay.sol +52 -0
- package/dist/core/sol/harness.py +508 -0
- package/dist/core/system.js +12 -3
- package/dist/interchange/check.d.ts +18 -1
- package/dist/interchange/check.js +9 -2
- package/dist/interchange/cli.d.ts +2 -0
- package/dist/interchange/cli.js +45 -0
- package/dist/interchange/format.d.ts +1 -1
- package/dist/interchange/format.js +15 -7
- package/dist/kernel/cdcl.js +32 -12
- package/dist/kernel/reader.js +3 -2
- package/package.json +12 -3
|
@@ -0,0 +1,508 @@
|
|
|
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: return None, 'no receipt'
|
|
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]}
|
|
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 Exception as e: res = {'err': f'{type(e).__name__}: {e}'[:300]}
|
|
493
|
+
elif op == 'at':
|
|
494
|
+
try: res = {'id': at(req['a'], req['state'])}
|
|
495
|
+
except Exception as e: res = {'bad': f'{type(e).__name__}: {e}'[:300]}
|
|
496
|
+
elif op == 'get': res = {'state': state_of(req['id'])}
|
|
497
|
+
elif op == 'call': res = call(req)
|
|
498
|
+
elif op == 'coverage': res = {'hit': []}
|
|
499
|
+
else: res = {'error': f'no op {op}'}
|
|
500
|
+
except Exception as e:
|
|
501
|
+
res = {'error': f'{type(e).__name__}: {e}'[:500]}
|
|
502
|
+
fout.write(json.dumps(res) + '\n'); fout.flush()
|
|
503
|
+
finally:
|
|
504
|
+
if S.get('anvil'): S['anvil'].kill()
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
if __name__ == '__main__':
|
|
508
|
+
main()
|
package/dist/core/system.js
CHANGED
|
@@ -153,9 +153,18 @@ export function asRule(m, kinds = {}) {
|
|
|
153
153
|
r = r.params(Object.fromEntries(m.params.map(p => [p, kindOf(p)])));
|
|
154
154
|
if (m.inputs.length)
|
|
155
155
|
r = r.inputs(Object.fromEntries(m.inputs.map(i => [i, kindOf(i)])));
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
156
|
+
// (a state variable given an integer's kind, x beside x$neg as Int keeps one, is that integer to the laws: both start at
|
|
157
|
+
// constants)
|
|
158
|
+
const ints = Object.keys(m.state).filter(v => kinds[v] && `${v}$neg` in m.state && m.state[v].op === 'const' && m.state[`${v}$neg`].op === 'const');
|
|
159
|
+
const at = (v) => m.state[v].value;
|
|
160
|
+
r = r.state({ ...mapValues(Object.fromEntries(Object.entries(m.state).filter(([v]) => !ints.some(i => v === i || v === `${i}$neg`))), e => (e.op === 'const' ? e.value : () => new Term(e))),
|
|
161
|
+
...Object.fromEntries(ints.map(v => [v, kinds[v].from(at(v) - at(`${v}$neg`))])) });
|
|
162
|
+
// (a map given a kind of cells, its parts as the machine has them (m.has, m.value), is those cells to the laws)
|
|
163
|
+
const cells = Object.entries(kinds).filter(([n, k]) => k.vars(n).length > 1 && k.vars(n).every(p => p in (m.maps ?? {})));
|
|
164
|
+
const parts = new Set(cells.flatMap(([n, k]) => k.vars(n)));
|
|
165
|
+
const plainMaps = Object.fromEntries(Object.entries(m.maps ?? {}).filter(([n]) => !parts.has(n)));
|
|
166
|
+
if (Object.keys(plainMaps).length || cells.length)
|
|
167
|
+
r = r.maps({ ...plainMaps, ...Object.fromEntries(cells.map(([n, k]) => [n, k.from(k.decode(n, Object.fromEntries(k.vars(n).map(p => [p, m.maps[p]]))))])) });
|
|
159
168
|
if (m.step.flags && Object.keys(m.step.flags).length)
|
|
160
169
|
r = r.flags(() => mapValues(m.step.flags, c => new Cond(c)));
|
|
161
170
|
r = r.step(() => ({ ...mapValues(m.step.state, e => new Term(e)), ...mapValues(m.step.maps, (w, map) => ({ map, ...w })) }));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Certificate, type Json } from './format.js';
|
|
1
|
+
import { type Certificate, type Document, type Json, fromInterchange, toInterchange } from './format.js';
|
|
2
2
|
export type Claim = {
|
|
3
3
|
name: string;
|
|
4
4
|
accepted: boolean;
|
|
@@ -10,7 +10,24 @@ export type Report = {
|
|
|
10
10
|
claims: Claim[];
|
|
11
11
|
malformed?: string;
|
|
12
12
|
};
|
|
13
|
+
export declare const decidedBy: {
|
|
14
|
+
goals: string;
|
|
15
|
+
qgoals: string;
|
|
16
|
+
laws: string;
|
|
17
|
+
stepLaws: string;
|
|
18
|
+
kInduction: string;
|
|
19
|
+
progress: string;
|
|
20
|
+
liveness: string;
|
|
21
|
+
loop: string;
|
|
22
|
+
recur: string;
|
|
23
|
+
fold: string;
|
|
24
|
+
cyclic: string;
|
|
25
|
+
qmachine: string;
|
|
26
|
+
termination: string;
|
|
27
|
+
};
|
|
13
28
|
export declare function checkCertificate(c: Certificate): Claim[];
|
|
14
29
|
export declare function checkDocument(doc: unknown): Report;
|
|
15
30
|
export declare function goalsOf(c: Certificate): Certificate;
|
|
16
31
|
export type { Json };
|
|
32
|
+
export { fromInterchange, toInterchange };
|
|
33
|
+
export type { Certificate, Document };
|
|
@@ -27,6 +27,10 @@ const failing = (goals, trees) => {
|
|
|
27
27
|
};
|
|
28
28
|
// (A certificate of no claims, an empty set of laws, is the kernel's answer on it all the same: a claim of its own.)
|
|
29
29
|
const all = (names, r, why) => (names.length ? names : ['(no claims)']).map(name => ({ name, accepted: r.ok, ...(r.ok ? {} : { why: r.why ?? why?.() ?? 'refused' }) }));
|
|
30
|
+
// The kernel's entry point that decides each kind (docs/interchange.md's table), named in the CLI's verdict.
|
|
31
|
+
export const decidedBy = { goals: 'kernel.ts check', qgoals: 'kernel.ts checkQTree', laws: 'kernel.ts checkLaws', stepLaws: 'kernel.ts checkStepLaws', kInduction: 'kernel.ts checkKInduction',
|
|
32
|
+
progress: 'kernel.ts checkLaws, progressObligations', liveness: 'kernel.ts livenessParts, checkStepLaws', loop: 'kernel.ts loopObligations', recur: 'kernel.ts checkRecur',
|
|
33
|
+
fold: 'kernel.ts foldObligations', cyclic: 'cyclic.ts refuseCyclic', qmachine: 'kernel.ts checkQMachine', termination: 'cyclic.ts refuseCyclic' };
|
|
30
34
|
// The kernel's verdict on a certificate, for each thing it claims.
|
|
31
35
|
export function checkCertificate(c) {
|
|
32
36
|
switch (c.kind) {
|
|
@@ -67,8 +71,9 @@ export function checkDocument(doc) {
|
|
|
67
71
|
let c;
|
|
68
72
|
try {
|
|
69
73
|
c = fromInterchange(doc);
|
|
70
|
-
// The guard: the certificate read, written again, is the document (its columns in any order
|
|
71
|
-
|
|
74
|
+
// The guard: the certificate read, written again, is the document (its columns in any order; at its version, which
|
|
75
|
+
// the reader checked holds what it read).
|
|
76
|
+
if (!sameJson({ ...resolved(toInterchange(c, doc.meta)), version: doc.version }, resolved(doc)))
|
|
72
77
|
return { accepted: false, claims: [], malformed: 'read back, the document is not the same (a field the format drops, or a value it changes)' };
|
|
73
78
|
}
|
|
74
79
|
catch (e) {
|
|
@@ -109,3 +114,5 @@ export function goalsOf(c) {
|
|
|
109
114
|
case 'termination': return { kind: 'goals', goals: c.obligations.flatMap(o => cyclic(o.cyclic)) };
|
|
110
115
|
}
|
|
111
116
|
}
|
|
117
|
+
// (the format's reader and writer, beside the checker, for `gdp-wired/interchange`)
|
|
118
|
+
export { fromInterchange, toInterchange };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// gdp-wired-check: interchange documents in, the kernel's verdict on each claim out.
|
|
3
|
+
// gdp-wired-check [--json] [--goals <out.json>] <file.json>... (or - for standard input)
|
|
4
|
+
// Each file: `accepted` or `refused` with the kind and the kernel's entry point that decided it, then each claim (a
|
|
5
|
+
// law, a step law, a node, a goal) and why a refused one is. Exit 0 when every claim of every file is accepted, 1 when
|
|
6
|
+
// one is refused (or a file isn't a document), 2 on bad use.
|
|
7
|
+
// --goals: the first file's goals, each with its tree, written as a `goals` document (the tree part of the check, for a
|
|
8
|
+
// second checker: interchange/py/check.py).
|
|
9
|
+
// Shipped as the package's `gdp-wired-check` bin; built alone (interchange/build.ts) as one file, an executable and a
|
|
10
|
+
// WebAssembly module. Node's modules are reached at run time (as core/cli.ts reaches them), so the library's build
|
|
11
|
+
// carries no Node types.
|
|
12
|
+
import { checkDocument, decidedBy, goalsOf } from "./check.js";
|
|
13
|
+
import { fromInterchange, toInterchange } from "./format.js";
|
|
14
|
+
const proc = globalThis.process;
|
|
15
|
+
const fs = proc.getBuiltinModule('node:fs');
|
|
16
|
+
const args = proc.argv.slice(2), json = args.includes('--json'), gi = args.indexOf('--goals'), goalsOut = gi >= 0 ? args[gi + 1] : undefined;
|
|
17
|
+
const files = args.filter((a, i) => !a.startsWith('--') && (gi < 0 || i !== gi + 1));
|
|
18
|
+
if (!files.length || (gi >= 0 && !goalsOut)) {
|
|
19
|
+
proc.stderr.write('usage: gdp-wired-check [--json] [--goals <out.json>] <file.json>... (- reads standard input)\n');
|
|
20
|
+
proc.exit(2);
|
|
21
|
+
}
|
|
22
|
+
const read = (f) => JSON.parse(f === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(f, 'utf8'));
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const file of files) {
|
|
25
|
+
let report;
|
|
26
|
+
try {
|
|
27
|
+
report = checkDocument(read(file));
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
report = { accepted: false, claims: [], malformed: `not JSON: ${e instanceof Error ? e.message : String(e)}` };
|
|
31
|
+
}
|
|
32
|
+
out.push({ file, report });
|
|
33
|
+
}
|
|
34
|
+
if (goalsOut)
|
|
35
|
+
fs.writeFileSync(goalsOut, JSON.stringify(toInterchange(goalsOf(fromInterchange(read(files[0]))))));
|
|
36
|
+
const say = (s) => proc.stdout.write(`${s}\n`);
|
|
37
|
+
if (json)
|
|
38
|
+
say(JSON.stringify(out.length === 1 ? out[0].report : out));
|
|
39
|
+
else
|
|
40
|
+
for (const { file, report } of out) {
|
|
41
|
+
say(`${file}: ${report.accepted ? 'accepted' : 'refused'}${report.kind ? ` (${report.kind}, by ${decidedBy[report.kind] ?? 'the kernel'})` : ''}${report.malformed ? `: ${report.malformed}` : ''}`);
|
|
42
|
+
for (const c of report.claims)
|
|
43
|
+
say(` ${c.accepted ? 'accepted' : 'refused '} ${c.name}${c.why ? `: ${c.why}` : ''}`);
|
|
44
|
+
}
|
|
45
|
+
proc.exit(out.every(o => o.report.accepted) ? 0 : 1);
|
|
@@ -2,7 +2,7 @@ import type { C, E, Law, Machine } from '../core/machine.js';
|
|
|
2
2
|
import type { Fold, Goal, Instances, KInduction, Liveness, Loop, QC, QE, QGoal, QLaw, QMachine, Recur, StepLaw, Tree } from '../kernel/kernel.js';
|
|
3
3
|
import type { Cyclic } from '../kernel/cyclic.js';
|
|
4
4
|
import type { Lin } from '../core/solver.js';
|
|
5
|
-
export declare const FORMAT = "gdp-wired-interchange", VERSION = "1.
|
|
5
|
+
export declare const FORMAT = "gdp-wired-interchange", VERSION = "1.1", VERSIONS: string[];
|
|
6
6
|
export type LawsProof = {
|
|
7
7
|
instances: Record<string, Instances>;
|
|
8
8
|
trees: Record<string, Tree>;
|