-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
842 lines (687 loc) · 29 KB
/
Copy pathscript.js
File metadata and controls
842 lines (687 loc) · 29 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
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//------------------------------------------ variable defining -------------------------------------------------------------
let blockchain = []; // Array to hold the blockchain
let blockchainUsr = [];
let peer = null;
let connections = []; // Array to hold all peer connections
let reservePool = []; // Array to hold votes in the reserve pool
let resultant_vote = [];
/*********************************************initialisation**************************************************************/
function initializePeer() {
peer = new Peer({
host: "localhost",
port: 3000,
path: "/peerjs",
});
peer.on("open", (id) => {
const peerIdElement = document.getElementById("peer-id");
if (peerIdElement) {
peerIdElement.textContent = "Your Peer ID: ${id}";
}
console.log("Your Peer ID:", id);
sessionStorage.setItem("authorityPeerId", id);
if (window.location.pathname.includes("authority")) {
const authorityPeerIdElement =
document.getElementById("authority-peer-id");
if (authorityPeerIdElement) {
authorityPeerIdElement.textContent = id;
}
} else {
fetch("/get-authority")
.then((response) => response.json())
.then((data) => {
const authorityIdElement = document.getElementById("authority-id");
if (data.authorityID && authorityIdElement) {
authorityIdElement.textContent = data.authorityID;
console.log(`authority id : ${data.authorityID}`);
}
});
}
});
peer.on("connection", (connection) => {
connections.push(connection);
console.log("Incoming peer connection:", connection.peer);
connection.send({ type: "authorityId", id: connection.peer });
broadcastBlockchain();
// handleConnection(connection);
connection.on("data", (data) => {
if (data.type === "vote") {
console.log("Vote received from user:", data.data);
resultant_vote.push(data.data);
reservePool.push(data.data);
let result_box = resultant_vote.length;
updateReservePoolDisplay();
updateVoteCount(data.data.candidate, result_box);
// Update vote count in result.html
// Here you can handle the received vote data as needed
if (reservePool.length >= 4) {
createBlockFromReservePool(); // Create a block if enough votes are present
}
}
if (data.type === "syncs_blockchain") {
console.log("Blockchain sync requested by:", connection.peer);
// Send the current blockchain data to the requesting peer
connection.send({
type: "blockchainUpdate",
blockchain: JSON.parse(JSON.stringify(blockchain)), // Send a copy of the blockchain
});
console.log(`Blockchain broadcasted to peer ${connection.peer}`);
}
});
});
}
/********************************************* functions ****************************************************************/
function getMerkleProof(voteHash, blockNumber) {
// Find the block in the blockchain array
console.log("ye blockno " + blockNumber);
const block = blockchainUsr.find((b) => b.header.blockNumber === blockNumber);
console.log("ye blockno " + block);
if (!block) {
console.log(`Block number ${blockNumber} not found.`);
return;
}
const merkleTree = block.data.merkleTree;
const hashes = block.data.votes;
// Check if the provided voteHash exists in the votes
if(hashes.length > 2){
if (!hashes.includes(voteHash)) {
console.log(`Vote hash ${voteHash} not found in block ${blockNumber}.`);
return;
}
// Initialize proof object
let proof = {
siblingHash: null,
uncleHash: null,
merkleRoot: block.header.merkleRoot,
};
// Find the index of the vote hash in the votes array
let index = hashes.indexOf(voteHash);
// Traverse the Merkle tree to find siblings and uncle hashes
let currentLevel = 2; // Start from the leaves level (3rd level in this case)
const currentLayer = merkleTree[currentLevel].hashes;
const parentLayer = merkleTree[currentLevel - 1].hashes;
// Determine if index is even or odd
const isEven = index % 2 === 0;
// Set sibling hash
proof.siblingHash = isEven
? currentLayer[index + 1] || null
: currentLayer[index - 1] || null;
// Calculate parent index and uncle index
const parentIndex = Math.floor(index / 2);
const uncleIndex = parentIndex ^ 1; // XOR to get the other index
proof.uncleHash = parentLayer[uncleIndex] || null;
// to show in dashboard
document.getElementById("vote-hash-output").textContent = voteHash;
document.getElementById("block-number-output").textContent = blockNumber;
document.getElementById("sibling-hash-output").textContent =
proof.siblingHash;
document.getElementById("uncle-hash-output").textContent = proof.uncleHash;
document.getElementById("merkle-root-output").textContent = proof.merkleRoot;
// Log the proof to the console
console.log(
`Merkle Proof for vote hash ${voteHash} in block ${blockNumber}:`
);
console.log(`Sibling Hash: ${proof.siblingHash}`);
console.log(`Uncle Hash: ${proof.uncleHash}`);
console.log(`Merkle Root: ${proof.merkleRoot}`);
}
else if(hashes.length > 0 && hashes.length <= 2){
if (!hashes.includes(voteHash)) {
console.log(`Vote hash ${voteHash} not found in block ${blockNumber}.`);
return;
}
// Initialize proof object
let proof = {
siblingHash: null,
merkleRoot: block.header.merkleRoot,
};
// Find the index of the vote hash in the votes array
let index = hashes.indexOf(voteHash);
let currentLevel = 1; // Start from the leaves level (2nd level in this case)
const currentLayer = merkleTree[currentLevel].hashes;
// Determine if index is even or odd
const isEven = index % 2 === 0;
// Set sibling hash
proof.siblingHash = isEven
? currentLayer[index + 1] || null
: currentLayer[index - 1] || null;
// to show in dashboard
document.getElementById("vote-hash-output").textContent = voteHash;
document.getElementById("block-number-output").textContent = blockNumber;
document.getElementById("sibling-hash-output").textContent =
proof.siblingHash;
document.getElementById("merkle-root-output").textContent = proof.merkleRoot;
document.getElementById("uncle_hash").style.display = 'none';
}
}
//-------------------------------------------------------------------------------------------------------------------------------
function broadcastBlockchain() {
connections.forEach((connection) => {
connection.send({
type: "blockchainUpdate",
blockchain: JSON.parse(JSON.stringify(blockchain)), // Send a copy of the blockchain
});
console.log(`Blockchain broadcasted to peer ${connection.peer}`);
});
}
//----------------------------------------------------------------------------------------------------------------------------------
// Function to send unique messages containing hashed votes to each user
function sendUniqueMessageToEachPeer(hashedVotes) {
let array = [];
hashedVotes.forEach(({ peerId, hash }) => {
// Find the connection associated with this peerId
const userConnection = connections.find((conn) => conn.peer === peerId);
if (userConnection) {
array = [hash, blockchain.length];
// Send a unique message to this peer with their hashed vote
userConnection.send({
type: "uniqueVoteMessage",
message: `Thank you for voting! Your vote has been recorded. Hash: ${hash} and Block Number : ${blockchain.length}`,
values: array,
});
console.log(
`Sent message to peer ${peerId}: Thank you for voting. Hash: ${hash}`
);
array = [];
} else {
console.log(`No connection found for peer ${peerId}`);
}
});
}
//-------------------------------------------------------------------------------------------------------------------------------
function updateVoteCount(candidate, result_box) {
const voteCountElement = document.getElementById(`votes${candidate}`);
const totalVotes = document.getElementById("totalVotes");
if (totalVotes) {
totalVotes.textContent = result_box;
}
if (voteCountElement) {
let currentVotes = parseInt(voteCountElement.innerText.split(": ")[1]);
voteCountElement.innerText = `Votes: ${currentVotes + 1}`;
}
}
//---------------------------------------------------------------------------------------------------------------------------------
function updateReservePoolDisplay() {
const reservePoolDisplay = document.getElementById("reserve-pool-display");
reservePoolDisplay.value = JSON.stringify(reservePool, null, 2); // Display reserve pool in a formatted JSON style
}
//---------------------------------------------------------------------------------------------------------------------------------
function updateBlockchainDisplay() {
const blockchainDisplayAuth = document.getElementById(
"blockchain-display-authority"
);
blockchainDisplayAuth.value = JSON.stringify(blockchain, null, 2); // Display blockchain in formatted JSON
}
//--------------------------------------------------------------------------------------------------------------------------------
function updateBlockchainDisplayUsr(blockchainUsr) {
const blockchainDisplayUser = document.getElementById("blockchain-display");
blockchainDisplayUser.value = JSON.stringify(blockchainUsr, null, 2); // Display blockchain in formatted JSON
}
//--------------------------------------------------------------------------------------------------------------------------------
function generateUniqueHex(input) {
const timestamp = Date.now().toString(16); // Get the current timestamp in hex
const randomNumber = Math.floor(Math.random() * 1000000000000000) + 1;
let randomString = randomNumber.toString();
const combined = input + timestamp + randomString; // Combine input and timestamp
let hash = 0;
for (let i = 0; i < combined.length; i++) {
hash = (hash << 5) - hash + combined.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
let hex = (hash >>> 0).toString(16); // Convert hash to hex
while (hex.length < 16) {
hex = "0" + hex; // Pad with zeros
}
return hex.slice(-16); // Ensure it's 16 characters long
}
//-------------------------------------------------------------------------------------------------------------------------------
function sumHex(hex1, hex2) {
const num1 = parseInt(hex1, 16); // Convert first hex string to number
const num2 = parseInt(hex2, 16); // Convert second hex string to number
const sum = num1 + num2; // Calculate the sum of the two numbers
return sum.toString(16).padStart(16, "0"); // Convert sum back to hex and ensure it's 16 characters long
}
//------------------------------------------------------------------------------------------------------------------------------
//block hash;
async function generateBlockHash(merkleRoot, timestamp) {
const data = merkleRoot + timestamp; // Concatenate values to hash
const encoder = new TextEncoder(); // Create a new TextEncoder
const dataBuffer = encoder.encode(data); // Encode the data as a Uint8Array
// Use SubtleCrypto to hash the data
const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
// Convert the hashBuffer to a hex string
const hashArray = Array.from(new Uint8Array(hashBuffer));
const blockHash = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return blockHash; // Return the hexadecimal hash string
}
//----------------------------------------------------------------------------------------------------------------------------
function checkForVoteData() {
const voting_Hash = document.getElementById("vote_Hash").textContent;
const block_number = document.getElementById("block_Num").textContent;
if (voting_Hash && block_number) {
console.log(
"Vote submitted with hash:",
voting_Hash,
"and block number:",
block_number
);
window.location.href = `/after_vote?voting_Hash=${voting_Hash}&block_number=${block_number}`;
} else {
// If data is not yet available, check again after a short delay
setTimeout(checkForVoteData, 1000); // Check every 500 milliseconds
}
}
//-----------------------------------------------------------------------------------------------------------------------------
// Function to create a block from the reserve pool
async function createBlockFromReservePool() {
if (reservePool.length < 4) return; // Ensure there are enough votes
// Hashing function
const hashData = (data) => {
return generateUniqueHex(data); // Use the new unique hex generation function
};
// Hashing votes
const hashedVotes = reservePool.map((vote) => ({
peerId: vote.peerId, // Store the peerId along with the hashed vote
hash: hashData(JSON.stringify(vote)),
}));
// Combine hashes for Merkle tree
const combinedHashes = [
sumHex(hashedVotes[0].hash, hashedVotes[1].hash),
sumHex(hashedVotes[2].hash, hashedVotes[3].hash),
];
//merkle root
const merkleRoot = sumHex(combinedHashes[0], combinedHashes[1]);
// Create block data
const timestamp = Date.now();
const blockHash = await generateBlockHash(merkleRoot, timestamp);
// Previous hash (can be the last block's hash if applicable)
const prevHash = blockchain.length
? blockchain[blockchain.length - 1].header.hash
: "0";
const blockNumber = blockchain.length ? blockchain.length + 1 : 1;
const blockData = {
header: {
blockNumber: blockNumber,
merkleRoot: merkleRoot,
hash: blockHash, // Block hash
prevHash: prevHash,
timestamp: timestamp,
},
data: {
votes: hashedVotes.map((vote) => vote.hash),
merkleTree: [
{ hashes: [merkleRoot] }, // Layer containing the merkle root
{ hashes: combinedHashes }, // Layer of combined hashes
{ hashes: hashedVotes.map((vote) => vote.hash) }, // Original hashes
],
},
};
// Add block to blockchain
blockchain.push(blockData);
console.log("New block created:", blockData); // Log the created block data
updateBlockchainDisplay(); // Update the display to show the new block
//to update user
sendUniqueMessageToEachPeer(hashedVotes);
broadcastBlockchain();
// Clear the reserve pool for new votes
reservePool = [];
updateReservePoolDisplay(); // Update display to show cleared reserve pool
}
/****************************************** ending vote function *************************************************************/
// Function to create a block from the reserve pool
async function createBlockFromReservePool_lessThanFour() {
if(reservePool.length === 3){
// Hashing function
const hashData = (data) => {
return generateUniqueHex(data); // Use the new unique hex generation function
};
// Hashing votes
const hashedVotes = reservePool.map((vote) => ({
peerId: vote.peerId, // Store the peerId along with the hashed vote
hash: hashData(JSON.stringify(vote)),
}));
// Combine hashes for Merkle tree
const combinedHashes = [
sumHex(hashedVotes[0].hash, hashedVotes[1].hash),
sumHex(hashedVotes[2].hash, hashedVotes[2].hash),
];
//merkle root
const merkleRoot = sumHex(combinedHashes[0], combinedHashes[1]);
// Create block data
const timestamp = Date.now();
const blockHash = await generateBlockHash(merkleRoot, timestamp);
// Previous hash (can be the last block's hash if applicable)
const prevHash = blockchain.length
? blockchain[blockchain.length - 1].header.hash
: "0";
const blockNumber = blockchain.length ? blockchain.length + 1 : 1;
const blockData = {
header: {
blockNumber: blockNumber,
merkleRoot: merkleRoot,
hash: blockHash, // Block hash
prevHash: prevHash,
timestamp: timestamp,
},
data: {
votes: hashedVotes.map((vote) => vote.hash),
merkleTree: [
{ hashes: [merkleRoot] }, // Layer containing the merkle root
{ hashes: combinedHashes }, // Layer of combined hashes
{ hashes: [...hashedVotes.map((vote) => vote.hash), hashedVotes[hashedVotes.length - 1].hash] }, // Duplicate last vote hash
],
},
};
// Add block to blockchain
blockchain.push(blockData);
console.log("New block created:", blockData); // Log the created block data
updateBlockchainDisplay(); // Update the display to show the new block
//to update user
sendUniqueMessageToEachPeer(hashedVotes);
broadcastBlockchain();
// Clear the reserve pool for new votes
reservePool = [];
updateReservePoolDisplay(); // Update display to show cleared reserve pool
}
else if(reservePool.length === 2){
// Hashing function
const hashData = (data) => {
return generateUniqueHex(data); // Use the new unique hex generation function
};
// Hashing votes
const hashedVotes = reservePool.map((vote) => ({
peerId: vote.peerId, // Store the peerId along with the hashed vote
hash: hashData(JSON.stringify(vote)),
}));
//merkle root
const merkleRoot = sumHex(hashedVotes[0].hash, hashedVotes[1].hash);
// Create block data
const timestamp = Date.now();
const blockHash = await generateBlockHash(merkleRoot, timestamp);
// Previous hash (can be the last block's hash if applicable)
const prevHash = blockchain.length
? blockchain[blockchain.length - 1].header.hash
: "0";
const blockNumber = blockchain.length ? blockchain.length + 1 : 1;
const blockData = {
header: {
blockNumber: blockNumber,
merkleRoot: merkleRoot,
hash: blockHash, // Block hash
prevHash: prevHash,
timestamp: timestamp,
},
data: {
votes: hashedVotes.map((vote) => vote.hash),
merkleTree: [
{ hashes: [merkleRoot] }, // Layer containing the merkle root
{ hashes: hashedVotes.map((vote) => vote.hash) }, // Original hashes
],
},
};
// Add block to blockchain
blockchain.push(blockData);
console.log("New block created:", blockData); // Log the created block data
updateBlockchainDisplay(); // Update the display to show the new block
//to update user
sendUniqueMessageToEachPeer(hashedVotes);
broadcastBlockchain();
// Clear the reserve pool for new votes
reservePool = [];
updateReservePoolDisplay(); // Update display to show cleared reserve pool
}
else if(reservePool.length === 1){
// Hashing function
const hashData = (data) => {
return generateUniqueHex(data); // Use the new unique hex generation function
};
// Hashing votes
const hashedVotes = reservePool.map((vote) => ({
peerId: vote.peerId, // Store the peerId along with the hashed vote
hash: hashData(JSON.stringify(vote)),
}));
//merkle root
const merkleRoot = sumHex(hashedVotes[0].hash, hashedVotes[0].hash);
// Create block data
const timestamp = Date.now();
const blockHash = await generateBlockHash(merkleRoot, timestamp);
// Previous hash (can be the last block's hash if applicable)
const prevHash = blockchain.length
? blockchain[blockchain.length - 1].header.hash
: "0";
const blockNumber = blockchain.length ? blockchain.length + 1 : 1;
const blockData = {
header: {
blockNumber: blockNumber,
merkleRoot: merkleRoot,
hash: blockHash, // Block hash
prevHash: prevHash,
timestamp: timestamp,
},
data: {
votes: hashedVotes.map((vote) => vote.hash),
merkleTree: [
{ hashes: [merkleRoot] }, // Layer containing the merkle root
{ hashes: hashedVotes.map((vote) => [vote.hash, vote.hash]).flat()}, // Original hashes
],
},
};
// Add block to blockchain
blockchain.push(blockData);
console.log("New block created:", blockData); // Log the created block data
updateBlockchainDisplay(); // Update the display to show the new block
//to update user
sendUniqueMessageToEachPeer(hashedVotes);
broadcastBlockchain();
// Clear the reserve pool for new votes
reservePool = [];
updateReservePoolDisplay(); // Update display to show cleared reserve pool
}
else{
console.log("NO Votes in resever pool ");
}
}
/******************************************connection with authority*************************************************************/
//------------------------------------------------by Dashboard-------------------------------------------------------
const connect_authority = document.getElementById("connect-authority");
if (connect_authority) {
connect_authority.onclick = function () {
const peerId = document.getElementById("authority-peer-id").value; // Get authority Peer ID
const conn = peer.connect(peerId); // Connect to authority
conn.on("open", () => {
connections.push(conn); // Store connection
console.log("Connected to authority:", peerId); // Log successful connection
// Request authority ID from the connected authority peer
conn.send({ type: "syncs_blockchain" });
});
// Handle incoming data from authority
conn.on("data", (data) => {
if (data.type === "authorityId") {
console.log("Authority ID received:", data.id); // Log received authority ID
}
if (data.type === "blockchainUpdate") {
console.log("Received blockchain update");
// Replace blockchain only if the received blockchain is longer
if (data.blockchain.length > blockchainUsr.length) {
blockchainUsr = JSON.parse(JSON.stringify(data.blockchain)); // Update with the new blockchain
if (window.location.pathname != "/vote") {
updateBlockchainDisplayUsr(blockchainUsr);
}
console.log("Blockchain updated with new data ");
}
}
});
conn.on("error", (err) => {
console.error("Connection error:", err); // Log any connection errors
});
};
}
//----------------------------------------- by voting page----------------------------------------------------------
const connect_authority_voting = document.getElementById(
"connect-authority-voting"
);
if (connect_authority_voting) {
connect_authority_voting.onclick = function () {
const peerId = document.getElementById("authority-peer-id").value; // Get authority Peer ID
const conn = peer.connect(peerId); // Connect to authority
conn.on("open", () => {
connections.push(conn); // Store connection
console.log("Connected to authority:", peerId); // Log successful connection
// Request authority ID from the connected authority peer
conn.send({ type: "requestAuthorityId" });
});
// Handle incoming data from authority
conn.on("data", (data) => {
if (data.type === "authorityId") {
console.log("Authority ID received:", data.id); // Log received authority ID
}
if (data.type === "uniqueVoteMessage") {
console.log("Unique vote message:", data.message); // Handle unique message from authority
if (data.values && Array.isArray(data.values)) {
const [hash, blockNumber] = data.values; // Destructure to get hash and block number
document.getElementById("vote_Hash").textContent = hash;
document.getElementById("block_Num").textContent = blockNumber;
checkForVoteData();
} else {
console.log("No additional values found in uniqueVoteMessage");
}
}
});
conn.on("error", (err) => {
console.error("Connection error:", err); // Log any connection errors
});
};
}
/*****************************************************voting logic********************************************************/
// Handle form submission for voting
const vote_form = document.getElementById("vote-form");
if (vote_form) {
vote_form.onsubmit = function (event) {
event.preventDefault(); // Prevent default form submission
const selectedCandidate = document.querySelector(
'input[name="candidate"]:checked'
); // Get selected candidate
const voteConfirmation = document.getElementById("voteConfirmation").value; // Get vote confirmation
// Check if a candidate is selected and the vote is confirmed
if (selectedCandidate && voteConfirmation.trim().toLowerCase() === "vote") {
const voteData = {
candidate: selectedCandidate.value, // Store selected candidate
peerId: peer.id, //peer id
};
const authorityConnection = connections[0]; // Get the first connection (authority)
if (authorityConnection) {
authorityConnection.send({ type: "vote", data: voteData }); // Send vote data to authority
console.log("Vote sent to authority:", voteData); // Log vote sent
// Show success message
document.getElementById("successMessage").style.display = "block";
document.getElementById("votingOptions").style.display = "none"; // Hide voting options
checkForVoteData();
} else {
console.log("No authority connection available."); // Log if no connection
}
} else {
alert(
'Please select a candidate and confirm your vote by typing "vote".'
); // Alert if validation fails
}
};
}
/*************************************************** DOM *********************************************************/
// DOM Event Listeners
document.addEventListener("DOMContentLoaded", () => {
initializePeer();
// Manually send authority ID to the server
const sendPeerIdBtn = document.getElementById("send-peer-id");
if (sendPeerIdBtn) {
sendPeerIdBtn.addEventListener("click", () => {
const authorityPeerId = sessionStorage.getItem("authorityPeerId");
if (authorityPeerId) {
// Send authority ID to server
fetch(`/set-authority?id=${authorityPeerId}`).then(() => {
// Fetch and display the updated authority ID
fetch("/get-authority")
.then((response) => response.json())
.then((data) => {
const authorityIdElement =
document.getElementById("authority-id");
if (data.authorityID && authorityIdElement) {
authorityIdElement.textContent = data.authorityID;
console.log(`Authority ID updated to: ${data.authorityID}`);
}
});
});
}
});
}
const endVote = document.getElementById('end_of_voting');
if (endVote) {
endVote.addEventListener("click", () => {
// Collect voting data
const votingData = {
totalVotes: parseInt(document.getElementById("totalVotes").textContent) || 0,
candidates: {
candidateA: parseInt(document.getElementById("votesCandidateA").textContent.replace('Votes: ', '')) || 0,
candidateB: parseInt(document.getElementById("votesCandidateB").textContent.replace('Votes: ', '')) || 0,
candidateC: parseInt(document.getElementById("votesCandidateC").textContent.replace('Votes: ', '')) || 0
}
};
// Send voting data to the server
fetch("/end-voting", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(votingData)
})
.then(response => response.json())
.then(data => {
alert(data.message);
console.log("Voting ended successfully.");
createBlockFromReservePool_lessThanFour();
})
.catch(error => console.error("Error:", error));
console.log("Voting is ending");
});
}
const verify_button = document.getElementById("get-hashes-button-dash");
if (verify_button) {
verify_button.addEventListener("click", () => {
const blockNumber = parseInt(
document.getElementById("block-number-input").value
);
console.log("block no hai yr : " + blockNumber);
const voteHash = document.getElementById("vote-hash-input").value.trim(); // Get the vote hash input
if (!isNaN(blockNumber) && voteHash) {
// Check if both inputs are valid
getCombinedHashes(voteHash, blockNumber); // Pass both inputs to the function
} else {
console.log("Please enter a valid vote hash and block number.");
}
});
function getCombinedHashes(voteHash, blockNumber) {
// Call the getMerkleProof function with the provided vote hash and block number
console.log("block no hai yr : " + blockNumber);
getMerkleProof(voteHash, blockNumber);
}
}
const showReservePoolBtn = document.getElementById("show-reserve-pool");
if (showReservePoolBtn) {
showReservePoolBtn.addEventListener("click", () => {
const reservePoolSection = document.getElementById(
"reserve-pool-section"
);
reservePoolSection.style.display =
reservePoolSection.style.display === "none" ? "block" : "none"; // Toggle display
});
}
const showBlockchainBtn = document.getElementById("show-blockchain");
if (showBlockchainBtn) {
showBlockchainBtn.addEventListener("click", () => {
const blockchainSection = document.getElementById("blockchain-section");
blockchainSection.style.display =
blockchainSection.style.display === "none" ? "block" : "none"; // Toggle display
});
}
});
//-------------------------------------------------- 😜end of code😜 ----------------------------------------------------//