-
Notifications
You must be signed in to change notification settings - Fork 33
/
subscribe_to_pay_via_routes.js
432 lines (379 loc) · 13.4 KB
/
subscribe_to_pay_via_routes.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
432
const EventEmitter = require('events');
const {randomBytes} = require('crypto');
const asyncAuto = require('async/auto');
const asyncMapSeries = require('async/mapSeries');
const {chanFormat} = require('bolt07');
const {chanNumber} = require('bolt07');
const nextTick = require('async/nextTick');
const {returnResult} = require('asyncjs-util');
const {isLnd} = require('./../../lnd_requests');
const {paymentFailure} = require('./../../lnd_responses');
const routeFailureKeys = require('./../offchain/route_failure_keys');
const {rpcRouteFromRoute} = require('./../../lnd_requests');
const msAsISO = ms => new Date(ms).toISOString();
const {isArray} = Array;
const isHash = n => /^[0-9A-F]{64}$/i.test(n);
const hexAsBytes = hex => Buffer.from(hex, 'hex');
const method = 'sendToRouteV2';
const notFoundIndex = -1;
const {now} = Date;
const nsAsMs = ns => Number(BigInt(ns) / BigInt(1e6));
const payHashLength = Buffer.alloc(32).length;
const timeoutError = 'payment attempt not completed before timeout';
const unknownWireError = 'unknown wire error';
/** Subscribe to the attempts of paying via specified routes
Requires `offchain:write` permission
{
[id]: <Payment Hash Hex String>
lnd: <Authenticated LND API Object>
[pathfinding_timeout]: <Time to Spend Finding a Route Milliseconds Number>
routes: [{
fee: <Total Fee Tokens To Pay Number>
fee_mtokens: <Total Fee Millitokens To Pay String>
hops: [{
channel: <Standard Format Channel Id String>
channel_capacity: <Channel Capacity Tokens Number>
fee: <Fee Number>
fee_mtokens: <Fee Millitokens String>
forward: <Forward Tokens Number>
forward_mtokens: <Forward Millitokens String>
[messages]: [{
type: <Message Type Number String>
value: <Message Raw Value Hex Encoded String>
}]
public_key: <Public Key Hex String>
timeout: <Timeout Block Height Number>
}]
[messages]: [{
type: <Message Type Number String>
value: <Message Raw Value Hex Encoded String>
}]
mtokens: <Total Millitokens To Pay String>
[payment]: <Payment Identifier Hex String>
timeout: <Expiration Block Height Number>
tokens: <Total Tokens To Pay Number>
[total_mtokens]: <Total Millitokens String>
}]
}
@throws
<Error>
@returns
<EventEmitter Object>
@event 'failure'
{
failure: [
<Code Number>
<Failure Message String>
{
channel: <Standard Format Channel Id String>
[index]: <Failure Hop Index Number>
[mtokens]: <Millitokens String>
[policy]: {
base_fee_mtokens: <Base Fee Millitokens String>
cltv_delta: <Locktime Delta Number>
fee_rate: <Fees Charged in Millitokens Per Million Number>
[is_disabled]: <Channel is Disabled Bool>
max_htlc_mtokens: <Maximum HLTC Millitokens value String>
min_htlc_mtokens: <Minimum HTLC Millitokens Value String>
}
public_key: <Public Key Hex String>
[update]: {
chain: <Chain Id Hex String>
channel_flags: <Channel Flags Number>
extra_opaque_data: <Extra Opaque Data Hex String>
message_flags: <Message Flags Number>
signature: <Channel Update Signature Hex String>
}
}
]
}
@event 'paying'
{
route: {
fee: <Total Fee Tokens To Pay Number>
fee_mtokens: <Total Fee Millitokens To Pay String>
hops: [{
channel: <Standard Format Channel Id String>
channel_capacity: <Channel Capacity Tokens Number>
fee: <Fee Number>
fee_mtokens: <Fee Millitokens String>
forward: <Forward Tokens Number>
forward_mtokens: <Forward Millitokens String>
public_key: <Public Key Hex String>
timeout: <Timeout Block Height Number>
}]
mtokens: <Total Millitokens To Pay String>
timeout: <Expiration Block Height Number>
tokens: <Total Tokens To Pay Number>
}
}
@event 'routing_failure'
{
[channel]: <Standard Format Channel Id String>
[height]: <Failure Height Context Number>
[index]: <Failure Hop Index Number>
[mtokens]: <Failure Related Millitokens String>
[policy]: {
base_fee_mtokens: <Base Fee Millitokens String>
cltv_delta: <Locktime Delta Number>
fee_rate: <Fees Charged in Millitokens Per Million Number>
[is_disabled]: <Channel is Disabled Bool>
max_htlc_mtokens: <Maximum HLTC Millitokens value String>
min_htlc_mtokens: <Minimum HTLC Millitokens Value String>
}
public_key: <Public Key Hex String>
reason: <Failure Reason String>
route: {
fee: <Total Fee Tokens To Pay Number>
fee_mtokens: <Total Fee Millitokens To Pay String>
hops: [{
channel: <Standard Format Channel Id String>
channel_capacity: <Channel Capacity Tokens Number>
fee: <Fee Number>
fee_mtokens: <Fee Millitokens String>
forward: <Forward Tokens Number>
forward_mtokens: <Forward Millitokens String>
public_key: <Public Key Hex String>
timeout: <Timeout Block Height Number>
}]
mtokens: <Total Millitokens To Pay String>
safe_fee: <Payment Forwarding Fee Rounded Up Tokens Number>
safe_tokens: <Payment Tokens Rounded Up Number>
timeout: <Expiration Block Height Number>
tokens: <Total Tokens To Pay Number>
}
[timeout_height]: <Failure Related CLTV Timeout Height Number>
[update]: {
chain: <Chain Id Hex String>
channel_flags: <Channel Flags Number>
extra_opaque_data: <Extra Opaque Data Hex String>
message_flags: <Message Flags Number>
signature: <Channel Update Signature Hex String>
}
}
@event 'success'
{
fee: <Fee Paid Tokens Number>
fee_mtokens: <Fee Paid Millitokens String>
hops: [{
channel: <Standard Format Channel Id String>
channel_capacity: <Hop Channel Capacity Tokens Number>
fee_mtokens: <Hop Forward Fee Millitokens String>
forward_mtokens: <Hop Forwarded Millitokens String>
timeout: <Hop CLTV Expiry Block Height Number>
}]
id: <Payment Hash Hex String>
is_confirmed: <Is Confirmed Bool>
is_outgoing: <Is Outoing Bool>
mtokens: <Total Millitokens Sent String>
route: {
fee: <Total Fee Tokens To Pay Number>
fee_mtokens: <Total Fee Millitokens To Pay String>
hops: [{
channel: <Standard Format Channel Id String>
channel_capacity: <Channel Capacity Tokens Number>
fee: <Fee Number>
fee_mtokens: <Fee Millitokens String>
forward: <Forward Tokens Number>
forward_mtokens: <Forward Millitokens String>
public_key: <Public Key Hex String>
timeout: <Timeout Block Height Number>
}]
mtokens: <Total Millitokens To Pay String>
safe_fee: <Payment Forwarding Fee Rounded Up Tokens Number>
safe_tokens: <Payment Tokens Rounded Up Number>
timeout: <Expiration Block Height Number>
tokens: <Total Tokens To Pay Number>
}
safe_fee: <Payment Forwarding Fee Rounded Up Tokens Number>
safe_tokens: <Payment Tokens Rounded Up Number>
secret: <Payment Secret Preimage Hex String>
tokens: <Total Tokens Sent Number>
}
*/
module.exports = args => {
if (!!args.id && !isHash(args.id)) {
throw new Error('ExpectedPaymentHashToPayViaRoutes');
}
if (!isLnd({method, lnd: args.lnd, type: 'router'})) {
throw new Error('ExpectedAuthenticatedLndToPayViaRoutes');
}
if (!isArray(args.routes) || !args.routes.length) {
throw new Error('ExpectedArrayOfPaymentRoutesToPayViaRoutes');
}
const id = args.id || randomBytes(payHashLength).toString('hex');
if (!!args.routes.find(n => !isArray(n.hops))) {
throw new Error('ExpectedRouteHopsToPayViaRoutes');
}
if (!!args.routes.find(n => n.hops.find(hop => !hop.public_key))) {
throw new Error('ExpectedPublicKeyInPayViaRouteHops');
}
try {
args.routes.forEach(({hops}) => {
return hops.forEach(({channel}) => chanNumber({channel}));
});
} catch (err) {
throw new Error('ExpectedValidRouteChannelIdsForPayViaRoutes');
}
const emitter = new EventEmitter();
let isPayDone = false;
const pathfindingTimeout = args.pathfinding_timeout;
let payFailed = null;
let payResult = null;
const start = now();
asyncMapSeries(args.routes, (route, cbk) => {
// Exit early without trying a payment when there is a definitive result
if (!!isPayDone) {
return nextTick(cbk);
}
if (!!pathfindingTimeout && now() - start > pathfindingTimeout) {
return cbk([503, 'PathfindingTimeoutExceeded']);
}
return asyncAuto({
// Wait for subscription pick up
waitForSubscribers: cbk => nextTick(cbk),
// Try paying
attempt: ['waitForSubscribers', ({}, cbk) => {
emitter.emit('paying', {route});
return args.lnd.router[method]({
payment_hash: Buffer.from(id, 'hex'),
route: rpcRouteFromRoute(route),
},
(err, res) => {
if (!!err && err.details === unknownWireError) {
return cbk(null, {});
}
if (!!err && err.details === timeoutError) {
return cbk(null, {});
}
if (!!err) {
return cbk([503, 'UnexpectedErrorWhenPayingViaRoute', {err}]);
}
if (!res) {
return cbk([503, 'ExpectedResponseFromLndWhenPayingViaRoute']);
}
const confAt = !!res.preimage ? res.resolve_time_ns : undefined;
return cbk(null, {
confirmed_at: !!confAt ? msAsISO(nsAsMs(confAt)) : undefined,
failure: res.failure,
preimage: res.preimage,
});
});
}],
// Public keys associated with a failure
keys: ['attempt', ({attempt}, cbk) => {
const {keys} = routeFailureKeys({route, failure: attempt.failure});
return cbk(null, keys);
}],
// Attempt to clean up failed probe state
deleteProbe: ['attempt', ({attempt}, cbk) => {
// Exit early when the payment didn't fail
if (!attempt.failure) {
return cbk();
}
// Exit early when this is a real payment
if (!!args.id) {
return cbk();
}
args.lnd.default.deletePayment({
payment_hash: hexAsBytes(id),
},
err => {
// Ignore errors trying to clean up probe data
return cbk();
});
}],
// Parsed out failure
failure: ['attempt', 'keys', ({attempt, keys}, cbk) => {
if (!attempt.failure) {
return cbk();
}
const {failure} = attempt;
const {channel} = (route.hops[failure.failure_source_index] || {});
const from = route.hops[failure.failure_source_index - 1] || {};
return cbk(null, paymentFailure({
channel,
failure,
keys,
key: from.public_key,
index: failure.failure_source_index,
}));
}],
// Attempt success
success: ['attempt', ({attempt}, cbk) => {
if (!!attempt.failure || !attempt.preimage) {
return cbk();
}
if (!Buffer.isBuffer(attempt.preimage)) {
return cbk([503, 'UnexpectedResultWhenPayingViaSendToRouteSync']);
}
isPayDone = true;
return cbk(null, {
confirmed_at: attempt.confirmed_at,
fee: route.fee,
fee_mtokens: route.fee_mtokens,
hops: route.hops,
mtokens: route.mtokens,
safe_fee: route.safe_fee,
safe_tokens: route.safe_tokens,
secret: attempt.preimage.toString('hex'),
tokens: route.tokens,
});
}],
// Set pay result and pay error
result: ['failure', 'success', ({failure, success}, cbk) => {
// Exit early when there was no result of the pay attempt
if (!failure && !success) {
return cbk();
}
// A routing failure was encountered
if (!!failure && !!failure.details) {
isPayDone = failure.details.index === route.hops.length;
emitter.emit('routing_failure', {
route,
channel: failure.details.channel,
height: failure.details.height,
index: failure.details.index,
mtokens: failure.details.mtokens,
policy: failure.details.policy,
public_key: failure.details.public_key,
reason: failure.message,
timeout_height: failure.details.timeout_height,
update: failure.details.update,
});
}
// A failure instance has been received for this route
if (!!failure) {
payFailed = failure;
emitter.emit('failure', {
failure: [failure.code, failure.message, failure.details],
});
return cbk();
}
payResult = success;
emitter.emit('success', {
id,
route,
confirmed_at: success.confirmed_at,
fee: success.fee,
fee_mtokens: success.fee_mtokens,
hops: success.hops,
mtokens: success.mtokens,
safe_fee: success.safe_fee,
safe_tokens: success.safe_tokens,
secret: success.secret,
tokens: success.tokens,
});
return cbk();
}],
},
returnResult({}, cbk));
},
err => {
if (!!err && !!emitter.listenerCount('error')) {
emitter.emit('error', err);
}
return emitter.emit('end');
});
return emitter;
};