-
Notifications
You must be signed in to change notification settings - Fork 25
/
internal_apps.go
546 lines (470 loc) · 11.8 KB
/
internal_apps.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
package main
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/lucsky/cuid"
)
const (
COINFLIP_TAX = 9999
)
// hide and reveal
type HiddenMessage struct {
Preview string `json:"preview"`
Content string `json:"content"`
CopyMessage *TelegramCopyMessage `json:"copyMessage"`
Times int `json:"times"`
Crowdfund int `json:"crowdfund"`
Public bool `json:"public"`
Satoshis int `json:"satoshis"`
}
func getHiddenId(message *tgbotapi.Message) string {
return hashString("%d%d", message.MessageID, message.Chat.ID)[:7]
}
func findHiddenKey(hiddenId string) (key string, ok bool) {
found := rds.Keys("hidden:*:" + hiddenId).Val()
if len(found) == 0 {
return "", false
}
return found[0], true
}
func getHiddenMessage(
ctx context.Context,
redisKey string,
) (sourceuser int, id string, hiddenmessage HiddenMessage, err error) {
data, err := rds.Get(redisKey).Bytes()
if err != nil {
return
}
err = json.Unmarshal(data, &hiddenmessage)
if err != nil {
return
}
keyparts := strings.Split(redisKey, ":")
id = keyparts[2]
sourceuser, err = strconv.Atoi(keyparts[1])
if err != nil {
return
}
if hiddenmessage.Preview == "" {
hiddenmessage.Preview = translateTemplate(ctx, t.HIDDENDEFAULTPREVIEW,
t.T{"Sats": hiddenmessage.Satoshis})
}
return
}
func revealKeyboard(
ctx context.Context,
fullRedisKey string,
hiddenmessage HiddenMessage,
havepaid int,
) *tgbotapi.InlineKeyboardMarkup {
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
fmt.Sprintf(translateTemplate(ctx, t.HIDDENREVEALBUTTON, t.T{
"Sats": hiddenmessage.Satoshis,
"Public": hiddenmessage.Public,
"Crowdfund": hiddenmessage.Crowdfund,
"Times": hiddenmessage.Times,
"HavePaid": havepaid,
})),
fmt.Sprintf("reveal=%s", fullRedisKey),
),
},
},
}
}
func settleReveal(
ctx context.Context,
sats int,
hiddenId string,
toId int,
fromIds []int,
) (receiver *User, err error) {
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return
}
defer txn.Rollback()
receiver, _ = loadUser(toId)
giverNames := make([]string, 0, len(fromIds))
msats := sats * 1000
random, err := randomHex()
if err != nil {
return
}
receiverHash := hashString(random) // for the proxied transaction
desc := fmt.Sprintf("reveal of %s", hiddenId)
for _, fromId := range fromIds {
if fromId == toId {
continue
}
// A->proxy->B (for many A, one B)
_, err = txn.Exec(`
INSERT INTO lightning.transaction (from_id, to_id, amount, tag, description)
VALUES ($1, $2, $3, 'reveal', $4)
`, fromId, s.ProxyAccount, msats, desc)
if err != nil {
return
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction AS t
(payment_hash, from_id, to_id, amount, tag, description)
VALUES ($1, $2, $3, $4, 'reveal', $5)
ON CONFLICT (payment_hash) DO UPDATE SET amount = t.amount + $4
`, receiverHash, s.ProxyAccount, toId, msats, desc)
if err != nil {
return
}
// check sender balance
if balance := getBalance(txn, fromId); balance < 0 {
err = errors.New("insufficient balance")
return
}
// check proxy balance (should be always zero)
if errW := checkProxyBalance(txn); err != nil {
err = errW
log.Error().Err(err).Msg("proxy balance check on reveal")
return
}
giver, _ := loadUser(fromId)
giverNames = append(giverNames, giver.AtName(ctx))
send(ctx, giver, t.HIDDENREVEALMSG, t.T{
"Sats": sats,
"Id": hiddenId,
})
}
err = txn.Commit()
if err != nil {
return
}
send(ctx, receiver, t.HIDDENSOURCEMSG, t.T{
"Sats": sats * len(fromIds),
"Revealers": strings.Join(giverNames, " "),
"Id": hiddenId,
})
return
}
// giveaway
type GiveAwayData struct {
FromId int
Sats int
ToSpecific string
}
func giveawayKeyboard(
ctx context.Context,
giverId int,
sats int,
receiverName string,
) *tgbotapi.InlineKeyboardMarkup {
giveawayid := cuid.Slug()
buttonData := fmt.Sprintf("give=%s", giveawayid)
saveGiveawayData(giveawayid, giverId, sats, receiverName)
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.CANCEL),
fmt.Sprintf("cancel=%d", giverId),
),
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.GIVEAWAYCLAIM),
buttonData,
),
},
},
}
}
func saveGiveawayData(giveId string, from int, sats int, to string) {
jdata, _ := json.Marshal(GiveAwayData{
FromId: from,
Sats: sats,
ToSpecific: to,
})
rds.Set("giveaway:"+giveId, string(jdata), s.GiveAwayTimeout)
}
func getGiveawayData(giveId string) (from *User, to *User, sats int, err error) {
jdata, _ := rds.Eval(`
local giveid = KEYS[1]
local result = redis.call("get", giveid)
redis.call("del", giveid)
return result
`, []string{"giveaway:" + giveId}).Val().(string)
var data GiveAwayData
err = json.Unmarshal([]byte(jdata), &data)
if err != nil {
return nil, nil, 0, err
}
from, err = loadUser(data.FromId)
if err != nil {
log.Warn().Err(err).Int("id", data.FromId).Msg("failed to load user on giveaway")
return nil, nil, 0, err
}
if data.ToSpecific != "" {
to, err = loadTelegramUsername(data.ToSpecific)
if err != nil {
log.Warn().Err(err).Str("username", data.ToSpecific).
Msg("failed to load giveaway specific receiver")
return nil, nil, 0, err
}
}
sats = data.Sats
return from, to, sats, nil
}
// giveflip
func giveflipKeyboard(
ctx context.Context,
giveflipid string,
giverId int,
nparticipants int,
sats int,
) *tgbotapi.InlineKeyboardMarkup {
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.CANCEL),
fmt.Sprintf("cancel=%d", giverId),
),
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.GIVEFLIPJOIN),
fmt.Sprintf("gifl=%d-%d-%d-%s", giverId, nparticipants, sats, giveflipid),
),
},
},
}
}
// coinflip
func coinflipKeyboard(
ctx context.Context,
coinflipid string,
initiatorId int,
nparticipants,
sats int,
) *tgbotapi.InlineKeyboardMarkup {
if coinflipid == "" {
coinflipid = cuid.Slug()
}
if initiatorId != 0 {
rds.SAdd("coinflip:"+coinflipid, initiatorId)
}
rds.Expire("coinflip:"+coinflipid, s.GiveAwayTimeout)
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.COINFLIPJOIN),
fmt.Sprintf("flip=%d-%d-%s", nparticipants, sats, coinflipid),
),
},
},
}
}
func settleCoinflip(
ctx context.Context,
sats int,
toId int,
fromIds []int,
) (receiver *User, err error) {
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return
}
defer txn.Rollback()
receiver, _ = loadUser(toId)
giverNames := make([]string, 0, len(fromIds))
msats := int64(sats) * 1000
// receiver must also have the necessary sats in his balance at the time
receiverBalance := getBalance(txn, toId)
if receiverBalance < msats+COINFLIP_TAX {
err = errors.New("Receiver has insufficient balance.")
return
}
random, err := randomHex()
if err != nil {
return
}
receiverHash := hashString(random) // for the proxied transaction
// then we create a transfer from each of the other participants
for _, fromId := range fromIds {
if fromId == toId {
continue
}
// A->proxy->B (for many A, one B)
_, err = txn.Exec(`
INSERT INTO lightning.transaction (from_id, to_id, amount, fees, tag)
VALUES ($1, $2, $3, $4, 'coinflip')
`, fromId, s.ProxyAccount, msats, COINFLIP_TAX)
if err != nil {
return
}
// check sender balance
if balance := getBalance(txn, fromId); balance < 0 {
err = errors.New("insufficient balance")
return
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction AS t (payment_hash, from_id, to_id, amount, tag)
VALUES ($1, $2, $3, $4, 'coinflip')
ON CONFLICT (payment_hash) DO UPDATE SET amount = t.amount + $4
`, receiverHash, s.ProxyAccount, toId, msats)
if err != nil {
return
}
// check proxy balance (should be always zero)
if errW := checkProxyBalance(txn); err != nil {
err = errW
log.Error().Err(err).Msg("proxy balance check on coinflip")
return
}
giver, _ := loadUser(fromId)
giverNames = append(giverNames, giver.AtName(ctx))
send(ctx, giver, t.COINFLIPGIVERMSG, t.T{
"IndividualSats": sats,
"Receiver": receiver.AtName(ctx),
})
}
err = txn.Commit()
if err != nil {
return
}
send(ctx, receiver, t.COINFLIPWINNERMSG, t.T{
"TotalSats": sats * len(fromIds),
"Senders": strings.Join(giverNames, " "),
})
return
}
// fundraise
func fundraiseKeyboard(
ctx context.Context,
fundraiseid string,
initiatorId int,
receiverId int,
nparticipants int,
sats int,
) *tgbotapi.InlineKeyboardMarkup {
if fundraiseid == "" {
fundraiseid = cuid.Slug()
}
if initiatorId != 0 {
rds.SAdd("fundraise:"+fundraiseid, initiatorId)
}
rds.Expire("fundraise:"+fundraiseid, s.GiveAwayTimeout)
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.FUNDRAISEJOIN),
fmt.Sprintf("raise=%d-%d-%d-%s", receiverId, nparticipants, sats, fundraiseid),
),
},
},
}
}
func settleFundraise(
ctx context.Context,
sats int,
toId int,
fromIds []int,
) (receiver *User, err error) {
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return
}
defer txn.Rollback()
receiver, _ = loadUser(toId)
giverNames := make([]string, 0, len(fromIds))
msats := sats * 1000
random, err := randomHex()
if err != nil {
return
}
receiverHash := hashString(random) // for the proxied transaction
for _, fromId := range fromIds {
if fromId == toId {
continue
}
// A->proxy->B (for many A, one B)
_, err = txn.Exec(`
INSERT INTO lightning.transaction (from_id, to_id, amount, tag)
VALUES ($1, $2, $3, 'fundraise')
`, fromId, s.ProxyAccount, msats)
if err != nil {
return
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction AS t (payment_hash, from_id, to_id, amount, tag)
VALUES ($1, $2, $3, $4, 'fundraise')
ON CONFLICT (payment_hash) DO UPDATE SET amount = t.amount + $4
`, receiverHash, s.ProxyAccount, toId, msats)
if err != nil {
return
}
balance := getBalance(txn, fromId)
if balance < 0 {
err = errors.New("insufficient balance")
return
}
// check proxy balance (should be always zero)
if errW := checkProxyBalance(txn); err != nil {
err = errW
log.Error().Err(err).Msg("proxy balance check on fundraise")
return
}
giver, _ := loadUser(fromId)
giverNames = append(giverNames, giver.AtName(ctx))
send(ctx, giver, t.FUNDRAISEGIVERMSG, t.T{
"IndividualSats": sats,
"Receiver": receiver.AtName(ctx),
})
}
err = txn.Commit()
if err != nil {
return
}
send(ctx, receiver, t.FUNDRAISERECEIVERMSG, t.T{
"TotalSats": sats * len(fromIds),
"Senders": strings.Join(giverNames, " "),
})
return
}
// rename groups
func renameKeyboard(
ctx context.Context,
renamerId int,
chatId int64,
sats int,
name string,
) *tgbotapi.InlineKeyboardMarkup {
hash := sha256.Sum256([]byte(name))
renameId := hex.EncodeToString(hash[:])[:12]
rds.Set(
fmt.Sprintf("rename:%s", renameId),
fmt.Sprintf("%d|~|%d|~|%s", chatId, sats, name),
time.Minute*60,
)
return &tgbotapi.InlineKeyboardMarkup{
[][]tgbotapi.InlineKeyboardButton{
{
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.CANCEL),
fmt.Sprintf("cancel=%d", renamerId),
),
tgbotapi.NewInlineKeyboardButtonData(
translate(ctx, t.YES),
fmt.Sprintf("rnm=%s", renameId),
),
},
},
}
}