-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
431 lines (391 loc) · 10.9 KB
/
server.js
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
var request = require('request-promise')
const fs = require('fs')
const path = require('path')
const express = require('express')
const http = require('http')
const config = require('./config.js')
const cache = {}
const getCache = (type, id, ttl, callback) => {
if (!cache[type]) cache[type] = {}
if (!cache[type][id] || (new Date()).getTime() - cache[type][id].date.getTime() > ttl) {
cache[type][id] = {
date: new Date(),
data: callback()
}
}
return cache[type][id].data
}
class LND {
constructor(options) {
this.macaroon = fs.readFileSync(options.macaroon).toString('hex')
this.url = options.url
}
getInfo = async () => {
const data = await request({
url: `${this.url}/v1/getinfo`,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'GET'
})
return data;
}
getChannelBalance = async () => {
const data = await request({
url: `${this.url}/v1/balance/channels`,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'GET'
})
return data;
}
getNodeInfo = async nodeId => {
const data = await request({
url: `${this.url}/v1/graph/node/${nodeId}`,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'GET'
})
return data;
}
listChannels = async peer => {
let url = `${this.url}/v1/channels`
if (peer) {
peer = Buffer.from(peer, 'hex').toString('base64')
url += `?peer=${encodeURIComponent(peer)}`
}
const data = await request({
url,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'GET'
})
return data;
}
fwdinghistory = async (startTime, endTime, indexOffset, numMaxEvents) => {
let url = `${this.url}/v1/switch`
let requestBody = {
}
if (startTime) requestBody.start_time = String(startTime)
if (endTime) requestBody.end_time = String(endTime)
if (indexOffset) requestBody.index_offset = indexOffset
if (numMaxEvents) requestBody.num_max_events = numMaxEvents
const data = await request({
url,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'POST',
form: JSON.stringify(requestBody)
})
return data;
}
buildRoute = async ({ hops, channelId, amt}) => {
let url = `${this.url}/v2/router/route`
let requestBody = {
amt_msat: String((parseInt(amt) || 1) * 1000),
outgoing_chan_id: channelId,
hop_pubkeys: hops.map(hop => Buffer.from(hop, 'hex').toString('base64')),
final_cltv_delta: 128
}
const data = await request({
url,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'POST',
form: JSON.stringify(requestBody),
})
return data;
}
addInvoice = async ({ amt, memo, expiry }) => {
let url = `${this.url}/v1/invoices`
let requestBody = {
value: amt,
memo,
expiry: String(expiry || 3600)
}
const data = await request({
url,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'POST',
form: JSON.stringify(requestBody),
})
return data;
}
sendToRoute = async ({ route, paymentAddr, paymentHash}) => {
let url = `${this.url}/v2/router/route/send`
let lastHop = route.hops[route.hops.length -1]
lastHop.mpp_record = {
payment_addr: paymentAddr,
total_amt_msat: String(parseInt(route.total_amt_msat) - parseInt(route.total_fees_msat))
}
let requestBody = {
route,
paymentHash
}
const data = await request({
url,
headers: {
'Grpc-Metadata-macaroon': this.macaroon,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
json: true,
method: 'POST',
form: JSON.stringify(requestBody),
})
return data;
}
}
const getInfo = async () => await getCache('info', 'own', 30 * 60 * 1000, async () => {
return await lnd.getInfo()
})
const getChannelBalance = async () => await getCache('channelBalance', 'own', 15 * 60 * 1000, async () => {
return await lnd.getChannelBalance()
})
const getNodeInfo = async nodeId => await getCache('nodeInfo', nodeId, 30 * 60 * 1000, async () => {
const info = await lnd.getNodeInfo(nodeId)
return info
})
const getRingConfig = ring => fs.readFileSync(path.join(__dirname, `./rings/${ring}.json`), { encoding: 'utf8'})
const lnd = new LND({
macaroon: config.lnd.macaroon,
url: config.lnd.url
})
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use(express.static(
__dirname,
{ dotfiles: 'allow' }
))
app.use(express.static(
path.join(__dirname, './dist/')
))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './dist/index.html'))
})
app.get('/getRings', async (req, res) => {
res.setHeader('Content-Type', 'application/json')
let rings = fs.readdirSync('./rings')
.filter(file => /json/.test(file))
.map(file => file.replace('.json', ''))
res.send(rings)
})
app.post('/addRing', async (req, res) => {
const info = await getInfo()
const name = req.body.name
const ring = name.replace(/[^a-zA-Z0-9]/g, '')
let hops = req.body.hops
const hopsInValid = hops.some(hop => !/^[a-z0-9]{66}$/i.test(hop.pubkey))
if (!name || !hops) {
res.status(400)
return res.send({
error: 'INVALID_FORM'
})
}
if (hopsInValid) {
res.status(400)
return res.send({
error: 'HOPS_INVALID'
})
}
const myNodeIndex = hops.findIndex(hop => hop === info.identity_pubkey)
if (myNodeIndex >= 0 && myNodeIndex < hops.length) {
hops = hops.slice(myNodeIndex, hops.length).concat(hops.slice(0, myNodeIndex)).filter(hop => hop.pubkey !== info.identity_pubkey)
}
const json = {
name,
hops
}
fs.writeFile(path.join(__dirname, `./rings/${ring}.json`), JSON.stringify(json), (err, data) => {
res.setHeader('Content-Type', 'application/json')
json.id = ring
res.send(json)
})
})
app.post('/editRing', async (req, res) => {
const ringConfig = req.body.ringConfig
if (!ringConfig) {
res.status(400)
return res.send({
error: 'INVALID_FORM'
})
}
const ring = ringConfig.id
if (!ring) {
res.status(400)
return res.send({
error: 'INVALID_FORM'
})
}
const hopsInValid = ringConfig.hops.some(hop => !/[a-z0-9]{66}/i.test(hop.pubkey))
if (hopsInValid) {
res.status(400)
return res.send({
error: 'HOPS_INVALID'
})
}
fs.writeFile(path.join(__dirname, `./rings/${ring}.json`), JSON.stringify(ringConfig), (err, data) => {
res.setHeader('Content-Type', 'application/json')
res.send(ringConfig)
})
})
app.post('/deleteRing', async (req, res) => {
const ring = req.body.ring
if (!ring) {
res.status(400)
return res.send({
error: 'VALUE_MISSING'
})
}
fs.unlink(path.join(__dirname, `./rings/${ring}.json`), (err, data) => {
res.setHeader('Content-Type', 'application/json')
res.send({
id: ring
})
})
})
app.get('/getRingConfig', async (req, res) => {
const ring = req.query.ring
fs.readFile(path.join(__dirname, `./rings/${ring}.json`), { encoding: 'utf8'}, (err, data) => {
res.setHeader('Content-Type', 'application/json')
if (err) {
res.status(404)
return res.send({
error: 'FILE_NOT_FOUND'
})
}
data = JSON.parse(data)
data.id = ring
if (!data.hops[0].label) {
data.hops = data.hops.map(hop => ({
pubkey: hop,
label: null
}))
}
res.send(data)
})
})
app.get('/getInfo', async (req, res) => {
const info = await getInfo()
info.channelBalance = await getChannelBalance()
res.setHeader('Content-Type', 'application/json')
res.send(info)
})
app.get('/getNodeInfo', async (req, res) => {
const nodeId = req.query.nodeId
if (!/^[a-z0-9]{66}$/i.test(nodeId)) {
res.status(400)
return res.send({
error: 'PUB_KEY_INVALID'
})
}
const nodeInfo = await getNodeInfo(nodeId)
res.setHeader('Content-Type', 'application/json')
res.send(nodeInfo)
})
app.get('/listChannels', async (req, res) => {
const peer = req.query.peer
res.setHeader('Content-Type', 'application/json')
try {
const channels = await getCache('listChannels', peer || 'all', 10 * 60 * 1000, async () => {
return await lnd.listChannels(peer)
})
res.send(channels)
} catch (e) {
res.send(e.error)
}
})
app.post('/fwdinghistory', async (req, res) => {
const startTime = req.body.startTime
const endTime = req.body.endTime
const indexOffset = req.body.indexOffset
const numMaxEvents = req.body.numMaxEvents
res.setHeader('Content-Type', 'application/json')
try {
const history = await getCache('fwdinghistory', String(startTime) + String(endTime) + String(indexOffset) + String(numMaxEvents), 10 * 60 * 1000, async () => {
return await lnd.fwdinghistory(startTime, endTime, indexOffset, numMaxEvents)
})
res.send(history)
} catch (e) {
res.send(e.error)
}
})
app.post('/buildRoute', async (req, res) => {
const hops = req.body.hops
const amt = req.body.amt || 10
res.setHeader('Content-Type', 'application/json')
try {
const route = await getCache('buildRoute', JSON.stringify(hops) + amt, 1 * 60 * 1000, async () => {
return await lnd.buildRoute({
hops,
amt
})
})
res.send(route)
} catch (e) {
res.send(e)
}
})
app.post('/addInvoice', async (req, res) => {
const amt = req.body.amt
const memo = req.body.memo
res.setHeader('Content-Type', 'application/json')
try {
const invoice = await lnd.addInvoice({
amt,
memo
})
res.send(invoice)
} catch (e) {
res.send(e)
}
})
app.post('/sendToRoute', async (req, res) => {
const route = req.body.route
const paymentAddr = req.body.paymentAddr
const paymentHash = req.body.paymentHash
res.setHeader('Content-Type', 'application/json')
try {
const status = await lnd.sendToRoute({
route,
paymentAddr,
paymentHash
})
res.send(status)
} catch (e) {
res.status(500)
res.send(e)
}
})
let port = process.env.PORT || (config.server && config.server.port ? config.server.port : 80)
http.createServer(app).listen(port)
console.info('Created http server with port', port)