forked from fiatjaf/lntxbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lnurl-service.go
315 lines (266 loc) · 8.69 KB
/
lnurl-service.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
package main
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/docopt/docopt-go"
"github.com/fiatjaf/go-lnurl"
decodepay "github.com/fiatjaf/ln-decodepay"
"github.com/fiatjaf/lntxbot/t"
"github.com/gorilla/mux"
)
func handleCreateLNURLWithdraw(ctx context.Context, opts docopt.Opts) (enc string) {
u := ctx.Value("initiator").(User)
maxMSats, err := parseSatoshis(opts)
if err != nil {
send(ctx, u, t.ERROR, t.T{"Err": err.Error()})
return
}
maxSats := maxMSats / 1000
go u.track("lnurl generate", map[string]interface{}{"sats": maxSats})
challenge := hashString("%s:%d:%d", s.TelegramBotToken, u.Id, maxSats)
nexturl := fmt.Sprintf("%s/lnurl/withdraw?challenge=%s", s.ServiceURL, challenge)
rds.Set("lnurlwithdraw:"+challenge,
fmt.Sprintf(`%d-%d`, u.Id, maxSats), 30*time.Minute)
enc, err = lnurl.LNURLEncode(nexturl)
if err != nil {
log.Error().Err(err).Msg("error encoding lnurl on withdraw")
return
}
send(ctx, u, qrURL(enc), `<code>`+enc+"</code>")
return
}
func serveLNURL() {
ctx := context.WithValue(context.Background(), "origin", "external")
router.Path("/lnurl/withdraw").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug().Str("url", r.URL.String()).Msg("lnurl-withdraw first request")
qs := r.URL.Query()
challenge := qs.Get("challenge")
if challenge == "" {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Malformed lnurl."))
return
}
val, err := rds.Get("lnurlwithdraw:" + challenge).Result()
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Unknown lnurl."))
return
}
// get user id and maxWithdrawable from redis value
parts := strings.Split(val, "-")
if len(parts) != 2 {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Internal mismatch."))
return
}
chUserId, err1 := strconv.Atoi(parts[0])
chMax, err2 := strconv.Atoi(parts[1])
if err1 != nil || err2 != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Internal mismatch."))
return
}
u, err := loadUser(chUserId)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Couldn't load withdrawee user."))
return
}
json.NewEncoder(w).Encode(lnurl.LNURLWithdrawResponse{
Callback: fmt.Sprintf("%s/lnurl/withdraw/invoice", s.ServiceURL),
K1: challenge,
MaxWithdrawable: 1000 * int64(chMax),
MinWithdrawable: 1000 * int64(chMax),
DefaultDescription: fmt.Sprintf(
"%s lnurl withdraw from %s", u.AtName(ctx), s.ServiceId),
Tag: "withdrawRequest",
LNURLResponse: lnurl.OkResponse(),
})
})
router.Path("/lnurl/withdraw/invoice").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(context.Background(), "origin", "external")
log.Debug().Str("url", r.URL.String()).Msg("lnurl second request")
qs := r.URL.Query()
challenge := qs.Get("k1")
bolt11 := qs.Get("pr")
val, err := rds.Get("lnurlwithdraw:" + challenge).Result()
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Unknown lnurl."))
return
}
// get user id and maxWithdrawable from redis value
parts := strings.Split(val, "-")
if len(parts) != 2 {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Internal mismatch."))
return
}
chUserId, err1 := strconv.Atoi(parts[0])
chMax, err2 := strconv.Atoi(parts[1])
if err1 != nil || err2 != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Internal mismatch."))
return
}
payer, err := loadUser(chUserId)
if err != nil {
json.NewEncoder(w).Encode(
lnurl.ErrorResponse("Couldn't load withdrawee user."))
return
}
// double-check the challenge (it's a hash of the parameters + our secret)
if challenge != hashString("%s:%d:%d", s.TelegramBotToken, payer.Id, chMax) {
json.NewEncoder(w).Encode(
lnurl.ErrorResponse("Invalid amount for this lnurl."))
return
}
if err := rds.Del("lnurlwithdraw:" + challenge).Err(); err != nil {
// if error stop here to prevent extra withdrawals
log.Error().Err(err).Str("challenge", challenge).
Msg("error deleting used challenge on lnurl withdraw")
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Redis error. Please report."))
return
}
inv, err := decodepay.Decodepay(bolt11)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Invalid payment request."))
return
}
if inv.MSatoshi > int64(chMax)*1000 {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Amount too big."))
return
}
// print the bolt11 just because
send(ctx, payer, bolt11, ctx.Value("message"))
go payer.track("outgoing lnurl-withdraw redeemed", map[string]interface{}{
"sats": float64(inv.MSatoshi) / 1000,
})
// do the pay flow with these odd opts and fake message.
opts := docopt.Opts{
"pay": true,
"<invoice>": bolt11,
"now": true,
}
handlePay(ctx, payer, opts)
json.NewEncoder(w).Encode(lnurl.OkResponse())
})
router.Path("/lnurl/pay").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug().Str("url", r.URL.String()).Msg("lnurl-pay first request")
qs := r.URL.Query()
username := qs.Get("username")
if username == "" {
username = qs.Get("userid")
}
u, params, err := lnurlPayUserParams(ctx, username)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Invalid username or id."))
return
}
go u.track("incoming lnurl-pay attempt", nil)
json.NewEncoder(w).Encode(params)
})
router.Path("/.well-known/lnurlp/{username}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(context.Background(), "origin", "external")
username := mux.Vars(r)["username"]
qs := r.URL.Query()
receiver, params, err := lnurlPayUserParams(ctx, username)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Invalid username or id."))
return
}
if amount := qs.Get("amount"); amount == "" {
log.Debug().Str("url", r.URL.String()).Msg("lnurl-pay first request")
go receiver.track("incoming lnurl-pay attempt", nil)
json.NewEncoder(w).Encode(params)
} else {
log.Debug().Str("url", r.URL.String()).Str("amount", amount).
Msg("lnurl-pay second request")
// amount
msatoshi, err := strconv.ParseInt(amount, 10, 64)
if err != nil {
json.NewEncoder(w).Encode(lnurl.ErrorResponse("Invalid msatoshi amount."))
return
}
// payer data
var hhash [32]byte
payerdata := qs.Get("payerdata")
if payerdata == "" {
hhash = params.HashMetadata()
} else {
hhash = params.HashWithPayerData(payerdata)
}
var payerData lnurl.PayerDataValues
json.Unmarshal([]byte(payerdata), &payerData)
// webhook
webhook := qs.Get("webhook")
bolt11, _, err := receiver.makeInvoice(ctx, &MakeInvoiceArgs{
IgnoreInvoiceSizeLimit: true,
Msatoshi: msatoshi,
DescriptionHash: hex.EncodeToString(hhash[:]),
Extra: InvoiceExtra{
Comment: qs.Get("comment"),
PayerData: &payerData,
Webhook: webhook,
},
})
if err != nil {
log.Warn().Err(err).Msg("failed to generate lnurl-pay invoice")
json.NewEncoder(w).Encode(
lnurl.ErrorResponse("Failed to generate invoice."))
return
}
json.NewEncoder(w).Encode(lnurl.LNURLPayValues{
LNURLResponse: lnurl.OkResponse(),
PR: bolt11,
Routes: []struct{}{},
Disposable: lnurl.FALSE,
})
}
})
}
func lnurlPayUserParams(
ctx context.Context,
username string,
) (receiver User, params lnurl.LNURLPayParams, err error) {
isTelegramUsername := false
if id, errx := strconv.Atoi(username); errx == nil {
// case in which username is a number
receiver, err = loadUser(id)
} else {
// case in which username is a real username
receiver, err = ensureTelegramUsername(username)
isTelegramUsername = true
}
if err != nil {
return
}
var metadata lnurl.Metadata
metadata.Description = fmt.Sprintf("Fund %s account on t.me/%s.",
receiver.AtName(ctx), s.ServiceId)
if isTelegramUsername {
// get user avatar from public t.me/ page
if b, err := getTelegramUserPicture(username); err == nil {
metadata.Image.Bytes = b
metadata.Image.Ext = "jpeg"
}
// add internet identifier
metadata.LightningAddress = fmt.Sprintf("%s@%s",
username, getHost())
}
params = lnurl.LNURLPayParams{
LNURLResponse: lnurl.OkResponse(),
Tag: "payRequest",
Callback: fmt.Sprintf("%s/.well-known/lnurlp/%s",
s.ServiceURL, username),
MaxSendable: 1000000000,
MinSendable: 100000,
Metadata: metadata,
CommentAllowed: 422,
PayerData: lnurl.PayerDataSpec{
FreeName: &lnurl.PayerDataItemSpec{},
LightningAddress: &lnurl.PayerDataItemSpec{},
Email: &lnurl.PayerDataItemSpec{},
},
}
params.EncodedMetadata = params.MetadataEncoded()
return
}