-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgarbled-circuit.html
More file actions
344 lines (327 loc) · 12.1 KB
/
Copy pathgarbled-circuit.html
File metadata and controls
344 lines (327 loc) · 12.1 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
<html>
<body>
<style>
body {
background-color: black;
color: white;
}
.container {
font-family: 'Courier New', Courier, monospace;
font-size: 20px;
position: relative; /* for its "absolute" child */
white-space: pre; /* mind the spaces in the html */
}
.overlay {
z-index: 1;
position: absolute;
top: 0px;
left: 0px;
}
.btn {
height: 1lh;
position: absolute;
background-color: #404040;
cursor: pointer;
transition: background-color 0.1s ease;
}
.btn:active {
background-color: black;
}
.txt {
height: 1lh;
position: absolute;
}
.hide {
display: none;
}
.blinking-border {
animation: blink-border 1.2s steps(1, end) forwards;
z-index: 2;
}
@keyframes blink-border {
0%, 40%, 80% { outline: 2px solid white; }
20%, 60%, 100% { outline: none; }
}
.protoTxt {
background: rgba(0, 0, 0, 0.3); /* for the overlapping parts */
}
</style>
<!-- mind the spaces -->
<div class="container"><div class="board" id="board">
#message #PTR
┌────────────────────┐
│ │
!L00!L01│ AND │
!S0#0_──┤ │
│ @0@1 #DSP00 │!L20!L21
│ #DSP01 @2_├───┐
!L10!L11│ #DSP02 │ │ ┌────────────────────┐
@S1@v1@1_──┤ #DSP03 │ │ │ │
@OT1 │ @ROW0 @E0 │ └──┤ XOR │ #L60 0
│ │ │ │ #L61 1
└────────────────────┘ │ @2@5 #DSP20 │
│ #DSP21 @6_├── @6 @FIN
┌────────────────────┐ │ #DSP22 │
│ │ │ #DSP23 │
!L30!L31│ OR │ ┌──┤ @ROW2 @E2 │
!S3#3_──┤ │ │ │ │
│ @3@4 #DSP10 │ │ └────────────────────┘
│ #DSP11 @5_├───┘
!L40!L41│ #DSP12 │!L50!L51 !GL
@S4@v4@4_──┤ #DSP13 │ !GT
@OT4 │ @ROW1 @E1 │ !RT
│ │ !ET
└────────────────────┘ !SI
!SEND
</div>
<div class="overlay">
<div class="btn protoBtn" style="top: -1000lh; left: -1000ch">B</div>
<div class="txt protoTxt" style="top: -1000lh; left: -1001ch">T</div>
</div>
</div>
<script>
function parseBoard(s) {
var locations = {};
var symbols = {};
var row = 0;
var col = 0;
var regex = /(.*?)([!@#])(\w+)/gs;
var replaced = s.replace(regex, (all, before, symbol, name) => {
var lines = before.split("\n");
if (lines.length == 1) {
col += lines[0].length;
} else {
row += lines.length - 1;
col = lines.pop().length;
}
locations[name] = [row, col];
symbols[name] = symbol;
col += 1 + name.length;
return before + " ".repeat(1 + name.length);
});
return [replaced, locations, symbols];
}
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
function shuffle(arr) {
for (var i = arr.length - 1; i != 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
// it's more "authentic" to remove the pointer bits in encryption
function noPTR(s) {
return [...s].filter(c => !pointers.includes(c)).join('');
}
function encrypt(inLabel0, inLabel1, outLabel) {
return `E,${noPTR(inLabel0)},${noPTR(inLabel1)},${outLabel}`;
}
function decrypt(inLabel0, inLabel1, ciphertext) {
var prefix = `E,${noPTR(inLabel0)},${noPTR(inLabel1)},`;
return ciphertext.startsWith(prefix) ? ciphertext.replace(prefix, "") : "";
}
var pointers = ['🔴', '🔵'];
function generateWireLabels() {
labels = [
[ '🐱', '🐶' ],
[ '🐭', '🐰' ],
[ '🐮', '🐴' ],
[ '🐷', '🐏' ],
[ '🐻', '🐵' ],
[ '🦁', '🦊' ],
[ '🐪', '🦙' ],
].map(twoLabels => shuffle(twoLabels));
if (pointAndPermute) {
labels.forEach((twoLabels) => {
let p = shuffle(pointers.slice());
twoLabels[0] += p[0];
twoLabels[1] += p[1];
});
}
console.log("labels: ", labels);
}
var gates = [
["AND", 0, 1, 2, (a, b) => a & b],
["OR", 3, 4, 5, (a, b) => a | b],
["XOR", 2, 5, 6, (a, b) => a ^ b]
];
function generateTable(in0Labels, in1Labels, outLabels, fn) {
return [[0, 0], [0, 1], [1, 0], [1, 1]]
.map(([v1, v2]) => [in0Labels[v1], in1Labels[v2], outLabels[fn(v1, v2)]]);
}
function generateTabels() {
tables = gates.map(([name, in0, in1, out, fn]) => generateTable(labels[in0], labels[in1], labels[out], fn));
}
function sortTableRowsByPointers(t) {
var pointers = ([l0, l1, _]) => [...l0].slice(-1) + [...l1].slice(-1);
t.sort((rowA, rowB) => pointers(rowA).localeCompare(pointers(rowB)));
}
function reorderTables() {
tables.forEach(!pointAndPermute ? shuffle : sortTableRowsByPointers);
}
function generateCiphertexts() {
ciphertexts = tables.map(t => t.map(row => encrypt(...row)));
console.log("generateCiphertexts: ", ciphertexts);
}
function setMessage(s) {
message = s;
blink("message", "black", 80);
}
var wires = ['', '', '', '', '', '', ''];
var labels = wires.map(_ => ['', '']);
var tables;
var ciphertexts;
var updaters = [];
var rowOfGate = [0, 0, 0];
var message = "";
var [board, loc, symbols] = parseBoard(document.querySelector("#board").innerText);
document.querySelector("#board").innerText = board;
console.log("loc: ", loc);
console.log("symbols: ", symbols);
function setRow(node, row) { node.style.top = row + "lh"; }
function setCol(node, col) { node.style.left = col + "ch"; }
function createNode(protoNodeSeletor, name, captionFn) {
var protoNode = document.querySelector(protoNodeSeletor);
var node = protoNode.cloneNode(true);
//node.id = "id" + name; // for debugging only
node.setAttribute("data-name", name); // divs don't have "name" attribute but can use "data-name"
var symbolToClass = { "@": "evaluatorOnly", "!": "generatorOnly", "#": "both" };
node.classList.add(symbolToClass[symbols[name]]);
setRow(node, loc[name][0]);
setCol(node, loc[name][1]);
protoNode.parentNode.appendChild(node);
updaters.push(() => node.innerText = captionFn());
return node;
}
function Text(name, captionFn) {
return createNode(".protoTxt", name, captionFn);
}
function Button(name, captionFn, listener) {
var node = createNode(".protoBtn", name, captionFn);
node.onclick = () => { listener(); updateUI(); };
return node;
}
function updateUI() {
updaters.forEach((u) => u());
}
function byName(name) {
return document.querySelector(`[data-name="${name}"]`);
}
function blink(name, color, duration) {
var node = byName(name);
var origColor = node.style.color;
node.style.color = color;
setTimeout(() => node.style.color = origColor, duration);
}
Text("message", () => message);
for (let w = 0; w < wires.length; w++) { // wire labels and wires
for (let v = 0; v < 2; v++) {
Text("L" + w + v, () => labels[w][v]);
}
Text(`${w}`, () => wires[w]);
Text(`${w}_`, () => wires[w]);
}
gates.forEach(([name, in0, in1, out, fn], g) => {
Button(`ROW${g}`, () => "▼", () => { // row selectors
rowOfGate[g] = (rowOfGate[g] + 1) % 4;
setRow(byName(in0), loc["" + in0][0] + rowOfGate[g]);
setRow(byName(in1), loc["" + in1][0] + rowOfGate[g]);
});
Button("E" + g, () => "►", () => { // eval
let r = rowOfGate[g];
if (plaintext = decrypt(wires[in0], wires[in1], ciphertexts[g][r])) {
wires[out] = plaintext;
setMessage(`Decrypted! ${wires[in0]} ${name} ${wires[in1]} = ${wires[out]}`);
display[g][r] = "";
} else {
setMessage("Decryption error: Invalid key.");
shakeString(() => display[g][r], (v) => display[g][r] = v);
}
});
});
function shakeString(getter, setter) { // hacky, expensive
var count = 4;
var h = () => {
setter(count % 2 == 0 ? " " + getter() : getter().substring(1));
if (--count != 0) setTimeout(h, 80);
updateUI();
};
setTimeout(h, 80);
}
function forEachDisplayIndex(fn) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 4; j++) {
fn(i, j);
}
}
}
function setDisplay(fn) { forEachDisplayIndex((i, j) => display[i][j] = fn(i, j)) }
var display = [['','','',''], ['','','',''], ['','','','']];
forEachDisplayIndex((i, j) => Text("DSP" + i + j, () => display[i][j]));
var inputValues = [0, 0, , 0, 0, , ]; // Generator wires: 0, 3 Evaluator wires: 1, 4
[1, 4].forEach(w => {
Button(`S${w}`, () => "▼", () => inputValues[w] = 1 - inputValues[w]);
Text(`v${w}`, () => inputValues[w]);
Button(`OT${w}`, () => "►", () => {
wires[w] = labels[w][inputValues[w]];
setMessage(`Label of ${inputValues[w]} => ${wires[w]} (OT)`);
byName(`S${w}`).classList.add("hide");
byName(`OT${w}`).classList.add("hide");
});
});
function displayTable() { setDisplay((i, j) => tables[i][j].join('')); }
Button("GL", () => "Generate Wire Labels", () => generateWireLabels());
Button("GT", () => "Generate Tables", () => {
generateTabels();
displayTable();
});
Button("RT", () => "Reorder Tables", () => {
reorderTables();
displayTable();
});
Button("ET", () => "Encrypt Tables", () => {
generateCiphertexts();
setDisplay((i, j) => "🔒🔒🧳");
})
Button("S0", () => "▼", () => { wires[0] = labels[0][inputValues[0]]; inputValues[0] = 1 - inputValues[0]; });
Button("S3", () => "▼", () => { wires[3] = labels[3][inputValues[3]]; inputValues[3] = 1 - inputValues[3]; });
Text("SI", () => "Select Inputs with ▼");
Button("SEND", () => "Send to the Evaluator", () => {
if (wires[0] == '' || wires[3] == '') {
setMessage("select both inputs for the generator");
if (wires[0] == '') blink("S0", "black", 80);
if (wires[3] == '') blink("S3", "black", 80);
return;
}
setMessage("Garbled Circuit (Evaluator)");
document.querySelectorAll(".generatorOnly").forEach(n => n.classList.add("hide"));
document.querySelectorAll(".evaluatorOnly").forEach(n => n.classList.remove("hide"));
byName("S1").classList.add("blinking-border");
});
Text("FIN", () => wires[6] == '' ? '' : '🎉🎉🎉');
Text("PTR", () => !pointAndPermute ? '' :
pointers[0] + pointers[0] + "\n" + pointers[0] + pointers[1] + "\n"
+ pointers[1] + pointers[0] + "\n" + pointers[1] + pointers[1]);
// ?startFrom=evaluator&w0=1&w3=0&pointAndPermute=1
var params = new URLSearchParams(document.location.search);
var pointAndPermute = params.get("pointAndPermute") == 1;
if (params.get("startFrom") != "evaluator") {
setMessage("Garbled Circuit (Generator)");
document.querySelectorAll(".evaluatorOnly").forEach(n => n.classList.add("hide"));
byName("GL").classList.add("blinking-border");
} else {
setMessage("Garbled Circuit (Evaluator)");
document.querySelectorAll(".generatorOnly").forEach(n => n.classList.add("hide"));
generateWireLabels();
generateTabels();
reorderTables();
generateCiphertexts();
setDisplay((i, j) => "🔒🔒🧳");
wires[0] = labels[0][params.get("w0") || 0]; // default input for the generator
wires[3] = labels[3][params.get("w3") || 0]; // default input for the generator
byName("S1").classList.add("blinking-border");
}
updateUI();
</script>
</body>
</html>