-
Notifications
You must be signed in to change notification settings - Fork 43
/
CypherPokerAnalyzer.js
1312 lines (1269 loc) · 52 KB
/
CypherPokerAnalyzer.js
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
/**
* @file Monitors and analyzes a CypherPoker game (hand) for cryptographic correctness
* and ranks the completed hands of the game to determine the winner.
*
* @version 0.4.1
* @author Patrick Bay
* @copyright MIT License
*/
/**
* @class Monitors and analyzes a CypherPoker game (hand) for cryptographic correctness
* and ranks the completed hands of the game to determine the winner.
*/
class CypherPokerAnalyzer extends EventDispatcher {
/**
* The cards captured for an associated game are about to be analyzed.
*
* @event CypherPokerAnalyzer#analyzing
* @type {Event}
* @property {CypherPokerAnalyzer} analyzer A reference to this instance.
* @property {CypherPokerAnalyzer#analysis} analysis A reference to the current analysis.
* property.
*/
/**
* The cards captured for an associated game have been fully analyzed. A successful
* analysis is usually followed by scoring.
*
* @event CypherPokerAnalyzer#analyzed
* @type {Event}
* @property {CypherPokerAnalyzer} analyzer A reference to this instance.
* @property {CypherPokerAnalyzer#analysis} analysis A reference to the current analysis.
* property.
*/
/**
* The cards captured for an associated game have been scored and ranked (post analysis).
*
* @event CypherPokerAnalyzer#scored
* @type {Event}
* @property {CypherPokerAnalyzer} analyzer A reference to this instance.
* @property {CypherPokerAnalyzer#analysis} analysis A reference to the current analysis.
* property.
*/
/**
* Creates a new instance.
*
* @param {CypherPokerGame} game The game instance with which this instance
* is to be associated. Event listeners are added to the {@link CypherPokerGame}
* instance at this time so the analyzer should usually be instantiated at the
* beginning of a new game (hand).
*
*/
constructor(game) {
super();
this._game = game;
this.game.addEventListener("gamecardsencrypt", this.onEncryptCards, this);
this.game.addEventListener("gamedealmsg", this.onGameDealMessage, this);
this.game.addEventListener("gamedealprivate", this.onSelectCards, this);
this.game.addEventListener("gamedealpublic", this.onSelectCards, this);
this.game.addEventListener("gamedeal", this.onCardDeal, this);
this.game.addEventListener("gamedecrypt", this.onGameDecrypt, this);
this.game.addEventListener("gameanalyze", this.onGameAnalyze, this);
this.game.addEventListener("gameplayerkeychain", this.onPlayerKeychain, this);
}
/**
* @property {Boolean} True if the instance is active (tracking game actions),
* false if not.
*
* @readonly
*/
get active() {
if (this._active == undefined) {
this._active = false;
}
return (this._active);
}
/**
* @property {Number} keychainCommitTimeout=10000 The amount of time, in milliseconds,
* to wait at the end of a game for all players' keychains to be comitted before timing out.
*/
get keychainCommitTimeout() {
if (this._keychainCommitTimeout == undefined) {
this._keychainCommitTimeout = 10000;
}
return (this._keychainCommitTimeout);
}
set keychainCommitTimeout (KRSTSet) {
this._keychainCommitTimeout = KRSTSet;
}
/**
* @property {Boolean} allKeychainsCommitted True when all players associated
* with the {@link CypherPokerAnalyzer#game} instance have committed an
* end-game keychain.
*
* @readonly
*/
get allKeychainsCommitted() {
if (this._keychains == undefined) {
this._keychains = new Object();
}
var allPlayersCommitted = true;
var numCommitted = 0;
for (var count=0; count < this.players.length; count++) {
var player = this.players[count];
if (this._keychains[player.privateID] == undefined) {
this._keychains[player.privateID] = Array.from(player.keychain);
}
var keychain = this._keychains[player.privateID];
if (keychain.length == 0) {
allPlayersCommitted = false;
break;
} else {
numCommitted++;
}
}
if (allPlayersCommitted) {
return (true);
}
return (false);
}
/**
* @property {Array} communityCards An array of {@link CypherPokerCard}
* instances of the community cards reported by the final decryptors.
*
* @readonly
*/
get communityCards() {
if (this._communityCards == undefined) {
this._communityCards = new Array();
}
return (this._communityCards);
}
/**
* @property {Object} privateCards={} An object of named arrays, with each
* array named using the private ID of the associated player and containing
* the {@link CypherPokerCard} instances of the decrypted private cards for
* that player.
*
* @readonly
*/
get privateCards() {
if (this._privateCards == undefined) {
this._privateCards = new Object();
}
return (this._privateCards);
}
/**
* @property {Array} deck An array of named objects, with each
* array element storing an object representing a snapshot of the
* deck generation and encryption processes.
*
* @readonly
*/
get deck() {
if (this._deck == undefined) {
this._deck = new Array();
}
return (this._deck);
}
/**
* @property {Array} Returns a copy of the mapped deck of the associated
* {@link CypherPokerAnalyzer#game} instance
* (the {@link CypherPokerGame#cardDecks}<code>faceup</code> property),
* or an empty array if none exists.
*
* @readonly
*/
get mappedDeck() {
if (this._mappedDeck == undefined) {
this._mappedDeck = new Array();
}
return (this._mappedDeck);
}
/**
* @property {Object} deals Contains name/value pairs with each name representing
* the source (dealing) private ID of the player and the associated value being an
* array of objects, each containing a <code>fromPID</code> private ID of the sender
* of the data, a <code>type</code> denoting the type of dealing operation ("select" or "decrypt"),
* the card values in a <code>cards</code> array, and a <code>private</code> property
* indicating whether the deal was for private / hole cards or for public / community ones.
* Each entry is stored in order of operation.
*
* @readonly
*/
get deals() {
if (this._deals == undefined) {
this._deals = new Object();
}
return (this._deals);
}
/**
* @property {Object} keychains Name/value pairs of player keychains with
* each name representing a player private ID and associated value being their
* keychain. The keychain is copied from the associated {@link CypherPokerAnalayzer#game}
* instance once a game completes.
*
* @readonly
*/
get keychains() {
if (this._keychains == undefined) {
this._keychains = new Object();
}
return (this._keychains);
}
/**
* @property {CypherPokerGame} game=null The game instance associated with this
* analyzer, as set at instantiation time.
*
* @readonly
*/
get game() {
if (this._game == undefined) {
this._game = null;
}
return (this._game);
}
/**
* @property {CypherPoker} cypherpoker=null The {@link CypherPoker} instance
* associated with {@link CypherPokerAnalyzer#game}.
*
* @readonly
*/
get cypherpoker() {
if (this.game == null) {
return (null);
}
return (this.game.cypherpoker);
}
/**
* @property {CypherPoker} cypherpoker A reference to the
* {@link CypherPokerAnalyzer#game}'s <code>cypherpoker</code> instance or
* <code>null</code> if none exists.
*/
get cypherpoker() {
if ((this._game != null) && (this._game != undefined)) {
return (this._game.cypherpoker);
}
return (null);
}
/**
* @property {TableObject} A copy of the table associated with the {@link CypherPokerAnalyzer#game}
* instance.
*/
get table() {
if (this._table == undefined) {
this._table = this.game.getTable();
}
return (this._table);
}
/**
* @property {Array} Indexed list of {CypherPokerPlayer} instances copied
* from the associated {@link CypherPokerAnalyzer#game} instance.
*/
get players() {
if (this._players == undefined) {
this.refreshPlayers();
}
return (this._players);
}
/**
* @property {Object} analysis The partial or full analysis of the
* completed game.
* @property {Object} analysis.private Name/value pairs with each name matching
* a player private ID and value containing an array of their verified private
* {@link CypherPokerCard} instances.
* @property {Array} analysis.public Array of verified public {@link CypherPokerCard}
* instances.
* @property {Boolean} analysis.complete=false Set to true when the hand has been
* fully validated as far as possible.
* @property {Error} analysis.error=null The analysis error object, if one exists.
*
* @readonly
*/
get analysis() {
if (this._analysis == undefined) {
this._analysis = new Object();
this._analysis.private = new Object();
this._analysis.public = new Array();
this._analysis.complete = false;
this._analysis.error = null;
}
return (this._analysis);
}
/**
* Refreshes the {@link CypherPokerAnalyzer#players} array with data from
* the associated {@link CypherPokerAnalyzer#game}.
*
* @private
*/
refreshPlayers() {
this._players = new Array();
for (var count=0; count < this.game.players.length; count++) {
this._players.push(this.game.players[count].copy());
}
}
/**
* Returns a {@link CypherPokerPlayer} instance associated with the analyzer's
* game instance.
*
* @param {String} privateID The private ID of the player to return.
*
* @return {CypherPokerPlayer} The {@link CypherPokerPlayer} for the private ID
* associated with this instance. <code>null</code> is returned if no matching
* player private ID can be found.
*/
getPlayer(privateID) {
for (var count=0; count < this.players.length; count++) {
if (this.players[count].privateID == privateID) {
return (this.players[count]);
}
}
return (null);
}
/**
* Returns a condensed array containing the copied properties of the
* {@link CypherPokerAnalyzer#players} array. Use the object returned by
* this function with <code>JSON.stringify</code> instead of using
* {@link CypherPokerAnalyzer#players} directly in order to prevent circular
* reference errors.
*
* @param {Boolean} [includeKeychains=false] If true, the {@link CypherPokerPlayer#keychain}
* array of each player will be included in the returned object.
* @param {Boolean} [includePasswords=false] If true, the {@link CypherPokerAccount#password}
* property of each {@link CypherPokerPlayer#account} reference will be included
* with the returned object.
*
* @return {Object} The condensed players array associated with this instance's
* game reference.
*/
getPlayers(includeKeychains=false, includePasswords=false) {
var returnArr = new Array();
for (var count=0; count < this.players.length; count++) {
var playerObj = this.players[count].toObject(includeKeychains, includePasswords);
returnArr.push(playerObj);
}
return (returnArr);
}
/**
* Returns the {@link CypherPokerPlayer} that is currently flagged as the dealer
* in the {@link CypherPokerAnalyzer#players} array.
*
* @return {CypherPokerPlayer} The {@link CypherPokerPlayer} instance that
* is flagged as a dealer. <code>null</code> is returned if no dealer is flagged.
*/
getDealer() {
for (var count=0; count < this.players.length; count++) {
if (this.players[count].isDealer) {
return (this.players[count]);
}
}
return (null);
}
/**
* Removes all of the event listeners added to the {@link CypherPokerAnalyzer.game}
* reference at instantiation.
*
* @private
*/
removeGameListeners() {
this.game.removeEventListener("gamecardsencrypt", this.onEncryptCards, this);
this.game.removeEventListener("gamedealmsg", this.onGameDealMessage, this);
this.game.removeEventListener("gamedealprivate", this.onSelectCards, this);
this.game.removeEventListener("gamedealpublic", this.onSelectCards, this);
this.game.removeEventListener("gamedeal", this.onCardDeal, this);
this.game.removeEventListener("gamedecrypt", this.onGameDecrypt, this);
this.game.removeEventListener("gameanalyze", this.onGameAnalyze, this);
//"gameplayerkeychain" is removed separately, once all keychains are received
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPoker#event:gamecardsencrypt} event.
*
* @param {Event} event A {@link CypherPoker#event:gameplayerkeychain} event object.
*
* @async
* @private
*/
async onEncryptCards(event) {
var temp = this.table;
this._active = true;
var infoObj = new Object();
if (this.deck.length == 0) {
//store current face-up deck as generated by dealer
var generatedDeck = event.game.cardDecks.faceup;
var cardsArr = new Array();
for (var count=0; count < generatedDeck.length; count++) {
cardsArr.push(generatedDeck[count].mapping);
this.mappedDeck.push(this.game.getMappedCard(generatedDeck[count].mapping));
}
infoObj.fromPID = this.getDealer().privateID;
infoObj.cards = cardsArr;
this.deck.push (infoObj);
}
infoObj = new Object();
infoObj.fromPID = event.player.privateID;
infoObj.cards = Array.from(event.selected);
this.deck.push (infoObj);
}
/**
* Returns a reference to a {@link CypherPokerCard} based on its mapping.
*
* @param {String} mapping The plaintext or face-up card mapping value to
* find.
*
* @return {CypherPokerCard} The matching card instance or <code>null</code>
* if none exists.
*/
getMappedCard(mapping) {
for (var count=0; count < this.mappedDeck.length; count++) {
if (this.mappedDeck[count].mapping == mapping) {
return (this.mappedDeck[count]);
}
}
return (null);
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPoker#event:gamedecrypt} event.
*
* @param {Event} event A {@link CypherPoker#event:gamedecrypt} event object.
*
* @async
* @private
*/
async onGameDecrypt(event) {
this._active = true;
//we have partially decrypted some cards
if (event.private) {
this.storeDeal(event.payload.sourcePID, this.game.ownPID, event.selected, true, true);
} else {
this.storeDeal(event.payload.sourcePID, this.game.ownPID, event.selected, false, true);
}
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPoker#event:gamedeal} event.
*
* @param {Event} event A {@link CypherPoker#event:gamedeal} event object.
*
* @async
* @private
*/
async onCardDeal(event) {
this._active = true;
var cards = event.cards;
if (event.private == false) {
//new community cards have been dealt
for (var count=0; count < cards.length; count++) {
this.communityCards.push(cards[count]);
}
} else {
//new private cards have been dealt
this.privateCards[event.game.ownPID]=new Array();
for (var count=0; count < cards.length; count++) {
this.privateCards[event.game.ownPID].push(cards[count]);
}
}
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches either a {@link CypherPoker#event:gamedealprivate} or
* {@link CypherPoker#event:gamedealpublic} event.
*
* @param {Event} event A {@link CypherPoker#event:gamedealprivate} or
* {@link CypherPoker#event:gamedealpublic} event object.
*
* @async
* @private
*/
async onSelectCards(event) {
this._active = true;
var selected = event.selected;
if (event.type == "gamedealprivate") {
//private card selection
this.storeDeal(this.game.ownPID, this.game.ownPID, selected, true, false);
} else {
//we have selected a private card
this.storeDeal(this.game.ownPID, this.game.ownPID, selected, false, false);
}
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPoker#event:gamedealmsg} event.
*
* @param {Event} event A {@link CypherPoker#event:gamedealmsg} event object.
*
* @async
* @private
*/
async onGameDealMessage(event) {
this._active = true;
var resultObj = event.data.result;
if ((resultObj.data.payload.cards != undefined) && (resultObj.data.payload.cards != null)) {
var cardsArr = resultObj.data.payload.cards;
if (typeof(cardsArr.length) == "number") {
//this message contains fully decrypted community cards
//and is handled in "onCardDeal"
return(true);
}
}
//partially decrypted public or private cards:
var selected = resultObj.data.payload.selected;
//the player that dealt (selected) the cards:
var dealingPlayer = this.getPlayer(resultObj.data.payload.sourcePID);
//the player that sent the "gamedeal" message:
var fromPlayer = this.getPlayer(resultObj.from);
//the selected card values:
if (dealingPlayer.privateID == fromPlayer.privateID) {
//player is selecting a card
if (resultObj.data.payload.private) {
//private card selection
this.storeDeal(dealingPlayer.privateID, fromPlayer.privateID, selected, true, false);
} else {
//public card selection
this.storeDeal(dealingPlayer.privateID, fromPlayer.privateID, selected, false, false);
}
} else {
//player has decrypted card(s)
if (resultObj.data.payload.private) {
//private cards
this.storeDeal(dealingPlayer.privateID, fromPlayer.privateID, selected, true, true);
} else {
//public card(s)
this.storeDeal(dealingPlayer.privateID, fromPlayer.privateID, selected, false, true);
}
}
return(true);
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPokerGame#event:gameanalyze} event.
*
* @param {Event} event A {@link CypherPokerGame#event:gameanalyze} event object.
*
* @async
* @private
*/
async onGameAnalyze(event) {
this.refreshPlayers(); //refresh the players array
if ((this._keychains == null) || (this._keychains == undefined)) {
this._keychains = new Object();
}
this._keychains[this.game.ownPID] = Array.from(this.getPlayer(this.game.ownPID).keychain);
this.removeGameListeners();
this._keychainCommitTimeout = setTimeout(this.onKCSTimeout, this.keychainCommitTimeout, this, event.game);
return (true);
}
/**
* Called when the keychain submission timer elapses and not all players have
* committed their keychains.
*
* @param {CypherPokerAnalayzer} context The execution context of the instance.
* @param {CypherPokerGame} game The game instance for which the timeout
* occurred.
* @private
*/
onKCSTimeout(context, game) {
context.analysis.complete = true;
throw (new Error("Not all players have committed their keychains in time (table ID: "+context.table.tableID+")"));
}
/**
* Event handler invoked when the associated {@link CypherPokerAnalyzer#game}
* instance dispatches a {@link CypherPoker#event:gameplayerkeychain} event.
*
* @param {Event} event A {@link CypherPoker#event:gameplayerkeychain} event object.
*
* @async
* @private
*/
async onPlayerKeychain(event) {
this._active = true;
if (this._keychains == undefined) {
this._keychains = new Object();
}
var player = event.player;
var game = event.game;
this._keychains[player.privateID] = Array.from(event.keychain);
if (this.allKeychainsCommitted) {
this.game.removeEventListener("gameplayerkeychain", this.onPlayerKeychain, this);
//all keychains committed, we can clear the timeout and start the analysis
clearTimeout(this._keychainCommitTimeout);
event = new Event("analyzing");
event.analyzer = this;
event.analysis = this.analysis;
this.dispatchEvent(event);
try {
this._analysis = await this.analyzeCards();
} catch (err) {
console.error(err);
alert ("Post-game analysis failed. Awaiting contract confirmation...");
return (false);
}
event = new Event("analyzed");
event.analyzer = this;
event.analysis = this.analysis;
this.dispatchEvent(event);
this._analysis = await this.scoreHands(this._analysis);
this._analysis.complete = true;
this._analysis.error = null;
event = new Event("scored");
event.analyzer = this;
event.analysis = this.analysis;
this.dispatchEvent(event);
this.game.debug ("Final hand/game analysis:");
this.game.debug (this.analysis, "dir");
this.game.debug (this.deals, "dir");
this._active = false;
}
return (true);
}
/**
* Analyzes the stored information for cryptographic correctness and returns
* the verified, decrypted cards (as {@link CypherPokerCard} instances),
* for each player along with the public / community cards. This function should
* only be called when the game has completed and all keychains received.
*
* @return {Promise} The promise resolves with an object containing a <code>players</code>
* object containing name/value pairs with each name matching a player private ID and containing
* an array of {@link CypherPokerCard} instances, and a <code>public</code>
* property containing an array of the public / community {@link CypherPokerCard} instances.
* If the analysis fails it is rejected with an <code>Error</code> which includes a
* <code>message</code> and numeric <code>code</code> identifying the analysis failure.
*
* @async
* @private
*/
async analyzeCards() {
//step 1: analyze the full deck (creation & encryption)
if (this.deck.length == 0) {
return (null);
}
//todo: check to ensure that all values are quadratic residues
var cardsObj = new Object();
cardsObj.private = new Object();
cardsObj.public = new Array();
var faceUpMappings = Array.from(this.deck[0].cards); //generated plaintext (quadratic residues) values
var previousDeck = Array.from(faceUpMappings);
for (var count = 1; count < this.deck.length; count++) {
var currentDeck = Array.from(this.deck[count].cards);
var keychain = this.keychains[this.deck[count].fromPID];
var promises = new Array();
for (var count2=0; count2 < previousDeck.length; count2++) {
promises.push(this.cypherpoker.crypto.invoke("encrypt", {value:previousDeck[count2], keypair:keychain[keychain.length-1]}));
}
var promiseResults = await Promise.all(promises);
var compareDeck = new Array();
for (count2 = 0; count2 < promiseResults.length; count2++) {
compareDeck.push(promiseResults[count2].data.result);
}
if (this.compareDecks(currentDeck, compareDeck) == false) {
var error = new Error("Deck encryption at stage "+count+" by \""+this.deck[count].fromPID+"\" failed.");
error.code = 1;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
previousDeck = currentDeck;
}
//previousDeck should now contain the fully encrypted deck
var encryptedDeck = previousDeck;
//step 1: passed
//step 2: analyze private / public card selections and decryptions
for (var privateID in this.deals) {
var dealArray = this.deals[privateID];
var decrypting = false; //currently decrypting cards?
var previousType = "select"; //should match dealArray[0].type
for (count = 0; count < dealArray.length; count++) {
var currentDeal = dealArray[count];
if ((currentDeal == undefined) || (currentDeal == null)) {
//not a deal history object
break;
}
if (count > 0) {
var previousDeal = dealArray[count-1];
var previousCards = previousDeal.cards;
var previousPID = previousDeal.fromPID;
var previousPrivate = previousDeal.private;
previousType = previousDeal.type;
}
var sourcePID = privateID; //card dealer / selector
var fromPID = currentDeal.fromPID; //private ID of "cards" (result) sender
var type = currentDeal.type; //"select" or "decrypt"
var privateDeal = currentDeal.private; //private / hole cards?
var cards = currentDeal.cards; //numeric card value strings, encrypted or plaintext;
if (cardsObj.private[sourcePID] == undefined) {
cardsObj.private[sourcePID] = new Array();
};
if ((previousType == "select") && (type == "select")) {
//probably the first entry but...
if (count > 0) {
var error = new Error("Multiple sequential \"select\" sequences in deal.");
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
if (this.removeFromDeck(cards, encryptedDeck) == false) {
var error = new Error("Duplicates found in \"select\" deal index "+count+" for \""+fromPID+"\" for \""+sourcePID+"\".");
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
} else if ((previousType == "select") && (type == "decrypt") && (count < (dealArray.length - 1))) {
//starting a new decryption operation (deal or select cards)
decrypting = true;
} else if ((previousType == "decrypt") && (type == "select")) {
//ending decryption operation (final decryption outstanding)
keychain = this.keychains[sourcePID];
promises = new Array();
promiseResults = new Array();
for (count2=0; count2 < previousCards.length; count2++) {
promises.push(this.cypherpoker.crypto.invoke("decrypt", {value:previousCards[count2], keypair:keychain[keychain.length-1]}));
}
promiseResults = await Promise.all(promises);
var dealtCards = new Array();
for (count2 = 0; count2 < promiseResults.length; count2++) {
var card = this.getMappedCard(promiseResults[count2].data.result);
if (card == null) {
var error = new Error("Final decryption (deal "+count+") by \""+this.getPlayer(fromPID).account.address+"\" for \""+this.getPlayer(sourcePID).account.address+"\" does not map: "+promiseResults[count2].data.result);
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
if (previousPrivate) {
cardsObj.private[sourcePID].push(card);
} else {
cardsObj.public.push(card);
}
}
if (this.removeFromDeck(cards, encryptedDeck) == false) {
var error = new Error("Duplicates found in \"select\" deal index "+count+" for \""+this.getPlayer(fromPID).account.address+"\" for \""+this.getPlayer(sourcePID).account.address+"\".");
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
} else {
//decryption in progress
if (count == (dealArray.length - 1)) {
//final decryption for source
keychain = this.keychains[sourcePID];
promises = new Array();
promiseResults = new Array();
for (count2=0; count2 < cards.length; count2++) {
promises.push(this.cypherpoker.crypto.invoke("decrypt", {value:cards[count2], keypair:keychain[keychain.length-1]}));
}
promiseResults = await Promise.all(promises);
for (count2 = 0; count2 < promiseResults.length; count2++) {
var card = this.getMappedCard(promiseResults[count2].data.result);
if (card == null) {
var error = new Error("Final decryption (deal "+count+") by \""+fromPID+"\" does not map: "+promiseResults[count2].data.result);
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
if (privateDeal) {
cardsObj.private[sourcePID].push(card);
} else {
cardsObj.public.push(card);
}
}
} else {
//continuing decryption from another player
keychain = this.keychains[fromPID];
compareDeck = new Array();
promises = new Array();
promiseResults = new Array();
//decrypt current cards to compare to what was sent by current player...
for (count2=0; count2 < previousCards.length; count2++) {
promises.push(this.cypherpoker.crypto.invoke("decrypt", {value:previousCards[count2], keypair:keychain[keychain.length-1]}));
}
promiseResults = await Promise.all(promises);
for (count2 = 0; count2 < promiseResults.length; count2++) {
compareDeck.push(promiseResults[count2].data.result);
}
if (this.compareDecks(compareDeck, cards) == false) {
var error = new Error("Previous round ("+count+") of decryption by \""+this.getPlayer(fromPID).account.address+"\" for \""+this.getPlayer(sourcePID).account.address+"\" does not match computed results.");
error.code = 2;
this._analysis.error = error;
this._analysis.complete = true;
throw (error);
}
}
}
}
}
return (cardsObj);
}
/**
* Returns all of the available, unordered 5-hand permutations for a set of supplied cards.
*
* @param {Array} cardsArr Values or {@link CypherPokerCard} instance for
* which to produce permutatuions, up to a maximum of 7 elements.
*
* @return {Array} Each array element contains a unique 5-card permutation
* from the input set. If there are less than 6 cards provided, only one
* permutation is returned.
*
* @private
*/
createCardPermutations(cardsArr) {
var permArray = new Array();
if (cardsArr.length <= 5) {
//only one hand permutation available
permArray.push (cardsArr);
} else if (cardsArr.length == 6) {
//only private card 2 (index 1)
permArray.push ([cardsArr[1], cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[5]]);
//only private card 1 (index 0)
permArray.push ([cardsArr[0], cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[5]]);
//both private cards
permArray.push ([cardsArr[1], cardsArr[0], cardsArr[3], cardsArr[4], cardsArr[5]]);
permArray.push ([cardsArr[1], cardsArr[2], cardsArr[0], cardsArr[4], cardsArr[5]]);
permArray.push ([cardsArr[1], cardsArr[2], cardsArr[3], cardsArr[0], cardsArr[5]]);
permArray.push ([cardsArr[1], cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[0]]);
} else {
//no private cards
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[6]]);
//private card 1 (index 0)
permArray.push ([cardsArr[0], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[0], cardsArr[4], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[0], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[0], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[0]]);
//private card 2 (index 1)
permArray.push ([cardsArr[1], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[1], cardsArr[4], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[1], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[1], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[1]]);
//both private cards
permArray.push ([cardsArr[0], cardsArr[1], cardsArr[4], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[0], cardsArr[3], cardsArr[1], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[0], cardsArr[3], cardsArr[4], cardsArr[1], cardsArr[6]]);
permArray.push ([cardsArr[0], cardsArr[3], cardsArr[4], cardsArr[5], cardsArr[1]]);
permArray.push ([cardsArr[2], cardsArr[0], cardsArr[1], cardsArr[5], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[0], cardsArr[4], cardsArr[1], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[0], cardsArr[4], cardsArr[5], cardsArr[1]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[0], cardsArr[1], cardsArr[6]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[0], cardsArr[5], cardsArr[1]]);
permArray.push ([cardsArr[2], cardsArr[3], cardsArr[4], cardsArr[0], cardsArr[1]]);
}
return (permArray);
}
/**
* Generates player card permutations for analysis and scores the
* hands.
*
* @param {Object} cardsObj A player card object matching the format of the
* {@link CypherPokerAnalyzer#analysis} object.
*
* @private
*/
async scoreHands(cardsObj) {
var playersObj = cardsObj.private;
cardsObj.hands = new Object();
var playerHands = new Object();
var highestScore = -1;
var highestHand = new Array;
var winningPlayers = new Array();
var winningHands = new Array();
for (var privateID in playersObj) {
var player = this.getPlayer(privateID);
//private ID may actually be some other object property
if (player != null) {
if (player.hasFolded == false) {
var fullCards = playersObj[privateID].concat(cardsObj.public);
cardsObj.hands[privateID] = new Array();
var perms = this.createCardPermutations(fullCards);
for (var count = 0; count < perms.length; count++) {
var handObj = new Object();
handObj.hand = perms[count];
handObj.score = -1; //default (not scored)
this.scoreHand (handObj);
cardsObj.hands[privateID].push(handObj);
if (handObj.score == highestScore) {
//this may be a split pot; see below
winningPlayers.push(player);
winningHands.push(handObj);
} else if (handObj.score > highestScore) {
//new best hand
winningPlayers = new Array();
winningHands = new Array();
winningPlayers.push(player);
winningHands.push(handObj);
highestScore = handObj.score;
}
}
}
}
}
if (winningPlayers.length > 1) {
//need to look at both private cards since we currently have a potential split pot
var newWinningPlayers = new Array();
var newWinningHands = new Array();
var highestScore = 0;
for (count = 0; count < winningPlayers.length; count++) {
var winningHand = winningHands[count]; //indexes match with winningPlayers
var hand = winningHand.hand;
var player = winningPlayers[count];
var playerPID = player.privateID;
var privateCard1 = this.analysis.private[playerPID][0];
var privateCard2 = this.analysis.private[playerPID][1];
//adjust score for highest card value
if (privateCard1.highvalue > privateCard2.highvalue) {
var currentScore = (privateCard1.highvalue * 10) + privateCard2.highvalue;
} else {
currentScore = (privateCard2.highvalue * 10) + privateCard1.highvalue;
}
winningHand.score = currentScore;
if (currentScore > highestScore) {
highestScore = currentScore;
newWinningPlayers = new Array();
newWinningHands = new Array();
newWinningPlayers.push(player);
newWinningHands.push(winningHand);
} else if (currentScore == highestScore) {
//both private card values are the same -- split pot
newWinningPlayers.push(player);
newWinningHands.push(winningHand);
}
}
winningPlayers = newWinningPlayers;
winningHands = newWinningHands;
}
//eliminate any duplicates
newWinningPlayers = new Array();
newWinningHands = new Array();
for (var count=0; count < winningPlayers.length; count++) {
var currentWinnerPID = winningPlayers[count];
var currentWinningHand = winningHands[count];
var existingWinnerPID = newWinningPlayers.find(winnerPID => {
return (winnerPID == currentWinnerPID);
}, this);
if (existingWinnerPID == undefined) {
newWinningPlayers.push(currentWinnerPID);
newWinningHands.push(currentWinningHand);
}
}
winningPlayers = newWinningPlayers;
winningHands = newWinningHands;
cardsObj.winningPlayers = winningPlayers;
cardsObj.winningHands = winningHands;
return (cardsObj);
}
/**
* Scores a 5 cards (or fewer) poker hand. The higher the score the
* better the hand.
*
* @param {Object} handObj A hand permutation and score object. This object
* is updated with the resulting score, hand name, and other information.
* @param {Array} handObj.hand Array of {@link CypherPokerCard} instances
* comprising the hand to score.
* @param {Number} handObj.score=-1 Calculated score of final hand. -1 means
* that the hand is not scored.
*
* @private
*/
scoreHand(handObj) {
if ((handObj.hand == undefined) || (handObj.hand == null)) {
return;
}