File size: 8,147 Bytes
8234d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16b63e4
 
 
 
 
8234d96
16b63e4
8234d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// ===========================================================================
//  Grader Web Worker — runs its OWN Pyodide, holds the hidden answer key.
//
//  The oracle / bug definitions / reasons live in THIS worker's Python
//  interpreter, in a separate thread with separate memory. The student's code
//  runs in the main-thread Pyodide and cannot reach into here: gc.get_objects(),
//  closure reflection and print(globals()) only see the student's own interpreter.
//
//  The worker receives {problem, source, tests(JSON)} and returns a JSON report.
//  Student code never executes here — only their TESTS *data* crosses the boundary.
// ===========================================================================
const PYODIDE_INDEX = "https://cdn.jsdelivr.net/pyodide/v0.26.2/full/";
importScripts(PYODIDE_INDEX + "pyodide.js");

const PROBLEMS = {
  Q1: { data: "q1.dat", public: "allocate" },
  Q2: { data: "q2.dat", public: "approve" },
};

// ----- Decryption (must match build_blackbox.py / PASSPHRASE) -----
const PASSPHRASE = "t2-unsw-bbt-v1-rotate-me";
let __keyBytes = null;
async function _sha256(bytes) {
  return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
}
async function decryptDat(b64) {
  if (!__keyBytes) __keyBytes = await _sha256(new TextEncoder().encode(PASSPHRASE));
  const cipher = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
  const out = new Uint8Array(cipher.length);
  const blk = new Uint8Array(__keyBytes.length + 8);
  blk.set(__keyBytes, 0);
  const dv = new DataView(blk.buffer);
  let counter = -1, ks = null;
  for (let off = 0; off < cipher.length; off++) {
    const c = Math.floor(off / 32);
    if (c !== counter) { counter = c; dv.setBigUint64(__keyBytes.length, BigInt(c), false); ks = await _sha256(blk); }
    out[off] = cipher[off] ^ ks[off % 32];
  }
  return new TextDecoder("utf-8").decode(out);
}

// ----- The grading harness (closure-isolated; identical to the verified one) -----
const HARNESS_FACTORY = `
def __bb_make():
    import sys, types, linecache, ast, json, inspect

    _og = inspect.getsource
    def _guard(obj, *a, **k):
        if getattr(obj, "__module__", None) in (None, "blackbox", "blackbox_impl"):
            raise OSError("source code is not available")
        return _og(obj, *a, **k)
    inspect.getsource = _guard
    inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))

    state = {}

    def install(public_name, source):
        ns = {}
        exec(compile(source, "blackbox_impl", "exec"), ns)
        combined = ns["blackbox"]
        ref = ns["reference"]
        bugs = ns["BUGS"]
        reasons = ns.get("REASONS", {})
        for k in ("reference", "BUGS", "REASONS", "_b1", "_b2", "_b3", "_b4", "_b5"):
            ns.pop(k, None)
        linecache.cache.clear()
        def _public(*a, **k):
            return combined(*a, **k)
        _public.__name__ = public_name
        sys.modules.pop("blackbox", None)
        pub = types.ModuleType("blackbox")
        setattr(pub, public_name, _public)
        sys.modules["blackbox"] = pub
        state.clear()
        state.update(fn=combined, ref=ref, bugs=bugs, reasons=reasons)

    def _s(v):
        return v if isinstance(v, str) else repr(v)

    def run(source, tests):
        fn = state["fn"]; ref = state["ref"]; BUGS = state["bugs"]; REASONS = state["reasons"]
        order = list(BUGS)
        linenos = {}
        try:
            tree = ast.parse(source)
            for node in ast.walk(tree):
                if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "TESTS" for t in node.targets):
                    if isinstance(node.value, (ast.List, ast.Tuple)):
                        for i, el in enumerate(node.value.elts):
                            linenos[i] = el.lineno
        except Exception:
            pass
        if not isinstance(tests, (list, tuple)):
            return json.dumps({"ok": False, "error": "Define a list named TESTS = [ ((args), expected), ... ] -- one case per line."})
        caught = {}
        rows = []
        for i, case in enumerate(tests):
            line = linenos.get(i)
            try:
                args, expected = case
                args = tuple(args)
            except Exception:
                rows.append({"line": line, "status": "malformed", "raw": repr(case)})
                continue
            try:
                actual = fn(*args)
            except Exception as e:
                rows.append({"line": line, "status": "error", "argstr": repr(args), "msg": str(e)})
                continue
            spec = ref(*args)
            bug = None
            for name in BUGS:
                try:
                    if BUGS[name][0](*args) != spec:
                        bug = name; break
                except Exception:
                    pass
            argstr = repr(args)
            valid_expected = (expected == spec)
            if actual != expected:
                if not valid_expected:
                    rows.append({"line": line, "status": "invalid", "argstr": argstr,
                                 "expected": _s(expected), "actual": _s(actual)})
                elif bug is None:
                    # Real discrepancy, but it can't be attributed to ONE of the 5
                    # bugs (e.g. several boundaries broken at once). Don't count it.
                    rows.append({"line": line, "status": "combo", "argstr": argstr,
                                 "actual": _s(actual), "expected": _s(expected)})
                else:
                    num = order.index(bug) + 1
                    first = bug not in caught
                    if first:
                        caught[bug] = line
                    rows.append({"line": line, "status": "bug" if first else "dup",
                                 "bug": bug, "num": num, "total": len(BUGS),
                                 "reason": REASONS.get(bug, "output differs from the spec"),
                                 "argstr": argstr, "actual": _s(actual), "expected": _s(expected)})
            else:
                if not valid_expected:
                    rows.append({"line": line, "status": "invalid", "argstr": argstr,
                                 "expected": _s(expected), "actual": _s(actual)})
                else:
                    rows.append({"line": line, "status": "ok", "argstr": argstr, "actual": _s(actual)})
        return json.dumps({"ok": True, "rows": rows, "caught": list(caught.keys()),
                           "caughtCount": len(caught), "totalBugs": len(BUGS), "numTests": len(tests)})

    class _H:
        pass
    h = _H()
    h.install = install
    h.run = run
    return h

__bb_make()
`;

let pyodide, harness, bbInstall, bbRun, installed = null;

async function init() {
  pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX });
  harness = pyodide.runPython(HARNESS_FACTORY);
  pyodide.runPython("del __bb_make");
  bbInstall = harness.install;
  bbRun = harness.run;
  postMessage({ type: "ready" });
}
const ready = init().catch((e) => postMessage({ type: "fatal", error: String(e) }));

async function ensureProblem(key) {
  if (installed === key) return;
  const b64 = (await (await fetch(PROBLEMS[key].data, { cache: "no-store" })).text()).trim();
  const src = await decryptDat(b64);
  if (!src.includes("def blackbox") || !src.includes("def reference")) {
    throw new Error("Could not decrypt " + PROBLEMS[key].data);
  }
  bbInstall(PROBLEMS[key].public, src);
  installed = key;
}

onmessage = async (e) => {
  const { id, problem, source, tests } = e.data;
  try {
    await ready;
    await ensureProblem(problem);
    pyodide.globals.set("__tests_json", tests);
    const testsPy = pyodide.runPython("import json\njson.loads(__tests_json)");
    const report = bbRun(source, testsPy);
    if (testsPy && typeof testsPy.destroy === "function") testsPy.destroy();
    pyodide.runPython("del __tests_json");
    postMessage({ id, ok: true, report });
  } catch (err) {
    postMessage({ id, ok: false, error: String((err && err.message) || err) });
  }
};