-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex_v0.12.html
2509 lines (2349 loc) · 91 KB
/
index_v0.12.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
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Mining Simulator</title>
<style>
body {
background-color: #25282E;
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
}
.body {
background-color: #FFF;
border-radius: 15px;
height: 50%;
margin: 100px auto;
overflow-x: hidden;
overflow-y: auto;
padding: 30px;
resize: both;
text-align: center;
width: 1000px;
}
.subbody {
background-color: #EEE;
border: 1px solid;
margin: 0;
width: 93%;
}
th, td {
padding: 0;
text-align: center;
}
canvas {
border-radius: 10px;
width: 100%;
}
button {
width: 100%;
}
table {
text-align: left;
width: 100%;
}
select, option, input, input[type="text"], [type="number"], [type="range"] {
text-align: center;
width: 100%;
}
textarea {
resize: vertical;
width: 100%;
}
</style>
<script type="text/javascript">
/*
There are two script tags on this page.
This, being the first, defines the blockchain as static objects:
Blockchain class:
Holds an array of miners, and provides some functions to
manage them, such as adding, removing, and generating peers.
Miner class:
Holds an array of outgoing and incoming miners, and an instance
of it's current header, which contains all the headers before it
too.
Header class:
Includes a nonce which is null by default, the difficulty, and a
hashing function, as well as an isBlock() function to check if it
qualifies. Each header instance also contains every header all the
way to the genesis block, by using the .prev reference.
The second script tag holds all the current-instance data, such as
the blockchain variable instance, and the functionality of the page.
*/
let blockReward = 1; // Each block awards 1 BTC
let blockDifficulty = "074DBE9000000000000000000000000000000000000000000000000000000000";
let minerNames = ["AARON", "ADAM", "ALAN", "ALBERT", "ALEX", "ALICE", "ANDREW", "ANTHONY", "ARTHUR", "AUSTIN", "BEN", "BILL", "BOB", "BOBBY", "BRANDON", "BRIAN", "BRUCE", "CARL", "CHARLES", "CHRIS", "DAN", "DANIEL", "DAVID", "DENNIS", "DONALD", "DOUGLAS", "DYLAN", "EDWARD", "ERIC", "ETHAN", "EUGENE", "FRANK", "GABRIEL", "GARY", "GEORGE", "GERALD", "GREGORY", "HAROLD", "HARRY", "HENRY", "JACK", "JACOB", "JAMES", "JASON", "JEFFREY", "JEREMY", "JERRY", "JESSE", "JOE", "JOHN", "JOHNNY", "JONATHAN", "JORDAN", "JOSE", "JOSEPH", "JOSHUA", "JUAN", "JUSTIN", "KEITH", "KENNETH", "KEVIN", "KYLE", "LARRY", "LAWRENCE", "LOGAN", "LOUIS", "MARK", "MATTHEW", "MICHAEL", "NATHAN", "NICHOLAS", "NOAH", "PATRICK", "PAUL", "PETER", "PHILIP", "RALPH", "RANDY", "RAYMOND", "RICHARD", "ROBERT", "ROGER", "RONALD", "ROY", "RUSSELL", "RYAN", "SAMUEL", "SCOTT", "SEAN", "STEPHEN", "STEVEN", "TERRY", "THOMAS", "TIMOTHY", "TYLER", "VINCENT", "WALTER", "WAYNE", "WILL", "ZACHARY"];
//minerNames = shuffle(minerNames);
let selectLowestHash = false;
// Compute a sha256 hash by calling sha256("data")
var sha256=function a(b) {function c(a,b) {return a>>>b|a<<32-b}for(var d,e,f=Math.pow,g=f(2,32),h="length",i="",j=[],k=8*b[h],l=a.h=a.h||[],m=a.k=a.k||[],n=m[h],o= {},p=2;64>n;p++)if(!o[p]) {for(d=0;313>d;d+=p)o[d]=p;l[n]=f(p,.5)*g|0,m[n++]=f(p,1/3)*g|0}for(b+="\x80";b[h]%64-56;)b+="\x00";for(d=0;d<b[h];d++) {if(e=b.charCodeAt(d),e>>8)return;j[d>>2]|=e<<(3-d)%4*8}for(j[j[h]]=k/g|0,j[j[h]]=k,e=0;e<j[h];) {var q=j.slice(e,e+=16),r=l;for(l=l.slice(0,8),d=0;64>d;d++) {var s=q[d-15],t=q[d-2],u=l[0],v=l[4],w=l[7]+(c(v,6)^c(v,11)^c(v,25))+(v&l[5]^~v&l[6])+m[d]+(q[d]=16>d?q[d]:q[d-16]+(c(s,7)^c(s,18)^s>>>3)+q[d-7]+(c(t,17)^c(t,19)^t>>>10)|0),x=(c(u,2)^c(u,13)^c(u,22))+(u&l[1]^u&l[2]^l[1]&l[2]);l=[w+x|0].concat(l),l[4]=l[4]+w|0}for(d=0;8>d;d++)l[d]=l[d]+r[d]|0}for(d=0;8>d;d++)for(e=3;e+1;e--) {var y=l[d]>>8*e&255;i+=(16>y?0:"")+y.toString(16)}return i};
// Instead of passing by reference, this allows every miner to have their own unique instance of the blockchain
function cloneObj(obj, depth) {
if (null == obj || "object" != typeof obj || depth <= 0) return obj;
var clone = Object.create(obj);
for (var attr in obj) {
if (obj.hasOwnProperty(attr))
clone[attr] = cloneObj(obj[attr], depth - 1);
}
return clone;
}
/*
Network Class
*/
class Network {
constructor() {
this.peers = [];
this.genesis = new Header();
this.genesis.blockchainID = 0;
// 6 binary zeros 0000 0010 0100 1101 ...
this.genesis.difficulty = blockDifficulty;
this.genesis.version = 0; // Not used
this.genesis.prevHeader = hexSetLength("0", 32);
this.genesis.merkleRoot = hexSetLength("0", 32); // Not used; deals with transactions
this.genesis.nBits = 0; // Not used
this.genesis.nonce = 0;
this.genesis.computeInitHash(); // The hash with nonce=0; used as a block identifier
// Holds transactions waiting to be put into blocks
this.transactionPool = [];
}
// Override toString by just listing the peer names in the network
toString() {
let s = ""
for (let i = 0; i < this.peers.length; i++) {
if(i > 0) s += ", "
if(this.peers[i].type == "Pool") {
let pool = cloneObj(this.peers[i], 1);
let poolMiners = cloneObj(pool.poolMiners, 1);
pool.poolMiners = []; // When we convert the cloned pool into a string, remove it's references to it's pool miners, so that those miner's toString isn't called too
s += pool.toString();
for (var j = 0; j < poolMiners.length; j++) {
// Append the pool mamanger's name to the beginning, so that when it's loaded and processed, the miner is added back into that pool
let temp = poolMiners[j];
poolMiners[j].name = pool.name + " " + poolMiners[j].name;
s += ",\n" + poolMiners[j];
poolMiners[j].name = temp;
}
} else {
s += this.peers[i].toString();
}
}
return "[" + s + "]";
}
// Remove every peer
clearPeers() {
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].destructor();
}
this.peers = [];
}
// Remove every block for each peer
clearBlocks() {
this.genesis.solver = "";
this.genesis.blockchainID = Math.random();
this.genesis.balances = {};
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].currentHeader = this.genesis;
if(this.peers[i].type == "Pool") {
this.peers[i].numShares = {};
this.peers[i].numBlocks = {};
this.peers[i].lastPayNumShares = {};
for (var j = this.peers[i].poolMiners.length - 1; j >= 0; j--) {
this.peers[i].poolMiners[j].currentHeader = this.genesis;
// Below: used for sampling
this.peers[i].poolMiners[j].totalBlocksMined = 0;
this.peers[i].poolMiners[j].totalSharesMined = 0;
this.peers[i].poolMiners[j].withheldBlocks = 0;
}
}
this.peers[i].totalBlocksMined = 0;
this.peers[i].totalSharesMined = 0;
this.peers[i].withheldBlocks = 0;
setTimeout(this.peers[i].updateHTML_Row(), 0);
}
}
// Add a peer to the network
add(peer) {
if(!this.peers.includes(peer)) {
peer.parent = this;
this.peers.push(peer);
}
}
// Add a peer with anywhere from n1 to n2 connections
addPeer(power, color, lag, n1, n2) {
let name = minerNames[this.peers.length % minerNames.length];
if(this.peers.length >= minerNames.length)
name += Math.floor(1 + this.peers.length / minerNames.length);
n1 = Math.max(0, Math.min(n1, this.peers.length));
n2 = Math.max(n1, Math.min(n2, this.peers.length));
let n = random(n1, n2);
var peers, peer = new Miner();
peer.parent = this;
peer.init(name, color, power, lag, this.genesis);
if(n >= 0) peers = shuffle(this.peers.slice(0));
for(let i = 0; i < n; i++) {
peer.addPeer(peers[i]);
}
this.peers.push(peer);
return peer;
}
// Add some peers with anywhere from n1 to n2 connections
// And anywhere from p1 to p2 computing power
// And a network lag between l1 and l2
addPeers(numPeers, n1, n2, p1, p2, l1, l2) {
let addedPeers = [];
for(let i = 0; i < numPeers; i++) {
let color = randomColor();
let power = random(p1, p2);
let lag = random(l1,l2)
addedPeers.push(this.addPeer(power, color, lag, 0, 0));
}
n1 = Math.max(0, Math.min(n1, this.peers.length - 1));
n2 = Math.max(n1, Math.min(n2, this.peers.length - 1));
let peers = this.peers.slice(0);
for(let i = 0; i < addedPeers.length; i++) {
peers = shuffle(peers);
let n = random(n1, n2);
for(let j = 0; j < n; j++) {
if(!addedPeers[i].addPeer(peers[j])) {
n++; // Unsuccessful, so add another
}
}
setTimeout(addedPeers[i].updateHTML_Row(), 0);
}
return addedPeers;
}
// Remove a peer object from the network
removePeer(peer) {
let i = this.peers.indexOf(peer);
if(i != -1) {
peer.destructor();
this.peers.splice(i, 1);
}
}
// Find a peer in the network by their name
findPeer(name) {
for (var i = 0; i < this.peers.length; i++) {
if(name == this.peers[i].name) return this.peers[i];
if(this.peers[i].type == "Pool") {
let peer = this.peers[i].findPeer(name);
if(peer != null) return peer;
}
}
return null;
}
}
/*
Miner Class
*/
class Miner {
constructor() {
this.name = "";
this.type = "Miner";
this.color = "#FFFFFF";
this.power = 0; // Hashes per second
this.peers = []; // Outgoing peers
this.incomingPeers = []; // Peers it receives headers from
this.currentHeader = null; // An instance of the entire blockchain
this.networkLag = 0; // The time overhead to send and receive a block
this.miningInterval = null; // The current thread reference, used for setInterval
this.HTML_Row = null; // The row in the HTML table corresponding to the miner
this.mineStartTime = 0;
this.mineStopTime = 0;
this.totalMineTime = 0;
this.totalBlocksMined = 0;
this.totalSharesMined = 0;
this.parent = null;
}
destructor() {
this.stopMining();
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].removeIncomingPeer(this);
}
for (var i = this.incomingPeers.length - 1; i >= 0; i--) {
this.incomingPeers[i].removePeer(this);
}
if(this.HTML_Row != null && this.HTML_Row.parentElement != null) {
this.HTML_Row.parentElement.removeChild(this.HTML_Row);
}
}
// Call this after setting the name, power, lag, and currentHeader for the miner
init(name, color, power, lag, header) {
this.name = name;
this.color = color;
this.power = parseInt(power);
this.networkLag = parseInt(lag);
this.currentHeader = cloneObj(header, 8);
if(this.HTML_Row == null) {
this.HTML_Row = document.getElementById("trFor" + name);
if(this.HTML_Row == null) {
this.HTML_Row = document.createElement("tr");
this.HTML_Row.id = "trFor" + name;
minerTable.appendChild(this.HTML_Row);
}
}
setTimeout(this.updateHTML_Row(), 0);
}
isMining() {
return this.miningInterval != null;
}
startMining() {
if(this.miningInterval != null) this.stopMining(); // Restart
if(this.power <= 0) return;
if(this.mineStartTime == 0) this.mineStartTime = new Date().getTime();
let self = this;
this.miningInterval = setInterval(function() {
setTimeout(self.mine(), 0);
}, 1000 / this.power);
setTimeout(this.updateHTML_Row(), 0);
}
stopMining() {
clearInterval(this.miningInterval);
if(this.mineStartTime != 0) {
this.mineStopTime = new Date().getTime();
this.totalMineTime += this.mineStopTime - this.mineStartTime;
}
this.mineStartTime = 0;
this.mineStopTime = 0;
this.miningInterval = null;
setTimeout(this.updateHTML_Row(), 0);
}
// Mine a single hash, guess a nonce, hash it, then check if it's a block
mine() {
this.currentHeader.nonce = random(0, 4294967296);
this.currentHeader.computeHash();
// Pass along shareDifficulty even if it doesn't exist.
// If it does exist (in a pool), then it will be checked instead of the block difficulty.
if(this.currentHeader.isBlock()) {
this.totalBlocksMined++;
this.totalSharesMined++;
// A block/share has been found!
if(this.parent.type == "Pool") {
// If the miner belongs to a pool, submit it to the pool
if(this.networkLag == 0) {
this.parent.submit(this, this.currentHeader.nonce, this.currentHeader.initHash);
} else {
setTimeout(function(that, nonce, initHash) { // Network lag using setTimeout
that.parent.submit(that, nonce, initHash);
}, this.networkLag, this, this.currentHeader.nonce, this.currentHeader.initHash);
}
} else {
let newHeader = new Header();
newHeader.prev = this.currentHeader;
newHeader.blockchainID = this.currentHeader.blockchainID;
this.currentHeader.solver = this.name;
// Only award yourself if you're mining for the network
if(this.currentHeader.balances[this.name] === undefined) {
this.currentHeader.balances[this.name] = blockReward;
} else {
this.currentHeader.balances[this.name] += blockReward;
}
newHeader.balances = cloneObj(this.currentHeader.balances, 1);
newHeader.difficulty = blockDifficulty;
newHeader.prevHeader = this.currentHeader.hash;
newHeader.height = this.currentHeader.height + 1;
newHeader.merkleRoot = this.currentHeader.merkleRoot;
newHeader.computeInitHash();
this.broadcast(newHeader); // also sets this miner's current header to the new header
}
} else if(this.currentHeader.isBlock(this.shareDifficulty)) {
this.totalSharesMined++;
if(this.parent.type == "Pool") {
if(this.networkLag == 0) {
this.parent.submit(this, this.currentHeader.nonce, this.currentHeader.initHash);
} else {
setTimeout(function(that, nonce, initHash) { // Network lag using setTimeout
that.parent.submit(that, nonce, initHash);
}, this.networkLag, this, this.currentHeader.nonce, this.currentHeader.initHash);
}
}
}
}
// Called when another user finds a block
broadcast(newHeader) {
// If the blockchain ID is outdated, disregard the message
// This is only necessary because when you clear all blocks, the ones in-flight need to be rejected upon being received, since the blockchains will now be entirely different
if(this.currentHeader.blockchainID != newHeader.blockchainID) return;
// Prevent the infinite broadcasting loop by doing nothing when the headers are equal
if(newHeader.height > this.currentHeader.height) {
this.currentHeader = cloneObj(newHeader, 8);
if(this.networkLag == 0) { // Then no setTimeout function is required
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].broadcast(newHeader);
}
} else {
for (var i = 0; i < this.peers.length; i++) {
setTimeout(function(peer) { // Network lag using setTimeout
peer.broadcast(newHeader);
}, this.networkLag, this.peers[i]);
}
}
setTimeout(this.updateHTML_Row(), 0);
}
// Select the lowest hash when the blockheights are equal
// If selectLowestHash==false, then blocks of equal height will be ignored
if(selectLowestHash && newHeader.height == this.currentHeader.height) {
if(parseInt(newHeader.initHash.substring(0, 15), 16) < parseInt(this.currentHeader.initHash.substring(0, 15), 16)) {
this.currentHeader = cloneObj(newHeader, 8);
if(this.networkLag == 0) { // Then no setTimeout function is required
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].broadcast(newHeader);
}
} else {
for (var i = 0; i < this.peers.length; i++) {
setTimeout(function(peer) { // Network lag using setTimeout
peer.broadcast(newHeader);
}, this.networkLag, this.peers[i]);
}
}
setTimeout(this.updateHTML_Row(), 0);
}
}
}
// Get the miner's header at a blockheight, where blockHeight=0 is the genesis block
getHeader(blockHeight) {
let header = this.currentHeader;
if(blockHeight < 0 || blockHeight > header.height) return null;
// Search from the current block all the way down until it finds the correct number
for(let i = header.height; i > blockHeight;) {
if(header == null) break;
header = header.prev;
i = header.height;
}
return header;
}
// Get the miner's header at a number of blocks back, where blocksBack=0 is the current header
getHeaderBack(blocksBack) {
let header = this.currentHeader;
if(blocksBack < 0 || blocksBack > header.height) return null;
for(let i = 0; i < blocksBack; i++) {
if(header == null) break;
header = header.prev;
}
return header;
}
// Count how much computing power was not wasted
countBlockDurations() {
let totalDuration = 0;
let header = this.currentHeader;
for(let i = header.height; i > 0;) {
if(header == null) break;
totalDuration += header.duration;
header = header.prev;
i = header.height;
}
return totalDuration;
}
// Override the toString function
toString() {
let clone = cloneObj(this, 8);
clone.parent = clone.parent.name;
let peers = [];
// Prevent an infinite loop by changing each peer to the peer name
// so that the peer's toString's aren't called too
for(let i = 0; i < clone.peers.length; i++)
clone.peers[i] = clone.peers[i].name;
for(let i = 0; i < clone.incomingPeers.length; i++)
clone.incomingPeers[i] = clone.incomingPeers[i].name;
return JSON.stringify(clone, null, 2);
}
// Add a miner to the miner's outgoing peers
addPeer(peer) {
if(this == peer) return false;
if(this.peers.includes(peer)) return false;
this.peers.push(peer);
peer.addIncomingPeer(this);
setTimeout(this.updateHTML_Row(), 0);
return true;
}
// Add a miner to the miner's incoming peers (automatically called by addPeer
addIncomingPeer(peer) {
if(this == peer) return false;
if(this.incomingPeers.includes(peer)) return false;
this.incomingPeers.push(peer);
setTimeout(this.updateHTML_Row(), 0);
return true;
}
// Remove a miner from the outgoing peers
removePeer(peer) {
let i = this.peers.indexOf(peer);
if(i != -1) {
peer.removeIncomingPeer(this); // This miner from that miner's incoming peers
this.peers.splice(i, 1);
setTimeout(this.updateHTML_Row(), 0);
}
}
// Remove a miner from the incoming peers (automatically called by removePeer)
removeIncomingPeer(peer) {
let i = this.incomingPeers.indexOf(peer);
if(i != -1) {
this.incomingPeers.splice(i, 1);
setTimeout(this.updateHTML_Row(), 0);
}
}
// List the outgoing peer names
listPeers() {
let names = [];
for(let i = 0; i < this.peers.length; i++) {
names.push(this.peers[i].name);
}
return names.join(", ");
}
// List the incoming peer names
listIncomingPeers() {
let names = [];
for(let i = 0; i < this.incomingPeers.length; i++) {
names.push(this.incomingPeers[i].name);
}
return names.join(", ");
}
// Update the miner's row in the HTML table
updateHTML_Row() {
if(this.HTML_Row == null) return;
let headerHash = "null", prevHeaderHash = "null";
let balance = "";
if(this.currentHeader != null) {
balance = this.currentHeader.balances[this.name];
if(balance === undefined) balance = "";
else balance = truncateBalance(balance) + " BTC";
}
if(this.currentHeader.prev != null) {
// Only show the first few characters of the header
prevHeaderHash = this.currentHeader.prev.hash.substring(0, 6) + " ...";
}
if(this.currentHeader != null) {
// Only show the first few characters of the header
headerHash = this.currentHeader.initHash.substring(0, 6) + " ...";
}
let name = this.name;
let type;
if(this.type == "Miner") type = "";
else if(this.type == "Block Withholding Miner") type = "BWH";
else if(this.type == "Fork After Withholding Miner") type = "FAW";
else type = this.type;
if(type.length > 0) name += " (" + type + ")";
// Miner name column
let html = "<td style=\"background-color:"+this.color+"\"></td>";
html += "<td><button onclick=\"loadMiner_HTML('" + this.name + "')\">" + name + "</button></td>";
// Remove miner column
html += "<td><button onclick=\"removeMiner_HTML(\'" + this.name + "\')\">X</button></td>";
// Computing power column
html += "<td>" + this.power + " H/s</td>";
// Network lag column
html += "<td>" + this.networkLag + " ms</td>";
// Broadcast peers column
if(this.peers.length == 0) {
// Red indicating zero peers
html += "<td><button style=\"background-color: #FF5B50\">" + this.peers.length + " peers</button></td>";
} else {
html += "<td><button onclick=\"alert(\'" + this.listPeers() + "\')\">" + this.peers.length + " peers</button></td>";
}
// Incoming peers column
if(this.incomingPeers.length == 0) {
// Red indicating zero peers
html += "<td><button style=\"background-color: #FF5B50\">" + this.incomingPeers.length + " peers</button></td>";
} else {
html += "<td><button onclick=\"alert(\'" + this.listIncomingPeers() + "\')\">" + this.incomingPeers.length + " peers</button></td>";
}
// Mining column
if(this.isMining()) {
html += "<td><button style=\"background-color: #60FF50\" onclick=\"toggleMining('" + this.name + "')\">Yes</button></td>";
} else {
html += "<td><button onclick=\"toggleMining('" + this.name + "')\">No</button></td>";
}
// Miner balance column
html += "<td>" + balance + "</td>";
// Previous header column
if(this.currentHeader.prev != null && this.currentHeader.prev.solver == this.name) { // If you received the reward
// Green indicating this miner's block is the most recent
html += "<td><button style=\"background-color: #60FF50\" onclick=\"minerBlockClicked_HTML(\'" + this.name + "\'," + this.currentHeader.prev.height + ")\">" + prevHeaderHash + "</button></td>";
} else if(this.currentHeader.prev != null) {
html += "<td><button onclick=\"minerBlockClicked_HTML(\'" + this.name + "\'," + this.currentHeader.prev.height + ")\">" + prevHeaderHash + "</button></td>";
} else {
// Only occurs at blockheight zero
html += "<td><button>~</button></td>";
}
// Block height column
html += "<td>" + this.currentHeader.height + "</td>";
// Current header column
if(this.currentHeader.solver == this.name) {
// Green indicates this miner solved it
html += "<td><button style=\"background-color: #60FF50\" onclick=\"minerBlockClicked_HTML(\'" + this.name + "\'," + this.currentHeader.height + ")\">" + headerHash + "</button></td>";
} else {
html += "<td><button onclick=\"minerBlockClicked_HTML(\'" + this.name + "\'," + this.currentHeader.height + ")\">" + headerHash + "</button></td>";
}
this.HTML_Row.innerHTML = html;
}
}
/*
PoolManager Class
*/
class PoolManager extends Miner {
constructor() {
super();
this.type = "Pool";
this.poolMiners = [];
this.poolMinerNameCounter = 0;
this.HTML_Row2 = null;
// 0b000111110 ...
this.shareDifficulty = "3F00000000000000000000000000000000000000000000000000000000000000";
this.numShares = {};
this.numBlocks = {};
this.lastPayNumShares = {};
this.sumOfShares = 0;
this.sumOfSharesPayoutNumber = 100;
}
// Not automatic, called when we want to remove this miner
destructor() {
this.clearPoolMiners();
if(this.HTML_Row2 != null) {
minerTable.removeChild(this.HTML_Row2);
}
super.destructor();
}
toString() {
let clone = cloneObj(this, 8);
clone.parent = clone.parent.name;
let peers = [];
// Prevent an infinite loop by changing each peer to the peer name
// so that the peer's toString's aren't called too
for(let i = 0; i < clone.peers.length; i++)
clone.peers[i] = clone.peers[i].name;
for(let i = 0; i < clone.incomingPeers.length; i++)
clone.incomingPeers[i] = clone.incomingPeers[i].name;
for(let i = 0; i < clone.poolMiners.length; i++) {
clone.poolMiners[i] = clone.poolMiners[i].toString();
}
return JSON.stringify(clone, null, 2);
}
init(name, color, power, lag, header) {
super.init(name, color, power, lag, header);
this.HTML_Row2 = document.getElementById("tr2For" + name);
if(this.HTML_Row2 == null) {
this.HTML_Row2 = document.createElement("tr");
this.HTML_Row2.id = "tr2For" + name;
minerTable.appendChild(this.HTML_Row2);
}
// !!! Generates the extra miner when loading the JSON --> Needs fix
if(power > 0) {
color = randomColor();
this.poolMinerNameCounter++;
this.genPoolMiner("MINER " + this.poolMinerNameCounter, color, power, lag);
}
setTimeout(this.updateHTML_Row(), 0);
}
clearPoolMiners() {
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
this.poolMiners[i].destructor();
}
this.poolMiners = [];
}
startMining() {
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
this.poolMiners[i].startMining();
}
}
stopMining() {
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
this.poolMiners[i].stopMining();
}
}
isMining() {
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
if(!this.poolMiners[i].isMining()) return false;
}
if(this.poolMiners.length == 0) return false;
return true;
}
addPoolMiner(miner) {
miner.parent = this;
// Add the shareDifficulty attribute to pool miners
miner.shareDifficulty = this.shareDifficulty;
let found = false
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
if(miner.name == this.poolMiners[i].name) {
found = true;
break;
}
}
if(found) {
if(this.poolMiners[i] != miner) {
// Occurs when the whole type of the miner changes
if(this.poolMiners[i] !== undefined) {
// Remove the old miner's table
//console.log(this.poolMiners[i].HTML_Row)
this.poolMiners[i].destructor();
console.log("Pool's destructor called");
}
this.poolMiners[i] = miner;
}
} else {
if(miner.HTML_Row != null) {
minerTable.removeChild(miner.HTML_Row);
}
miner.HTML_Row = null;
// Bind it so that the updateHTML_Row function's this is this miner
miner.updateHTML_Row = this.updateHTML_Row.bind(this);
miner.addPeer(this); // The miner will report back to the pool
this.addPeer(miner); // The pool reports to the miner
this.poolMiners.push(miner);
}
this.updatePower();
setTimeout(this.updateHTML_Row(), 0);
}
removePoolMiner(miner) {
let i = this.poolMiners.indexOf(miner);
if(i >= 0) {
super.removePeer(miner);
this.poolMiners[i].destructor();
this.poolMiners.splice(i, 1);
}
this.updatePower();
setTimeout(this.updateHTML_Row(), 0);
}
genPoolMiner(name, color, power, lag) {
let miner = new Miner();
miner.parent = this;
// Add the shareDifficulty attribute to pool miners
miner.shareDifficulty = this.shareDifficulty;
miner.HTML_Row = this.HTML_Row;
miner.init(name, color, power, lag, this.currentHeader);
miner.HTML_Row = null;
// Bind that this to this this so that that this is equal to this this and not that this.
miner.updateHTML_Row = this.updateHTML_Row.bind(this);
miner.addPeer(this); // The miner will report back to the pool
this.addPeer(miner); // The pool reports to the miner
this.poolMiners.push(miner);
this.updatePower();
}
// Pool Payment Scheme
submit(sender, nonce, initHash) {
// We don't want to even consider if the submission is for a different block, since there's a rare chance that nonce may be a block for the most recent header
if(this.currentHeader.initHash != initHash) return;
this.currentHeader.nonce = nonce;
this.currentHeader.computeHash();
if(this.currentHeader.isBlock()) {
if(sender.type == "Block Withholding Miner") console.log(sender.name + " is submitting \n" + sender.currentHeader.initHash + "\n" + this.currentHeader.initHash);
if(this.numBlocks[sender.name] === undefined) {
this.numBlocks[sender.name] = 1;
} else {
this.numBlocks[sender.name]++;
}
let newHeader = new Header();
newHeader.prev = this.currentHeader;
newHeader.blockchainID = this.currentHeader.blockchainID;
// Give both the pool and the pool miner credit
newHeader.solver = this.name + " --> " + sender.name;
// Only award yourself if you're mining for the network
if(this.currentHeader.balances[this.name] === undefined) {
this.currentHeader.balances[this.name] = blockReward;
} else {
this.currentHeader.balances[this.name] += blockReward;
}
newHeader.balances = cloneObj(this.currentHeader.balances, 1);
newHeader.difficulty = blockDifficulty;
newHeader.prevHeader = this.currentHeader.hash;
newHeader.height = this.currentHeader.height + 1;
newHeader.merkleRoot = this.currentHeader.merkleRoot;
newHeader.computeInitHash();
if(this.sumOfShares >= this.sumOfSharesPayoutNumber) {
this.payout(newHeader);
} else {
if(this.networkLag == 0) { // Then no setTimeout function is required
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].broadcast(newHeader);
}
} else {
for (var i = 0; i < this.peers.length; i++) {
setTimeout(function(peer) { // Network lag using setTimeout
peer.broadcast(newHeader);
}, this.networkLag, this.peers[i]);
}
}
}
setTimeout(this.updateHTML_Row(), 0);
} else if(this.currentHeader.isBlock(this.shareDifficulty)) {
if(this.numShares[sender.name] === undefined) { // Increment the pool's private share counter for that sender
this.numShares[sender.name] = 1;
} else {
this.numShares[sender.name]++;
}
this.sumOfShares++; // Pay Per Last Num Shares (PPLNS)
}
}
// Pay the users for their work
payout(header) {
/*let header = new Header();
header.prev = this.currentHeader;
header.blockchainID = this.currentHeader.blockchainID;
// Give both the pool and the pool miner credit
header.balances = cloneObj(this.currentHeader.balances, 1);
header.difficulty = blockDifficulty;
header.prevHeader = this.currentHeader.hash;
header.height = this.currentHeader.height + 1;
header.merkleRoot = this.currentHeader.merkleRoot;
header.computeInitHash();*/
let amountToGive = header.balances[this.name] || 0; //blockReward;
if(amountToGive == 0) return;
header.balances[this.name] = 0;
let snapshotOfShares = cloneObj(this.numShares, 1);
this.numShares = {};
let combinedNumShares = 0, shares, amount;
// Calculate the total number of shares
for (var i = 0; i < this.poolMiners.length; i++) {
shares = snapshotOfShares[this.poolMiners[i].name] || 0;
combinedNumShares += shares;
}
//console.log("Pool " + this.name + " has " + amountToGive + " BTC to distribute.");
for (var i = 0; i < this.poolMiners.length; i++) {
shares = snapshotOfShares[this.poolMiners[i].name] || 0;
if(shares == 0) continue;
// Truncating makes it so anything less then a Satoshi is cut off
//amount = truncateBalance((shares / combinedNumShares) * amountToGive);
amount = (shares / combinedNumShares) * amountToGive;
// Ensure the pool miner's balance is initialized
if(header.balances[this.poolMiners[i].name] === undefined) {
header.balances[this.poolMiners[i].name] = 0;
}
//console.log("Pool " + this.name + " sent " + this.poolMiners[i].name + " " + amount + " BTC.");
// Instead of transferring money like normal, we will not tamper with the pools balance to make it easier to look at
//header.balances[this.name] -= amount;
header.balances[this.poolMiners[i].name] += amount;
// Keeps track of the total number of shares for this sample
if(this.lastPayNumShares[this.poolMiners[i].name] === undefined) {
this.lastPayNumShares[this.poolMiners[i].name] = 0;
}
this.lastPayNumShares[this.poolMiners[i].name] += shares;
}
this.sumOfShares -= this.sumOfSharesPayoutNumber;
// Send out the new block
this.currentHeader = header;
if(this.networkLag == 0) { // Then no setTimeout function is required
for (var i = 0; i < this.peers.length; i++) {
this.peers[i].broadcast(header);
}
} else {
for (var i = 0; i < this.peers.length; i++) {
setTimeout(function(peer) { // Network lag using setTimeout
peer.broadcast(header);
}, this.networkLag, this.peers[i]);
}
}
setTimeout(this.updateHTML_Row(), 0);
}
findPeer(name) {
for (var i = this.poolMiners.length - 1; i >= 0; i--) {
if(name == this.poolMiners[i].name) return this.poolMiners[i];
/*if(this.poolMiners[i].type == "Pool") { // Recursively handle pool inception
let peer = this.poolMiners[i].findPeer(name);
if(peer != null) return peer;
}*/
}
return null;
}
updatePower() {
this.power = 0;
for(var i = 0; i < this.poolMiners.length; i++) {
this.power += parseInt(this.poolMiners[i].power);
}
}
// Override the original mine function with nothing
mine(){}
// allowPoolMiners is an optional parameter
removePeer(peer, allowPoolMiners) {
// Don't allow removing the pool's own miners
if(this.poolMiners.includes(peer)) {
if(allowPoolMiners) {
this.removePoolMiner(peer);
}
return;
}
super.removePeer(peer);
}
// Render the pool manager's row as well as it's miner's rows
updateHTML_Row() {
super.updateHTML_Row();
if(this.HTML_Row2 == null) return;
this.HTML_Row2.style.fontSize = "9pt";
let html = "<td colspan=\"1\"></td>";
html += "<td colspan=\"11\"><table style=\"background-color: #EEE\">";
html += "<tr>";
html += "<th width=\"16px\"></th>";
html += "<th>Name</th>";
html += "<th width=\"2%\"></th>";
html += "<th>Power</th>";
html += "<th>Lag</th>";
html += "<th>Broadcast<br>Peers</th>";
html += "<th>Incoming<br>Peers</th>";
html += "<th>Mining</th>";
html += "<th>Withheld<br>Blocks</th>";
html += "<th>Submitted<br>Blocks</th>";
html += "<th>Submitted<br>Shares</th>";
html += "<th>Current<br>Shares</th>";
html += "<th>Balance</th>";
html += "<th>Prev.<br>Header</th>";
html += "<th>Block<br>Height</th>";
html += "<th>Curr.<br>Header</th>";
html += "</tr>";
for(var i = 0, len = this.poolMiners.length; i < len; i++) {
html += "<tr>";
let headerHash = "null", prevHeaderHash = "null";
let balance = "";
if(this.poolMiners[i].currentHeader != null) {
balance = this.poolMiners[i].currentHeader.balances[this.poolMiners[i].name];
if(balance === undefined) balance = "0 BTC";
else balance = truncateBalance(balance) + " BTC";
}
let name = this.poolMiners[i].name;
let type = this.poolMiners[i].type;
if(type == "Miner") type = "";
else if(type == "Block Withholding Miner") type = "BWH";
else if(type == "Fork After Withholding Miner") type = "FAW";
if(type.length > 0) name += " (" + type + ")";
if(this.poolMiners[i].currentHeader.prev != null) {
// Only show the first few characters of the header
prevHeaderHash = this.poolMiners[i].currentHeader.prev.hash.substring(0, 4) + " ...";
}
if(this.poolMiners[i].currentHeader != null) {
// Only show the first few characters of the header
headerHash = this.poolMiners[i].currentHeader.initHash.substring(0, 4) + " ...";
}
html += "<td style=\"background-color: " + this.poolMiners[i].color + "\"></td>";
// Miner name column
html += "<td><button onclick=\"loadMiner_HTML('" + this.poolMiners[i].name + "')\">" + name + "</button></td>";
// Remove miner column
html += "<td><button onclick=\"removeMiner_HTML(\'" + this.poolMiners[i].name + "\', \'" + this.name + "\')\">X</button></td>";
// Computing power column
html += "<td>" + this.poolMiners[i].power + " H/s</td>";
// Network lag column
html += "<td>" + this.poolMiners[i].networkLag + " ms</td>";
// Broadcast peers column
if(this.peers.length == 0) {
// Red indicating zero peers
html += "<td><button style=\"background-color: #FF5B50\">" + this.poolMiners[i].peers.length + " peers</button></td>";
} else {
html += "<td><button onclick=\"alert(\'" + this.poolMiners[i].listPeers() + "\')\">" + this.poolMiners[i].peers.length + " peers</button></td>";
}
// Incoming peers column
if(this.incomingPeers.length == 0) {
// Red indicating zero peers
html += "<td><button style=\"background-color: #FF5B50\">" + this.poolMiners[i].incomingPeers.length + " peers</button></td>";