gdp-wired 0.42.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 +14 -3
- package/dist/core/cli.d.ts +8 -1
- package/dist/core/cli.js +271 -30
- package/dist/core/counts.d.ts +8 -1
- package/dist/core/counts.js +171 -302
- package/dist/core/data.js +2 -2
- package/dist/core/dsl.js +26 -30
- package/dist/core/effect-prims.d.ts +60 -0
- package/dist/core/effect-prims.js +625 -0
- package/dist/core/effect-schedule.d.ts +103 -0
- package/dist/core/effect-schedule.js +817 -0
- package/dist/core/effect.d.ts +36 -1
- package/dist/core/effect.js +656 -29
- package/dist/core/ex/harness.exs +2 -0
- package/dist/core/exists.d.ts +5 -0
- package/dist/core/exists.js +98 -34
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +5 -3
- package/dist/core/extract-check.d.ts +2 -0
- package/dist/core/extract-check.js +45 -4
- 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-print.js +9 -2
- package/dist/core/extract-py.js +2 -2
- package/dist/core/extract-rb.js +2 -2
- package/dist/core/extract-read.js +2 -1
- package/dist/core/extract-rs.js +12 -7
- package/dist/core/extract-sol.js +4 -4
- package/dist/core/extract-step.d.ts +18 -0
- package/dist/core/extract-step.js +135 -31
- package/dist/core/extract-swift.js +3 -3
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/extract.js +13 -1
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +10 -7
- 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/laws.d.ts +4 -0
- package/dist/core/laws.js +176 -9
- package/dist/core/machine.d.ts +3 -0
- package/dist/core/machine.js +17 -3
- package/dist/core/py/harness.py +64 -19
- package/dist/core/py/reader.py +51 -1
- package/dist/core/sol/Replay.sol +52 -0
- package/dist/core/sol/harness.py +508 -0
- package/dist/core/system.d.ts +44 -0
- package/dist/core/system.js +435 -0
- 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/kernel.js +3 -2
- package/dist/kernel/prove.d.ts +1 -0
- package/dist/kernel/prove.js +69 -8
- package/dist/kernel/reader.js +3 -2
- package/dist/lean-kernel/emit.js +3 -3
- package/dist/lean-kernel/lean-terms.d.ts +1 -0
- package/dist/lean-kernel/lean-terms.js +8 -4
- package/package.json +12 -3
package/dist/core/py/reader.py
CHANGED
|
@@ -10,6 +10,9 @@ import ast, builtins, json, os, sys
|
|
|
10
10
|
BUILTINS = {'min', 'max', 'abs', 'len', 'int', 'float', 'bool', 'str', 'isinstance', 'round', 'sum', 'any', 'all', 'print', 'repr', 'getattr', 'setattr', 'hasattr', 'type', 'list', 'dict', 'set', 'tuple', 'sorted', 'range', 'zip', 'enumerate'}
|
|
11
11
|
# Library functions the executor knows (their meaning, not their code).
|
|
12
12
|
KNOWN = {'time.time', 'time.monotonic', 'time.perf_counter', 'datetime.datetime.now', 'datetime.timedelta', 'math.floor', 'math.ceil', 'math.isfinite', 'math.isnan', 'math.isinf', 'threading.Lock', 'threading.RLock', 'asyncio.Lock'}
|
|
13
|
+
# The heads of a subscripted type an alias may stand for (`Mode = Literal[...]`).
|
|
14
|
+
TYPE_HEADS = {'Literal', 'Optional', 'Union', 'Final', 'Annotated', 'dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict', 'list', 'List', 'Sequence',
|
|
15
|
+
'set', 'Set', 'frozenset', 'FrozenSet', 'AbstractSet', 'MutableSet'}
|
|
13
16
|
TRANSPARENT = {'staticmethod', 'classmethod', 'property', 'dataclass', 'dataclasses.dataclass', 'override', 'typing.override', 'abstractmethod'}
|
|
14
17
|
|
|
15
18
|
def where(file, n):
|
|
@@ -85,6 +88,7 @@ class Module:
|
|
|
85
88
|
targets = n.targets if isinstance(n, ast.Assign) else [n.target]
|
|
86
89
|
for t in targets:
|
|
87
90
|
if isinstance(t, ast.Name) and n.value is not None: self.consts[t.id] = n.value
|
|
91
|
+
elif type(n).__name__ == 'TypeAlias' and isinstance(n.name, ast.Name): self.consts[n.name.id] = n.value # `type X = ...` (3.12)
|
|
88
92
|
elif isinstance(n, ast.If):
|
|
89
93
|
# `if TYPE_CHECKING:` imports and aliases: what the names are for the types (its else, `X = Any`, yields to it).
|
|
90
94
|
for m in n.orelse + n.body: self.scan(m)
|
|
@@ -234,16 +238,21 @@ class Reader:
|
|
|
234
238
|
if head in ('dict', 'Dict', 'Mapping', 'MutableMapping', 'defaultdict', 'OrderedDict') and len(args) == 2:
|
|
235
239
|
return {'k': 'map', 'key': self.ty(args[0], mod), 'val': self.ty(args[1], mod), 'py': head}
|
|
236
240
|
if head in ('list', 'List', 'Sequence'): return {'k': 'list', 'of': self.ty(args[0], mod)}
|
|
241
|
+
# (a set: a map of its keys alone, each held or not)
|
|
242
|
+
if head in ('set', 'Set', 'frozenset', 'FrozenSet', 'AbstractSet', 'MutableSet') and len(args) == 1: return {'k': 'map', 'key': self.ty(args[0], mod), 'val': {'k': 'none'}, 'set': True, 'py': head}
|
|
237
243
|
return {'k': 'opaque', 'why': f"{text(a)}"}
|
|
238
244
|
n = dotted(a)
|
|
239
245
|
if n in ('int',): return {'k': 'int'}
|
|
240
246
|
if n in ('float',): return {'k': 'float'}
|
|
241
247
|
if n in ('bool',): return {'k': 'bool'}
|
|
242
248
|
if n in ('str',): return {'k': 'str'}
|
|
249
|
+
if n in ('bytes', 'bytearray'): return {'k': 'str', 'bytes': True} # (a string of bytes: set and compared, never equal to a str)
|
|
243
250
|
if n in ('None',): return {'k': 'none'}
|
|
244
251
|
if n in ('Final', 'Any', 'typing.Any', 'object'): return {'k': 'any'}
|
|
245
252
|
if n in ('dict', 'Dict'): return {'k': 'opaque', 'why': f"{n} with no key and value types"}
|
|
246
253
|
if n in ('threading.Lock', 'asyncio.Lock', 'Lock'): return {'k': 'lock'}
|
|
254
|
+
al = self.alias_of(mod, n) if n and '.' not in n else None
|
|
255
|
+
if al: return self.ty(al[1], al[0])
|
|
247
256
|
if n:
|
|
248
257
|
hit = self.find_class(mod, n.split('.')[-1]) if '.' not in n or n.split('.')[0] in mod.imports else None
|
|
249
258
|
if hit:
|
|
@@ -251,6 +260,37 @@ class Reader:
|
|
|
251
260
|
if q: return {'k': 'rec', 'name': q}
|
|
252
261
|
return {'k': 'opaque', 'why': f"{n}, a type outside the files read"}
|
|
253
262
|
return {'k': 'opaque', 'why': text(a)}
|
|
263
|
+
def const_value(self, mod, v):
|
|
264
|
+
"""A constant's value, through constants bound to other constants' names (LONG = IDLE)."""
|
|
265
|
+
for _ in range(6):
|
|
266
|
+
if isinstance(v, ast.Name) and v.id in mod.consts and v.id not in mod.classes and v.id not in mod.funcs: v = mod.consts[v.id]
|
|
267
|
+
else: break
|
|
268
|
+
return v
|
|
269
|
+
def module_const(self, mod, x):
|
|
270
|
+
"""`m.NAME` where m is a module of the repository (imported whole, or `from pkg import m`) and NAME one of its
|
|
271
|
+
constants bound to a literal (a number, a string, a bool, None): that literal, else None."""
|
|
272
|
+
if not isinstance(x.value, ast.Name): return None
|
|
273
|
+
imp = mod.imports[x.value.id]
|
|
274
|
+
q = imp[1] if imp[0] == 'module' else f"{imp[1]}.{imp[2]}"
|
|
275
|
+
path = self.repo.path_of(q)
|
|
276
|
+
if not path or path == mod.path: return None
|
|
277
|
+
sub = Module(self.repo, path)
|
|
278
|
+
v = self.const_value(sub, sub.consts.get(x.attr))
|
|
279
|
+
lit = isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.op, ast.USub) and isinstance(v.operand, ast.Constant))
|
|
280
|
+
return self.expr(v, mod) if lit and not isinstance(getattr(v, 'value', getattr(getattr(v, 'operand', None), 'value', None)), bytes) else None
|
|
281
|
+
def alias_of(self, mod, name, depth=0):
|
|
282
|
+
"""A type alias a module names, through its imports: `Mode = Literal["a", "b"]`, `Key = int | str`, `X: TypeAlias = ...`,
|
|
283
|
+
`type X = ...`: (module, the type it stands for), or None (a class, or a constant that is no type)."""
|
|
284
|
+
if depth > 6 or mod is None or name in mod.classes: return None
|
|
285
|
+
v = mod.consts.get(name)
|
|
286
|
+
if v is not None:
|
|
287
|
+
typing = isinstance(v, ast.Subscript) and (dotted(v.value) or '').split('.')[-1] in TYPE_HEADS
|
|
288
|
+
return (mod, v) if typing or (isinstance(v, ast.BinOp) and isinstance(v.op, ast.BitOr)) else None
|
|
289
|
+
imp = mod.imports.get(name)
|
|
290
|
+
if imp and imp[0] == 'name':
|
|
291
|
+
p = self.repo.path_of(imp[1])
|
|
292
|
+
if p and p != mod.path: return self.alias_of(Module(self.repo, p), imp[2], depth + 1)
|
|
293
|
+
return None
|
|
254
294
|
def union(self, ts, a):
|
|
255
295
|
none = any(t['k'] == 'none' for t in ts)
|
|
256
296
|
rest = [t for t in ts if t['k'] != 'none']
|
|
@@ -433,6 +473,10 @@ class Reader:
|
|
|
433
473
|
return {'e': 'ext', 'q': f"{imp[1]}.{imp[2]}", 'text': n, 'patch': {'mod': mod.name, 'path': [n]}, 'p': p, **({'ret': ret} if ret else {})}
|
|
434
474
|
if n in mod.consts:
|
|
435
475
|
v = mod.consts[n]
|
|
476
|
+
# (a constant bound to another constant's name, LONG = IDLE: that one's value, a few deep)
|
|
477
|
+
for _ in range(6):
|
|
478
|
+
if isinstance(v, ast.Name) and v.id in mod.consts and v.id != n and v.id not in mod.classes and v.id not in mod.funcs: v = mod.consts[v.id]
|
|
479
|
+
else: break
|
|
436
480
|
if isinstance(v, ast.Constant) or (isinstance(v, ast.UnaryOp) and isinstance(v.operand, ast.Constant)): return self.expr(v, mod)
|
|
437
481
|
cm = self.const_map(v, mod, p)
|
|
438
482
|
if cm: return cm
|
|
@@ -464,6 +508,10 @@ class Reader:
|
|
|
464
508
|
if isinstance(x, ast.Attribute):
|
|
465
509
|
d = dotted(x)
|
|
466
510
|
base = d.split('.')[0] if d else None
|
|
511
|
+
# (a literal constant of another module of the repository, `boat.BRING_UP`: its value, as the module's own
|
|
512
|
+
# constants are read; what the module is set to at import, the check importing it as it ships)
|
|
513
|
+
lit = self.module_const(mod, x) if d and base in mod.imports and not (self.local_stack and base in self.local_stack[-1]) else None
|
|
514
|
+
if lit is not None: return {**lit, 'p': p}
|
|
467
515
|
if d and base in mod.imports and mod.imports[base][0] == 'module' and not (self.local_stack and base in self.local_stack[-1]):
|
|
468
516
|
q = mod.imports[base][1] + d[len(base):]
|
|
469
517
|
if q in KNOWN: return {'e': 'lib', 'q': q, 'p': p}
|
|
@@ -543,7 +591,9 @@ def main():
|
|
|
543
591
|
mod = r.mod
|
|
544
592
|
if mod.tree is None:
|
|
545
593
|
print(json.dumps({'error': f"{req['file']} doesn't parse"})); return
|
|
546
|
-
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': []
|
|
594
|
+
out = {'lang': 'python', 'file': os.path.basename(r.file), 'path': r.file, 'module': mod.name, 'root': os.path.abspath(req['root']), 'entries': [],
|
|
595
|
+
# (the module's constants bound to literals, as the code reads them: a law may name them too)
|
|
596
|
+
'consts': {k: v.value for k, v in ((k, r.const_value(mod, v)) for k, v in mod.consts.items()) if isinstance(v, ast.Constant) and isinstance(v.value, (int, float, str, bool)) and not (isinstance(v.value, float) and not v.value.is_integer())}}
|
|
547
597
|
for n in req['names'] or list(mod.classes):
|
|
548
598
|
if n in mod.classes: out['entries'].append({'k': 'class', 'rec': r.rec_of(mod, mod.classes[n])})
|
|
549
599
|
elif n in mod.funcs:
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
pragma solidity ^0.8.20;
|
|
3
|
+
|
|
4
|
+
// The re-entrant runs of core/extract-sol.ts replayed on the code: every address a run names is an Agent (its code set
|
|
5
|
+
// there), and one Director holds the run's script. A call of the script is made by its Agent; a call into an Agent (the
|
|
6
|
+
// contract sending it a value) runs the script's next calls from inside it, up to a return (the Agent's call returns, or
|
|
7
|
+
// reverts). The Director records whether each call of the script succeeded.
|
|
8
|
+
interface IDirector { function onCall() external returns (bool); }
|
|
9
|
+
|
|
10
|
+
contract Agent {
|
|
11
|
+
address constant DIRECTOR = address(uint160(0xD1EC70));
|
|
12
|
+
function act(address t, uint256 v, bytes calldata d) external returns (bool ok) {
|
|
13
|
+
require(msg.sender == DIRECTOR, "agent: the director only");
|
|
14
|
+
(ok, ) = t.call{value: v}(d);
|
|
15
|
+
}
|
|
16
|
+
receive() external payable { if (!IDirector(DIRECTOR).onCall()) revert("agent: the callee reverts"); }
|
|
17
|
+
fallback() external payable { if (!IDirector(DIRECTOR).onCall()) revert("agent: the callee reverts"); }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
contract Director {
|
|
21
|
+
uint8[] kinds;
|
|
22
|
+
address[] froms;
|
|
23
|
+
uint256[] values;
|
|
24
|
+
bool[] rets;
|
|
25
|
+
bytes[] datas;
|
|
26
|
+
uint256 at;
|
|
27
|
+
address target;
|
|
28
|
+
bool[] public oks;
|
|
29
|
+
|
|
30
|
+
// One transaction of the run: its first call, and inside it every call and return the script holds.
|
|
31
|
+
function run(address t, uint8[] calldata k, address[] calldata f, uint256[] calldata v, bool[] calldata r, bytes[] calldata d) external {
|
|
32
|
+
target = t; kinds = k; froms = f; values = v; rets = r; at = 0;
|
|
33
|
+
delete datas;
|
|
34
|
+
delete oks;
|
|
35
|
+
for (uint256 i; i < d.length; i++) datas.push(d[i]);
|
|
36
|
+
step();
|
|
37
|
+
require(at == kinds.length, "director: the script is left over");
|
|
38
|
+
}
|
|
39
|
+
function step() internal {
|
|
40
|
+
uint256 i = at++;
|
|
41
|
+
require(kinds[i] == 0, "director: a return outside a call");
|
|
42
|
+
oks.push(Agent(payable(froms[i])).act(target, values[i], datas[i]));
|
|
43
|
+
}
|
|
44
|
+
function onCall() external returns (bool) {
|
|
45
|
+
while (at < kinds.length) {
|
|
46
|
+
if (kinds[at] == 1) return rets[at++];
|
|
47
|
+
step();
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
function count() external view returns (uint256) { return oks.length; }
|
|
52
|
+
}
|
|
@@ -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()
|