-
Notifications
You must be signed in to change notification settings - Fork 25
/
user_operations.go
582 lines (507 loc) · 13.2 KB
/
user_operations.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
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/fiatjaf/go-cliche"
decodepay "github.com/fiatjaf/ln-decodepay"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/jmoiron/sqlx/types"
"github.com/juju/ratelimit"
)
// creating too many invoices is forbidden
// because we're not a faucet milking machine
// also making too many payments is wrong
var rateLimitBuckets = &sync.Map{}
func getRateLimitBucket(userId int) *ratelimit.Bucket {
bucket, ok := rateLimitBuckets.Load(userId)
if ok {
return bucket.(*ratelimit.Bucket)
} else {
// one can do a burst of 20 invoices/payments and after that only 1 every 10 minutes
bucket := ratelimit.NewBucket(time.Minute*10, 20)
rateLimitBuckets.Store(userId, bucket)
return bucket
}
}
func (u User) getTransaction(hash string) (txn Transaction, err error) {
err = pg.Get(&txn, `
SELECT
time,
telegram_peer,
anonymous,
status,
trigger_message,
tag,
coalesce(description, '') AS description,
fees::float/1000 AS fees,
amount::float/1000 AS amount,
payment_hash,
coalesce(preimage, '') AS preimage,
payee_node
FROM lightning.account_txn
WHERE account_id = $1
AND payment_hash LIKE $2 || '%'
ORDER BY time, amount DESC
LIMIT 1
`, u.Id, hash)
if err != nil {
return
}
txn.Description = escapeHTML(txn.Description)
// handle case in which it was paid internally and so two results were returned
if txn.Preimage.Valid == false {
txn.Preimage = sql.NullString{String: "internal_payment", Valid: true}
}
return
}
func (u User) invoicePrivateKey() *btcec.PrivateKey {
// derive custom private key for this user
seedhash := sha256.Sum256(
[]byte(fmt.Sprintf("invoicekeyseed:%d:%s", u.Id, s.TelegramBotToken)))
sk, _ := btcec.PrivKeyFromBytes(btcec.S256(), seedhash[:])
return sk
}
func (u User) makeInvoice(
ctx context.Context,
args *MakeInvoiceArgs,
) (bolt11 string, hash string, err error) {
if !args.IgnoreRateLimit {
if ok := getRateLimitBucket(u.Id).WaitMaxDuration(1, time.Second*5); !ok {
return "", "", errors.New("Creating too many invoices, please wait about 10 minutes.")
}
}
msatoshi := args.Msatoshi
log.Debug().Stringer("user", &u).
Str("desc", args.Description).Int64("msats", msatoshi).
Msg("generating invoice")
if args.Expiry == nil {
args.Expiry = &s.InvoiceTimeout
}
preimage := make([]byte, 32)
if _, err := rand.Read(preimage); err != nil {
return "", "", fmt.Errorf("can't create random preimage: %w", err)
}
// hide the user id inside the preimage (first 4 bytes)
binary.BigEndian.PutUint32(preimage, uint32(u.Id))
// TODO: "expireIn": int((*args.Expiry).Seconds()),
inv, err := ln.CreateInvoice(cliche.CreateInvoiceParams{
Msatoshi: msatoshi,
Preimage: hex.EncodeToString(preimage),
Description: args.Description,
DescriptionHash: args.DescriptionHash,
Label: fmt.Sprintf("lntxbotuser=%d", u.Id),
})
if err != nil {
return "", "", fmt.Errorf("failed to create invoice: %w", err)
}
var messageId interface{}
if message := ctx.Value("message"); message != nil {
switch m := message.(type) {
case *tgbotapi.Message:
messageId = m.MessageID
}
}
saveInvoiceData(inv.PaymentHash, InvoiceData{
UserId: u.Id,
MessageId: messageId,
Preimage: hex.EncodeToString(preimage),
MakeInvoiceArgs: args,
})
if args.BlueWallet {
encodedinv, _ := json.Marshal(map[string]interface{}{
"hash": inv.PaymentHash,
"bolt11": inv.Invoice,
"desc": args.Description,
"amount": msatoshi / 1000,
"expiry": int((*args.Expiry)),
})
rds.Set("justcreatedbluewalletinvoice:"+strconv.Itoa(u.Id), string(encodedinv), time.Minute*10)
}
return inv.Invoice, inv.PaymentHash, nil
}
func (u User) payInvoice(
ctx context.Context,
bolt11 string,
manuallySpecifiedMsatoshi int64,
) (hash string, err error) {
if ok := getRateLimitBucket(u.Id).WaitMaxDuration(1, time.Second*5); !ok {
return "", errors.New("Making too many payments, please wait about 5 minutes.")
}
inv, err := decodepay.Decodepay(bolt11)
if err != nil {
return "", errors.New("Failed to decode invoice: " + err.Error())
}
if u.TelegramChatId != 0 {
bot.Send(tgbotapi.NewChatAction(u.TelegramChatId, "Sending payment..."))
}
amount := inv.MSatoshi
hash = inv.PaymentHash
if amount == 0 {
amount = manuallySpecifiedMsatoshi
if amount == 0 {
return hash, errors.New("Can't send 0.")
}
}
// check first if it is internal
if data, err := loadInvoiceData(inv.PaymentHash); err == nil {
// it's an internal invoice. mark as paid internally.
err = u.addInternalPendingInvoice(
ctx,
data.UserId,
data.Msatoshi,
hash,
data.Description,
)
if err != nil {
return hash, err
}
if data.Msatoshi > amount {
return hash,
fmt.Errorf("Invoice is for %d, can't pay less.", data.Msatoshi)
} else if amount > data.Msatoshi*2 {
return hash,
fmt.Errorf("Invoice is for %d, can't pay more than the double.",
data.Msatoshi)
}
go paymentReceived(ctx, hash, data.Msatoshi)
go paymentHasSucceeded(ctx, amount, 0, data.Preimage, data.Tag, hash)
return hash, nil
} else {
// it's an invoice from elsewhere, continue and
// actually send the lightning payment
err = u.actuallySendExternalPayment(ctx, bolt11, inv, amount)
if err != nil {
return hash, err
}
return hash, nil
}
}
func (u User) actuallySendExternalPayment(
ctx context.Context,
bolt11 string,
inv decodepay.Bolt11,
msatoshi int64,
) (err error) {
hash := inv.PaymentHash
// insert payment as pending
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
log.Debug().Err(err).Msg("database error starting transaction")
return ErrDatabase
}
defer txn.Rollback()
// if not tg this will just be ignored
// TODO
var tgMessageId int
if message := ctx.Value("message"); message != nil {
if m, ok := message.(*tgbotapi.Message); ok {
tgMessageId = m.MessageID
}
}
fee_reserve := float64(msatoshi) * 0.005
if msatoshi < 1000000 {
fee_reserve += 5000 // account for exemptfee
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction
(from_id, amount, fees, description, payment_hash, pending,
trigger_message, remote_node)
VALUES ($1, $2, $3, $4, $5, true, $6, $7)
`, u.Id, msatoshi, int64(fee_reserve), inv.Description,
hash, tgMessageId, inv.Payee)
if err != nil {
log.Debug().Err(err).Int64("msatoshi", msatoshi).
Msg("database error inserting transaction")
return errors.New("Payment already in course.")
}
if balance := getBalance(txn, u.Id); balance < 0 {
return errors.New("Insufficient balance.")
}
err = txn.Commit()
if err != nil {
log.Debug().Err(err).Msg("database error committing transaction")
return ErrDatabase
}
// perform payment
go func() {
_, err := ln.PayInvoice(cliche.PayInvoiceParams{
Invoice: bolt11,
Msatoshi: msatoshi,
})
if err != nil {
send(ctx, t.ERROR, t.T{"Err": err.Error()})
}
}()
return nil
}
func (u User) addInternalPendingInvoice(
ctx context.Context,
targetId int,
msats int64,
hash string,
desc interface{},
) (err error) {
// insert payment as pending
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
log.Debug().Err(err).Msg("database error starting transaction")
return ErrDatabase
}
defer txn.Rollback()
// if not tg this will just be ignored
var tgMessageId int
if message := ctx.Value("message"); message != nil {
if m, ok := message.(*tgbotapi.Message); ok {
tgMessageId = m.MessageID
}
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction
(from_id, to_id, amount, description, payment_hash, pending, trigger_message)
VALUES ($1, $2, $3, $4, $5, true, $6)
`, u.Id, targetId, msats, desc, hash, tgMessageId)
if err != nil {
log.Debug().Err(err).Msg("database error inserting transaction")
return errors.New("Payment already in course.")
}
balance := getBalance(txn, u.Id)
if balance < 0 {
return ErrInsufficientBalance
}
err = txn.Commit()
if err != nil {
log.Debug().Err(err).Msg("database error committing transaction")
return ErrDatabase
}
return nil
}
func (u User) sendInternally(
ctx context.Context,
target *User,
anonymous bool,
msats int64,
fees int64,
desc string,
hash string,
tag string,
) error {
if target.Id == u.Id {
return errors.New("Can't pay yourself.")
}
if msats == 0 {
// if nothing was provided, end here
return ErrInvalidAmount
}
var (
descn = sql.NullString{String: desc, Valid: desc != ""}
tagn = sql.NullString{String: tag, Valid: tag != ""}
hashn = sql.NullString{String: hash, Valid: hash != ""}
)
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return ErrDatabase
}
defer txn.Rollback()
// if not tg this will just be ignored
var tgMessageId int
if message := ctx.Value("message"); message != nil {
if m, ok := message.(*tgbotapi.Message); ok {
tgMessageId = m.MessageID
}
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction (
from_id,
to_id,
anonymous,
amount,
fees,
description,
tag,
payment_hash,
trigger_message
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
CASE WHEN $8::text IS NOT NULL
THEN $8::text
ELSE md5(random()::text) || md5(random()::text)
END,
$9
)
`, u.Id, target.Id, anonymous, msats, fees, descn, tagn, hashn, tgMessageId)
if err != nil {
return ErrDatabase
}
balance := getBalance(txn, u.Id)
if balance < 0 {
return ErrInsufficientBalance
}
err = txn.Commit()
if err != nil {
return ErrDatabase
}
return nil
}
func (u User) sendThroughProxy(
ctx context.Context,
// these must be unique across payments that must be combined, otherwise different
sourcehash string,
targethash string,
// ~ this is very important
sourceMessageId int,
targetMessageId int,
target *User,
msats int,
sourcedesc string,
targetdesc string,
pending bool,
tag string,
) (string, error) {
var (
tagn = sql.NullString{String: tag, Valid: tag != ""}
sourcedescn = sql.NullString{String: sourcedesc, Valid: sourcedesc != ""}
targetdescn = sql.NullString{String: targetdesc, Valid: targetdesc != ""}
)
// start transaction
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return "Database error.", err
}
defer txn.Rollback()
// send transaction source->proxy, then proxy->target
// both are updated if exist
_, err = txn.Exec(`
INSERT INTO lightning.transaction AS t
(payment_hash, from_id, to_id, amount, description, tag, trigger_message)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (payment_hash) DO UPDATE SET
amount = t.amount + $4,
description = $5,
tag = $6,
trigger_message = $7
`, sourcehash, u.Id, s.ProxyAccount, msats, sourcedescn, tagn, sourceMessageId)
if err != nil {
return "Database error.", err
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction AS t
(proxied_with, payment_hash, from_id, to_id, amount,
description, tag, trigger_message, pending)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`, sourcehash, targethash, s.ProxyAccount, target.Id, msats,
targetdescn, tagn, targetMessageId, pending)
if err != nil {
return "Database error.", err
}
// check balance
balance := getBalance(txn, u.Id)
if balance < 0 {
return fmt.Sprintf("Insufficient balance. Needs %.3f sat more.",
-float64(balance)/1000),
errors.New("insufficient balance")
}
// check proxy balance (should be always zero)
if err := checkProxyBalance(txn); err != nil {
log.Error().Err(err).Msg("proxy balance check")
return "Database error.", err
}
err = txn.Commit()
if err != nil {
return "Unable to pay due to internal database error.", err
}
return "", nil
}
func (u User) payToInternalService(ctx context.Context, msats int64, desc string, tag string) error {
if msats == 0 {
// if nothing was provided, end here
return ErrInvalidAmount
}
var (
descn = sql.NullString{String: desc, Valid: desc != ""}
tagn = sql.NullString{String: tag, Valid: tag != ""}
)
txn, err := pg.BeginTxx(ctx, &sql.TxOptions{})
if err != nil {
return ErrDatabase
}
defer txn.Rollback()
// if not tg this will just be ignored
var tgMessageId int
if message := ctx.Value("message"); message != nil {
if m, ok := message.(*tgbotapi.Message); ok {
tgMessageId = m.MessageID
}
}
_, err = txn.Exec(`
INSERT INTO lightning.transaction (
from_id,
amount,
description,
tag,
trigger_message
)
VALUES (
$1,
$2,
$3,
$4,
$5
)
`, u.Id, msats, descn, tagn, tgMessageId)
if err != nil {
return ErrDatabase
}
balance := getBalance(txn, u.Id)
if balance < 0 {
return ErrInsufficientBalance
}
err = txn.Commit()
if err != nil {
return ErrDatabase
}
return nil
}
func (u User) setAppData(appname string, data interface{}) (err error) {
j, err := json.Marshal(data)
if err != nil {
return
}
_, err = pg.Exec(`
UPDATE account AS u
SET appdata = jsonb_set(u.appdata, ARRAY[$2], $3, true)
WHERE id = $1
`, u.Id, appname, types.JSONText(j))
return
}
func (u User) getAppData(appname string, data interface{}) (err error) {
var j types.JSONText
err = pg.Get(&j, `
SELECT coalesce(appdata -> $2, '{}'::jsonb)
FROM account
WHERE id = $1
`, u.Id, appname)
if err != nil {
return err
}
err = j.Unmarshal(data)
return
}