-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
flipmanager.go
1643 lines (1545 loc) · 52.8 KB
/
flipmanager.go
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
package chat
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"math"
"math/big"
"sort"
"strconv"
"strings"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/chat/flip"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/clockwork"
)
type sentMessageResult struct {
MsgID chat1.MessageID
Err error
}
type sentMessageListener struct {
globals.Contextified
libkb.NoopNotifyListener
utils.DebugLabeler
outboxID chat1.OutboxID
listenCh chan sentMessageResult
}
type startFlipSendStatus struct {
status types.FlipSendStatus
flipConvID chat1.ConversationID
}
func newSentMessageListener(g *globals.Context, outboxID chat1.OutboxID) *sentMessageListener {
return &sentMessageListener{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "sentMessageListener", false),
outboxID: outboxID,
listenCh: make(chan sentMessageResult, 10),
}
}
func (n *sentMessageListener) NewChatActivity(uid keybase1.UID, activity chat1.ChatActivity,
source chat1.ChatActivitySource) {
if source != chat1.ChatActivitySource_LOCAL {
return
}
st, err := activity.ActivityType()
if err != nil {
n.Debug(context.Background(), "NewChatActivity: failed to get type: %s", err)
return
}
switch st {
case chat1.ChatActivityType_INCOMING_MESSAGE:
msg := activity.IncomingMessage().Message
if msg.IsOutbox() {
return
}
if n.outboxID.Eq(msg.GetOutboxID()) {
n.listenCh <- sentMessageResult{
MsgID: msg.GetMessageID(),
}
}
case chat1.ChatActivityType_FAILED_MESSAGE:
for _, obr := range activity.FailedMessage().OutboxRecords {
if obr.OutboxID.Eq(&n.outboxID) {
n.listenCh <- sentMessageResult{
Err: errors.New("failed to send message"),
}
break
}
}
}
}
type flipTextMetadata struct {
LowerBound string
ShuffleItems []string
DeckShuffle bool
HandCardCount uint
HandTargets []string
ConvMemberShuffle bool
}
type hostMessageInfo struct {
flipTextMetadata
ConvID chat1.ConversationID
MsgID chat1.MessageID
}
type loadGameJob struct {
uid gregor1.UID
hostConvID chat1.ConversationID
hostMsgID chat1.MessageID
gameID chat1.FlipGameID
flipConvID chat1.ConversationID
resCh chan chat1.UICoinFlipStatus
errCh chan error
}
type convParticipationsRateLimit struct {
count int
reset time.Time
}
type FlipManager struct {
globals.Contextified
utils.DebugLabeler
dealer *flip.Dealer
visualizer *FlipVisualizer
clock clockwork.Clock
ri func() chat1.RemoteInterface
started bool
shutdownMu sync.Mutex
shutdownCh chan struct{}
dealerShutdownCh chan struct{}
dealerCancel context.CancelFunc
forceCh chan struct{}
loadGameCh chan loadGameJob
maybeInjectCh chan func()
deck string
cardMap map[string]int
cardReverseMap map[int]string
gamesMu sync.Mutex
games *lru.Cache
dirtyGames map[chat1.FlipGameIDStr]chat1.FlipGameID
flipConvs *lru.Cache
gameMsgIDs *lru.Cache
gameOutboxIDMu sync.Mutex
gameOutboxIDs *lru.Cache
partMu sync.Mutex
maxConvParticipations int
maxConvParticipationsReset time.Duration
convParticipations map[chat1.ConvIDStr]convParticipationsRateLimit
// testing only
testingServerClock clockwork.Clock
}
func NewFlipManager(g *globals.Context, ri func() chat1.RemoteInterface) *FlipManager {
games, _ := lru.New(200)
flipConvs, _ := lru.New(200)
gameMsgIDs, _ := lru.New(200)
gameOutboxIDs, _ := lru.New(200)
m := &FlipManager{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "FlipManager", false),
ri: ri,
clock: clockwork.NewRealClock(),
games: games,
dirtyGames: make(map[chat1.FlipGameIDStr]chat1.FlipGameID),
forceCh: make(chan struct{}, 10),
loadGameCh: make(chan loadGameJob, 200),
convParticipations: make(map[chat1.ConvIDStr]convParticipationsRateLimit),
maxConvParticipations: 1000,
maxConvParticipationsReset: 5 * time.Minute,
visualizer: NewFlipVisualizer(128, 80),
cardMap: make(map[string]int),
cardReverseMap: make(map[int]string),
flipConvs: flipConvs,
gameMsgIDs: gameMsgIDs,
gameOutboxIDs: gameOutboxIDs,
maybeInjectCh: make(chan func(), 2000),
}
dealer := flip.NewDealer(m)
m.dealer = dealer
m.deck = "2♠️,3♠️,4♠️,5♠️,6♠️,7♠️,8♠️,9♠️,10♠️,J♠️,Q♠️,K♠️,A♠️,2♣️,3♣️,4♣️,5♣️,6♣️,7♣️,8♣️,9♣️,10♣️,J♣️,Q♣️,K♣️,A♣️,2♦️,3♦️,4♦️,5♦️,6♦️,7♦️,8♦️,9♦️,10♦️,J♦️,Q♦️,K♦️,A♦️,2♥️,3♥️,4♥️,5♥️,6♥️,7♥️,8♥️,9♥️,10♥️,J♥️,Q♥️,K♥️,A♥️"
for index, card := range strings.Split(m.deck, ",") {
m.cardMap[card] = index
m.cardReverseMap[index] = card
}
return m
}
func (m *FlipManager) Start(ctx context.Context, uid gregor1.UID) {
defer m.Trace(ctx, nil, "Start")()
m.shutdownMu.Lock()
if m.started {
m.shutdownMu.Unlock()
return
}
m.started = true
var dealerCtx context.Context
shutdownCh := make(chan struct{})
dealerShutdownCh := make(chan struct{})
m.shutdownCh = shutdownCh
m.dealerShutdownCh = dealerShutdownCh
dealerCtx, m.dealerCancel = context.WithCancel(context.Background())
m.shutdownMu.Unlock()
go func(shutdownCh chan struct{}) {
_ = m.dealer.Run(dealerCtx)
close(shutdownCh)
}(dealerShutdownCh)
go m.updateLoop(shutdownCh)
go m.notificationLoop(shutdownCh)
go m.loadGameLoop(shutdownCh)
go m.maybeInjectLoop(shutdownCh)
}
func (m *FlipManager) Stop(ctx context.Context) (ch chan struct{}) {
defer m.Trace(ctx, nil, "Stop")()
m.dealer.Stop()
m.shutdownMu.Lock()
defer m.shutdownMu.Unlock()
m.started = false
if m.shutdownCh != nil {
m.dealerCancel()
close(m.shutdownCh)
m.shutdownCh = nil
}
if m.dealerShutdownCh != nil {
ch = m.dealerShutdownCh
m.dealerShutdownCh = nil
} else {
ch = make(chan struct{})
close(ch)
}
return ch
}
func (m *FlipManager) makeBkgContext() context.Context {
ctx := context.Background()
return globals.ChatCtx(ctx, m.G(), keybase1.TLFIdentifyBehavior_CHAT_SKIP, nil, nil)
}
func (m *FlipManager) isHostMessageInfoMsgID(msgID chat1.MessageID) bool {
// The first message in a flip thread is metadata about the flip, which is
// message ID 2 since conversations have an initial message from creation.
return chat1.MessageID(2) == msgID
}
func (m *FlipManager) startMsgID() chat1.MessageID {
return chat1.MessageID(3)
}
func (m *FlipManager) isStartMsgID(msgID chat1.MessageID) bool {
// The first message after the host message is the flip start message,
// which will have message ID 3
return m.startMsgID() == msgID
}
func (m *FlipManager) getVisualizer() *FlipVisualizer {
return m.visualizer
}
func (m *FlipManager) notifyDirtyGames() {
m.gamesMu.Lock()
if len(m.dirtyGames) == 0 {
m.gamesMu.Unlock()
return
}
dirtyGames := m.dirtyGames
m.dirtyGames = make(map[chat1.FlipGameIDStr]chat1.FlipGameID)
m.gamesMu.Unlock()
ctx := m.makeBkgContext()
ui, err := m.G().UIRouter.GetChatUI()
if err != nil || ui == nil {
m.Debug(ctx, "notifyDirtyGames: no chat UI available for notification")
return
}
var updates []chat1.UICoinFlipStatus
m.Debug(ctx, "notifyDirtyGames: notifying about %d games", len(dirtyGames))
for _, dg := range dirtyGames {
if game, ok := m.games.Get(dg.FlipGameIDStr()); ok {
status := game.(chat1.UICoinFlipStatus)
m.getVisualizer().Visualize(&status)
presentStatus := status.DeepCopy()
m.sortParticipants(&presentStatus)
updates = append(updates, presentStatus)
}
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := ui.ChatCoinFlipStatus(ctx, updates); err != nil {
m.Debug(ctx, "notifyDirtyGames: failed to notify status: %s", err)
} else {
m.Debug(ctx, "notifyDirtyGames: UI notified")
}
}
func (m *FlipManager) notificationLoop(shutdownCh chan struct{}) {
duration := 50 * time.Millisecond
next := m.clock.Now().Add(duration)
m.Debug(context.Background(), "notificationLoop: starting")
for {
select {
case <-m.clock.AfterTime(next):
m.notifyDirtyGames()
next = m.clock.Now().Add(duration)
case <-m.forceCh:
m.notifyDirtyGames()
next = m.clock.Now().Add(duration)
case <-shutdownCh:
m.Debug(context.Background(), "notificationLoop: exiting")
return
}
}
}
func (m *FlipManager) sortParticipants(status *chat1.UICoinFlipStatus) {
sort.Slice(status.Participants, func(i, j int) bool {
return status.Participants[i].Username < status.Participants[j].Username
})
}
func (m *FlipManager) addParticipant(ctx context.Context, status *chat1.UICoinFlipStatus,
update flip.CommitmentUpdate) {
username, deviceName, _, err := m.G().GetUPAKLoader().LookupUsernameAndDevice(ctx,
keybase1.UID(update.User.U.String()), keybase1.DeviceID(update.User.D.String()))
if err != nil {
m.Debug(ctx, "addParticipant: failed to get username/device (using IDs): %s", err)
username = libkb.NewNormalizedUsername(update.User.U.String())
deviceName = update.User.D.String()
}
status.Participants = append(status.Participants, chat1.UICoinFlipParticipant{
Uid: update.User.U.String(),
DeviceID: update.User.D.String(),
Username: username.String(),
DeviceName: deviceName,
Commitment: update.Commitment.String(),
})
endingS := ""
if len(status.Participants) > 1 {
endingS = "s"
}
status.ProgressText = fmt.Sprintf("Gathered %d commitment%s", len(status.Participants), endingS)
}
func (m *FlipManager) finalizeParticipants(ctx context.Context, status *chat1.UICoinFlipStatus,
cc flip.CommitmentComplete) {
completeMap := make(map[string]bool)
mapKey := func(u, d string) string {
return u + "," + d
}
for _, p := range cc.Players {
completeMap[mapKey(p.Ud.U.String(), p.Ud.D.String())] = true
}
var filteredParts []chat1.UICoinFlipParticipant
for _, p := range status.Participants {
if completeMap[mapKey(p.Uid, p.DeviceID)] {
filteredParts = append(filteredParts, p)
}
}
filteredMap := make(map[string]bool)
for _, p := range filteredParts {
filteredMap[mapKey(p.Uid, p.DeviceID)] = true
}
status.Participants = filteredParts
for _, p := range cc.Players {
if !filteredMap[mapKey(p.Ud.U.String(), p.Ud.D.String())] {
m.addParticipant(ctx, status, flip.CommitmentUpdate{
User: p.Ud,
Commitment: p.C,
})
}
}
}
func (m *FlipManager) addReveal(ctx context.Context, status *chat1.UICoinFlipStatus,
update flip.RevealUpdate) {
numReveals := 0
for index, p := range status.Participants {
if p.Reveal != nil {
numReveals++
}
if p.Uid == update.User.U.String() && p.DeviceID == update.User.D.String() {
reveal := update.Reveal.String()
status.Participants[index].Reveal = &reveal
numReveals++
}
}
status.ProgressText = fmt.Sprintf("%d participants have revealed secrets", numReveals)
}
func (m *FlipManager) cardIndex(card string) (int, error) {
if index, ok := m.cardMap[card]; ok {
return index, nil
}
return 0, fmt.Errorf("unknown card: %s", card)
}
func (m *FlipManager) addCardHandResult(ctx context.Context, status *chat1.UICoinFlipStatus,
result flip.Result, hmi hostMessageInfo) {
deckIndex := 0
numCards := len(result.Shuffle)
handSize := int(hmi.HandCardCount)
var uiHandResult []chat1.UICoinFlipHand
for _, target := range hmi.HandTargets {
if numCards-handSize < deckIndex {
uiHandResult = append(uiHandResult, chat1.UICoinFlipHand{
Target: target,
})
continue
}
uiHand := chat1.UICoinFlipHand{
Target: target,
}
for di := deckIndex; di < deckIndex+handSize; di++ {
card := hmi.ShuffleItems[result.Shuffle[di]]
cardIndex, err := m.cardIndex(card)
if err != nil {
m.Debug(ctx, "addCardHandResult: failed to get card: %s", err)
m.setGenericError(status, "Failed to describe card hand result")
return
}
uiHand.Hand = append(uiHand.Hand, cardIndex)
}
uiHandResult = append(uiHandResult, uiHand)
deckIndex += handSize
}
resultInfo := chat1.NewUICoinFlipResultWithHands(uiHandResult)
status.ResultInfo = &resultInfo
}
func (m *FlipManager) setGenericError(status *chat1.UICoinFlipStatus, errMsg string) {
status.Phase = chat1.UICoinFlipPhase_ERROR
status.ProgressText = errMsg
errorInfo := chat1.NewUICoinFlipErrorWithGeneric(status.ProgressText)
status.ErrorInfo = &errorInfo
}
func (m *FlipManager) resultToText(result chat1.UICoinFlipResult) string {
typ, err := result.Typ()
if err != nil {
return ""
}
switch typ {
case chat1.UICoinFlipResultTyp_COIN:
if result.Coin() {
return "HEADS"
}
return "TAILS"
case chat1.UICoinFlipResultTyp_NUMBER:
return result.Number()
case chat1.UICoinFlipResultTyp_DECK:
var cards []string
for _, cardIndex := range result.Deck() {
cards = append(cards, m.cardReverseMap[cardIndex])
}
return strings.TrimRight(strings.Join(cards, ", "), " ")
case chat1.UICoinFlipResultTyp_SHUFFLE:
return strings.TrimRight(strings.Join(result.Shuffle(), ", "), " ")
case chat1.UICoinFlipResultTyp_HANDS:
var rows []string
for index, hand := range result.Hands() {
if len(hand.Hand) == 0 {
rows = append(rows, fmt.Sprintf("%d. %s: 🤨", index+1, hand.Target))
} else {
var cards []string
for _, cardIndex := range hand.Hand {
cards = append(cards, m.cardReverseMap[cardIndex])
}
rows = append(rows, fmt.Sprintf("%d. %s: %s", index+1, hand.Target,
strings.TrimRight(strings.Join(cards, ", "), " ")))
}
}
return strings.Join(rows, "\n")
}
return ""
}
func (m *FlipManager) addResult(ctx context.Context, status *chat1.UICoinFlipStatus, result flip.Result,
convID chat1.ConversationID) {
defer func() {
if status.ResultInfo != nil {
status.ResultText = m.resultToText(*status.ResultInfo)
}
if len(status.ResultText) > 0 {
status.ProgressText += " (complete)"
}
}()
hmi, err := m.getHostMessageInfo(ctx, convID)
switch {
case err != nil:
m.Debug(ctx, "addResult: failed to describe result: %s", err)
m.setGenericError(status, "Failed to describe result")
case result.Big != nil:
lb := new(big.Int)
res := new(big.Int)
lb.SetString(hmi.LowerBound, 0)
res.Add(lb, result.Big)
resultInfo := chat1.NewUICoinFlipResultWithNumber(res.String())
status.ResultInfo = &resultInfo
case result.Bool != nil:
resultInfo := chat1.NewUICoinFlipResultWithCoin(*result.Bool)
status.ResultInfo = &resultInfo
case result.Int != nil:
resultInfo := chat1.NewUICoinFlipResultWithNumber(fmt.Sprintf("%d", *result.Int))
status.ResultInfo = &resultInfo
case len(result.Shuffle) > 0:
if hmi.HandCardCount > 0 {
m.addCardHandResult(ctx, status, result, hmi)
return
}
if len(hmi.ShuffleItems) != len(result.Shuffle) {
m.setGenericError(status, "Failed to describe shuffle result")
return
}
items := make([]string, len(hmi.ShuffleItems))
for index, r := range result.Shuffle {
items[index] = utils.EscapeForDecorate(ctx, hmi.ShuffleItems[r])
}
var resultInfo chat1.UICoinFlipResult
if hmi.DeckShuffle {
var cardIndexes []int
for _, card := range items {
cardIndex, err := m.cardIndex(card)
if err != nil {
m.Debug(ctx, "addResult: failed to get card: %s", err)
m.setGenericError(status, "Failed to describe deck result")
return
}
cardIndexes = append(cardIndexes, cardIndex)
}
resultInfo = chat1.NewUICoinFlipResultWithDeck(cardIndexes)
} else {
resultInfo = chat1.NewUICoinFlipResultWithShuffle(items)
}
status.ResultInfo = &resultInfo
}
}
func (m *FlipManager) queueDirtyGameID(ctx context.Context, gameID chat1.FlipGameID, force bool) {
m.gamesMu.Lock()
m.dirtyGames[gameID.FlipGameIDStr()] = gameID
m.gamesMu.Unlock()
if force {
select {
case m.forceCh <- struct{}{}:
default:
m.Debug(ctx, "queueDirtyGameID: failed to write onto forceCh!")
}
}
}
func (m *FlipManager) getErrorParticipant(ctx context.Context, a flip.UserDevice) chat1.UICoinFlipErrorParticipant {
username, deviceName, _, err := m.G().GetUPAKLoader().LookupUsernameAndDevice(ctx,
keybase1.UID(a.U.String()), keybase1.DeviceID(a.D.String()))
if err != nil {
m.Debug(ctx, "getErrorParticipant: failed to get names: %s", err)
return chat1.UICoinFlipErrorParticipant{
User: a.U.String(),
Device: a.D.String(),
}
}
return chat1.UICoinFlipErrorParticipant{
User: username.String(),
Device: deviceName,
}
}
func (m *FlipManager) formatError(ctx context.Context, rawErr error) chat1.UICoinFlipError {
switch terr := rawErr.(type) {
case flip.AbsenteesError:
// lookup all the absentees
var absentees []chat1.UICoinFlipErrorParticipant
for _, a := range terr.Absentees {
absentees = append(absentees, m.getErrorParticipant(ctx, a))
}
return chat1.NewUICoinFlipErrorWithAbsentee(chat1.UICoinFlipAbsenteeError{
Absentees: absentees,
})
case flip.TimeoutError:
return chat1.NewUICoinFlipErrorWithTimeout()
case flip.GameAbortedError:
return chat1.NewUICoinFlipErrorWithAborted()
case flip.DuplicateRegistrationError:
return chat1.NewUICoinFlipErrorWithDupreg(m.getErrorParticipant(ctx, terr.U))
case flip.DuplicateCommitmentCompleteError:
return chat1.NewUICoinFlipErrorWithDupcommitcomplete(m.getErrorParticipant(ctx, terr.U))
case flip.DuplicateRevealError:
return chat1.NewUICoinFlipErrorWithDupreveal(m.getErrorParticipant(ctx, terr.U))
case flip.CommitmentMismatchError:
return chat1.NewUICoinFlipErrorWithCommitmismatch(m.getErrorParticipant(ctx, terr.U))
}
return chat1.NewUICoinFlipErrorWithGeneric(rawErr.Error())
}
func (m *FlipManager) handleSummaryUpdate(ctx context.Context, gameID chat1.FlipGameID,
update *flip.GameSummary, convID chat1.ConversationID, force bool) (status chat1.UICoinFlipStatus) {
defer m.queueDirtyGameID(ctx, gameID, force)
if update.Err != nil {
var parts []chat1.UICoinFlipParticipant
oldGame, ok := m.games.Get(gameID.FlipGameIDStr())
if ok {
parts = oldGame.(chat1.UICoinFlipStatus).Participants
}
formatted := m.formatError(ctx, update.Err)
status = chat1.UICoinFlipStatus{
GameID: gameID.FlipGameIDStr(),
Phase: chat1.UICoinFlipPhase_ERROR,
ProgressText: fmt.Sprintf("Something went wrong: %s", update.Err),
Participants: parts,
ErrorInfo: &formatted,
}
m.games.Add(gameID.FlipGameIDStr(), status)
return status
}
status = chat1.UICoinFlipStatus{
GameID: gameID.FlipGameIDStr(),
Phase: chat1.UICoinFlipPhase_COMPLETE,
}
m.addResult(ctx, &status, update.Result, convID)
for _, p := range update.Players {
m.addParticipant(ctx, &status, flip.CommitmentUpdate{
User: p.Device,
Commitment: p.Commitment,
})
if p.Reveal != nil {
m.addReveal(ctx, &status, flip.RevealUpdate{
User: p.Device,
Reveal: *p.Reveal,
})
}
}
status.ProgressText = "Complete"
m.games.Add(gameID.FlipGameIDStr(), status)
return status
}
func (m *FlipManager) handleUpdate(ctx context.Context, update flip.GameStateUpdateMessage, force bool) (err error) {
gameID := update.Metadata.GameID
defer m.Trace(ctx, &err, "handleUpdate: gameID: %s", gameID)()
defer func() {
if err == nil {
m.queueDirtyGameID(ctx, gameID, force)
}
}()
var status chat1.UICoinFlipStatus
rawGame, ok := m.games.Get(gameID.FlipGameIDStr())
if ok {
status = rawGame.(chat1.UICoinFlipStatus)
} else {
status = chat1.UICoinFlipStatus{
GameID: gameID.FlipGameIDStr(),
}
}
switch {
case update.Err != nil:
m.Debug(ctx, "handleUpdate: error received")
status.Phase = chat1.UICoinFlipPhase_ERROR
status.ProgressText = fmt.Sprintf("Something went wrong: %s", update.Err)
formatted := m.formatError(ctx, update.Err)
status.ErrorInfo = &formatted
case update.Commitment != nil:
m.Debug(ctx, "handleUpdate: commit received")
// Only care about these while we are in the commitment phase
if status.Phase == chat1.UICoinFlipPhase_COMMITMENT {
status.ErrorInfo = nil
status.Phase = chat1.UICoinFlipPhase_COMMITMENT
m.addParticipant(ctx, &status, *update.Commitment)
}
case update.CommitmentComplete != nil:
m.Debug(ctx, "handleUpdate: complete received")
status.ErrorInfo = nil
status.Phase = chat1.UICoinFlipPhase_REVEALS
m.finalizeParticipants(ctx, &status, *update.CommitmentComplete)
case update.Reveal != nil:
m.Debug(ctx, "handleUpdate: reveal received")
m.addReveal(ctx, &status, *update.Reveal)
case update.Result != nil:
m.Debug(ctx, "handleUpdate: result received")
status.Phase = chat1.UICoinFlipPhase_COMPLETE
status.ErrorInfo = nil
m.addResult(ctx, &status, *update.Result, update.Metadata.ConversationID)
default:
return errors.New("unknown update kind")
}
m.games.Add(gameID.FlipGameIDStr(), status)
return nil
}
func (m *FlipManager) updateLoop(shutdownCh chan struct{}) {
m.Debug(context.Background(), "updateLoop: starting")
for {
select {
case msg := <-m.dealer.UpdateCh():
err := m.handleUpdate(m.makeBkgContext(), msg, false)
if err != nil {
m.Debug(context.TODO(), "updateLoop: error handling update: %+v", err)
}
case <-shutdownCh:
m.Debug(context.Background(), "updateLoop: exiting")
return
}
}
}
const gameIDTopicNamePrefix = "__keybase_coinflip_game_"
func (m *FlipManager) gameTopicNameFromGameID(gameID chat1.FlipGameID) string {
return fmt.Sprintf("%s%s", gameIDTopicNamePrefix, gameID)
}
var errFailedToParse = errors.New("failed to parse")
func (m *FlipManager) parseMultiDie(arg string, nPlayersApprox int) (start flip.Start, err error) {
lb := new(big.Int)
val, ok := lb.SetString(arg, 0)
if !ok {
return start, errFailedToParse
}
// needs to be a positive number > 0
if val.Sign() <= 0 {
return start, errFailedToParse
}
return flip.NewStartWithBigInt(m.clock.Now(), val, nPlayersApprox), nil
}
const shuffleSeparaters = ",,"
func (m *FlipManager) parseShuffle(arg string, nPlayersApprox int) (start flip.Start, metadata flipTextMetadata, err error) {
if strings.ContainsAny(arg, shuffleSeparaters) {
var shuffleItems []string
for _, tok := range strings.FieldsFunc(arg, func(c rune) bool {
return strings.ContainsRune(shuffleSeparaters, c)
}) {
shuffleItems = append(shuffleItems, strings.Trim(tok, " "))
}
return flip.NewStartWithShuffle(m.clock.Now(), int64(len(shuffleItems)), nPlayersApprox),
flipTextMetadata{
ShuffleItems: shuffleItems,
}, nil
}
return start, metadata, errFailedToParse
}
func (m *FlipManager) parseRange(arg string, nPlayersApprox int) (start flip.Start, metadata flipTextMetadata, err error) {
if !strings.Contains(arg, "..") || strings.Contains(arg, ",") {
return start, metadata, errFailedToParse
}
toks := strings.Split(arg, "..")
if len(toks) != 2 {
return start, metadata, errFailedToParse
}
lb, ok := new(big.Int).SetString(toks[0], 0)
if !ok {
return start, metadata, errFailedToParse
}
ub, ok := new(big.Int).SetString(toks[1], 0)
if !ok {
return start, metadata, errFailedToParse
}
one := new(big.Int).SetInt64(1)
diff := new(big.Int)
diff.Sub(ub, lb)
diff = diff.Add(diff, one)
if diff.Sign() <= 0 {
return start, metadata, errFailedToParse
}
return flip.NewStartWithBigInt(m.clock.Now(), diff, nPlayersApprox), flipTextMetadata{
LowerBound: lb.String(),
}, nil
}
func (m *FlipManager) parseSpecials(arg string, usernames []string,
nPlayersApprox int) (start flip.Start, metadata flipTextMetadata, err error) {
switch {
case strings.HasPrefix(arg, "cards"):
deckShuffle, deckShuffleMetadata, _ := m.parseShuffle(m.deck, nPlayersApprox)
deckShuffleMetadata.DeckShuffle = true
if arg == "cards" {
return deckShuffle, deckShuffleMetadata, nil
}
toks := strings.Split(arg, " ")
if len(toks) < 3 {
return deckShuffle, deckShuffleMetadata, nil
}
handCount, err := strconv.ParseUint(toks[1], 0, 0)
if err != nil {
return deckShuffle, deckShuffleMetadata, nil
}
var targets []string
handParts := strings.Split(strings.Join(toks[2:], " "), ",")
if len(handParts) == 1 && (handParts[0] == "@here" || handParts[0] == "@channel") {
targets = usernames
} else {
for _, pt := range handParts {
t := strings.Trim(pt, " ")
if len(t) > 0 {
targets = append(targets, t)
}
}
}
return deckShuffle, flipTextMetadata{
ShuffleItems: deckShuffleMetadata.ShuffleItems,
HandCardCount: uint(handCount),
HandTargets: targets,
}, nil
case arg == "@here" || arg == "@channel":
if len(usernames) == 0 {
return flip.NewStartWithShuffle(m.clock.Now(), 1, nPlayersApprox), flipTextMetadata{
ShuffleItems: []string{"@here"},
ConvMemberShuffle: true,
}, nil
}
return flip.NewStartWithShuffle(m.clock.Now(), int64(len(usernames)), nPlayersApprox),
flipTextMetadata{
ShuffleItems: usernames,
ConvMemberShuffle: true,
}, nil
}
return start, metadata, errFailedToParse
}
func (m *FlipManager) startFromText(text string, convMembers []string) (start flip.Start, metadata flipTextMetadata) {
var err error
nPlayersApprox := len(convMembers)
toks := strings.Split(strings.TrimRight(text, " "), " ")
if len(toks) == 1 {
return flip.NewStartWithBool(m.clock.Now(), nPlayersApprox), flipTextMetadata{}
}
// Combine into one argument if there is more than one
arg := strings.Join(toks[1:], " ")
// Check for special flips
if start, metadata, err = m.parseSpecials(arg, convMembers, nPlayersApprox); err == nil {
return start, metadata
}
// Check for /flip 20
if start, err = m.parseMultiDie(arg, nPlayersApprox); err == nil {
return start, flipTextMetadata{
LowerBound: "1",
}
}
// Check for /flip mikem,karenm,lisam
if start, metadata, err = m.parseShuffle(arg, nPlayersApprox); err == nil {
return start, metadata
}
// Check for /flip 2..8
if start, metadata, err = m.parseRange(arg, nPlayersApprox); err == nil {
return start, metadata
}
// Just shuffle the one unknown thing
return flip.NewStartWithShuffle(m.clock.Now(), 1, nPlayersApprox), flipTextMetadata{
ShuffleItems: []string{arg},
}
}
func (m *FlipManager) getHostMessageInfo(ctx context.Context, convID chat1.ConversationID) (res hostMessageInfo, err error) {
m.Debug(ctx, "getHostMessageInfo: getting host message info for: %s", convID)
uid, err := utils.AssertLoggedInUID(ctx, m.G())
if err != nil {
return res, err
}
reason := chat1.GetThreadReason_COINFLIP
msg, err := m.G().ChatHelper.GetMessage(ctx, uid, convID, 2, false, &reason)
if err != nil {
return res, err
}
if !msg.IsValid() {
return res, errors.New("host message invalid")
}
if !msg.Valid().MessageBody.IsType(chat1.MessageType_FLIP) {
return res, fmt.Errorf("invalid host message type: %v", msg.GetMessageType())
}
body := msg.Valid().MessageBody.Flip().Text
if err := json.Unmarshal([]byte(body), &res); err != nil {
return res, err
}
return res, nil
}
func (m *FlipManager) DescribeFlipText(ctx context.Context, text string) string {
defer m.Trace(ctx, nil, "DescribeFlipText")()
start, metadata := m.startFromText(text, nil)
typ, err := start.Params.T()
if err != nil {
m.Debug(ctx, "DescribeFlipText: failed get start typ: %s", err)
return ""
}
switch typ {
case flip.FlipType_BIG:
if metadata.LowerBound == "1" {
return fmt.Sprintf("*%s-sided die roll*", new(big.Int).SetBytes(start.Params.Big()))
}
lb, _ := new(big.Int).SetString(metadata.LowerBound, 0)
ub := new(big.Int).Sub(new(big.Int).SetBytes(start.Params.Big()), new(big.Int).SetInt64(1))
return fmt.Sprintf("*Number in range %s..%s*", metadata.LowerBound,
new(big.Int).Add(lb, ub))
case flip.FlipType_BOOL:
return "*HEADS* or *TAILS*"
case flip.FlipType_SHUFFLE:
if metadata.DeckShuffle {
return "*Shuffling a deck of cards*"
} else if metadata.ConvMemberShuffle {
return "*Shuffling all members of the conversation*"
} else if metadata.HandCardCount > 0 {
return fmt.Sprintf("*Dealing hands of %d cards*", metadata.HandCardCount)
}
return fmt.Sprintf("*Shuffling %s*",
strings.TrimRight(strings.Join(metadata.ShuffleItems, ", "), " "))
}
return ""
}
func (m *FlipManager) setStartFlipSendStatus(ctx context.Context, outboxID chat1.OutboxID,
status types.FlipSendStatus, flipConvID *chat1.ConversationID) {
payload := startFlipSendStatus{
status: status,
}
if flipConvID != nil {
payload.flipConvID = *flipConvID
}
m.flipConvs.Add(outboxID.String(), payload)
m.G().MessageDeliverer.ForceDeliverLoop(ctx)
}
// StartFlip implements the types.CoinFlipManager interface
func (m *FlipManager) StartFlip(ctx context.Context, uid gregor1.UID, hostConvID chat1.ConversationID,
tlfName, text string, inOutboxID *chat1.OutboxID) (err error) {
defer m.Trace(ctx, &err, "StartFlip: convID: %s", hostConvID)()
gameID := flip.GenerateGameID()
m.Debug(ctx, "StartFlip: using gameID: %s", gameID)
// Get host conv using local storage, just bail out if we don't have it
hostConv, err := utils.GetVerifiedConv(ctx, m.G(), uid, hostConvID,
types.InboxSourceDataSourceLocalOnly)
if err != nil {
return err
}
// First generate the message representing the flip into the host conversation. We also wait for it
// to actually get sent before doing anything flip related.
var outboxID chat1.OutboxID
if inOutboxID != nil {
outboxID = *inOutboxID
} else {
if outboxID, err = storage.NewOutboxID(); err != nil {
return err
}
}
// Generate dev channel for game message
var conv chat1.ConversationLocal
var participants []string
m.setStartFlipSendStatus(ctx, outboxID, types.FlipSendStatusInProgress, nil)
convCreatedCh := make(chan error)
go func() {
var err error
topicName := m.gameTopicNameFromGameID(gameID)
membersType := hostConv.GetMembersType()
switch membersType {
case chat1.ConversationMembersType_IMPTEAMUPGRADE:
// just override this to use native
membersType = chat1.ConversationMembersType_IMPTEAMNATIVE
fallthrough
case chat1.ConversationMembersType_IMPTEAMNATIVE:
tlfName = utils.AddUserToTLFName(m.G(), tlfName, keybase1.TLFVisibility_PRIVATE,
membersType)
default:
}
// Get conv participants
if participants, err = utils.GetConvParticipantUsernames(ctx, m.G(), uid, hostConvID); err != nil {
convCreatedCh <- err
return
}
// Preserve the ephemeral lifetime from the conv/message to the game
// conversation.
elf, err := utils.EphemeralLifetimeFromConv(ctx, m.G(), hostConv)
if err != nil {
m.Debug(ctx, "StartFlip: failed to get ephemeral lifetime from conv: %s", err)
convCreatedCh <- err
return
}
var retentionPolicy *chat1.RetentionPolicy
if elf != nil {
retentionPolicy = new(chat1.RetentionPolicy)
*retentionPolicy = chat1.NewRetentionPolicyWithEphemeral(chat1.RpEphemeral{Age: *elf})
}
conv, _, err = NewConversationWithMemberSourceConv(ctx, m.G(), uid, tlfName, &topicName,
chat1.TopicType_DEV, membersType,