-
Notifications
You must be signed in to change notification settings - Fork 25
/
invoice.go
258 lines (220 loc) · 6.25 KB
/
invoice.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
package main
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"strconv"
"time"
"github.com/docopt/docopt-go"
"github.com/fiatjaf/go-lnurl"
"github.com/fiatjaf/lntxbot/t"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
cmap "github.com/orcaman/concurrent-map"
"gopkg.in/antage/eventsource.v1"
)
type InvoiceData struct {
UserId int
MessageId interface{}
Preimage string
*MakeInvoiceArgs
}
func (inv InvoiceData) Hash() string {
preimage, err := hex.DecodeString(inv.Preimage)
if err != nil {
log.Error().Err(err).Interface("data", inv).
Msg("failed to decode preimage on InvoiceData")
return ""
}
hash := sha256.Sum256(preimage)
return hex.EncodeToString(hash[:])
}
type MakeInvoiceArgs struct {
IgnoreRateLimit bool
Description string
DescriptionHash string
Msatoshi int64
Expiry *time.Duration
Tag string
Extra InvoiceExtra
BlueWallet bool
}
type InvoiceExtra struct {
// lnurlpay comment
Comment string
// lnurlpay payerdata
PayerData *lnurl.PayerDataValues
// webhook
Webhook string
// telegram message
Message *tgbotapi.Message
}
var waitingInvoices = cmap.New() // make(map[string][]chan Invoice)
func waitInvoice(hash string) (inv <-chan InvoiceData) {
wait := make(chan InvoiceData)
waitingInvoices.Upsert(hash, wait,
func(exists bool, arr interface{}, v interface{}) interface{} {
if exists {
return append(arr.([]interface{}), v)
} else {
return []interface{}{v}
}
},
)
return wait
}
func resolveWaitingInvoice(hash string, inv InvoiceData) {
if chans, ok := waitingInvoices.Get(hash); ok {
for _, ch := range chans.([]interface{}) {
select {
case ch.(chan InvoiceData) <- inv:
default:
}
}
waitingInvoices.Remove(hash)
}
}
func handleInvoice(ctx context.Context, opts docopt.Opts, desc string) {
u := ctx.Value("initiator").(*User)
if opts["lnurl"].(bool) {
// print static lnurl-pay for this user
code := createLNURLPayCode(u, "")
send(ctx, qrURL(code), code)
go u.track("print lnurl", nil)
} else {
msats, err := parseSatoshis(opts)
if err != nil {
if opts["any"].(bool) {
msats = 0
} else {
handleHelp(ctx, "receive")
return
}
}
go u.track("make invoice", map[string]interface{}{"sats": msats / 1000})
if desc == "" {
desc = "to @lntxbot"
}
bolt11, _, err := u.makeInvoice(ctx, &MakeInvoiceArgs{
Msatoshi: msats,
Description: u.Username + ": " + desc,
Extra: InvoiceExtra{Message: ctx.Value("message").(*tgbotapi.Message)},
})
if err != nil {
log.Warn().Err(err).Msg("failed to generate invoice")
send(ctx, u, t.FAILEDINVOICE, t.T{"Err": err.Error()})
return
}
// send invoice with qr code
send(ctx, qrURL(bolt11), "<pre>"+bolt11+"</pre>")
}
}
// what happens when a payment is received
var userPaymentStream = cmap.New() // make(map[int]eventsource.EventSource)
func paymentReceived(
ctx context.Context,
hash string,
amount int64,
) (user *User, err error) {
data, err := loadInvoiceData(hash)
if err != nil {
log.Debug().Err(err).Interface("hash", hash).
Msg("no invoice stored for this hash, not a bot invoice?")
return
}
user, err = loadUser(data.UserId)
if err != nil {
log.Error().Err(err).Int("user-id", data.UserId).Interface("data", data).
Msg("couldn't load user on paymentReceived")
return
}
_, err = pg.Exec(`
INSERT INTO lightning.transaction
(to_id, amount, description, payment_hash, preimage, tag)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (payment_hash) DO UPDATE SET to_id = $1
`, user.Id, amount, data.Description, hash,
data.Preimage, sql.NullString{String: data.Tag, Valid: data.Tag != ""})
if err != nil {
log.Error().Err(err).
Stringer("user", user).Str("hash", hash).
Msg("failed to save payment received.")
send(ctx, user, t.FAILEDTOSAVERECEIVED, t.T{"Hash": hash}, data.MessageId)
return
}
go resolveWaitingInvoice(hash, data)
user.track("got payment", map[string]interface{}{
"sats": amount / 1000,
})
// send to user stream if the user is listening
if ies, ok := userPaymentStream.Get(strconv.Itoa(user.Id)); ok {
go ies.(eventsource.EventSource).SendEventMessage(
`{"payment_hash": "`+hash+`", "msatoshi": `+
strconv.FormatInt(data.Msatoshi, 10)+`}`,
"payment-received", "")
}
tmplParams := t.T{
"Sats": data.Msatoshi / 1000,
"Hash": hash[:5],
}
if comment := data.Extra.Comment; comment != "" {
tmplParams["Comment"] = comment
}
if payer := data.Extra.PayerData; payer != nil {
tmplParams["SenderName"] = senderNameFromPayerData(*payer)
}
send(ctx, user, t.PAYMENTRECEIVED, tmplParams)
return
}
func saveInvoiceData(hash string, data InvoiceData) error {
b, _ := json.Marshal(data)
return rds.Set("invdata:"+hash, string(b), *data.Expiry).Err()
}
func loadInvoiceData(hash string) (data InvoiceData, err error) {
b, err := rds.Get("invdata:" + hash).Result()
if err != nil {
return
}
err = json.Unmarshal([]byte(b), &data)
return
}
func checkAllIncomingPayments(ctx context.Context) {
// TODO
// from := time.Now().AddDate(0, 0, -7)
// var lastInvoiceTime time.Time
// err := pg.Get(&lastInvoiceTime, `
// SELECT max(time) FROM lightning.transaction WHERE from_id IS NULL
// `)
// if err != nil {
// log.Error().Err(err).Msg("failed to get last invoice time from db")
// }
// if lastInvoiceTime.Before(from) {
// from = lastInvoiceTime
// }
// res, err := ln.Call("audit", eclair.Params{"from": from.Unix()})
// if err != nil {
// log.Error().Err(err).Msg("failed to call 'audit'")
// return
// }
// log.Debug().Time("from", from).Int64("n", res.Get("received.#").Int()).
// Msg("checking incoming payments")
// for _, recv := range res.Get("received").Array() {
// hash := recv.Get("paymentHash").String()
// var exists bool
// if err := pg.Get(&exists, `
// SELECT true FROM lightning.transaction
// WHERE payment_hash = $1
// `, hash); err != nil && err != sql.ErrNoRows {
// log.Error().Err(err).Str("hash", hash).Msg("checking existence of invoice hash")
// continue
// }
// if !exists {
// var amount int64 = 0
// for _, part := range recv.Get("parts").Array() {
// amount += part.Get("amount").Int()
// }
// go paymentReceived(ctx, hash, amount)
// }
// }
}