-
Notifications
You must be signed in to change notification settings - Fork 25
/
lnurl.go
484 lines (413 loc) · 13.1 KB
/
lnurl.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
package account
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/mail"
"net/url"
"strings"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/zpay32"
"github.com/tyler-smith/go-bip32"
"github.com/fiatjaf/go-lnurl"
"github.com/breez/breez/data"
)
type LoginResponse struct {
lnurl.LNURLResponse
Token string `json:"token"`
}
func (a *Service) HandleLNURL(rawString string) (result *data.LNUrlResponse, err error) {
var lightningAddress string
handleLNUrlError := fmt.Errorf("%q does not contain an LNURL", rawString)
encodedLnurl, ok := lnurl.FindLNURLInText(rawString)
if !ok {
// ref. Lightning-Address https://github.com/andrerfneves/lightning-address/blob/master/DIY.md
parsedAddress, err := mail.ParseAddress(rawString)
if err != nil {
return nil, fmt.Errorf("%v : %w", handleLNUrlError, err)
}
parts := strings.Split(parsedAddress.Address, "@")
if len(parts) != 2 {
return nil, fmt.Errorf("%w : %q is not an e-mail address", handleLNUrlError, parsedAddress.Address)
}
lightningAddress = parsedAddress.Address
var url url.URL
if strings.Contains(parts[1], ".onion") {
url.Scheme = "http"
} else {
url.Scheme = "https"
}
url.Host = parts[1]
url.Path = ".well-known/lnurlp/" + parts[0]
encodedLnurl = url.String()
}
lnurl.Client.Timeout = time.Second * 60
rawurl, iparams, err := lnurl.HandleLNURL(encodedLnurl)
if err != nil {
return nil, fmt.Errorf("%s : %w", handleLNUrlError, err)
}
switch params := iparams.(type) {
case lnurl.LNURLAuthParams:
return &data.LNUrlResponse{
Action: &data.LNUrlResponse_Auth{
Auth: &data.LNURLAuth{
Tag: params.Tag,
Callback: params.Callback,
K1: params.K1,
Host: params.Host,
},
},
}, nil
case lnurl.LNURLWithdrawResponse:
qs := params.CallbackURL.Query()
qs.Set("k1", params.K1)
params.CallbackURL.RawQuery = qs.Encode()
a.lnurlWithdrawing = params.CallbackURL.String()
a.log.Infof("lnurl response: %v", a.lnurlWithdrawing)
return &data.LNUrlResponse{
Action: &data.LNUrlResponse_Withdraw{
Withdraw: &data.LNUrlWithdraw{
MinAmount: int64(math.Ceil(
float64(params.MinWithdrawable) / 1000,
)),
MaxAmount: int64(math.Floor(
float64(params.MaxWithdrawable) / 1000,
)),
DefaultDescription: params.DefaultDescription,
},
},
}, nil
case lnurl.LNURLChannelResponse:
return &data.LNUrlResponse{
Action: &data.LNUrlResponse_Channel{
Channel: &data.LNURLChannel{
K1: params.K1,
Callback: params.Callback,
Uri: params.URI,
},
},
}, nil
case lnurl.LNURLPayParams:
/* 2. `LN WALLET` gets JSON response from `LN SERVICE` of form:
{
callback: String, // the URL from LN SERVICE which will accept the pay request parameters
maxSendable: MilliSatoshi, // max amount LN SERVICE is willing to receive
minSendable: MilliSatoshi, // min amount LN SERVICE is willing to receive, can not be less than 1 or more than `maxSendable`
metadata: String, // metadata json which must be presented as raw string here, this is required to pass signature verification at a later step
commentAllowed: Number, // optional number of characters accepted for the `comment` query parameter on subsequent callback, defaults to 0 if not provided. (no comment allowed)
tag: "payRequest" // type of LNURL
}
*/
a.log.Info("lnurl.LNURLPayParams.")
host := ""
if url, err := url.Parse(rawurl); err == nil {
host = url.Host
}
a.lnurlPayMetadata.encoded = params.EncodedMetadata
a.lnurlPayMetadata.data = [][]string{}
return &data.LNUrlResponse{
Action: &data.LNUrlResponse_PayResponse1{
PayResponse1: &data.LNURLPayResponse1{
Host: host,
LightningAddress: lightningAddress,
Callback: params.Callback,
MinAmount: int64(math.Floor(float64(params.MinSendable) / 1000)),
MaxAmount: int64(math.Floor(float64(params.MaxSendable) / 1000)),
CommentAllowed: params.CommentAllowed,
Metadata: []*data.LNUrlPayMetadata{
{
Entry: []string{},
Description: params.Metadata.Description,
LongDescription: params.Metadata.LongDescription,
Image: &data.LNUrlPayImage{
DataUri: params.Metadata.Image.DataURI,
Ext: params.Metadata.Image.Ext,
Bytes: params.Metadata.Image.Bytes,
},
},
},
},
},
}, nil
default:
return nil, errors.New("Unsupported LNURL")
}
}
// FinishLNURLAuth logs in using lnurl auth protocol
func (a *Service) FinishLNURLAuth(authParams *data.LNURLAuth) (string, error) {
key, err := a.getLNURLAuthKey()
if err != nil {
return "", err
}
// hash host using master key
h := hmac.New(sha256.New, key.Key)
if _, err := h.Write([]byte(authParams.Host)); err != nil {
return "", err
}
sha := h.Sum(nil)
// create 4 elements derivation path using hashed value.
first16 := sha[:16]
for i := 0; i < 4; i++ {
nextChildIndex := binary.BigEndian.Uint32(first16[i*4 : i*4+4])
for key, err = key.NewChildKey(nextChildIndex); err != nil; {
nextChildIndex++
}
}
// this is the result keypair.
linkingPrivKey, linkingPubKey := btcec.PrivKeyFromBytes(key.Key)
k1Decoded, err := hex.DecodeString(authParams.K1)
if err != nil {
return "", fmt.Errorf("failed to decode k1 challenge %w", err)
}
// sign the challenge
sig := ecdsa.Sign(linkingPrivKey, k1Decoded)
//convert to DER
wireSig, err := lnwire.NewSigFromSignature(sig)
if err != nil {
return "", fmt.Errorf("can't convert sig to wire format: %v", err)
}
der := wireSig.ToSignatureBytes()
// call the service
url, err := url.Parse(authParams.Callback)
if err != nil {
return "", fmt.Errorf("invalid callback url %v", err)
}
query := url.Query()
query.Add("key", hex.EncodeToString(linkingPubKey.SerializeCompressed()))
query.Add("sig", hex.EncodeToString(der))
if authParams.Jwt {
query.Add("jwt", "true")
}
url.RawQuery = query.Encode()
client := &http.Client{}
if tor := a.TorConfig; tor != nil {
a.log.Info("FinishLNURLAuth: using Tor")
if client, err = tor.NewHttpClient(); err != nil {
return "", err
}
}
resp, err := client.Get(url.String())
if err != nil {
return "", err
}
// check response
var lnurlresp LoginResponse
err = json.NewDecoder(resp.Body).Decode(&lnurlresp)
if err != nil {
return "", err
}
if lnurlresp.Status == "ERROR" {
return "", errors.New(lnurlresp.Reason)
}
return lnurlresp.Token, nil
}
func (a *Service) FinishLNURLWithdraw(bolt11 string) (err error) {
a.log.Info("FinishLNURLWithdraw")
callback := a.lnurlWithdrawing
client := &http.Client{}
if tor := a.TorConfig; tor != nil {
a.log.Info("FinishLNURLWithdraw: using Tor")
if client, err = tor.NewHttpClient(); err != nil {
return err
}
}
resp, err := client.Get(callback + "&pr=" + bolt11)
if err != nil {
a.log.Errorf("FinishLNURLWithdraw request error:", err.Error())
return err
}
if resp.StatusCode == 204 {
a.log.Info("FinishLNURLWithdraw response code: 204, skipping body parsing")
return nil
} else {
a.log.Infof("FinishLNURLWithdraw response code:", resp.StatusCode)
}
var lnurlresp lnurl.LNURLResponse
err = json.NewDecoder(resp.Body).Decode(&lnurlresp)
if err != nil {
a.log.Errorf("FinishLNURLWithdraw parse error:", err.Error())
return err
}
if lnurlresp.Status == "ERROR" {
a.log.Errorf("FinishLNURLWithdraw lnurl response error:", lnurlresp.Reason)
return errors.New(lnurlresp.Reason)
}
a.log.Info("FinishLNURLWithdraw ends without errors")
return nil
}
func (a *Service) getLNURLAuthKey() (*bip32.Key, error) {
needsBackup := false
key, err := a.breezDB.FetchLNURLAuthKey(func() ([]byte, error) {
needsBackup = true
return bip32.NewSeed()
})
if err != nil {
return nil, fmt.Errorf("failed to fetch lnurl key %w", err)
}
if needsBackup {
a.requestBackup()
}
// Create master private key from seed
masterKey, err := bip32.NewMasterKey(key)
if err != nil {
return nil, fmt.Errorf("error creating lnurl master key: %w", err)
}
return masterKey, nil
}
func (a *Service) FinishLNURLPay(params *data.LNURLPayResponse1) (*data.LNUrlPayInfo, error) {
// Ref. https://github.com/lnurl/luds/blob/luds/06.md
a.log.Infof("FinishLNURLPay: params: %+v", params)
/*
5. LN WALLET makes a GET request using
{
<callback><?|&>amount=<milliSatoshi>
}
`amount` being the amount specified by the user in millisatoshis.
*/
url, err := url.Parse(params.Callback)
if err != nil {
return nil, fmt.Errorf("invalid callback url %v", err)
}
query := url.Query()
query.Add("amount", fmt.Sprintf("%d", params.Amount))
// source: backup/crypto.go
nonce := make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
query.Add("nonce", hex.EncodeToString(nonce))
if params.CommentAllowed > 0 && params.Comment != "" {
query.Add("comment", params.Comment)
}
url.RawQuery = query.Encode()
a.log.Infof("FinishLNURLPay: request.url: %v", url)
client := &http.Client{}
if tor := a.TorConfig; tor != nil {
a.log.Info("FinishLNURLPay: using Tor")
if client, err = tor.NewHttpClient(); err != nil {
return nil, err
}
}
resp, err := client.Get(url.String())
if err != nil {
return nil, err
}
if (resp.StatusCode < 200 || resp.StatusCode >= 300) && resp.StatusCode != 320 {
return nil, fmt.Errorf("error in http request: %s", resp.Status)
}
a.log.Infof("FinishLNURLPay: response.Status: %s", resp.Status)
/*
6. `LN Service` takes the GET request and returns JSON response of form:
```Typescript
{
pr: string, // bech32-serialized lightning invoice
routes: [] // an empty array
}
```
or
```JSON
{"status":"ERROR", "reason":"error details..."}
```
*/
var payResponse2 lnurl.LNURLPayValues
if err = json.NewDecoder(resp.Body).Decode(&payResponse2); err != nil {
return nil, err
}
if payResponse2.Status == "ERROR" {
return nil, errors.New(payResponse2.Reason)
}
a.log.Infof("FinishLNURLPay: payResponse2 %+v", payResponse2)
// 7. `LN WALLET` Verifies that `h` tag in provided invoice is a hash of `metadata` string converted to byte array in UTF-8 encoding.
invoice, err := zpay32.Decode(payResponse2.PR, a.activeParams)
if err != nil {
return nil, err
}
/* 8. `LN WALLET` Verifies that amount in provided invoice equals an amount previously specified by user.
amount from client is in millisats.
*/
a.log.Info("FinishLNURLPay: verify invoice.amount == params.Amount.")
if params.Amount != uint64(*invoice.MilliSat) {
return nil, errors.New("invoice amount does not match the amount set by user")
}
// If `successAction` is not null: `LN WALLET` makes sure that `tag` value of is of supported type, aborts a payment otherwise.
sa := payResponse2.SuccessAction
var _sa *data.SuccessAction
if sa != nil {
if t := sa.Tag; t != "message" &&
t != "url" &&
t != "aes" {
return nil, fmt.Errorf("unknown SuccessAction: %s", t)
}
_sa = &data.SuccessAction{
Tag: sa.Tag,
Description: sa.Description,
Url: sa.URL,
Message: sa.Message,
Ciphertext: sa.Ciphertext,
Iv: sa.IV,
}
a.log.Infof("FinishLNURLPay: Found SuccessAction: %+v", *sa)
}
// 8.`LN WALLET` pays the invoice, no additional user confirmation is required at this point.
info := &data.LNUrlPayInfo{
PaymentHash: hex.EncodeToString(invoice.PaymentHash[:]),
SuccessAction: _sa,
Comment: params.Comment,
InvoiceDescription: description(a.lnurlPayMetadata.data),
Host: params.Host,
LightningAddress: params.LightningAddress,
Metadata: params.Metadata,
Invoice: payResponse2.PR,
}
a.breezDB.SaveLNUrlPayInfo(info)
return info, nil
}
func (a *Service) DecryptLNUrlPayMessage(paymentHash string, preimage []byte) (string, error) {
info, err := a.breezDB.FetchLNUrlPayInfo(paymentHash)
if err != nil {
return "",
fmt.Errorf("Unable to get LNUrl-Pay info from database: %s", err)
}
if info != nil {
sa := &lnurl.SuccessAction{
Tag: info.SuccessAction.Tag,
Description: info.SuccessAction.Description,
URL: info.SuccessAction.Url,
Message: info.SuccessAction.Message,
Ciphertext: info.SuccessAction.Ciphertext,
IV: info.SuccessAction.Iv,
}
if sa.Ciphertext == "" {
return "", errors.New("LNUrl-Pay CipherText is empty.")
}
if info.SuccessAction.Message, err = sa.Decipher(preimage); err != nil {
return "", fmt.Errorf("Could not decrypt message: %v", err)
}
if err = a.breezDB.SaveLNUrlPayInfo(info); err != nil {
return "", fmt.Errorf("Could not save deciphered message: %s", err)
}
a.log.Info("DecryptLNUrlPayMessage: message = %q", info.SuccessAction.Message)
return info.SuccessAction.Message, nil
}
return "", errors.New("DecryptLNUrlPayMessage: could not find lnUrlPayInfo with given paymentHash.")
}
// / Returns the description from the metadata.
func description(metadata [][]string) string {
for _, e := range metadata {
if e[0] == "text/plain" {
return e[1]
}
}
return ""
}