-
Notifications
You must be signed in to change notification settings - Fork 4
/
lnd.js
264 lines (247 loc) · 8.78 KB
/
lnd.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
const assert = require('assert');
const crypto = require('crypto');
const fs = require('fs');
const getTagDataFromPaymentRequest= require('../getTagDataFromPaymentRequest');
const HttpLightningBackend = require('../HttpLightningBackend');
const tlsCheck = require('../tlsCheck');
const tls = require('tls');
const url = require('url');
const { ValidationError } = require('@bleskomat/form');
class Backend extends HttpLightningBackend {
// lnd's REST API documentation:
// https://api.lightning.community/#lnd-rest-api-reference
static name = 'lnd';
constructor(options) {
super(Backend.name, options, {
defaultOptions: {
baseUrl: null,
cert: null,
hostname: '127.0.0.1:8080',
macaroon: null,
protocol: 'https',
requestContentType: 'json',
},
requiredOptions: ['macaroon'],
});
this.options.headers['Grpc-Metadata-macaroon'] = this.options.macaroon;
}
processOptions(options) {
let { cert, macaroon } = options;
if (cert) {
if (typeof cert === 'string') {
cert = fs.readFileSync(cert).toString('utf8');
} else if (typeof cert === 'object' && cert.data) {
cert = cert.data;
if (Buffer.isBuffer(cert)) {
cert = cert.toString('utf8');
}
}
}
if (macaroon) {
if (typeof macaroon === 'string') {
macaroon = fs.readFileSync(macaroon).toString('hex');
} else if (typeof macaroon === 'object' && macaroon.data) {
macaroon = macaroon.data;
if (Buffer.isBuffer(macaroon)) {
macaroon = macaroon.toString('hex');
}
}
}
options.cert = cert;
options.macaroon = macaroon;
return options;
}
checkOptions(options) {
if (options.cert) {
if (typeof options.cert === 'string') {
fs.statSync(options.cert);
} else if (typeof options.cert === 'object') {
assert.ok(options.cert.data && (typeof options.cert.data === 'string' || Buffer.isBuffer(options.cert.data)), 'Invalid option ("cert"): Expected { data: Buffer/String }');
} else {
throw new Error('Invalid option ("cert"): Object or string expected');
}
}
if (typeof options.macaroon === 'string') {
fs.statSync(options.macaroon);
} else if (typeof options.macaroon === 'object') {
assert.ok(options.macaroon.data && (typeof options.macaroon.data === 'string' || Buffer.isBuffer(options.macaroon.data)), 'Invalid option ("macaroon"): Expected { data: Buffer/String }');
} else {
throw new Error('Invalid option ("cert"): Object or string expected');
}
options = this.processOptions(options);
HttpLightningBackend.prototype.checkOptions.call(this, options);
}
getNodeUri() {
return this.getNodeInfo().then(info => {
return info.uris[0];
});
}
// https://api.lightning.community/#v1-getinfo
getNodeInfo() {
return this.request('get', '/v1/getinfo').then(result => {
assert.ok(result.uris && result.uris instanceof Array && result.uris.length > 0, 'Unexpected response from LN Backend [GET /v1/getinfo]: "uris"');
return result;
});
}
// https://api.lightning.community/#post-v1-channels
openChannel(remoteId, localAmt, pushAmt, makePrivate) {
return this.request('post', '/v1/channels', {
node_pubkey_string: remoteId,
local_funding_amount: localAmt,
push_sat: pushAmt,
private: makePrivate === 1 || makePrivate === true,
});
}
// https://api.lightning.community/#v1-channels-transactions
payInvoice(invoice) {
return this.request('post', '/v1/channels/transactions', { payment_request: invoice }).then(result => {
assert.ok(!result.payment_error, result.payment_error);
assert.ok(result.payment_preimage, 'Unexpected response from LN Backend [POST /v1/invoices]: Missing "payment_preimage"');
const paymentHash = getTagDataFromPaymentRequest(invoice, 'payment_hash');
const preimage = Buffer.from(result.payment_preimage, 'base64').toString('hex');
assert.strictEqual(crypto.createHash('sha256').update(Buffer.from(preimage, 'hex')).digest('hex'), paymentHash, `Payment preimage does not match payment hash in invoice: preimage = ${preimage}, invoice = ${invoice}`);
return { id: null, preimage };
});
}
// https://api.lightning.community/#post-v1-invoices
addInvoice(amount, extra) {
let data = {
value_msat: amount,
};
if (extra && extra.descriptionHash) {
data.description_hash = Buffer.from(extra.descriptionHash, 'hex').toString('base64');
}
return this.request('post', '/v1/invoices', data).then(result => {
assert.ok(result.payment_request, 'Unexpected response from LN Backend [POST /v1/invoices]: Missing "payment_request"');
return {
id: null,
invoice: result.payment_request,
};
});
}
// https://api.lightning.community/#v1-invoice
getInvoiceStatus(paymentHash) {
const r_hash = encodeURIComponent(paymentHash);
return this.request('get', `/v1/invoice/${r_hash}`).then(result => {
assert.strictEqual(typeof result, 'object', `Unexpected response from LN Backend [GET /v1/invoice/${r_hash}]`);
assert.notStrictEqual(typeof result.r_preimage, 'undefined', `Unexpected response from LN Backend [GET /v1/invoice/${r_hash}]: Missing "r_preimage"`);
assert.notStrictEqual(typeof result.settled, 'undefined', `Unexpected response from LN Backend [GET /v1/invoice/${r_hash}]: Missing "settled"`);
const preimage = (result.r_preimage && Buffer.from(result.r_preimage, 'base64').toString('hex')) || null;
const settled = result.settled === true;
return { preimage, settled };
});
}
// https://api.lightning.community/#v1-balance-channels
getBalance() {
return this.request('get', '/v1/balance/channels').then(result => {
assert.strictEqual(typeof result, 'object', 'Unexpected response from LN Backend [GET /v1/balance/channels]');
assert.strictEqual(typeof result.local_balance, 'object', 'Unexpected response from LN Backend [GET /v1/balance/channels]: Missing "local_balance"');
assert.strictEqual(typeof result.local_balance.msat, 'string', 'Unexpected response from LN Backend [GET /v1/balance/channels]: Missing "local_balance.msat"');
return parseInt(result.local_balance.msat);
});
}
validateResponseBody(body) {
assert.ok(!body.error, body.error);
}
};
Backend.prototype.checkMethodErrorMessages = {
payInvoice: {
ok: [
'no_route',
],
notOk: [
'Socks5 proxy rejected connection - Failure',
'verification failed',
'cannot determine data format',
'field data extends past end of buffer',
'fields out of order',
'invoice not for current active network',
'encoding/hex: invalid byte',
],
},
};
Backend.form = {
label: 'Lightning Network Daemon (lnd)',
inputs: [
{
name: 'baseUrl',
label: 'Base URL',
help: 'Base URL of your lnd node\'s REST API. Onion addresses are supported.',
type: 'text',
placeholder: 'https://127.0.0.1:8080',
default: '',
required: true,
validate: function(value) {
if (value) {
let parsedUrl;
try { parsedUrl = url.parse(value); } catch (error) {
throw new ValidationError('"Base URL" must be a valid URL - e.g. https://127.0.0.1:8080');
}
const { hostname, protocol } = parsedUrl;
assert.ok(hostname.substr(-6) === '.onion' || protocol === 'https:', new ValidationError('Except in the case of onion addresses, "Base URL" must use the https protocol.'));
}
},
},
{
name: 'cert',
label: 'TLS Certificate',
help: 'Automatically retrieved from service at the URL provided above. Please check this against your lnd\'s tls.cert file.',
type: 'textarea',
default: '',
readonly: true,
required: function(data) {
const baseUrl = data && data['lnd[baseUrl]'] || null;
return baseUrl && baseUrl.split('://')[0] === 'https';
},
validate: function(value, data) {
if (value) {
const baseUrl = data && data['lnd[baseUrl]'] || null;
if (baseUrl) {
let parsedUrl;
try { parsedUrl = url.parse(baseUrl); } catch (error) {
// Base URL not valid. Skip this check.
}
const { host } = parsedUrl;
return tlsCheck(host, {
requestCert: false,
rejectUnauthorized: false,
secureContext: tls.createSecureContext({
ca: value,
}),
}).then(result => {
assert.ok(result.authorized, new ValidationError(`Unable to establish secure connection to ${host} with the provided TLS certificate`));
});
}
}
},
rows: 4,
},
{
name: 'fingerprint',
label: 'Fingerprint (sha1)',
type: 'text',
default: '',
disabled: true,
},
{
name: 'fingerprint256',
label: 'Fingerprint (sha256)',
type: 'text',
default: '',
disabled: true,
},
{
name: 'macaroon',
label: 'Macaroon (hex)',
help: 'Use `xxd -c 10000 -p -u ./admin.macaroon` to print a macaroon file as hexadecimal. The macaroon provided must have permission to pay invoices.',
type: 'password',
placeholder: '02EF72..',
default: '',
required: true,
process: function(value) {
return value && value.trim();
},
},
],
};
module.exports = Backend;