-
Notifications
You must be signed in to change notification settings - Fork 30
/
service.go
348 lines (325 loc) · 10.4 KB
/
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
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
package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip04"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type Service struct {
cfg *Config
db *gorm.DB
lnClient LNClient
ReceivedEOS bool
Logger *logrus.Logger
}
/*var supportedMethods = map[string]bool{
NIP_47_PAY_INVOICE_METHOD: true,
NIP_47_GET_BALANCE_METHOD: true,
NIP_47_GET_INFO_METHOD: true,
NIP_47_MAKE_INVOICE_METHOD: true,
NIP_47_LOOKUP_INVOICE_METHOD: true,
NIP_47_LIST_TRANSACTIONS_METHOD: true,
}*/
func (svc *Service) GetUser(c echo.Context) (user *User, err error) {
sess, _ := session.Get(CookieName, c)
userID := sess.Values["user_id"]
if svc.cfg.LNBackendType == LNDBackendType {
//if we self-host, there is always only one user
userID = 1
}
if userID == nil {
return nil, nil
}
user = &User{}
err = svc.db.Preload("Apps").First(&user, userID).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return
}
func (svc *Service) StartSubscription(ctx context.Context, sub *nostr.Subscription) error {
go func() {
<-sub.EndOfStoredEvents
svc.ReceivedEOS = true
svc.Logger.Info("Received EOS")
}()
go func() {
for event := range sub.Events {
go func(event *nostr.Event) {
resp, err := svc.HandleEvent(ctx, event)
if err != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
}).Errorf("Failed to process event: %v", err)
}
if resp != nil {
status, err := sub.Relay.Publish(ctx, *resp)
if err != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"status": status,
"replyEventId": resp.ID,
}).Errorf("Failed to publish reply: %v", err)
return
}
nostrEvent := NostrEvent{}
result := svc.db.Where("nostr_id = ?", event.ID).First(&nostrEvent)
if result.Error != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"status": status,
"replyEventId": resp.ID,
}).Error(result.Error)
return
}
nostrEvent.ReplyId = resp.ID
if status == nostr.PublishStatusSucceeded {
nostrEvent.State = NOSTR_EVENT_STATE_PUBLISH_CONFIRMED
nostrEvent.RepliedAt = time.Now()
svc.db.Save(&nostrEvent)
svc.Logger.WithFields(logrus.Fields{
"nostrEventId": nostrEvent.ID,
"eventId": event.ID,
"status": status,
"replyEventId": resp.ID,
"appId": nostrEvent.AppId,
}).Info("Published reply")
} else if status == nostr.PublishStatusFailed {
nostrEvent.State = NOSTR_EVENT_STATE_PUBLISH_FAILED
svc.db.Save(&nostrEvent)
svc.Logger.WithFields(logrus.Fields{
"nostrEventId": nostrEvent.ID,
"eventId": event.ID,
"status": status,
"replyEventId": resp.ID,
"appId": nostrEvent.AppId,
}).Info("Failed to publish reply")
} else {
nostrEvent.State = NOSTR_EVENT_STATE_PUBLISH_UNCONFIRMED
svc.db.Save(&nostrEvent)
svc.Logger.WithFields(logrus.Fields{
"nostrEventId": nostrEvent.ID,
"eventId": event.ID,
"status": status,
"replyEventId": resp.ID,
"appId": nostrEvent.AppId,
}).Info("Reply sent but no response from relay (timeout)")
}
}
}(event)
}
svc.Logger.Info("Subscription ended")
}()
select {
case <-sub.Relay.Context().Done():
svc.Logger.Errorf("Relay error %v", sub.Relay.ConnectionError)
return sub.Relay.ConnectionError
case <-ctx.Done():
if ctx.Err() != context.Canceled {
svc.Logger.Errorf("Subscription error %v", ctx.Err())
return ctx.Err()
}
svc.Logger.Info("Exiting subscription.")
return nil
}
}
func (svc *Service) HandleEvent(ctx context.Context, event *nostr.Event) (result *nostr.Event, err error) {
//don't process historical events
if !svc.ReceivedEOS {
return nil, nil
}
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
}).Info("Processing Event")
// make sure we don't know the event, yet
nostrEvent := NostrEvent{}
findEventResult := svc.db.Where("nostr_id = ?", event.ID).Find(&nostrEvent)
if findEventResult.RowsAffected != 0 {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
}).Warn("Event already processed")
return nil, nil
}
app := App{}
err = svc.db.Preload("User").First(&app, &App{
NostrPubkey: event.PubKey,
}).Error
if err != nil {
ss, err := nip04.ComputeSharedSecret(event.PubKey, svc.cfg.NostrSecretKey)
if err != nil {
return nil, err
}
resp, _ := svc.createResponse(event, Nip47Response{
Error: &Nip47Error{
Code: NIP_47_ERROR_UNAUTHORIZED,
Message: "The public key does not have a wallet connected.",
},
}, ss)
return resp, err
}
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Info("App found for nostr event")
//to be extra safe, decrypt using the key found from the app
ss, err := nip04.ComputeSharedSecret(app.NostrPubkey, svc.cfg.NostrSecretKey)
if err != nil {
return nil, err
}
payload, err := nip04.Decrypt(event.Content, ss)
if err != nil {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"eventKind": event.Kind,
"appId": app.ID,
}).Errorf("Failed to decrypt content: %v", err)
return nil, err
}
nip47Request := &Nip47Request{}
err = json.Unmarshal([]byte(payload), nip47Request)
if err != nil {
return nil, err
}
switch nip47Request.Method {
case NIP_47_PAY_INVOICE_METHOD:
return svc.HandlePayInvoiceEvent(ctx, nip47Request, event, app, ss)
case NIP_47_PAY_KEYSEND_METHOD:
return svc.HandlePayKeysendEvent(ctx, nip47Request, event, app, ss)
case NIP_47_GET_BALANCE_METHOD:
return svc.HandleGetBalanceEvent(ctx, nip47Request, event, app, ss)
case NIP_47_MAKE_INVOICE_METHOD:
return svc.HandleMakeInvoiceEvent(ctx, nip47Request, event, app, ss)
case NIP_47_LOOKUP_INVOICE_METHOD:
return svc.HandleLookupInvoiceEvent(ctx, nip47Request, event, app, ss)
case NIP_47_LIST_TRANSACTIONS_METHOD:
return svc.HandleListTransactionsEvent(ctx, nip47Request, event, app, ss)
case NIP_47_GET_INFO_METHOD:
return svc.HandleGetInfoEvent(ctx, nip47Request, event, app, ss)
default:
return svc.createResponse(event, Nip47Response{
ResultType: nip47Request.Method,
Error: &Nip47Error{
Code: NIP_47_ERROR_NOT_IMPLEMENTED,
Message: fmt.Sprintf("Unknown method: %s", nip47Request.Method),
}}, ss)
}
}
func (svc *Service) createResponse(initialEvent *nostr.Event, content interface{}, ss []byte) (result *nostr.Event, err error) {
payloadBytes, err := json.Marshal(content)
if err != nil {
return nil, err
}
msg, err := nip04.Encrypt(string(payloadBytes), ss)
if err != nil {
return nil, err
}
resp := &nostr.Event{
PubKey: svc.cfg.IdentityPubkey,
CreatedAt: nostr.Now(),
Kind: NIP_47_RESPONSE_KIND,
Tags: nostr.Tags{[]string{"p", initialEvent.PubKey}, []string{"e", initialEvent.ID}},
Content: msg,
}
err = resp.Sign(svc.cfg.NostrSecretKey)
if err != nil {
return nil, err
}
return resp, nil
}
func (svc *Service) GetMethods(app *App) []string {
appPermissions := []AppPermission{}
findPermissionsResult := svc.db.Find(&appPermissions, &AppPermission{
AppId: app.ID,
})
if findPermissionsResult.RowsAffected == 0 {
// No permissions created for this app. It can do anything
return strings.Split(NIP_47_CAPABILITIES, " ")
}
requestMethods := make([]string, 0, len(appPermissions))
for _, appPermission := range appPermissions {
requestMethods = append(requestMethods, appPermission.RequestMethod)
}
return requestMethods
}
func (svc *Service) hasPermission(app *App, event *nostr.Event, requestMethod string, amount int64) (result bool, code string, message string) {
// find all permissions for the app
appPermissions := []AppPermission{}
findPermissionsResult := svc.db.Find(&appPermissions, &AppPermission{
AppId: app.ID,
})
if findPermissionsResult.RowsAffected == 0 {
// No permissions created for this app. It can do anything
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"requestMethod": requestMethod,
"appId": app.ID,
"pubkey": app.NostrPubkey,
}).Info("No permissions found for app")
return true, "", ""
}
appPermission := AppPermission{}
findPermissionResult := findPermissionsResult.Limit(1).Find(&appPermission, &AppPermission{
RequestMethod: requestMethod,
})
if findPermissionResult.RowsAffected == 0 {
// No permission for this request method
return false, NIP_47_ERROR_RESTRICTED, fmt.Sprintf("This app does not have permission to request %s", requestMethod)
}
expiresAt := appPermission.ExpiresAt
if !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
svc.Logger.WithFields(logrus.Fields{
"eventId": event.ID,
"requestMethod": requestMethod,
"expiresAt": expiresAt.Unix(),
"appId": app.ID,
"pubkey": app.NostrPubkey,
}).Info("This pubkey is expired")
return false, NIP_47_ERROR_EXPIRED, "This app has expired"
}
if requestMethod == NIP_47_PAY_INVOICE_METHOD {
maxAmount := appPermission.MaxAmount
if maxAmount != 0 {
budgetUsage := svc.GetBudgetUsage(&appPermission)
if budgetUsage+amount/1000 > int64(maxAmount) {
return false, NIP_47_ERROR_QUOTA_EXCEEDED, "Insufficient budget remaining to make payment"
}
}
}
return true, "", ""
}
func (svc *Service) GetBudgetUsage(appPermission *AppPermission) int64 {
var result struct {
Sum uint
}
svc.db.Table("payments").Select("SUM(amount) as sum").Where("app_id = ? AND preimage IS NOT NULL AND created_at > ?", appPermission.AppId, GetStartOfBudget(appPermission.BudgetRenewal, appPermission.App.CreatedAt)).Scan(&result)
return int64(result.Sum)
}
func (svc *Service) PublishNip47Info(ctx context.Context, relay *nostr.Relay) error {
ev := &nostr.Event{}
ev.Kind = NIP_47_INFO_EVENT_KIND
ev.Content = NIP_47_CAPABILITIES
ev.CreatedAt = nostr.Now()
ev.PubKey = svc.cfg.IdentityPubkey
err := ev.Sign(svc.cfg.NostrSecretKey)
if err != nil {
return err
}
status, err := relay.Publish(ctx, *ev)
if err != nil || status != nostr.PublishStatusSucceeded {
return fmt.Errorf("Nostr publish not successful: %s error: %s", status, err)
}
return nil
}