-
Notifications
You must be signed in to change notification settings - Fork 1
/
take-survey.html
634 lines (529 loc) · 27.1 KB
/
take-survey.html
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/x-icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords"
content="PORPOISE, Proof of Reputation, Protocol, zero knowledge proof, zkSNARK, crypto, Mina Protocol, Protokit, surveys, predictions">
<meta name="description" content="Take a PORPOISE Survey">
<title>PORPOISE Network</title>
<link rel="stylesheet" href="/take-survey.css">
<script src="./utilities.js"></script>
<script>
// global variables for a given user's survey
let prediction = "";
let predictionSalt = 0;
let surveyLeafs = [];
let paddedSurveyLeafs;
let surveyRoot;
let deadlineTimestamp;
let keyID = "";
let username = "";
let publicKeySting = "";
let surveyIsExpired = false;
const urlPrefix = 'https://zkporpoise.replit.app';
const urlEncodedDolphin = '%F0%9F%90%AC';
const urlEncodedAlarmClock = '%E2%8F%B0';
const urlEncodedCrystalBall = '%F0%9F%94%AE';
const urlEncodedBallotBox = '%F0%9F%97%B3';
const urlEncodedDoor = '%F0%9F%9A%AA';
const urlEncodedSalt = '%F0%9F%A7%82';
const urlEncodedCheck = '%E2%9C%85';
const urlEncodedFountainPen = '%F0%9F%96%8B';
const urlEncodedDisguisedFace = '%F0%9F%A5%B8';
const urlEncodedPlunger = '%F0%9F%AA%A0';
const urlEncodedToilet = '%F0%9F%9A%BD';
const urlEncodedToiletPaper = '%F0%9F%A7%BB';
const urlEncodedKey = '%F0%9F%94%91';
loginMessage = "Login to PORPOISE";
// this function gets called once on page load
function getSurveyComponents() {
document.getElementById("loginContainer").style.display = "none";
retrievePublicKey();
// Get the search parameters from the URL
//const urlParams = new URLSearchParams(window.location.search);
const queryString = window.location.search;
const urlParams = parseQueryString(queryString.slice(1, queryString.size));
const numParams = Object.keys(urlParams).length;
console.log("URL Params: ", urlParams);
if (numParams >= 5) {
const numOptions = numParams - 3;
console.log("Number of options: ", numOptions);
// Retrieve the body, deadline, and oracle content
const dolphin = urlParams['🐬'];
const alarmclock = urlParams['⏰'];
const oracle = urlParams['🔮'];
console.log('🐬 Dolphin:', dolphin);
console.log('⏰ Deadline:', alarmclock);
console.log('🔮 Oracle: ', oracle);
// check if the required parameters where supplied
if (dolphin === null) {
document.getElementById('🐬').innerHTML = "Missing 🐬 in URL.";
return 0;
} else {
document.getElementById('🐬').innerHTML = '🐬 ' + dolphin.replace(/-/g, ' ');
surveyLeafs.push(dolphin);
}
if (alarmclock === null) {
document.getElementById('🐬').innerHTML = "Missing ⏰ in URL.";
return 0;
} else {
deadlineTimestamp = alarmclock;
updateCountdown();
surveyLeafs.push(mapBigIntTo256BitNumber(BigInt(alarmclock)));
}
if (oracle === null) {
document.getElementById('⏰').innerHTML = '';
document.getElementById('🐬').innerHTML = "Missing 🔮 in URL.";
return 0;
} else {
if (oracle === '0') {
//document.getElementById('🔮').innerHTML = '🔮: No oracle for this survey.';
} else {
//document.getElementById('🔮').innerHTML = '🔮: ' + oracle.slice(0, 6) + '...' + oracle.slice(-6);
}
surveyLeafs.push(oracle);
}
// loop over the options and store in an options array
const options = [];
for (let i = 1; i <= numOptions; i++) {
let option = urlParams['🗳' + i];
if (option !== undefined) {
options.push(option);
surveyLeafs.push(option);
}
}
// if there are not at least two options, then the survey is not valid
if (options.length < 2) {
document.getElementById('⏰').innerHTML = '';
//document.getElementById('🔮').innerHTML = '';
document.getElementById('🐬').innerHTML = "A PORPOISE survey must have at least 2 options (🗳1 & 🗳2)."
return 0;
} else {
padArrayToPowerOfTwo(surveyLeafs, '0').then((leafs) => {
console.log("Number of leafs: ", leafs.length);
paddedSurveyLeafs = leafs;
return computeMerkleRoot(leafs, [], 1);
})
.then((merkle) => {
surveyRoot = arrayBufferToHex(merkle[0]);
console.log("Merkle Root: ", surveyRoot);
setOptions(options);
});
}
} else {
const message = "Not enough emojis for a PORPOISE-compatible survey.";
document.getElementById('🐬').innerHTML = message;
console.log(message)
}
return 1;
}
// we need this function because there seem to be a lot of mobile browsers
// that don't like URLSearchParams
function parseQueryString(queryString) {
if (!queryString) {
return {};
}
// Split the query string into key-value pairs
const queryParams = queryString.split('&');
// Create an object to store the parsed parameters
const params = {};
// Iterate over each key-value pair and populate the object
queryParams.forEach(param => {
const [key, value] = param.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value);
});
return params;
}
function generatePrediction() {
if (surveyIsExpired) {
console.log("Survey is expired, changes can no longer be made.")
return 0;
}
if (keyID === "") {
console.log("You must log in with a passkey first");
document.getElementById("loginContainer").style.display = "block";
return 0;
}
if (prediction === undefined) {
document.getElementById("prediction").innerText = "You must make a prediction first!"
document.getElementById("inputContainer").style.display = "block";
return 0;
} else {
predictionSalt = (predictionSalt === 0) ? generateRandomString(18) : predictionSalt;
console.log("Prediction Salt: ", predictionSalt);
predictionCommitment(predictionSalt, prediction, stringToBuffer(surveyRoot, 'hex')).then((commitmentBuffer) => {
const commitment = arrayBufferToHex(commitmentBuffer);
setPredictionHTMLElements(commitment);
savePrediction(prediction, predictionSalt, commitment);
getPasskeySignature(commitment);
})
}
}
function setPredictionHTMLElements(commitment) {
postString = `I just made a prediction with 🐬#PORPOISENetwork!: ${commitment}\n\nMake your own prediction here:\n${window.location.href}`
let predictionElement = document.getElementById("prediction");
predictionElement.innerHTML = "Share with friends! "; // + commitment.slice(0, 5) + '... ';
predictionElement.title = "Post your prediction commitment somewhere public to build your reputation!";
let copyPredictionElement = document.createElement('button');
copyPredictionElement.setAttribute('class', 'button-28');
copyPredictionElement.setAttribute('id', 'prediction-commitment-📋');
copyPredictionElement.setAttribute('value', postString);
copyPredictionElement.setAttribute('onclick', 'copyCommitment()')
copyPredictionElement.innerText = '📋';
predictionElement.appendChild(copyPredictionElement);
//let saltElement = document.getElementById("salt");
//saltElement.innerText = "🧂: " + predictionSalt;//.slice(0, 13) + '... ';
//saltElement.title = "Kind of like a password that helps you reveal your prediction commitment later."
//let copySaltElement = document.createElement('button');
//copySaltElement.setAttribute('class', 'button-28');
//copySaltElement.setAttribute('id', 'prediction-🧂-📋');
//copySaltElement.setAttribute('value', predictionSalt);
//copySaltElement.setAttribute('onclick', 'copySalt()')
//copySaltElement.innerText = '📋';
//saltElement.appendChild(copySaltElement);
document.getElementById('save-prediction').innerText = '✅';
}
function copyCommitment() {
// Get the button element
const button = document.getElementById('prediction-commitment-📋');
// Create a temporary textarea
const textarea = document.createElement('textarea');
textarea.value = button.value; // Use textContent instead of value
// Append the textarea to the document
document.body.appendChild(textarea);
// Select the text in the textarea
textarea.select();
textarea.setSelectionRange(0, 99999); // For mobile devices
if (navigator.share) {
navigator.share({
title: document.getElementById('🐬').innerText,
text: button.value,
url: window.location.href // URL of the shared item
})
.then(() => {
console.log('Shared successfully');
})
.catch((error) => {
console.error('Error sharing:', error);
});
} else {
// Copy the selected text to the clipboard
document.execCommand('copy');
}
// Remove the temporary textarea
document.body.removeChild(textarea);
button.innerText = '✅';
}
function copySalt() {
// Get the button element
const button = document.getElementById('prediction-🧂-📋');
// Create a temporary textarea
const textarea = document.createElement('textarea');
textarea.value = button.value; // Use textContent instead of value
// Append the textarea to the document
document.body.appendChild(textarea);
// Select the text in the textarea
textarea.select();
textarea.setSelectionRange(0, 99999); // For mobile devices
// Copy the selected text to the clipboard
document.execCommand('copy');
// Remove the temporary textarea
document.body.removeChild(textarea);
button.innerText = '✅';
}
function savePrediction(prediction, predictionSalt, commitment) {
const predictionLink = window.location.href + '&' + urlEncodedDoor + '=' + commitment + '&' +
urlEncodedSalt + '=' + predictionSalt + '&' + urlEncodedCheck + '=' + prediction;
localStorage.setItem(surveyRoot, predictionLink);
const storedLink = localStorage.getItem(surveyRoot);
console.log("Prediction Link: ", storedLink);
}
function getSavedPrediction() {
console.log("Checking for an existing saved prediction.")
const predictionLink = localStorage.getItem(surveyRoot);
if (predictionLink != null) {
const urlParams = parseQueryString(predictionLink.replace(window.location.origin + window.location.pathname + "?", ""));
prediction = urlParams['✔'];
predictionSalt = urlParams['🧂'];
console.log("Stored Prediction: ", prediction);
console.log("Stored Salt: ", predictionSalt);
return urlParams;
} else {
return null;
}
}
function setOptions(optionsArray) {
let optionsContainer = document.getElementById('🗳')
// if we've already made a prediction before, load the prediction and salt value
const urlParams = getSavedPrediction();
for (let i = 0; i < optionsArray.length; i++) {
console.log("Option", i, ": ", optionsArray[i]);
let paragraphElement = document.createElement('p');
paragraphElement.innerText = '🗳' + (i + 1) + ". " + optionsArray[i].replace(/-/g, ' ');
let inputElement = document.createElement('input');
inputElement.setAttribute('type', 'radio');
inputElement.setAttribute('name', 'options');
inputElement.setAttribute('class', 'radio-buttons')
inputElement.setAttribute('value', optionsArray[i]);
inputElement.setAttribute('id', '🗳' + (i + 1) + 'input');
if (prediction === optionsArray[i]) {
inputElement.setAttribute('checked', true);
setPredictionHTMLElements(urlParams['🚪']);
}
paragraphElement.appendChild(inputElement);
optionsContainer.appendChild(paragraphElement);
}
const radioButtons = document.querySelectorAll('input[type="radio"]');
// Add event listener to each radio button
radioButtons.forEach(button => {
button.addEventListener('change', () => {
// Check which radio button is selected
if (button.checked && !surveyIsExpired) {
console.log('Selected option:', button.value);
prediction = button.value;
}
if (!document.getElementById("save-prediction").style.display) {
document.getElementById("save-prediction").style.display = "inline-block";
}
});
});
}
function convertUTCtoDate(utcTimestamp) {
// Create a new Date object with the UTC timestamp
// the UTC timestamp should be in miliseconds
const date = new Date(parseInt(utcTimestamp, 10));
// Get the individual components of the date and time
const year = date.getFullYear();
const month = date.getMonth() + 1; // Months are zero-indexed, so add 1
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log("User's timezone:", userTimezone);
const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${userTimezone}`;
return formattedDateTime;
}
function updateCountdown() {
const currentTime = new Date().getTime();
const timeDifference = deadlineTimestamp - currentTime;
if (timeDifference > 0) {
const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
// Display the countdown in the element
document.getElementById('⏰').innerHTML = '⏰: ' + `${days}d ${hours}h ${minutes}m ${seconds}s`;
// Update every second
setTimeout(updateCountdown, 1000);
} else {
// Display a message when the countdown reaches zero
document.getElementById('⏰').innerHTML = '⏰: 💀 Time is up!';
surveyIsExpired = true;
}
}
function generateRandomString(length) {
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let randomString = '';
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * charset.length);
randomString += charset[randomIndex];
}
return randomString;
}
function createAccount() {
// first clear out the other button options
const container = document.getElementById("loginContainer");
while (container.firstChild) {
container.removeChild(container.firstChild);
}
// then create a field for the user to choose a username
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Choose a Username');
input.setAttribute('id', 'username-input');
container.appendChild(input);
// finally create a submit button for saving the username
const button = document.createElement('button');
button.setAttribute('class', 'button-28');
button.setAttribute('onclick', 'createPasskey()');
button.innerText = '▶️';
container.appendChild(button);
}
function login() {
getPasskeySignature(loginMessage);
}
function createPasskey() {
username = document.getElementById("username-input").value;
const publicKey = {
challenge: new TextEncoder().encode(crypto.randomUUID()),
rp: {
id: window.location.host,
name: document.title,
},
timeout: 60_000,
user: {
id: new TextEncoder().encode(crypto.randomUUID()),
name: username,
displayName: username
},
pubKeyCredParams: [{ type: "public-key", alg: -7 }] // -7 denotes ECDSA
}
console.log("Creating Passkey with username: ", username);
navigator.credentials.create({ publicKey }).then((pubKeyCredential) => {
const {
id // the key id a.k.a. kid
} = pubKeyCredential;
const pubKey = pubKeyCredential.response.getPublicKey();
const registerLink = urlPrefix + '/register' + '?' +
urlEncodedDisguisedFace + '=' + username + '&' +
urlEncodedKey + '=' + arrayBufferToBase64UrlString(pubKey) + '&' +
urlEncodedToiletPaper + '=' + id;
// save the public key so we can use it for signature verification later
const base64UrlEncodedPublicKey = storePublicKey(id, pubKey, username);
return fetch(registerLink).then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok.")
} else {
// reload the page after creating and caching the passkey
location.reload();
}
}).catch((err) => {
// TODO: put some logic here to surface the error
console.log("ERROR Registering Passkey: ", err);
});
})
}
function storePublicKey(id, pubKeyArrayBuffer, username) {
const base64UrlString = arrayBufferToBase64UrlString(pubKeyArrayBuffer);
const userObject = {
keyID: id,
pubKey: base64UrlString,
username: username
}
// Store the Base64 string in localStorage
localStorage.setItem("userObject", JSON.stringify(userObject));
document.getElementById("username").innerText = document.getElementById("username").innerText.replace(/__/g, username).slice(0, 13);
return base64UrlString;
}
function arrayBufferToBase64String(myArrayBuffer) {
// Convert ArrayBuffer to Uint8Array
const uint8Array = new Uint8Array(myArrayBuffer);
// Convert Uint8Array to Base64 string
const base64String = btoa(String.fromCharCode.apply(null, uint8Array));
return base64String;
}
function arrayBufferToBase64UrlString(myArrayBuffer) {
const base64String = arrayBufferToBase64String(myArrayBuffer);
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
function retrievePublicKey() {
// Retrieve the Base64 string from localStorage
const userObject = JSON.parse(localStorage.getItem('userObject'));
if (!userObject) {
return null;
}
publicKeySting = userObject.pubKey;
keyID = userObject.keyID;
username = userObject.username;
document.getElementById("username").innerText = document.getElementById("username").innerText.replace(/__/g, username).slice(0, 13);;
}
function base64StringToArrayBuffer(base64String) {
// Convert Base64 string to Uint8Array
const uint8Array = new Uint8Array(atob(base64String).split('').map(char => char.charCodeAt(0)));
// Convert Uint8Array back to ArrayBuffer
const arrayBuffer = uint8Array.buffer;
return arrayBuffer;
}
function base64UrlStringToArrayBuffer(base64UrlString) {
base64String = base64UrlString.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((base64UrlString.length + 3) % 4);
return base64StringToArrayBuffer(base64String);
}
function getPasskeySignature(challengeString) {
console.log("Generating Passkey Signature")
const publicKey = {
challenge: new TextEncoder().encode(challengeString),
rpId: window.location.host,
timeout: 60_000,
};
navigator.credentials.get({
publicKey,
mediation: 'optional',
}).then((pubKeyCredential) => {
const { id } = pubKeyCredential;
keyID = id;
const { authenticatorData, clientDataJSON, signature, userHandle } = pubKeyCredential.response;
// relying party should verify all three of these values
const { type, challenge, origin } = JSON.parse(formatArrayBuf(clientDataJSON));
if (challengeString === loginMessage) {
const loginLink = urlPrefix + '/login' + '?' +
urlEncodedFountainPen + '=' + arrayBufferToBase64UrlString(signature) + '&' +
urlEncodedPlunger + '=' + arrayBufferToBase64UrlString(authenticatorData) + '&' +
urlEncodedToilet + '=' + arrayBufferToBase64UrlString(clientDataJSON) + '&' +
urlEncodedToiletPaper + '=' + keyID;
console.log("Login Link: ", loginLink);
return fetch(loginLink).then((response) => {
return response.json();
}).then((userData) => {
storePublicKey(userData.keyid, base64UrlStringToArrayBuffer(userData.base64urlencodedpublickey), userData.username);
location.reload();
})
} else {
const predictionLink = urlPrefix + '/predictAndVerify' + window.location.search + '&' +
urlEncodedSalt + '=' + predictionSalt + '&' + urlEncodedCheck + '=' + prediction + '&' +
urlEncodedFountainPen + '=' + arrayBufferToBase64UrlString(signature) + '&' + urlEncodedDisguisedFace + '=' + username + '&' +
urlEncodedPlunger + '=' + arrayBufferToBase64UrlString(authenticatorData) + '&' +
urlEncodedToilet + '=' + arrayBufferToBase64UrlString(clientDataJSON) + '&' +
urlEncodedToiletPaper + '=' + keyID;
console.log("Prediction Link:", predictionLink);
// otherwise we're making a prediction and we need to send the prediction off to be stored
// remember, the challenge String is the SHA256 hash of the concatenation of the salt + predictionHash + surveyRoot
return fetch(predictionLink).then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok.")
} else {
console.log("Prediction accepted.")
}
});
}
}).catch((err) => {
console.log("Prediction Submission Error: ", err);
})
}
function formatArrayBuf(buffer, encoding = 'utf-8') {
const decoder = new TextDecoder(encoding);
return decoder.decode(buffer);
}
</script>
</head>
<body onload="getSurveyComponents();">
<header>
<div id="username" title="Username">🥸:__</div>
<div id="menu" title="🐬 Home Menu"><a href="/">PORPOISE</a></div>
</header>
<div class="survey-container">
<h2 id="🐬"></h2>
<div id="loginContainer">
<p>You must login with a passkey first.</p>
<button class="button-28" type="submit" onclick="createAccount()">Create Key</button>
<button class="button-28" type="submit" onclick="login()">Login</button>
</div>
<fieldset id="🗳" class="options">
<legend>Make a Prediction:</legend>
</fieldset>
<p id="⏰" title="Remaining time for making predictions." class="timer"></p>
<div>
<button class="button-28" id="save-prediction" onclick="generatePrediction()"
title="Save your prediction to share later and post your commitment now.">💾</button>
<div>
<p id="prediction"></p>
</div>
</div>
</div>
<footer>
© 2024 PORPOISE Network.
</footer>
</body>
</html>