/
lnurl-pay.go
266 lines (237 loc) · 10.1 KB
/
lnurl-pay.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
package telegram
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"strings"
"github.com/LightningTipBot/LightningTipBot/internal/network"
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
"github.com/LightningTipBot/LightningTipBot/internal/errors"
"github.com/LightningTipBot/LightningTipBot/internal/runtime/mutex"
"github.com/LightningTipBot/LightningTipBot/internal/storage"
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
lnurl "github.com/fiatjaf/go-lnurl"
log "github.com/sirupsen/logrus"
)
// LnurlPayState saves the state of the user for an LNURL payment
type LnurlPayState struct {
*storage.Base
From *lnbits.User `json:"from"`
LNURLPayParams lnurl.LNURLPayParams `json:"LNURLPayParams"`
LNURLPayValues lnurl.LNURLPayValues `json:"LNURLPayValues"`
Amount int64 `json:"amount"`
Comment string `json:"comment"`
DescriptionHash string `json:"descriptionHash,omitempty"`
LanguageCode string `json:"languagecode"`
}
// lnurlPayHandler is invoked when the first lnurl response was a lnurlpay response
// at this point, the user hans't necessarily entered an amount yet
func (bot *TipBot) lnurlPayHandler(ctx intercept.Context, payParams *LnurlPayState) (context.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, fmt.Errorf("user has no wallet")
}
// object that holds all information about the send payment
id := fmt.Sprintf("lnurlp-%d-%s", m.Sender.ID, RandStringRunes(5))
payParams.Base = storage.New(storage.ID(id))
payParams.From = user
payParams.LanguageCode = ctx.Value("publicLanguageCode").(string)
// first we check whether an amount is present in the command
amount, amount_err := decodeAmountFromCommand(m.Text)
// we need to figure out whether the memo starts at position 2 or 3
// so either /lnurl <amount> <lnurl> [memo] or /lnurl <lnurl> [memo]
memoStartsAt := 2
if amount_err == nil {
// amount was present
memoStartsAt = 3
}
// check if memo is present in command
memo := GetMemoFromCommand(m.Text, memoStartsAt)
// shorten memo to allowed length
if len(memo) > int(payParams.LNURLPayParams.CommentAllowed) {
memo = memo[:payParams.LNURLPayParams.CommentAllowed]
}
if len(memo) > 0 {
payParams.Comment = memo
}
// amount is already present in the command, i.e., /lnurl <amount> <LNURL>
// amount not in allowed range from LNURL
if amount_err == nil &&
(int64(amount) > (payParams.LNURLPayParams.MaxSendable/1000) || int64(amount) < (payParams.LNURLPayParams.MinSendable/1000)) &&
(payParams.LNURLPayParams.MaxSendable != 0 && payParams.LNURLPayParams.MinSendable != 0) { // only if max and min are set
err := fmt.Errorf("amount not in range")
log.Warnf("[lnurlPayHandler] Error: %s", err.Error())
bot.trySendMessage(m.Sender, fmt.Sprintf(Translate(ctx, "lnurlInvalidAmountRangeMessage"), payParams.LNURLPayParams.MinSendable/1000, payParams.LNURLPayParams.MaxSendable/1000))
ResetUserState(user, bot)
return ctx, err
}
// set also amount in the state of the user
payParams.Amount = amount * 1000 // save as mSat
// calculate description hash of the metadata and save it
descriptionHash, err := bot.DescriptionHash(payParams.LNURLPayParams.Metadata, "")
if err != nil {
return nil, err
}
payParams.DescriptionHash = descriptionHash
// add result to persistent struct
runtime.IgnoreError(payParams.Set(payParams, bot.Bunt))
// now we actualy check whether the amount was in the command and if not, ask for it
if payParams.LNURLPayParams.MinSendable == payParams.LNURLPayParams.MaxSendable {
amount = payParams.LNURLPayParams.MaxSendable / 1000
payParams.Amount = amount * 1000 // save as mSat
} else if amount_err != nil || amount < 1 {
// // no amount was entered, set user state and ask for amount
bot.askForAmount(ctx, id, "LnurlPayState", payParams.LNURLPayParams.MinSendable, payParams.LNURLPayParams.MaxSendable, m.Text)
return ctx, nil
}
// We need to save the pay state in the user state so we can load the payment in the next ctx
paramsJson, err := json.Marshal(payParams)
if err != nil {
log.Errorf("[lnurlPayHandler] Error: %s", err.Error())
// bot.trySendMessage(m.Sender, err.Error())
return ctx, err
}
SetUserState(user, bot, lnbits.UserHasEnteredAmount, string(paramsJson))
// directly go to confirm
bot.lnurlPayHandlerSend(ctx)
return ctx, nil
}
// lnurlPayHandlerSend is invoked when the user has delivered an amount and is ready to pay
func (bot *TipBot) lnurlPayHandlerSend(ctx intercept.Context) (intercept.Context, error) {
m := ctx.Message()
user := LoadUser(ctx)
if user.Wallet == nil {
return ctx, errors.Create(errors.UserNoWalletError)
}
statusMsg := bot.trySendMessage(m.Sender, Translate(ctx, "lnurlGettingUserMessage"))
// assert that user has entered an amount
if user.StateKey != lnbits.UserHasEnteredAmount {
log.Errorln("[lnurlPayHandlerSend] state keys don't match")
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, fmt.Errorf("wrong state key")
}
// read the enter amount state from user.StateData
var enterAmountData EnterAmountStateData
err := json.Unmarshal([]byte(user.StateData), &enterAmountData)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
// use the enter amount state of the user to load the LNURL payment state
tx := &LnurlPayState{Base: storage.New(storage.ID(enterAmountData.ID))}
mutex.LockWithContext(ctx, tx.ID)
defer mutex.UnlockWithContext(ctx, tx.ID)
fn, err := tx.Get(tx, bot.Bunt)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
lnurlPayState := fn.(*LnurlPayState)
// LnurlPayState loaded
callbackUrl, err := url.Parse(lnurlPayState.LNURLPayParams.Callback)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
client, err := network.GetClientForScheme(callbackUrl)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
qs := callbackUrl.Query()
// add amount to query string
qs.Set("amount", strconv.FormatInt(lnurlPayState.Amount, 10)) // msat
// add comment to query string
if len(lnurlPayState.Comment) > 0 {
qs.Set("comment", lnurlPayState.Comment)
}
callbackUrl.RawQuery = qs.Encode()
res, err := client.Get(callbackUrl.String())
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Errorf("[lnurlPayHandlerSend] Error: %s", err.Error())
bot.tryEditMessage(statusMsg, Translate(ctx, "errorTryLaterMessage"))
return ctx, err
}
var response2 lnurl.LNURLPayValues
json.Unmarshal(body, &response2)
if response2.Status == "ERROR" || len(response2.PR) < 1 {
error_reason := "Could not receive invoice."
if len(response2.Reason) > 0 {
error_reason = response2.Reason
}
log.Errorf("[lnurlPayHandlerSend] Error in LNURLPayValues: %s", error_reason)
bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "lnurlPaymentFailed"), error_reason))
return ctx, fmt.Errorf("error in LNURLPayValues: %s", error_reason)
}
// todo: doesn't work with lnurls from lnbits??
// check whether description hash matches with expected hash
// decode invoice
// bolt11, err := decodepay.Decodepay(response2.PR)
// if err != nil {
// bot.trySendMessage(ctx.Sender(), helpPayInvoiceUsage(ctx, Translate(ctx, "invalidInvoiceHelpMessage")))
// errmsg := fmt.Sprintf("[/pay] Error: Could not decode invoice: %s", err.Error())
// log.Errorln(errmsg)
// return ctx, errors.New(errors.InvalidSyntaxError, err)
// }
// if bolt11.DescriptionHash != lnurlPayState.DescriptionHash {
// log.Errorf("[lnurlPayHandlerSend] Error: description hash doesn't match")
// bot.tryEditMessage(statusMsg, fmt.Sprintf(Translate(ctx, "errorReasonMessage"), "description hash doesn't match.\nExpected: `"+lnurlPayState.DescriptionHash+"` Received: `"+bolt11.DescriptionHash+"`"))
// return ctx, fmt.Errorf("description hash doesn't match")
// }
// all good
lnurlPayState.LNURLPayValues = response2
// add result to persistent struct
runtime.IgnoreError(lnurlPayState.Set(lnurlPayState, bot.Bunt))
bot.Telegram.Delete(statusMsg)
m.Text = fmt.Sprintf("/pay %s", response2.PR)
return bot.payHandler(ctx)
}
func (bot *TipBot) sendToLightningAddress(ctx intercept.Context, address string, amount int64) (intercept.Context, error) {
m := ctx.Message()
split := strings.Split(address, "@")
if len(split) != 2 {
return ctx, fmt.Errorf("lightning address format wrong")
}
host := strings.ToLower(split[1])
name := strings.ToLower(split[0])
// convert address scheme into LNURL Bech32 format
callback := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", host, name)
log.Infof("[sendToLightningAddress] %s: callback: %s", GetUserStr(m.Sender), callback)
lnurl, err := lnurl.LNURLEncode(callback)
if err != nil {
return ctx, err
}
if amount > 0 {
// only when amount is given, we will also add a comment to the command
// we do this because if the amount is not given, we will have to ask for it later
// in the lnurl handler and we don't want to add another step where we ask for a comment
// the command to pay to lnurl with comment is /lnurl <amount> <lnurl> <comment>
// check if comment is presentin lnrul-p
memo := GetMemoFromCommand(m.Text, 3)
m.Text = fmt.Sprintf("/lnurl %d %s", amount, lnurl)
// shorten comment to allowed length
if len(memo) > 0 {
m.Text = m.Text + " " + memo
}
} else {
// no amount was given so we will just send the lnurl
// this will invoke the "enter amount" dialog in the lnurl handler
m.Text = fmt.Sprintf("/lnurl %s", lnurl)
}
return bot.lnurlHandler(ctx)
}