-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
337 lines (281 loc) · 8.28 KB
/
server.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
package lightauth
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"time"
"github.com/dchest/uniuri"
"github.com/lightningnetwork/lnd/lnrpc"
)
const (
iNVALIDTOKEN = "Lightauth error: Invalid token"
tIMEEXPIRED = "Lightauth error: Your authorized time has expired, pay up some balances to buy more time"
iNVALIDCREDENTIALS = "Lightauth error: Invalid credentials"
mISSINGINVOICE = "Lightauth error: Missing invoice ID"
mISSINGPREIMAGE = "Lightauth error: Missing pre_image"
tRYAGAIN = "Lightauth error: We can't validate your payment yet, please try again"
iNVOICEALREADYCLAIMED = "Lightauth error: Invoice has already been claimed"
sOMETHINGWENTWRONG = "Lightauth error: Something went wrong"
)
// Route is a hash that stores all the information of a specific endpoint
type Route struct {
RouteInfo
Clients map[string]*Client
ID string
}
func (r *Route) save() error {
var err error
r.ID, err = database.Create(r)
if err != nil {
return err
}
return nil
}
// Client is a hash that stores all the information of a server's client
type Client struct {
Token string
ExpirationTime time.Time
Invoices map[string]*Invoice
Route *Route
ID string
mux sync.Mutex
}
func (c *Client) setExpirationTime(t time.Time) error {
c.mux.Lock()
defer c.mux.Unlock()
c.ExpirationTime = t
return c.save()
}
func (c *Client) getExpirationTime() time.Time {
c.mux.Lock()
defer c.mux.Unlock()
return c.ExpirationTime
}
func (c *Client) save() error {
if c.ID == "" {
var err error
c.ID, err = database.Create(c)
if err != nil {
return err
}
} else {
database.Edit(c)
}
return nil
}
func writeConstantHeaders(w http.ResponseWriter, rt RouteInfo) {
w.Header().Set("Light-Auth-Name", rt.Name)
w.Header().Set("Light-Auth-Mode", rt.Mode)
w.Header().Set("Light-Auth-Fee", strconv.Itoa(rt.Fee))
w.Header().Set("Light-Auth-Max-Invoices", strconv.Itoa(rt.MaxInvoices))
if rt.Mode == "time" {
w.Header().Set("Light-Auth-Time-Period", rt.Period)
}
}
func writeClientHeaders(w http.ResponseWriter, c *Client) error {
unpayedInvoices, err := c.getUnpayedInvoices()
if err != nil {
writeError(w, "Something went wrong", http.StatusInternalServerError)
return err
}
unpayedInvoicesRequests := []*Invoice{}
for _, v := range unpayedInvoices {
unpayedInvoicesRequests = append(unpayedInvoicesRequests, v)
}
invoicesJSON, err := getInvoicesJSON(unpayedInvoicesRequests)
if err != nil {
return err
}
w.Header().Set("Light-Auth-Token", c.Token)
w.Header().Set("Light-Auth-Invoices", invoicesJSON)
if c.Route.Mode == "time" {
// RFC3339
w.Header().Set("Light-Auth-Expiration-Time", c.ExpirationTime.Format("2006-01-02T15:04:05Z07:00"))
}
return err
}
func writeError(w http.ResponseWriter, message string, statusCode int) {
w.Header().Set("Light-Auth-Status", strconv.Itoa(statusCode))
fmt.Fprint(w, message)
}
func updateInvoice(paymentRequest string) error {
for _, r := range serverStore {
for _, c := range r.Clients {
if i, invoiceExists := c.Invoices[paymentRequest]; invoiceExists {
err := i.settle([]byte{})
if err != nil {
return err
}
if c.Route.Mode == "time" {
timePeriod := time.Millisecond
switch c.Route.Period {
case "millisecond":
timePeriod = time.Millisecond
case "second":
timePeriod = time.Second
case "minute":
timePeriod = time.Minute
default:
timePeriod = time.Millisecond
}
t := time.Now()
expirationTime := c.getExpirationTime()
if expirationTime.After(t) {
diff := expirationTime.Sub(t)
return c.setExpirationTime(t.Add(timePeriod).Add(diff))
}
return c.setExpirationTime(t.Add(timePeriod))
}
}
}
}
return nil
}
func (c *Client) getUnpayedInvoices() ([]*Invoice, error) {
unpayedInvoices := []*Invoice{}
for _, i := range c.Invoices {
if !i.isSettled() {
unpayedInvoices = append(unpayedInvoices, i)
}
}
numUnpayed := len(unpayedInvoices)
if numUnpayed < c.Route.MaxInvoices {
newInvoices, err := c.generateInvoices(c.Route.MaxInvoices - numUnpayed)
if err != nil {
return []*Invoice{}, err
}
unpayedInvoices = append(unpayedInvoices, newInvoices...)
}
return unpayedInvoices, nil
}
func (c *Client) generateInvoices(numberOfInvoices int) ([]*Invoice, error) {
ctxb := context.Background()
invoices := []*Invoice{}
for i := 0; i < numberOfInvoices; i++ {
addInvoiceResponse, err := lightningClient.AddInvoice(ctxb, &lnrpc.Invoice{Value: int64(c.Route.Fee)})
if err != nil {
log.Printf("Lightauth error: Failed to generate an invoice in the lighting node: %v\n", err)
return invoices, err
}
invoiceID := addInvoiceResponse.PaymentRequest
hash := addInvoiceResponse.RHash
expirationTime := time.Now().Add(time.Minute * 59)
i := Invoice{PaymentRequest: invoiceID, Settled: false, PaymentHash: hash, Client: c, ExpirationTime: expirationTime}
invoices = append(invoices, &i)
err = i.save()
if err != nil {
// Couldn't save the invoice, so we will not keep it in store
continue
}
c.Invoices[invoiceID] = &i
}
return invoices, nil
}
func discreteTypeValidator(c *Client, w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
invoiceID := readHeader(r.Header, "Light-Auth-Invoice")
if invoiceID == "" {
writeError(w, mISSINGINVOICE, http.StatusBadRequest)
return
}
preImageString := readHeader(r.Header, "Light-Auth-Pre-Image")
if preImageString == "" {
writeError(w, mISSINGPREIMAGE, http.StatusBadRequest)
return
}
i, invoiceExists := c.Invoices[invoiceID]
if !invoiceExists {
writeError(w, iNVALIDCREDENTIALS, http.StatusBadRequest)
return
}
preImage, err := hex.DecodeString(preImageString)
if err != nil {
writeError(w, iNVALIDCREDENTIALS, http.StatusBadRequest)
return
}
hasher := sha256.New()
hasher.Write(preImage)
hexPreImage := hex.EncodeToString(hasher.Sum(nil))
hexPaymentHash := hex.EncodeToString(i.PaymentHash)
if hexPreImage != hexPaymentHash {
writeError(w, iNVALIDCREDENTIALS, http.StatusBadRequest)
return
}
if i.isClaimed() {
writeError(w, iNVOICEALREADYCLAIMED, http.StatusBadRequest)
}
if !i.isSettled() {
writeError(w, tRYAGAIN, http.StatusConflict)
return
}
err = i.claim()
if err != nil {
writeError(w, sOMETHINGWENTWRONG, http.StatusInternalServerError)
return
}
w.Header().Set("Light-Auth-Invoice", invoiceID)
w.Header().Set("Light-Auth-Status", strconv.Itoa(http.StatusOK))
handler(w, r)
}
func timeTypeValidator(c *Client, w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
t := time.Now()
expired := c.ExpirationTime.Before(t)
if expired {
writeError(w, tIMEEXPIRED, http.StatusPaymentRequired)
return
}
w.Header().Set("Light-Auth-Status", strconv.Itoa(http.StatusOK))
handler(w, r)
}
// ServerMiddleware is a middleware that checks if the request is valid according to the fees declared for the
// route.
func ServerMiddleware(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
routeName := r.Method + r.URL.Path
rt, routeExists := serverStore[routeName]
if !routeExists {
handler(w, r)
return
}
token := readHeader(r.Header, "Light-Auth-Token")
if token == "" {
for {
// Token not found, create new one
if _, tokenExists := rt.Clients[token]; !tokenExists {
token = uniuri.New()
c := &Client{Token: token, Invoices: map[string]*Invoice{}, ExpirationTime: time.Now(), Route: rt}
err := c.save()
if err != nil {
log.Printf("Lightauth error: Could not save client: %v\n", err)
writeError(w, "Something went wrong", http.StatusInternalServerError)
return
}
rt.Clients[token] = c
break
}
}
}
writeConstantHeaders(w, rt.RouteInfo)
_, tokenExists := rt.Clients[token]
if !tokenExists {
// Token doesn't exist
writeError(w, iNVALIDTOKEN, http.StatusBadRequest)
return
}
var err error
c := rt.Clients[token]
err = writeClientHeaders(w, c)
if err != nil {
return
}
if rt.Mode == "time" {
timeTypeValidator(c, w, r, handler)
} else if rt.Mode == "discrete" {
discreteTypeValidator(c, w, r, handler)
}
}
}