thunder-bridge 1.1.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +115 -6
- package/dist/index.cjs +1677 -1301
- package/dist/index.d.cts +217 -166
- package/dist/index.d.ts +217 -166
- package/dist/index.js +1673 -1300
- package/dist/{rail-Dp8bs6uZ.d.cts → rail-CqUfuYXJ.d.cts} +176 -9
- package/dist/{rail-Dp8bs6uZ.d.ts → rail-CqUfuYXJ.d.ts} +176 -9
- package/dist/server.cjs +1003 -381
- package/dist/server.d.cts +79 -37
- package/dist/server.d.ts +79 -37
- package/dist/server.js +991 -380
- package/openapi.yaml +1 -1
- package/package.json +33 -13
package/dist/index.js
CHANGED
|
@@ -1,67 +1,9 @@
|
|
|
1
|
-
// src/errors.ts
|
|
2
|
-
var GatewayCheatError = class extends Error {
|
|
3
|
-
code;
|
|
4
|
-
paymentId;
|
|
5
|
-
constructor(code, paymentId) {
|
|
6
|
-
super(`gateway verification failed: ${code}`);
|
|
7
|
-
this.name = "GatewayCheatError";
|
|
8
|
-
this.code = code;
|
|
9
|
-
this.paymentId = paymentId;
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
var UnverifiedRecipientError = class extends Error {
|
|
13
|
-
lnAddress;
|
|
14
|
-
paymentId;
|
|
15
|
-
constructor(lnAddress, paymentId, cause) {
|
|
16
|
-
super(`could not reach ${lnAddress} to verify the invoice: ${String(cause)}`);
|
|
17
|
-
this.name = "UnverifiedRecipientError";
|
|
18
|
-
this.lnAddress = lnAddress;
|
|
19
|
-
this.paymentId = paymentId;
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
var ProblemError = class extends Error {
|
|
23
|
-
type;
|
|
24
|
-
title;
|
|
25
|
-
status;
|
|
26
|
-
detail;
|
|
27
|
-
constructor(problem) {
|
|
28
|
-
const title = problem.title ?? "Request failed";
|
|
29
|
-
super(problem.detail ? `${title}: ${problem.detail}` : title);
|
|
30
|
-
this.name = "ProblemError";
|
|
31
|
-
this.type = problem.type ?? "about:blank";
|
|
32
|
-
this.title = title;
|
|
33
|
-
this.status = problem.status ?? 0;
|
|
34
|
-
this.detail = problem.detail ?? null;
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
function isProblemType(problem, type) {
|
|
38
|
-
return problem.type === type;
|
|
39
|
-
}
|
|
40
|
-
var NO_WALLET_AVAILABLE = "urn:problem-type:thunder-bridge:no-wallet-available";
|
|
41
|
-
var REQUEST_IN_FLIGHT = "urn:problem-type:thunder-bridge:request-in-flight";
|
|
42
|
-
var IDEMPOTENCY_KEY_REUSED = "urn:problem-type:thunder-bridge:idempotency-key-reused";
|
|
43
|
-
var PAYMENT_ALREADY_WATCHED = "urn:problem-type:thunder-bridge:payment-already-watched";
|
|
44
|
-
var IdempotencyConflictError = class extends ProblemError {
|
|
45
|
-
conflict;
|
|
46
|
-
constructor(problem, conflict) {
|
|
47
|
-
super(problem);
|
|
48
|
-
this.name = "IdempotencyConflictError";
|
|
49
|
-
this.conflict = conflict;
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
|
-
var NoWalletAvailableError = class extends ProblemError {
|
|
53
|
-
wallets;
|
|
54
|
-
constructor(problem, wallets) {
|
|
55
|
-
super({ ...problem, type: NO_WALLET_AVAILABLE });
|
|
56
|
-
this.name = "NoWalletAvailableError";
|
|
57
|
-
this.wallets = wallets;
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
|
|
61
1
|
// ../core/bytes.ts
|
|
62
2
|
function bytesToHex(bytes) {
|
|
63
3
|
let hex = "";
|
|
64
|
-
for (const byte of bytes)
|
|
4
|
+
for (const byte of bytes) {
|
|
5
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
6
|
+
}
|
|
65
7
|
return hex;
|
|
66
8
|
}
|
|
67
9
|
function hexToBytes(hex) {
|
|
@@ -179,7 +121,9 @@ function withPadding(bytes) {
|
|
|
179
121
|
return padded;
|
|
180
122
|
}
|
|
181
123
|
function fillSchedule(schedule, reader, block) {
|
|
182
|
-
for (let at = 0; at < 16; at++)
|
|
124
|
+
for (let at = 0; at < 16; at++) {
|
|
125
|
+
schedule[at] = reader.getUint32(block + at * 4, false);
|
|
126
|
+
}
|
|
183
127
|
for (let at = 16; at < SCHEDULE_WORDS; at++) {
|
|
184
128
|
const recent2 = schedule[at - 15];
|
|
185
129
|
const distant = schedule[at - 2];
|
|
@@ -213,12 +157,16 @@ function compress(state, schedule) {
|
|
|
213
157
|
a = carried + (mixedA + majority | 0) | 0;
|
|
214
158
|
}
|
|
215
159
|
const rolling = [a, b, c, d, e, f, g, h];
|
|
216
|
-
for (let at = 0; at < state.length; at++)
|
|
160
|
+
for (let at = 0; at < state.length; at++) {
|
|
161
|
+
state[at] = state[at] + rolling[at] | 0;
|
|
162
|
+
}
|
|
217
163
|
}
|
|
218
164
|
function asBytes(state) {
|
|
219
165
|
const digest = new Uint8Array(state.length * 4);
|
|
220
166
|
const writer = new DataView(digest.buffer);
|
|
221
|
-
for (let at = 0; at < state.length; at++)
|
|
167
|
+
for (let at = 0; at < state.length; at++) {
|
|
168
|
+
writer.setUint32(at * 4, state[at], false);
|
|
169
|
+
}
|
|
222
170
|
return digest;
|
|
223
171
|
}
|
|
224
172
|
function rotate(value, by) {
|
|
@@ -259,20 +207,30 @@ function decodeInvoice(bolt11) {
|
|
|
259
207
|
};
|
|
260
208
|
}
|
|
261
209
|
function preimageMatchesHash(preimage, paymentHash) {
|
|
262
|
-
if (!isHex(preimage))
|
|
210
|
+
if (!isHex(preimage)) {
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
263
213
|
return bytesToHex(sha256(hexToBytes(preimage))) === paymentHash.toLowerCase();
|
|
264
214
|
}
|
|
265
215
|
function splitBech32(bolt11) {
|
|
266
216
|
const lower = bolt11.toLowerCase();
|
|
267
|
-
if (isBolt12Encoding(lower))
|
|
217
|
+
if (isBolt12Encoding(lower)) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
268
220
|
const separator = lower.lastIndexOf("1");
|
|
269
|
-
if (separator < 1)
|
|
221
|
+
if (separator < 1) {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
270
224
|
const dataChars = lower.slice(separator + 1);
|
|
271
|
-
if (dataChars.length < CHECKSUM_WORDS)
|
|
225
|
+
if (dataChars.length < CHECKSUM_WORDS) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
272
228
|
const words = [];
|
|
273
229
|
for (const char of dataChars) {
|
|
274
230
|
const value = BECH32_CHARSET.indexOf(char);
|
|
275
|
-
if (value === -1)
|
|
231
|
+
if (value === -1) {
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
276
234
|
words.push(value);
|
|
277
235
|
}
|
|
278
236
|
return { hrp: lower.slice(0, separator), words: words.slice(0, -CHECKSUM_WORDS) };
|
|
@@ -288,25 +246,35 @@ function taggedFields(words) {
|
|
|
288
246
|
const lengthWords = words[cursor + 1] * 32 + words[cursor + 2];
|
|
289
247
|
const dataStart = cursor + 1 + TAGGED_FIELD_LENGTH_WORDS;
|
|
290
248
|
const dataEnd = dataStart + lengthWords;
|
|
291
|
-
if (dataEnd > signatureStart)
|
|
292
|
-
|
|
249
|
+
if (dataEnd > signatureStart) {
|
|
250
|
+
return fields;
|
|
251
|
+
}
|
|
252
|
+
if (!fields.has(words[cursor])) {
|
|
253
|
+
fields.set(words[cursor], words.slice(dataStart, dataEnd));
|
|
254
|
+
}
|
|
293
255
|
cursor = dataEnd;
|
|
294
256
|
}
|
|
295
257
|
return fields;
|
|
296
258
|
}
|
|
297
259
|
function hexTag(fields, tag, expectedWords) {
|
|
298
260
|
const words = fields.get(tag);
|
|
299
|
-
if (words === void 0 || words.length !== expectedWords)
|
|
261
|
+
if (words === void 0 || words.length !== expectedWords) {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
300
264
|
return bytesToHex(wordsToBytes(words));
|
|
301
265
|
}
|
|
302
266
|
function expiryOf(words, fields) {
|
|
303
|
-
if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS)
|
|
267
|
+
if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS) {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
304
270
|
const expiry = fields.get(EXPIRY_TAG);
|
|
305
271
|
return readNumber(words.slice(0, TIMESTAMP_WORDS)) + (expiry ? readNumber(expiry) : DEFAULT_EXPIRY_SECS);
|
|
306
272
|
}
|
|
307
273
|
function amountFromHrp(hrp) {
|
|
308
274
|
const match = HRP_AMOUNT.exec(hrp);
|
|
309
|
-
if (match === null)
|
|
275
|
+
if (match === null) {
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
310
278
|
const [, digits, multiplier] = match;
|
|
311
279
|
return multiplier ? Number(digits) * HRP_MULTIPLIER_MSAT[multiplier] : Number(digits) * MSAT_PER_BTC;
|
|
312
280
|
}
|
|
@@ -328,105 +296,6 @@ function wordsToBytes(words) {
|
|
|
328
296
|
return Uint8Array.from(bytes);
|
|
329
297
|
}
|
|
330
298
|
|
|
331
|
-
// ../core/ed25519.ts
|
|
332
|
-
var ALGORITHM = { name: "Ed25519" };
|
|
333
|
-
var SEED_BYTES = 32;
|
|
334
|
-
var SIGNATURE_BYTES = 64;
|
|
335
|
-
var PUBLIC_KEY_BYTES = 32;
|
|
336
|
-
var PKCS8_HEADER = hexToBytes("302e020100300506032b657004220420");
|
|
337
|
-
async function signingKeyFromSeed(seed) {
|
|
338
|
-
if (seed.length !== SEED_BYTES) throw new Error(`an ed25519 seed is ${SEED_BYTES} bytes`);
|
|
339
|
-
const wrapped = new Uint8Array(PKCS8_HEADER.length + SEED_BYTES);
|
|
340
|
-
wrapped.set(PKCS8_HEADER);
|
|
341
|
-
wrapped.set(seed, PKCS8_HEADER.length);
|
|
342
|
-
const key = await crypto.subtle.importKey("pkcs8", asBuffer(wrapped), ALGORITHM, true, ["sign"]);
|
|
343
|
-
const jwk = await crypto.subtle.exportKey("jwk", key);
|
|
344
|
-
return {
|
|
345
|
-
publicKeyHex: bytesToHex(fromBase64Url(jwk.x ?? "")),
|
|
346
|
-
sign: async (payload) => bytesToHex(new Uint8Array(await crypto.subtle.sign(ALGORITHM, key, asBuffer(payload))))
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
async function verifyHex(publicKeyHex, signatureHex, payload) {
|
|
350
|
-
if (!isHex(publicKeyHex) || publicKeyHex.length !== PUBLIC_KEY_BYTES * 2) return false;
|
|
351
|
-
if (!isHex(signatureHex) || signatureHex.length !== SIGNATURE_BYTES * 2) return false;
|
|
352
|
-
try {
|
|
353
|
-
const key = await crypto.subtle.importKey(
|
|
354
|
-
"raw",
|
|
355
|
-
asBuffer(hexToBytes(publicKeyHex)),
|
|
356
|
-
ALGORITHM,
|
|
357
|
-
false,
|
|
358
|
-
["verify"]
|
|
359
|
-
);
|
|
360
|
-
return await crypto.subtle.verify(
|
|
361
|
-
ALGORITHM,
|
|
362
|
-
key,
|
|
363
|
-
asBuffer(hexToBytes(signatureHex)),
|
|
364
|
-
asBuffer(payload)
|
|
365
|
-
);
|
|
366
|
-
} catch {
|
|
367
|
-
return false;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
function fromBase64Url(text2) {
|
|
371
|
-
const padded = text2.replace(/-/g, "+").replace(/_/g, "/");
|
|
372
|
-
const raw = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
373
|
-
const bytes = new Uint8Array(raw.length);
|
|
374
|
-
for (let at = 0; at < raw.length; at++) bytes[at] = raw.charCodeAt(at);
|
|
375
|
-
return bytes;
|
|
376
|
-
}
|
|
377
|
-
function asBuffer(bytes) {
|
|
378
|
-
return bytes.buffer instanceof ArrayBuffer ? bytes : new Uint8Array(bytes);
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// ../core/hmac.ts
|
|
382
|
-
async function hmacHex(secret, payload) {
|
|
383
|
-
const raw = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
|
|
384
|
-
const key = await crypto.subtle.importKey(
|
|
385
|
-
"raw",
|
|
386
|
-
asBuffer2(raw),
|
|
387
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
388
|
-
false,
|
|
389
|
-
["sign"]
|
|
390
|
-
);
|
|
391
|
-
const message = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
|
|
392
|
-
return bytesToHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, asBuffer2(message))));
|
|
393
|
-
}
|
|
394
|
-
function equalInConstantTime(one, other) {
|
|
395
|
-
if (one.length !== other.length) return false;
|
|
396
|
-
let difference = 0;
|
|
397
|
-
for (let at = 0; at < one.length; at++) difference |= one.charCodeAt(at) ^ other.charCodeAt(at);
|
|
398
|
-
return difference === 0;
|
|
399
|
-
}
|
|
400
|
-
function asBuffer2(bytes) {
|
|
401
|
-
return bytes instanceof Uint8Array && bytes.buffer instanceof ArrayBuffer ? bytes : new Uint8Array(bytes);
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
// ../core/caller.ts
|
|
405
|
-
var KEY_HEADER = "x-client-key";
|
|
406
|
-
var SIGNATURE_HEADER = "x-signature";
|
|
407
|
-
var TIMESTAMP_HEADER = "x-timestamp";
|
|
408
|
-
var PREFIX = "ed25519=";
|
|
409
|
-
var SIGNING_LABEL = "request-signing";
|
|
410
|
-
async function callerKey(secret) {
|
|
411
|
-
return await signingKeyFromSeed(hexToBytes(await hmacHex(secret, SIGNING_LABEL)));
|
|
412
|
-
}
|
|
413
|
-
function paymentNamedBy(caller, paymentHash) {
|
|
414
|
-
return sha256Hex(`${caller}.payment-id.${paymentHash}`);
|
|
415
|
-
}
|
|
416
|
-
async function signedAs(key, method, path, body) {
|
|
417
|
-
const timestamp = String(Math.floor(Date.now() / 1e3));
|
|
418
|
-
return {
|
|
419
|
-
[KEY_HEADER]: key.publicKeyHex,
|
|
420
|
-
[TIMESTAMP_HEADER]: timestamp,
|
|
421
|
-
[SIGNATURE_HEADER]: `${PREFIX}${await key.sign(spoken(timestamp, method, path, body))}`
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
function spoken(timestamp, method, path, body) {
|
|
425
|
-
return new TextEncoder().encode(
|
|
426
|
-
`${timestamp}.${method.toUpperCase()}.${path}.${sha256Hex(body)}`
|
|
427
|
-
);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
299
|
// ../core/url.ts
|
|
431
300
|
var PRIVATE_SUFFIXES = ["localhost", "local", "internal", "lan", "arpa", "test", "invalid"];
|
|
432
301
|
function publicHttps(raw) {
|
|
@@ -449,11 +318,17 @@ function publicAddress(literal) {
|
|
|
449
318
|
return literal.includes(":") ? ipv6IsGlobal(literal) : ipv4IsGlobal(literal);
|
|
450
319
|
}
|
|
451
320
|
function hostIsPublic(host) {
|
|
452
|
-
if (host.startsWith("["))
|
|
321
|
+
if (host.startsWith("[")) {
|
|
322
|
+
return publicAddress(host.slice(1, -1));
|
|
323
|
+
}
|
|
453
324
|
const name = host.replace(/\.$/, "");
|
|
454
|
-
if (/^\d+\.\d+\.\d+\.\d+$/.test(name))
|
|
325
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(name)) {
|
|
326
|
+
return publicAddress(name);
|
|
327
|
+
}
|
|
455
328
|
const labels = name.split(".");
|
|
456
|
-
if (labels.length < 2 || labels.some((label) => label === ""))
|
|
329
|
+
if (labels.length < 2 || labels.some((label) => label === "")) {
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
457
332
|
return !PRIVATE_SUFFIXES.includes(labels[labels.length - 1]);
|
|
458
333
|
}
|
|
459
334
|
function ipv4IsGlobal(literal) {
|
|
@@ -462,25 +337,43 @@ function ipv4IsGlobal(literal) {
|
|
|
462
337
|
return false;
|
|
463
338
|
}
|
|
464
339
|
const [a, b] = parts;
|
|
465
|
-
if (a === 0 || a === 10 || a === 127 || a >= 240)
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
if (a ===
|
|
469
|
-
|
|
340
|
+
if (a === 0 || a === 10 || a === 127 || a >= 240) {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
if (a === 100 && b >= 64 && b < 128) {
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
if (a === 169 && b === 254) {
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
if (a === 172 && b >= 16 && b < 32) {
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
if (a === 192 && b === 168) {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
470
355
|
return true;
|
|
471
356
|
}
|
|
472
357
|
function ipv6IsGlobal(literal) {
|
|
473
358
|
const groups = ipv6Groups(literal.toLowerCase());
|
|
474
|
-
if (groups.length !== 8 || groups.some(Number.isNaN))
|
|
359
|
+
if (groups.length !== 8 || groups.some(Number.isNaN)) {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
475
362
|
const leading = groups.slice(0, 5).every((group) => group === 0);
|
|
476
|
-
if (leading && groups[5] === 0 && groups[6] === 0 && groups[7] <= 1)
|
|
363
|
+
if (leading && groups[5] === 0 && groups[6] === 0 && groups[7] <= 1) {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
477
366
|
if (leading && groups[5] === 65535) {
|
|
478
367
|
const [high, low] = [groups[6], groups[7]];
|
|
479
368
|
return ipv4IsGlobal(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
|
|
480
369
|
}
|
|
481
370
|
const first = groups[0];
|
|
482
|
-
if ((first & 65024) === 64512)
|
|
483
|
-
|
|
371
|
+
if ((first & 65024) === 64512) {
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
if ((first & 65472) === 65152) {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
484
377
|
return true;
|
|
485
378
|
}
|
|
486
379
|
function ipv6Groups(address) {
|
|
@@ -491,74 +384,276 @@ function ipv6Groups(address) {
|
|
|
491
384
|
return [...left, ...gap, ...right].map((group) => parseInt(group, 16));
|
|
492
385
|
}
|
|
493
386
|
|
|
494
|
-
//
|
|
495
|
-
var
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
);
|
|
501
|
-
if (
|
|
502
|
-
|
|
503
|
-
const invoice = decodeInvoice(payment.bolt11);
|
|
504
|
-
if (invoice.paymentHash === null || !equalIgnoringCase(invoice.paymentHash, payment.paymentHash)) {
|
|
505
|
-
throw cheat("hash_mismatch");
|
|
506
|
-
}
|
|
507
|
-
if (invoice.amountMsat !== request.amountMsat) throw cheat("amount_mismatch");
|
|
508
|
-
const payRequest = await payRequestFor(listed, payment);
|
|
509
|
-
if (typeof payRequest.metadata !== "string" || typeof payRequest.callback !== "string") {
|
|
510
|
-
throw new UnverifiedRecipientError(payment.lnAddress, payment.id, "no payRequest served");
|
|
511
|
-
}
|
|
512
|
-
if (invoice.descriptionHash !== sha256Hex(payRequest.metadata)) {
|
|
513
|
-
throw cheat("description_hash_mismatch");
|
|
514
|
-
}
|
|
515
|
-
if (!sameOrigin(payment.verifyUrl, payRequest.callback)) throw cheat("verify_url_foreign");
|
|
516
|
-
const issued = await reachable(payment.verifyUrl, payment);
|
|
517
|
-
if (typeof issued.pr !== "string" || !equalIgnoringCase(issued.pr, payment.bolt11)) {
|
|
518
|
-
throw cheat("invoice_not_issued");
|
|
387
|
+
// ../core/lnurl.ts
|
|
388
|
+
var BECH32_CHARSET2 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
389
|
+
var BECH32_GENERATOR = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
390
|
+
var CHECKSUM_SLOTS = [0, 1, 2, 3, 4, 5];
|
|
391
|
+
var LNURL_HRP = "lnurl";
|
|
392
|
+
function toLnurl(endpoint) {
|
|
393
|
+
const scheme = parsedScheme(endpoint);
|
|
394
|
+
if (scheme !== "https:" && scheme !== "http:") {
|
|
395
|
+
throw new Error(`${endpoint} is not an http or https URL`);
|
|
519
396
|
}
|
|
397
|
+
const words = toWords(new TextEncoder().encode(endpoint));
|
|
398
|
+
const data = [...words, ...checksumWords(LNURL_HRP, words)];
|
|
399
|
+
return `${LNURL_HRP}1${data.map((word) => BECH32_CHARSET2[word]).join("")}`.toUpperCase();
|
|
520
400
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
throw new GatewayCheatError("preimage_mismatch", payment.id);
|
|
401
|
+
function parsedScheme(endpoint) {
|
|
402
|
+
try {
|
|
403
|
+
return new URL(endpoint).protocol;
|
|
404
|
+
} catch {
|
|
405
|
+
return null;
|
|
527
406
|
}
|
|
528
|
-
return verified.preimage;
|
|
529
|
-
}
|
|
530
|
-
function isProvablyPaid(payment) {
|
|
531
|
-
if (payment.status !== "paid" || payment.preimage === null) return false;
|
|
532
|
-
const invoiceHash = decodeInvoice(payment.bolt11).paymentHash;
|
|
533
|
-
if (invoiceHash === null || !equalIgnoringCase(invoiceHash, payment.paymentHash)) return false;
|
|
534
|
-
return preimageMatchesHash(payment.preimage, invoiceHash);
|
|
535
407
|
}
|
|
536
|
-
|
|
537
|
-
const
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
408
|
+
function toWords(bytes) {
|
|
409
|
+
const words = [];
|
|
410
|
+
let accumulator = 0;
|
|
411
|
+
let bits = 0;
|
|
412
|
+
for (const byte of bytes) {
|
|
413
|
+
accumulator = accumulator << 8 | byte;
|
|
414
|
+
bits += 8;
|
|
415
|
+
while (bits >= 5) {
|
|
416
|
+
bits -= 5;
|
|
417
|
+
words.push(accumulator >> bits & 31);
|
|
418
|
+
}
|
|
542
419
|
}
|
|
543
|
-
|
|
420
|
+
if (bits > 0) {
|
|
421
|
+
words.push(accumulator << 5 - bits & 31);
|
|
422
|
+
}
|
|
423
|
+
return words;
|
|
544
424
|
}
|
|
545
|
-
|
|
425
|
+
function checksumWords(hrp, words) {
|
|
426
|
+
const expanded = [...hrp].map((char) => char.charCodeAt(0));
|
|
427
|
+
const values = [
|
|
428
|
+
...expanded.map((code) => code >> 5),
|
|
429
|
+
0,
|
|
430
|
+
...expanded.map((code) => code & 31),
|
|
431
|
+
...words,
|
|
432
|
+
...CHECKSUM_SLOTS.map(() => 0)
|
|
433
|
+
];
|
|
434
|
+
const polymod = bech32Polymod(values) ^ 1;
|
|
435
|
+
return CHECKSUM_SLOTS.map((slot) => polymod >> 5 * (5 - slot) & 31);
|
|
436
|
+
}
|
|
437
|
+
function bech32Polymod(values) {
|
|
438
|
+
let checksum = 1;
|
|
439
|
+
for (const value of values) {
|
|
440
|
+
const top = checksum >> 25;
|
|
441
|
+
checksum = (checksum & 33554431) << 5 ^ value;
|
|
442
|
+
for (let bit = 0; bit < 5; bit++) {
|
|
443
|
+
if (top >> bit & 1) {
|
|
444
|
+
checksum ^= BECH32_GENERATOR[bit];
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return checksum;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// ../core/sealed.ts
|
|
452
|
+
var VERSION = "v1";
|
|
453
|
+
var IV_BYTES = 12;
|
|
454
|
+
var MIN_SECRET_CHARS = 32;
|
|
455
|
+
var MAX_PLAIN_BYTES = 3e3;
|
|
456
|
+
var INFO = new TextEncoder().encode("thunder-bridge/sealed");
|
|
457
|
+
async function seal(secret, plaintext) {
|
|
458
|
+
const body = new TextEncoder().encode(plaintext);
|
|
459
|
+
if (body.length > MAX_PLAIN_BYTES) {
|
|
460
|
+
throw new Error(`sealed takes at most ${MAX_PLAIN_BYTES} bytes, this was ${body.length}`);
|
|
461
|
+
}
|
|
462
|
+
const key = await keyFor(secret);
|
|
463
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
464
|
+
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, body));
|
|
465
|
+
const joined = new Uint8Array(iv.length + cipher.length);
|
|
466
|
+
joined.set(iv);
|
|
467
|
+
joined.set(cipher, iv.length);
|
|
468
|
+
return `${VERSION}.${toBase64Url(joined)}`;
|
|
469
|
+
}
|
|
470
|
+
async function unseal(secret, sealed) {
|
|
471
|
+
const key = await keyFor(secret);
|
|
472
|
+
if (!sealed.startsWith(`${VERSION}.`)) {
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
const joined = fromBase64Url(sealed.slice(VERSION.length + 1));
|
|
476
|
+
if (joined === null || joined.length <= IV_BYTES) {
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
546
479
|
try {
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
return body;
|
|
556
|
-
} catch (cause) {
|
|
557
|
-
throw new UnverifiedRecipientError(payment.lnAddress, payment.id, cause);
|
|
480
|
+
const body = await crypto.subtle.decrypt(
|
|
481
|
+
{ name: "AES-GCM", iv: joined.slice(0, IV_BYTES) },
|
|
482
|
+
key,
|
|
483
|
+
joined.slice(IV_BYTES)
|
|
484
|
+
);
|
|
485
|
+
return new TextDecoder().decode(body);
|
|
486
|
+
} catch {
|
|
487
|
+
return null;
|
|
558
488
|
}
|
|
559
489
|
}
|
|
560
|
-
function
|
|
561
|
-
|
|
490
|
+
async function keyFor(secret) {
|
|
491
|
+
if (secret.length < MIN_SECRET_CHARS) {
|
|
492
|
+
throw new Error(`the sealing secret needs ${MIN_SECRET_CHARS} characters of randomness`);
|
|
493
|
+
}
|
|
494
|
+
const material = await crypto.subtle.importKey(
|
|
495
|
+
"raw",
|
|
496
|
+
new TextEncoder().encode(secret),
|
|
497
|
+
"HKDF",
|
|
498
|
+
false,
|
|
499
|
+
["deriveKey"]
|
|
500
|
+
);
|
|
501
|
+
return crypto.subtle.deriveKey(
|
|
502
|
+
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: INFO },
|
|
503
|
+
material,
|
|
504
|
+
{ name: "AES-GCM", length: 256 },
|
|
505
|
+
false,
|
|
506
|
+
["encrypt", "decrypt"]
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
function toBase64Url(bytes) {
|
|
510
|
+
let binary = "";
|
|
511
|
+
for (const byte of bytes) {
|
|
512
|
+
binary += String.fromCharCode(byte);
|
|
513
|
+
}
|
|
514
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
515
|
+
}
|
|
516
|
+
function fromBase64Url(text2) {
|
|
517
|
+
if (text2.length === 0 || !/^[A-Za-z0-9_-]+$/.test(text2)) {
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
try {
|
|
521
|
+
const binary = atob(text2.replace(/-/g, "+").replace(/_/g, "/"));
|
|
522
|
+
const bytes = new Uint8Array(binary.length);
|
|
523
|
+
for (let at = 0; at < bytes.length; at++) {
|
|
524
|
+
bytes[at] = binary.charCodeAt(at);
|
|
525
|
+
}
|
|
526
|
+
return bytes;
|
|
527
|
+
} catch {
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// ../core/hmac.ts
|
|
533
|
+
async function hmacHex(secret, payload) {
|
|
534
|
+
const raw = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
|
|
535
|
+
const key = await crypto.subtle.importKey(
|
|
536
|
+
"raw",
|
|
537
|
+
asBuffer(raw),
|
|
538
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
539
|
+
false,
|
|
540
|
+
["sign"]
|
|
541
|
+
);
|
|
542
|
+
const message = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
|
|
543
|
+
return bytesToHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, asBuffer(message))));
|
|
544
|
+
}
|
|
545
|
+
function equalInConstantTime(one, other) {
|
|
546
|
+
if (one.length !== other.length) {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
let difference = 0;
|
|
550
|
+
for (let at = 0; at < one.length; at++) {
|
|
551
|
+
difference |= one.charCodeAt(at) ^ other.charCodeAt(at);
|
|
552
|
+
}
|
|
553
|
+
return difference === 0;
|
|
554
|
+
}
|
|
555
|
+
function asBuffer(bytes) {
|
|
556
|
+
return bytes instanceof Uint8Array && bytes.buffer instanceof ArrayBuffer ? bytes : new Uint8Array(bytes);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// src/currency.ts
|
|
560
|
+
var ISO_4217_MINOR_UNITS = {
|
|
561
|
+
BHD: 3,
|
|
562
|
+
BIF: 0,
|
|
563
|
+
CLP: 0,
|
|
564
|
+
CZK: 2,
|
|
565
|
+
DJF: 0,
|
|
566
|
+
EUR: 2,
|
|
567
|
+
GBP: 2,
|
|
568
|
+
ISK: 0,
|
|
569
|
+
IQD: 3,
|
|
570
|
+
JOD: 3,
|
|
571
|
+
JPY: 0,
|
|
572
|
+
KRW: 0,
|
|
573
|
+
KWD: 3,
|
|
574
|
+
LYD: 3,
|
|
575
|
+
OMR: 3,
|
|
576
|
+
PLN: 2,
|
|
577
|
+
PYG: 0,
|
|
578
|
+
RWF: 0,
|
|
579
|
+
TND: 3,
|
|
580
|
+
UGX: 0,
|
|
581
|
+
USD: 2,
|
|
582
|
+
VND: 0,
|
|
583
|
+
VUV: 0,
|
|
584
|
+
XAF: 0,
|
|
585
|
+
XOF: 0,
|
|
586
|
+
XPF: 0
|
|
587
|
+
};
|
|
588
|
+
function minorUnitsOf(currency) {
|
|
589
|
+
const digits = ISO_4217_MINOR_UNITS[currency.toUpperCase()];
|
|
590
|
+
if (digits === void 0) {
|
|
591
|
+
throw new Error(
|
|
592
|
+
`${currency.toUpperCase()} is not a currency this knows the ISO 4217 minor unit of`
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
return digits;
|
|
596
|
+
}
|
|
597
|
+
function minorScaleOf(currency) {
|
|
598
|
+
return 10 ** minorUnitsOf(currency);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ../core/ed25519.ts
|
|
602
|
+
var ALGORITHM = { name: "Ed25519" };
|
|
603
|
+
var SEED_BYTES = 32;
|
|
604
|
+
var SIGNATURE_BYTES = 64;
|
|
605
|
+
var PUBLIC_KEY_BYTES = 32;
|
|
606
|
+
var PKCS8_HEADER = hexToBytes("302e020100300506032b657004220420");
|
|
607
|
+
async function signingKeyFromSeed(seed) {
|
|
608
|
+
if (seed.length !== SEED_BYTES) {
|
|
609
|
+
throw new Error(`an ed25519 seed is ${SEED_BYTES} bytes`);
|
|
610
|
+
}
|
|
611
|
+
const wrapped = new Uint8Array(PKCS8_HEADER.length + SEED_BYTES);
|
|
612
|
+
wrapped.set(PKCS8_HEADER);
|
|
613
|
+
wrapped.set(seed, PKCS8_HEADER.length);
|
|
614
|
+
const key = await crypto.subtle.importKey("pkcs8", asBuffer2(wrapped), ALGORITHM, true, ["sign"]);
|
|
615
|
+
const jwk = await crypto.subtle.exportKey("jwk", key);
|
|
616
|
+
return {
|
|
617
|
+
publicKeyHex: bytesToHex(fromBase64Url2(jwk.x ?? "")),
|
|
618
|
+
sign: async (payload) => bytesToHex(new Uint8Array(await crypto.subtle.sign(ALGORITHM, key, asBuffer2(payload))))
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
async function verifyHex(publicKeyHex, signatureHex, payload) {
|
|
622
|
+
if (!isHex(publicKeyHex) || publicKeyHex.length !== PUBLIC_KEY_BYTES * 2) {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
if (!isHex(signatureHex) || signatureHex.length !== SIGNATURE_BYTES * 2) {
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
const key = await crypto.subtle.importKey(
|
|
630
|
+
"raw",
|
|
631
|
+
asBuffer2(hexToBytes(publicKeyHex)),
|
|
632
|
+
ALGORITHM,
|
|
633
|
+
false,
|
|
634
|
+
["verify"]
|
|
635
|
+
);
|
|
636
|
+
return await crypto.subtle.verify(
|
|
637
|
+
ALGORITHM,
|
|
638
|
+
key,
|
|
639
|
+
asBuffer2(hexToBytes(signatureHex)),
|
|
640
|
+
asBuffer2(payload)
|
|
641
|
+
);
|
|
642
|
+
} catch {
|
|
643
|
+
return false;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
function fromBase64Url2(text2) {
|
|
647
|
+
const padded = text2.replace(/-/g, "+").replace(/_/g, "/");
|
|
648
|
+
const raw = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
649
|
+
const bytes = new Uint8Array(raw.length);
|
|
650
|
+
for (let at = 0; at < raw.length; at++) {
|
|
651
|
+
bytes[at] = raw.charCodeAt(at);
|
|
652
|
+
}
|
|
653
|
+
return bytes;
|
|
654
|
+
}
|
|
655
|
+
function asBuffer2(bytes) {
|
|
656
|
+
return bytes.buffer instanceof ArrayBuffer ? bytes : new Uint8Array(bytes);
|
|
562
657
|
}
|
|
563
658
|
|
|
564
659
|
// src/wire.ts
|
|
@@ -571,12 +666,13 @@ var REASONS = /* @__PURE__ */ new Set([
|
|
|
571
666
|
"cannot-prove-delivery",
|
|
572
667
|
"invoice-refused"
|
|
573
668
|
]);
|
|
574
|
-
function createRequestBody(params, trigger) {
|
|
669
|
+
function createRequestBody(params, trigger, replay) {
|
|
575
670
|
return JSON.stringify({
|
|
576
671
|
ln_addresses: params.lnAddresses,
|
|
577
672
|
incoming_amount: toAmount(params.amountMsat),
|
|
578
673
|
webhook: params.webhookUrl ? { url: params.webhookUrl } : void 0,
|
|
579
|
-
trigger: trigger ?? void 0
|
|
674
|
+
trigger: trigger ?? void 0,
|
|
675
|
+
replay
|
|
580
676
|
});
|
|
581
677
|
}
|
|
582
678
|
function quoteRequestBody(params) {
|
|
@@ -587,7 +683,9 @@ function quoteRequestBody(params) {
|
|
|
587
683
|
}
|
|
588
684
|
function quoteFromWire(body) {
|
|
589
685
|
const wire = asObject(body);
|
|
590
|
-
if (wire === null)
|
|
686
|
+
if (wire === null) {
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
591
689
|
const lnAddress = text(wire["ln_address"]);
|
|
592
690
|
const amountMsat = msatFrom(wire["amount"], 1);
|
|
593
691
|
const feeMsat = msatFrom(wire["fee"], 0);
|
|
@@ -595,13 +693,19 @@ function quoteFromWire(body) {
|
|
|
595
693
|
const maxMsat = msatFrom(wire["max_amount"], 0);
|
|
596
694
|
const metadata = text(wire["metadata"]);
|
|
597
695
|
const refusals3 = refusalsFrom(wire["refusals"]);
|
|
598
|
-
if (lnAddress === null || amountMsat === null || feeMsat === null)
|
|
599
|
-
|
|
696
|
+
if (lnAddress === null || amountMsat === null || feeMsat === null) {
|
|
697
|
+
return null;
|
|
698
|
+
}
|
|
699
|
+
if (minMsat === null || maxMsat === null || metadata === null || refusals3 === null) {
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
600
702
|
return { lnAddress, amountMsat, feeMsat, minMsat, maxMsat, metadata, refusals: refusals3 };
|
|
601
703
|
}
|
|
602
704
|
function paymentFromWire(body) {
|
|
603
705
|
const wire = asObject(body);
|
|
604
|
-
if (wire === null)
|
|
706
|
+
if (wire === null) {
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
605
709
|
const id = text(wire["id"]);
|
|
606
710
|
const lnAddress = text(wire["ln_address"]);
|
|
607
711
|
const bolt11 = text(wire["bolt11"]);
|
|
@@ -612,11 +716,21 @@ function paymentFromWire(body) {
|
|
|
612
716
|
const createdAt = secondsFrom(wire["created_at"]);
|
|
613
717
|
const status = wire["status"];
|
|
614
718
|
const preimage = wire["preimage"] ?? null;
|
|
615
|
-
if (id === null || lnAddress === null || bolt11 === null)
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
if (
|
|
619
|
-
|
|
719
|
+
if (id === null || lnAddress === null || bolt11 === null) {
|
|
720
|
+
return null;
|
|
721
|
+
}
|
|
722
|
+
if (paymentHash === null || verifyUrl === null) {
|
|
723
|
+
return null;
|
|
724
|
+
}
|
|
725
|
+
if (amountMsat === null || expiresAt === null || createdAt === null) {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
if (!isStatus(status)) {
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
if (preimage !== null && typeof preimage !== "string") {
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
620
734
|
return {
|
|
621
735
|
id,
|
|
622
736
|
lnAddress,
|
|
@@ -640,25 +754,34 @@ function watchRequestBody(params, trigger) {
|
|
|
640
754
|
verify_url: params.verifyUrl,
|
|
641
755
|
expires_at: expiresAt.toISOString(),
|
|
642
756
|
trigger: trigger ?? void 0,
|
|
757
|
+
replay: params.replay,
|
|
643
758
|
sealed: params.sealed,
|
|
644
759
|
webhook: params.webhookUrl ? { url: params.webhookUrl } : void 0
|
|
645
760
|
});
|
|
646
761
|
}
|
|
647
762
|
function settlementFromWire(body) {
|
|
648
763
|
const wire = asObject(body);
|
|
649
|
-
if (wire === null)
|
|
764
|
+
if (wire === null) {
|
|
765
|
+
return null;
|
|
766
|
+
}
|
|
650
767
|
const id = text(wire["id"]);
|
|
651
768
|
const paymentHash = text(wire["payment_hash"]);
|
|
652
769
|
const settledAt = secondsFrom(wire["settled_at"]);
|
|
653
770
|
const status = wire["status"];
|
|
654
771
|
const preimage = wire["preimage"] ?? null;
|
|
655
|
-
if (id === null || paymentHash === null || settledAt === null || !isStatus(status))
|
|
656
|
-
|
|
772
|
+
if (id === null || paymentHash === null || settledAt === null || !isStatus(status)) {
|
|
773
|
+
return null;
|
|
774
|
+
}
|
|
775
|
+
if (preimage !== null && typeof preimage !== "string") {
|
|
776
|
+
return null;
|
|
777
|
+
}
|
|
657
778
|
return { id, status, paymentHash, preimage, settledAt };
|
|
658
779
|
}
|
|
659
780
|
function triggerEventFromWire(body) {
|
|
660
781
|
const wire = asObject(body);
|
|
661
|
-
if (wire === null)
|
|
782
|
+
if (wire === null) {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
662
785
|
const id = text(wire["id"]);
|
|
663
786
|
const paymentHash = text(wire["payment_hash"]);
|
|
664
787
|
const verifyUrl = text(wire["verify_url"]);
|
|
@@ -667,10 +790,18 @@ function triggerEventFromWire(body) {
|
|
|
667
790
|
const status = wire["status"];
|
|
668
791
|
const preimage = wire["preimage"] ?? null;
|
|
669
792
|
const sealed = wire["sealed"] ?? null;
|
|
670
|
-
if (id === null || paymentHash === null || verifyUrl === null)
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
if (
|
|
793
|
+
if (id === null || paymentHash === null || verifyUrl === null) {
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
if (expiresAt === null || createdAt === null || !isStatus(status)) {
|
|
797
|
+
return null;
|
|
798
|
+
}
|
|
799
|
+
if (preimage !== null && typeof preimage !== "string") {
|
|
800
|
+
return null;
|
|
801
|
+
}
|
|
802
|
+
if (sealed !== null && typeof sealed !== "string") {
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
674
805
|
return {
|
|
675
806
|
id,
|
|
676
807
|
kind: kindOf(wire),
|
|
@@ -685,16 +816,32 @@ function triggerEventFromWire(body) {
|
|
|
685
816
|
amountMsat: wire["incoming_amount"] === void 0 ? null : msatFrom(wire["incoming_amount"], 1)
|
|
686
817
|
};
|
|
687
818
|
}
|
|
819
|
+
function socketTicketFromWire(body) {
|
|
820
|
+
const wire = asObject(body);
|
|
821
|
+
if (wire === null) {
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
const ticket = text(wire["ticket"]);
|
|
825
|
+
const expiresAt = secondsFrom(wire["expires_at"]);
|
|
826
|
+
if (ticket === null || expiresAt === null) {
|
|
827
|
+
return null;
|
|
828
|
+
}
|
|
829
|
+
return { ticket, expiresAt };
|
|
830
|
+
}
|
|
688
831
|
function kindOf(wire) {
|
|
689
832
|
const said = wire["kind"];
|
|
690
|
-
if (said === "minted" || said === "watched")
|
|
833
|
+
if (said === "minted" || said === "watched") {
|
|
834
|
+
return said;
|
|
835
|
+
}
|
|
691
836
|
return text(wire["ln_address"]) === null ? "watched" : "minted";
|
|
692
837
|
}
|
|
693
838
|
function toAmount(msat) {
|
|
694
839
|
return { value: String(msat), asset_code: ASSET_CODE, asset_scale: ASSET_SCALE };
|
|
695
840
|
}
|
|
696
841
|
function asObject(value) {
|
|
697
|
-
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
842
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
843
|
+
return null;
|
|
844
|
+
}
|
|
698
845
|
return value;
|
|
699
846
|
}
|
|
700
847
|
function text(value) {
|
|
@@ -702,27 +849,39 @@ function text(value) {
|
|
|
702
849
|
}
|
|
703
850
|
function msatFrom(value, least) {
|
|
704
851
|
const amount = asObject(value);
|
|
705
|
-
if (amount === null)
|
|
706
|
-
|
|
852
|
+
if (amount === null) {
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
if (amount["asset_code"] !== ASSET_CODE || amount["asset_scale"] !== ASSET_SCALE) {
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
707
858
|
const digits = amount["value"];
|
|
708
|
-
if (typeof digits !== "string" || !/^[0-9]+$/.test(digits))
|
|
859
|
+
if (typeof digits !== "string" || !/^[0-9]+$/.test(digits)) {
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
709
862
|
const msat = Number(digits);
|
|
710
863
|
return Number.isSafeInteger(msat) && msat >= least ? msat : null;
|
|
711
864
|
}
|
|
712
865
|
function refusalsFrom(value) {
|
|
713
|
-
if (!Array.isArray(value))
|
|
866
|
+
if (!Array.isArray(value)) {
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
714
869
|
const refusals3 = [];
|
|
715
870
|
for (const entry of value) {
|
|
716
871
|
const failure = asObject(entry);
|
|
717
872
|
const address = failure === null ? null : text(failure["address"]);
|
|
718
873
|
const reason = failure?.["reason"];
|
|
719
|
-
if (address === null || typeof reason !== "string" || !REASONS.has(reason))
|
|
874
|
+
if (address === null || typeof reason !== "string" || !REASONS.has(reason)) {
|
|
875
|
+
return null;
|
|
876
|
+
}
|
|
720
877
|
refusals3.push({ address, reason });
|
|
721
878
|
}
|
|
722
879
|
return refusals3;
|
|
723
880
|
}
|
|
724
881
|
function secondsFrom(value) {
|
|
725
|
-
if (typeof value !== "string")
|
|
882
|
+
if (typeof value !== "string") {
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
726
885
|
const milliseconds = Date.parse(value);
|
|
727
886
|
return Number.isNaN(milliseconds) ? null : Math.floor(milliseconds / 1e3);
|
|
728
887
|
}
|
|
@@ -730,910 +889,1064 @@ function isStatus(value) {
|
|
|
730
889
|
return value === "pending" || value === "paid" || value === "expired";
|
|
731
890
|
}
|
|
732
891
|
|
|
733
|
-
// src/
|
|
734
|
-
var
|
|
735
|
-
var
|
|
736
|
-
var
|
|
737
|
-
var
|
|
738
|
-
var
|
|
739
|
-
var
|
|
740
|
-
function
|
|
741
|
-
if (
|
|
742
|
-
|
|
743
|
-
`a trigger secret is the only thing guarding its stream, and nothing rate limits a guess at it, so it has to be at least ${TRIGGER_MIN_CHARS} characters nobody can predict`
|
|
744
|
-
);
|
|
892
|
+
// src/webhook.ts
|
|
893
|
+
var SIGNATURE_HEADER = "x-signature";
|
|
894
|
+
var TIMESTAMP_HEADER = "x-timestamp";
|
|
895
|
+
var GATEWAY_KEY_PREFIX = "ed25519=";
|
|
896
|
+
var DEFAULT_TOLERANCE_SECS = 300;
|
|
897
|
+
var CHALLENGE = "webhook-challenge";
|
|
898
|
+
var VERIFY_CHALLENGE = "verify-challenge";
|
|
899
|
+
async function verifyWebhookSignature(body, signature, credential, timestamp, options = {}) {
|
|
900
|
+
if (!recent(timestamp, options.toleranceSecs ?? DEFAULT_TOLERANCE_SECS)) {
|
|
901
|
+
return false;
|
|
745
902
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
903
|
+
if (!signature.startsWith(GATEWAY_KEY_PREFIX)) {
|
|
904
|
+
return false;
|
|
905
|
+
}
|
|
906
|
+
return await verifyHex(
|
|
907
|
+
credential.publicKey.toLowerCase(),
|
|
908
|
+
signature.slice(GATEWAY_KEY_PREFIX.length).toLowerCase(),
|
|
909
|
+
signed(timestamp, body)
|
|
910
|
+
);
|
|
751
911
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
token;
|
|
756
|
-
secret;
|
|
757
|
-
strangers = null;
|
|
758
|
-
speaks = null;
|
|
759
|
-
constructor(baseUrl, options) {
|
|
760
|
-
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
761
|
-
this.verify = options?.verify ?? true;
|
|
762
|
-
this.token = options?.token ?? null;
|
|
763
|
-
this.secret = options?.secret ?? null;
|
|
912
|
+
async function parseWebhook(body, signature, credential, timestamp, options = {}) {
|
|
913
|
+
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) {
|
|
914
|
+
return null;
|
|
764
915
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
get isPrivate() {
|
|
771
|
-
return this.token !== null;
|
|
916
|
+
const text2 = typeof body === "string" ? body : new TextDecoder().decode(body);
|
|
917
|
+
try {
|
|
918
|
+
return paymentFromWire(JSON.parse(text2));
|
|
919
|
+
} catch {
|
|
920
|
+
return null;
|
|
772
921
|
}
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
* instance does not change its mind. Anything other than a refusal counts as
|
|
780
|
-
* open, so an unreachable gateway fails closed
|
|
781
|
-
*/
|
|
782
|
-
async refusesStrangers() {
|
|
783
|
-
this.strangers ??= fetch(`${this.baseUrl}/incoming-payments/${STRANGER_PROBE}`, {
|
|
784
|
-
headers: { accept: "application/json" }
|
|
785
|
-
}).then((answer) => answer.status === 401).catch(() => false);
|
|
786
|
-
return await this.strangers;
|
|
922
|
+
}
|
|
923
|
+
async function parseWebhookRequest(request, credential, options = {}) {
|
|
924
|
+
const signature = request.headers.get(SIGNATURE_HEADER);
|
|
925
|
+
const timestamp = request.headers.get(TIMESTAMP_HEADER);
|
|
926
|
+
if (signature === null || timestamp === null) {
|
|
927
|
+
return null;
|
|
787
928
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
async createPayment(params, options) {
|
|
794
|
-
const sent = createRequestBody(
|
|
795
|
-
params,
|
|
796
|
-
options?.trigger ? sha256Hex(unguessable(options.trigger)) : null
|
|
797
|
-
);
|
|
798
|
-
const headers = await this.sending("/incoming-payments", sent);
|
|
799
|
-
if (options?.idempotencyKey) headers["idempotency-key"] = options.idempotencyKey;
|
|
800
|
-
const response = await fetch(`${this.baseUrl}/incoming-payments`, {
|
|
801
|
-
method: "POST",
|
|
802
|
-
headers,
|
|
803
|
-
body: sent
|
|
804
|
-
});
|
|
805
|
-
if (!response.ok) throw await problemFrom(response);
|
|
806
|
-
const payment = await paymentFrom(response);
|
|
807
|
-
if (this.verify) await proveOrigin(payment, params);
|
|
808
|
-
return payment;
|
|
929
|
+
return parseWebhook(await request.text(), signature, credential, timestamp, options);
|
|
930
|
+
}
|
|
931
|
+
async function parseWatchedWebhook(body, signature, credential, timestamp, options = {}) {
|
|
932
|
+
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) {
|
|
933
|
+
return null;
|
|
809
934
|
}
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
* it for one, and asking mints it
|
|
816
|
-
*/
|
|
817
|
-
async createQuote(params) {
|
|
818
|
-
const sent = quoteRequestBody(params);
|
|
819
|
-
const response = await fetch(`${this.baseUrl}/quotes`, {
|
|
820
|
-
method: "POST",
|
|
821
|
-
headers: await this.sending("/quotes", sent),
|
|
822
|
-
body: sent
|
|
823
|
-
});
|
|
824
|
-
if (!response.ok) throw await problemFrom(response);
|
|
825
|
-
const quote = quoteFromWire(await response.json().catch(() => null));
|
|
826
|
-
if (quote === null) {
|
|
827
|
-
throw new ProblemError({
|
|
828
|
-
status: response.status,
|
|
829
|
-
title: "The gateway answered with something that is not a quote"
|
|
830
|
-
});
|
|
831
|
-
}
|
|
832
|
-
return quote;
|
|
935
|
+
const text2 = typeof body === "string" ? body : new TextDecoder().decode(body);
|
|
936
|
+
try {
|
|
937
|
+
return triggerEventFromWire(JSON.parse(text2));
|
|
938
|
+
} catch {
|
|
939
|
+
return null;
|
|
833
940
|
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
async webhookKey() {
|
|
841
|
-
const response = await fetch(`${this.baseUrl}/webhook-key`);
|
|
842
|
-
if (!response.ok) throw await problemFrom(response);
|
|
843
|
-
const body = await response.json().catch(() => null);
|
|
844
|
-
if (body?.algorithm !== "ed25519" || typeof body.public_key !== "string") {
|
|
845
|
-
throw new ProblemError({
|
|
846
|
-
status: response.status,
|
|
847
|
-
title: "The gateway published no ed25519 webhook key"
|
|
848
|
-
});
|
|
849
|
-
}
|
|
850
|
-
return body.public_key;
|
|
941
|
+
}
|
|
942
|
+
async function parseWatchedWebhookRequest(request, credential, options = {}) {
|
|
943
|
+
const signature = request.headers.get(SIGNATURE_HEADER);
|
|
944
|
+
const timestamp = request.headers.get(TIMESTAMP_HEADER);
|
|
945
|
+
if (signature === null || timestamp === null) {
|
|
946
|
+
return null;
|
|
851
947
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
if (response.status === 404) return null;
|
|
858
|
-
if (!response.ok) throw await problemFrom(response);
|
|
859
|
-
return this.checked(await paymentFrom(response));
|
|
948
|
+
return parseWatchedWebhook(await request.text(), signature, credential, timestamp, options);
|
|
949
|
+
}
|
|
950
|
+
async function parseSettlement(body, signature, credential, timestamp, options = {}) {
|
|
951
|
+
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) {
|
|
952
|
+
return null;
|
|
860
953
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
*/
|
|
866
|
-
async getWatched(id) {
|
|
867
|
-
const path = `/incoming-payments/${encodeURIComponent(id)}`;
|
|
868
|
-
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
869
|
-
headers: await this.reading("GET", path)
|
|
870
|
-
});
|
|
871
|
-
if (response.status === 404) return null;
|
|
872
|
-
if (!response.ok) throw await problemFrom(response);
|
|
873
|
-
const watched = triggerEventFromWire(await response.json().catch(() => null));
|
|
874
|
-
if (watched === null) {
|
|
875
|
-
throw new ProblemError({
|
|
876
|
-
status: response.status,
|
|
877
|
-
title: "The gateway answered with something that is not a payment"
|
|
878
|
-
});
|
|
879
|
-
}
|
|
880
|
-
return this.proven(watched);
|
|
954
|
+
try {
|
|
955
|
+
return settlementFromWire(JSON.parse(textOf(body)));
|
|
956
|
+
} catch {
|
|
957
|
+
return null;
|
|
881
958
|
}
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
* Anything older than that window is not in the answer, and the list does not
|
|
889
|
-
* pretend otherwise
|
|
890
|
-
*/
|
|
891
|
-
async listPayments(limit) {
|
|
892
|
-
const path = `/incoming-payments${limit === void 0 ? "" : `?limit=${limit}`}`;
|
|
893
|
-
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
894
|
-
headers: await this.reading("GET", path)
|
|
895
|
-
});
|
|
896
|
-
if (!response.ok) throw await problemFrom(response);
|
|
897
|
-
const body = await response.json().catch(() => null);
|
|
898
|
-
const listed = Array.isArray(body?.payments) ? body.payments.map(triggerEventFromWire).filter((one) => one !== null) : null;
|
|
899
|
-
if (listed === null || typeof body?.settled_scanned !== "number") {
|
|
900
|
-
throw new ProblemError({
|
|
901
|
-
status: response.status,
|
|
902
|
-
title: "The gateway answered with something that is not a payment list"
|
|
903
|
-
});
|
|
904
|
-
}
|
|
905
|
-
return { payments: listed, scanned: body.settled_scanned };
|
|
959
|
+
}
|
|
960
|
+
async function parseSettlementRequest(request, credential, options = {}) {
|
|
961
|
+
const signature = request.headers.get(SIGNATURE_HEADER);
|
|
962
|
+
const timestamp = request.headers.get(TIMESTAMP_HEADER);
|
|
963
|
+
if (signature === null || timestamp === null) {
|
|
964
|
+
return null;
|
|
906
965
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
*/
|
|
913
|
-
async waitForPayment(id, options) {
|
|
914
|
-
const payment = paymentFromWire(await this.followed(id, options));
|
|
915
|
-
if (payment === null) {
|
|
916
|
-
throw new ProblemError({
|
|
917
|
-
status: 200,
|
|
918
|
-
title: `payment ${id} is watched rather than minted here, read it with waitForWatched`
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
return this.checked(payment);
|
|
966
|
+
return await parseSettlement(await request.text(), signature, credential, timestamp, options);
|
|
967
|
+
}
|
|
968
|
+
function isProvablySettled(settled) {
|
|
969
|
+
if (settled.status !== "paid" || settled.preimage === null) {
|
|
970
|
+
return false;
|
|
922
971
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
* gateway was told none of them, so it reads back as the shape a trigger
|
|
929
|
-
* streams rather than as a `Payment`. That is every bank transfer, and every
|
|
930
|
-
* Lightning invoice registered with `watchPayment` instead of `createPayment`.
|
|
931
|
-
*/
|
|
932
|
-
async waitForWatched(id, options) {
|
|
933
|
-
const watched = triggerEventFromWire(await this.followed(id, options));
|
|
934
|
-
if (watched === null) {
|
|
935
|
-
throw new ProblemError({
|
|
936
|
-
status: 200,
|
|
937
|
-
title: "The gateway answered with something that is not a payment"
|
|
938
|
-
});
|
|
939
|
-
}
|
|
940
|
-
return this.proven(watched);
|
|
972
|
+
return preimageMatchesHash(settled.preimage, settled.paymentHash);
|
|
973
|
+
}
|
|
974
|
+
async function answerWebhookChallenge(body, signature, credential, timestamp, options = {}) {
|
|
975
|
+
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) {
|
|
976
|
+
return null;
|
|
941
977
|
}
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
}
|
|
951
|
-
let socket = null;
|
|
952
|
-
let settled = false;
|
|
953
|
-
let attempt = 0;
|
|
954
|
-
let expiresAt = null;
|
|
955
|
-
let retry;
|
|
956
|
-
const abort = () => settle(() => reject(aborted()));
|
|
957
|
-
const settle = (finish) => {
|
|
958
|
-
if (settled) return;
|
|
959
|
-
settled = true;
|
|
960
|
-
options?.signal?.removeEventListener("abort", abort);
|
|
961
|
-
clearTimeout(retry);
|
|
962
|
-
finish();
|
|
963
|
-
socket?.close();
|
|
964
|
-
};
|
|
965
|
-
const again = () => {
|
|
966
|
-
if (settled) return;
|
|
967
|
-
if (expiresAt === null && attempt >= UNANSWERED_ATTEMPTS) {
|
|
968
|
-
settle(() => reject(new Error(`no gateway answered for payment ${id}`)));
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
if (expiresAt !== null && Date.now() >= expiresAt * 1e3) {
|
|
972
|
-
settle(() => reject(new Error(`payment ${id} went unreported past its expiry`)));
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
retry = setTimeout(() => void connect(), backoffMs(RECONNECT_DELAY_MS, attempt));
|
|
976
|
-
};
|
|
977
|
-
const connect = async () => {
|
|
978
|
-
if (settled) return;
|
|
979
|
-
attempt += 1;
|
|
980
|
-
let url = direct;
|
|
981
|
-
if (this.needsTicket(options?.tickets)) {
|
|
982
|
-
try {
|
|
983
|
-
url = `${base}/ws/tickets/${await this.wsTicket({ payment_id: id })}`;
|
|
984
|
-
} catch (refused) {
|
|
985
|
-
if (refused instanceof ProblemError) settle(() => reject(refused));
|
|
986
|
-
else again();
|
|
987
|
-
return;
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
if (settled) return;
|
|
991
|
-
const opened = new WebSocket(url);
|
|
992
|
-
socket = opened;
|
|
993
|
-
opened.onmessage = (event) => {
|
|
994
|
-
try {
|
|
995
|
-
const frame = JSON.parse(String(event.data));
|
|
996
|
-
const watched = triggerEventFromWire(frame);
|
|
997
|
-
if (watched === null) return;
|
|
998
|
-
expiresAt = watched.expiresAt;
|
|
999
|
-
attempt = 1;
|
|
1000
|
-
if (!TERMINAL.has(watched.status)) return;
|
|
1001
|
-
settle(() => resolve2(frame));
|
|
1002
|
-
} catch (refused) {
|
|
1003
|
-
settle(() => reject(refused));
|
|
1004
|
-
}
|
|
1005
|
-
};
|
|
1006
|
-
opened.onclose = again;
|
|
1007
|
-
};
|
|
1008
|
-
options?.signal?.addEventListener("abort", abort, { once: true });
|
|
1009
|
-
void connect();
|
|
1010
|
-
});
|
|
978
|
+
const nonce = challenged(typeof body === "string" ? body : new TextDecoder().decode(body));
|
|
979
|
+
return nonce === null ? null : JSON.stringify({ nonce });
|
|
980
|
+
}
|
|
981
|
+
async function answerWebhookChallengeRequest(request, credential, options = {}) {
|
|
982
|
+
const signature = request.headers.get(SIGNATURE_HEADER);
|
|
983
|
+
const timestamp = request.headers.get(TIMESTAMP_HEADER);
|
|
984
|
+
if (signature === null || timestamp === null) {
|
|
985
|
+
return null;
|
|
1011
986
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
const stopLosers = new AbortController();
|
|
1033
|
-
const signal = options?.signal ? AbortSignal.any([stopLosers.signal, options.signal]) : stopLosers.signal;
|
|
1034
|
-
let refused = null;
|
|
1035
|
-
try {
|
|
1036
|
-
const winner = await new Promise((resolve2) => {
|
|
1037
|
-
let waiting = ids.length;
|
|
1038
|
-
const lost = () => {
|
|
1039
|
-
waiting -= 1;
|
|
1040
|
-
if (waiting === 0) resolve2(null);
|
|
1041
|
-
};
|
|
1042
|
-
for (const id of ids) {
|
|
1043
|
-
this.waitForWatched(id, { ...options, signal }).then((watched) => watched.status === "paid" ? resolve2(watched) : lost()).catch((failure) => {
|
|
1044
|
-
refused ??= failure;
|
|
1045
|
-
lost();
|
|
1046
|
-
});
|
|
1047
|
-
}
|
|
1048
|
-
});
|
|
1049
|
-
if (winner === null && refused !== null) throw refused;
|
|
1050
|
-
return winner;
|
|
1051
|
-
} finally {
|
|
1052
|
-
stopLosers.abort();
|
|
987
|
+
const answer = await answerWebhookChallenge(
|
|
988
|
+
await request.clone().text(),
|
|
989
|
+
signature,
|
|
990
|
+
credential,
|
|
991
|
+
timestamp,
|
|
992
|
+
options
|
|
993
|
+
);
|
|
994
|
+
return answer === null ? null : new Response(answer, { headers: { "content-type": "application/json" } });
|
|
995
|
+
}
|
|
996
|
+
function textOf(body) {
|
|
997
|
+
return typeof body === "string" ? body : new TextDecoder().decode(body);
|
|
998
|
+
}
|
|
999
|
+
function challenged(text2) {
|
|
1000
|
+
return nonceOf(text2, CHALLENGE);
|
|
1001
|
+
}
|
|
1002
|
+
function nonceOf(text2, type) {
|
|
1003
|
+
try {
|
|
1004
|
+
const said = JSON.parse(text2);
|
|
1005
|
+
if (said["type"] !== type || typeof said["nonce"] !== "string") {
|
|
1006
|
+
return null;
|
|
1053
1007
|
}
|
|
1008
|
+
return said["nonce"];
|
|
1009
|
+
} catch {
|
|
1010
|
+
return null;
|
|
1054
1011
|
}
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1012
|
+
}
|
|
1013
|
+
function answerVerifyChallenge(body) {
|
|
1014
|
+
const nonce = nonceOf(body, VERIFY_CHALLENGE);
|
|
1015
|
+
return nonce === null ? null : JSON.stringify({ nonce });
|
|
1016
|
+
}
|
|
1017
|
+
async function answerVerifyChallengeRequest(request) {
|
|
1018
|
+
if (request.method !== "POST") {
|
|
1019
|
+
return null;
|
|
1020
|
+
}
|
|
1021
|
+
const answer = answerVerifyChallenge(await request.clone().text());
|
|
1022
|
+
return answer === null ? null : new Response(answer, { headers: { "content-type": "application/json" } });
|
|
1023
|
+
}
|
|
1024
|
+
function recent(timestamp, toleranceSecs) {
|
|
1025
|
+
const sent = Number(timestamp);
|
|
1026
|
+
if (!Number.isFinite(sent)) {
|
|
1027
|
+
return false;
|
|
1028
|
+
}
|
|
1029
|
+
return Math.abs(Math.floor(Date.now() / 1e3) - sent) <= toleranceSecs;
|
|
1030
|
+
}
|
|
1031
|
+
function signed(timestamp, body) {
|
|
1032
|
+
const encoder = new TextEncoder();
|
|
1033
|
+
const stamp = encoder.encode(`${timestamp}.`);
|
|
1034
|
+
const rest = typeof body === "string" ? encoder.encode(body) : new Uint8Array(body);
|
|
1035
|
+
const payload = new Uint8Array(stamp.length + rest.length);
|
|
1036
|
+
payload.set(stamp);
|
|
1037
|
+
payload.set(rest, stamp.length);
|
|
1038
|
+
return payload;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// src/bank.ts
|
|
1042
|
+
var DEFAULT_CURRENCY = "CZK";
|
|
1043
|
+
var DEFAULT_LOOK_BACK_SECS = 7 * 24 * 60 * 60;
|
|
1044
|
+
var DEFAULT_POLL_EVERY_SECS = 30;
|
|
1045
|
+
var IBAN = /^[A-Z]{2}[0-9]{2}[0-9A-Z]{8,30}$/;
|
|
1046
|
+
var FORBIDDEN_IN_SPD = "*";
|
|
1047
|
+
async function bankTransfer(params) {
|
|
1048
|
+
const currency = params.currency ?? DEFAULT_CURRENCY;
|
|
1049
|
+
refuseUnusable(params, currency);
|
|
1050
|
+
await refuseAnOpenGateway(params);
|
|
1051
|
+
const spd = shortPaymentDescriptor(params, currency);
|
|
1052
|
+
const subject = subjectOf(params.reference, params.amountMinor, currency);
|
|
1053
|
+
const polling = new URL(params.verifyUrl);
|
|
1054
|
+
polling.searchParams.set("ref", params.reference);
|
|
1055
|
+
polling.searchParams.set("minor", String(params.amountMinor));
|
|
1056
|
+
polling.searchParams.set("cc", currency);
|
|
1057
|
+
polling.searchParams.set("sig", await hmacHex(params.secret, `verify|${subject}`));
|
|
1058
|
+
const verifyUrl = polling.toString();
|
|
1059
|
+
const watched = await params.gateway.watchPayment({
|
|
1060
|
+
paymentHash: hashOf(await hmacHex(params.secret, `preimage|${subject}`)),
|
|
1061
|
+
verifyUrl,
|
|
1062
|
+
expiresAt: params.expiresAt,
|
|
1063
|
+
trigger: params.trigger,
|
|
1064
|
+
replay: params.replay,
|
|
1065
|
+
sealed: params.sealed,
|
|
1066
|
+
webhookUrl: params.webhookUrl
|
|
1067
|
+
});
|
|
1068
|
+
return { id: watched.id, paymentHash: watched.paymentHash, verifyUrl, spd };
|
|
1069
|
+
}
|
|
1070
|
+
function bankVerifyEndpoint(config) {
|
|
1071
|
+
const paced = {
|
|
1072
|
+
"cache-control": `max-age=${config.pollEverySecs ?? DEFAULT_POLL_EVERY_SECS}`
|
|
1073
|
+
};
|
|
1074
|
+
return async (request) => {
|
|
1075
|
+
const consented = await answerVerifyChallengeRequest(request);
|
|
1076
|
+
if (consented !== null) {
|
|
1077
|
+
return consented;
|
|
1078
1078
|
}
|
|
1079
|
-
const
|
|
1080
|
-
if (
|
|
1081
|
-
|
|
1079
|
+
const asked = readQuery(new URL(request.url));
|
|
1080
|
+
if (asked === null) {
|
|
1081
|
+
return Response.json({ settled: false }, { status: 400 });
|
|
1082
1082
|
}
|
|
1083
|
-
|
|
1083
|
+
const subject = subjectOf(asked.reference, asked.amountMinor, asked.currency);
|
|
1084
|
+
const expected = await hmacHex(config.secret, `verify|${subject}`);
|
|
1085
|
+
if (!equalInConstantTime(asked.signature, expected)) {
|
|
1086
|
+
return Response.json({ settled: false }, { status: 403 });
|
|
1087
|
+
}
|
|
1088
|
+
const since = unixNow() - (config.lookBackSecs ?? DEFAULT_LOOK_BACK_SECS);
|
|
1089
|
+
const landed = (await config.statement(since)).some((credit) => pays(credit, asked));
|
|
1090
|
+
if (!landed) {
|
|
1091
|
+
return Response.json({ settled: false }, { headers: paced });
|
|
1092
|
+
}
|
|
1093
|
+
return Response.json(
|
|
1094
|
+
{ settled: true, preimage: await hmacHex(config.secret, `preimage|${subject}`) },
|
|
1095
|
+
{ headers: paced }
|
|
1096
|
+
);
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
function readQuery(url) {
|
|
1100
|
+
const reference = url.searchParams.get("ref");
|
|
1101
|
+
const minor = Number(url.searchParams.get("minor"));
|
|
1102
|
+
const currency = url.searchParams.get("cc");
|
|
1103
|
+
const signature = url.searchParams.get("sig");
|
|
1104
|
+
if (!reference || !currency || !signature) {
|
|
1105
|
+
return null;
|
|
1084
1106
|
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
* heard of it. Every gateway you hand the same invoice to answers with the same
|
|
1088
|
-
* name, so watching at several of them adds up to one payment rather than
|
|
1089
|
-
* several, and no gateway's key is in the answer. Null when no secret was given,
|
|
1090
|
-
* because then the gateway names the payment and only it can
|
|
1091
|
-
*/
|
|
1092
|
-
async nameFor(paymentHash) {
|
|
1093
|
-
return this.secret === null ? null : paymentNamedBy((await this.speaking()).publicKeyHex, paymentHash);
|
|
1107
|
+
if (!Number.isInteger(minor) || minor <= 0) {
|
|
1108
|
+
return null;
|
|
1094
1109
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
if (this.needsTicket(options.tickets)) {
|
|
1116
|
-
try {
|
|
1117
|
-
url = `${base}/ws/tickets/${await this.wsTicket({ trigger_secret: secret })}`;
|
|
1118
|
-
} catch (refused) {
|
|
1119
|
-
options.onError?.(refused);
|
|
1120
|
-
again();
|
|
1121
|
-
return;
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
if (stopped) return;
|
|
1125
|
-
socket = new WebSocket(url);
|
|
1126
|
-
socket.onopen = () => {
|
|
1127
|
-
attempt = 1;
|
|
1128
|
-
};
|
|
1129
|
-
socket.onmessage = (event) => {
|
|
1130
|
-
try {
|
|
1131
|
-
const settled = triggerEventFromWire(JSON.parse(String(event.data)));
|
|
1132
|
-
if (settled !== null) options.onPayment(this.proven(settled));
|
|
1133
|
-
} catch (refused) {
|
|
1134
|
-
options.onError?.(refused);
|
|
1135
|
-
}
|
|
1136
|
-
};
|
|
1137
|
-
socket.onerror = () => options.onError?.(new Error(`could not follow trigger at ${base}`));
|
|
1138
|
-
socket.onclose = again;
|
|
1139
|
-
};
|
|
1140
|
-
void connect();
|
|
1141
|
-
return () => {
|
|
1142
|
-
stopped = true;
|
|
1143
|
-
clearTimeout(retry);
|
|
1144
|
-
socket?.close();
|
|
1145
|
-
};
|
|
1146
|
-
}
|
|
1147
|
-
needsTicket(asked) {
|
|
1148
|
-
return asked === true || this.token !== null;
|
|
1110
|
+
return { reference, amountMinor: minor, currency, signature };
|
|
1111
|
+
}
|
|
1112
|
+
function pays(credit, asked) {
|
|
1113
|
+
return credit.amountMinor === asked.amountMinor && credit.currency.toUpperCase() === asked.currency.toUpperCase() && credit.reference.toUpperCase().includes(asked.reference.toUpperCase());
|
|
1114
|
+
}
|
|
1115
|
+
function subjectOf(reference, amountMinor, currency) {
|
|
1116
|
+
return `${reference}|${amountMinor}|${currency.toUpperCase()}`;
|
|
1117
|
+
}
|
|
1118
|
+
function hashOf(preimage) {
|
|
1119
|
+
return bytesToHex(sha256(hexToBytes(preimage)));
|
|
1120
|
+
}
|
|
1121
|
+
function shortPaymentDescriptor(params, currency) {
|
|
1122
|
+
const fields = [
|
|
1123
|
+
`ACC:${params.iban}`,
|
|
1124
|
+
`AM:${major(params.amountMinor, currency)}`,
|
|
1125
|
+
`CC:${currency.toUpperCase()}`,
|
|
1126
|
+
`MSG:${params.reference}`
|
|
1127
|
+
];
|
|
1128
|
+
if (params.variableSymbol) {
|
|
1129
|
+
fields.push(`X-VS:${params.variableSymbol}`);
|
|
1149
1130
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
const minted = await response.json().catch(() => null);
|
|
1159
|
-
if (typeof minted?.ticket !== "string") {
|
|
1160
|
-
throw new ProblemError({
|
|
1161
|
-
status: response.status,
|
|
1162
|
-
title: "The gateway answered with something that is not a ticket"
|
|
1163
|
-
});
|
|
1164
|
-
}
|
|
1165
|
-
return encodeURIComponent(minted.ticket);
|
|
1131
|
+
return `SPD*1.0*${fields.join("*")}`;
|
|
1132
|
+
}
|
|
1133
|
+
function major(amountMinor, currency) {
|
|
1134
|
+
return (amountMinor / minorScaleOf(currency)).toFixed(minorUnitsOf(currency));
|
|
1135
|
+
}
|
|
1136
|
+
async function refuseAnOpenGateway(params) {
|
|
1137
|
+
if (params.allowPublicGateway === true) {
|
|
1138
|
+
return;
|
|
1166
1139
|
}
|
|
1167
|
-
|
|
1168
|
-
return
|
|
1140
|
+
if (await params.gateway.refusesStrangers()) {
|
|
1141
|
+
return;
|
|
1169
1142
|
}
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1143
|
+
throw new Error(
|
|
1144
|
+
"this gateway serves callers with no token, so it is not yours, and its operator would read the amount and the reference off every verify URL. Point at one that answers 401 to a stranger, or say allowPublicGateway"
|
|
1145
|
+
);
|
|
1146
|
+
}
|
|
1147
|
+
function refuseUnusable(params, currency) {
|
|
1148
|
+
if (!IBAN.test(params.iban)) {
|
|
1149
|
+
throw new Error(`${params.iban} is not an IBAN`);
|
|
1175
1150
|
}
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
return await this.speaks;
|
|
1151
|
+
if (!Number.isInteger(params.amountMinor) || params.amountMinor <= 0) {
|
|
1152
|
+
throw new Error("amountMinor must be a whole number of minor units above zero");
|
|
1179
1153
|
}
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
if (this.verify && unproven) throw new GatewayCheatError("preimage_mismatch", settled.id);
|
|
1183
|
-
return settled;
|
|
1154
|
+
if (params.reference.length === 0) {
|
|
1155
|
+
throw new Error("a transfer with no reference cannot be found");
|
|
1184
1156
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
throw new GatewayCheatError("preimage_mismatch", payment.id);
|
|
1188
|
-
}
|
|
1189
|
-
return payment;
|
|
1157
|
+
if (params.reference.includes(FORBIDDEN_IN_SPD)) {
|
|
1158
|
+
throw new Error("a reference cannot contain an asterisk, it separates the QR fields");
|
|
1190
1159
|
}
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
const payment = paymentFromWire(await response.json().catch(() => null));
|
|
1194
|
-
if (payment === null) {
|
|
1195
|
-
throw new ProblemError({
|
|
1196
|
-
status: response.status,
|
|
1197
|
-
title: "The gateway answered with something that is not a payment"
|
|
1198
|
-
});
|
|
1160
|
+
if (params.variableSymbol && !/^[0-9]{1,10}$/.test(params.variableSymbol)) {
|
|
1161
|
+
throw new Error("a variable symbol is up to ten digits");
|
|
1199
1162
|
}
|
|
1200
|
-
return payment;
|
|
1201
1163
|
}
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
const document = { ...problem, status: response.status };
|
|
1205
|
-
if (isProblemType(problem, NO_WALLET_AVAILABLE)) {
|
|
1206
|
-
return new NoWalletAvailableError(document, refusals(problem.wallets));
|
|
1207
|
-
}
|
|
1208
|
-
if (isProblemType(problem, REQUEST_IN_FLIGHT)) {
|
|
1209
|
-
return new IdempotencyConflictError(document, "request-in-flight");
|
|
1210
|
-
}
|
|
1211
|
-
if (isProblemType(problem, IDEMPOTENCY_KEY_REUSED)) {
|
|
1212
|
-
return new IdempotencyConflictError(document, "key-reused");
|
|
1213
|
-
}
|
|
1214
|
-
return new ProblemError(document);
|
|
1164
|
+
function unixNow() {
|
|
1165
|
+
return Math.floor(Date.now() / 1e3);
|
|
1215
1166
|
}
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1167
|
+
|
|
1168
|
+
// ../core/caller.ts
|
|
1169
|
+
var KEY_HEADER = "x-client-key";
|
|
1170
|
+
var SIGNATURE_HEADER2 = "x-signature";
|
|
1171
|
+
var TIMESTAMP_HEADER2 = "x-timestamp";
|
|
1172
|
+
var PREFIX = "ed25519=";
|
|
1173
|
+
var SIGNING_LABEL = "request-signing";
|
|
1174
|
+
async function callerKey(secret) {
|
|
1175
|
+
return await signingKeyFromSeed(hexToBytes(await hmacHex(secret, SIGNING_LABEL)));
|
|
1176
|
+
}
|
|
1177
|
+
function paymentNamedBy(caller, paymentHash) {
|
|
1178
|
+
return sha256Hex(`${caller}.payment-id.${paymentHash}`);
|
|
1179
|
+
}
|
|
1180
|
+
async function signedAs(key, method, path, body) {
|
|
1181
|
+
const timestamp = String(Math.floor(Date.now() / 1e3));
|
|
1182
|
+
return {
|
|
1183
|
+
[KEY_HEADER]: key.publicKeyHex,
|
|
1184
|
+
[TIMESTAMP_HEADER2]: timestamp,
|
|
1185
|
+
[SIGNATURE_HEADER2]: `${PREFIX}${await key.sign(spoken(timestamp, method, path, body))}`
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
function spoken(timestamp, method, path, body) {
|
|
1189
|
+
return new TextEncoder().encode(
|
|
1190
|
+
`${timestamp}.${method.toUpperCase()}.${path}.${sha256Hex(body)}`
|
|
1191
|
+
);
|
|
1221
1192
|
}
|
|
1222
1193
|
|
|
1223
|
-
// src/
|
|
1224
|
-
var
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
this.
|
|
1231
|
-
this.
|
|
1232
|
-
this.onRefused = options?.onRefused ?? (() => {
|
|
1233
|
-
});
|
|
1194
|
+
// src/errors.ts
|
|
1195
|
+
var GatewayCheatError = class extends Error {
|
|
1196
|
+
code;
|
|
1197
|
+
paymentId;
|
|
1198
|
+
constructor(code, paymentId) {
|
|
1199
|
+
super(`gateway verification failed: ${code}`);
|
|
1200
|
+
this.name = "GatewayCheatError";
|
|
1201
|
+
this.code = code;
|
|
1202
|
+
this.paymentId = paymentId;
|
|
1234
1203
|
}
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1204
|
+
};
|
|
1205
|
+
var WrapRefusedError = class extends Error {
|
|
1206
|
+
code;
|
|
1207
|
+
constructor(code, detail) {
|
|
1208
|
+
super(`wrapped invoice refused: ${code}, ${detail}`);
|
|
1209
|
+
this.name = "WrapRefusedError";
|
|
1210
|
+
this.code = code;
|
|
1238
1211
|
}
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
for (const [at, answer] of asked.entries()) {
|
|
1249
|
-
if (answer.status === "fulfilled") {
|
|
1250
|
-
taken.push(answer.value);
|
|
1251
|
-
continue;
|
|
1252
|
-
}
|
|
1253
|
-
refusals3.push(answer.reason);
|
|
1254
|
-
this.onRefused(this.urls[at], answer.reason);
|
|
1255
|
-
}
|
|
1256
|
-
if (taken[0] === void 0) throw refusals3[0];
|
|
1257
|
-
return taken[0];
|
|
1212
|
+
};
|
|
1213
|
+
var UnverifiedRecipientError = class extends Error {
|
|
1214
|
+
lnAddress;
|
|
1215
|
+
paymentId;
|
|
1216
|
+
constructor(lnAddress, paymentId, cause) {
|
|
1217
|
+
super(`could not reach ${lnAddress} to verify the invoice: ${String(cause)}`);
|
|
1218
|
+
this.name = "UnverifiedRecipientError";
|
|
1219
|
+
this.lnAddress = lnAddress;
|
|
1220
|
+
this.paymentId = paymentId;
|
|
1258
1221
|
}
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
const lost = () => {
|
|
1274
|
-
waiting -= 1;
|
|
1275
|
-
if (waiting === 0) resolve2(null);
|
|
1276
|
-
};
|
|
1277
|
-
for (const gateway of this.each) {
|
|
1278
|
-
gateway.waitForWatched(id, { ...options, signal }).then((watched) => {
|
|
1279
|
-
if (watched.status === "paid") return resolve2(watched);
|
|
1280
|
-
unpaid.push(watched);
|
|
1281
|
-
lost();
|
|
1282
|
-
}).catch((failure) => {
|
|
1283
|
-
refused ??= failure;
|
|
1284
|
-
lost();
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
});
|
|
1288
|
-
if (settled !== null) return settled;
|
|
1289
|
-
if (unpaid.length > 0) return unpaid[0];
|
|
1290
|
-
throw refused;
|
|
1291
|
-
} finally {
|
|
1292
|
-
stopLosers.abort();
|
|
1293
|
-
}
|
|
1222
|
+
};
|
|
1223
|
+
var ProblemError = class extends Error {
|
|
1224
|
+
type;
|
|
1225
|
+
title;
|
|
1226
|
+
status;
|
|
1227
|
+
detail;
|
|
1228
|
+
constructor(problem) {
|
|
1229
|
+
const title = problem.title ?? "Request failed";
|
|
1230
|
+
super(problem.detail ? `${title}: ${problem.detail}` : title);
|
|
1231
|
+
this.name = "ProblemError";
|
|
1232
|
+
this.type = problem.type ?? "about:blank";
|
|
1233
|
+
this.title = title;
|
|
1234
|
+
this.status = problem.status ?? 0;
|
|
1235
|
+
this.detail = problem.detail ?? null;
|
|
1294
1236
|
}
|
|
1295
1237
|
};
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
var VERSION = "v1";
|
|
1299
|
-
var IV_BYTES = 12;
|
|
1300
|
-
var MIN_SECRET_CHARS = 32;
|
|
1301
|
-
var MAX_PLAIN_BYTES = 3e3;
|
|
1302
|
-
var INFO = new TextEncoder().encode("thunder-bridge/sealed");
|
|
1303
|
-
async function seal(secret, plaintext) {
|
|
1304
|
-
const body = new TextEncoder().encode(plaintext);
|
|
1305
|
-
if (body.length > MAX_PLAIN_BYTES) {
|
|
1306
|
-
throw new Error(`sealed takes at most ${MAX_PLAIN_BYTES} bytes, this was ${body.length}`);
|
|
1307
|
-
}
|
|
1308
|
-
const key = await keyFor(secret);
|
|
1309
|
-
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
1310
|
-
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, body));
|
|
1311
|
-
const joined = new Uint8Array(iv.length + cipher.length);
|
|
1312
|
-
joined.set(iv);
|
|
1313
|
-
joined.set(cipher, iv.length);
|
|
1314
|
-
return `${VERSION}.${toBase64Url(joined)}`;
|
|
1238
|
+
function isProblemType(problem, type) {
|
|
1239
|
+
return problem.type === type;
|
|
1315
1240
|
}
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
);
|
|
1327
|
-
return new TextDecoder().decode(body);
|
|
1328
|
-
} catch {
|
|
1329
|
-
return null;
|
|
1241
|
+
var NO_WALLET_AVAILABLE = "urn:problem-type:thunder-bridge:no-wallet-available";
|
|
1242
|
+
var REQUEST_IN_FLIGHT = "urn:problem-type:thunder-bridge:request-in-flight";
|
|
1243
|
+
var IDEMPOTENCY_KEY_REUSED = "urn:problem-type:thunder-bridge:idempotency-key-reused";
|
|
1244
|
+
var PAYMENT_ALREADY_WATCHED = "urn:problem-type:thunder-bridge:payment-already-watched";
|
|
1245
|
+
var IdempotencyConflictError = class extends ProblemError {
|
|
1246
|
+
conflict;
|
|
1247
|
+
constructor(problem, conflict) {
|
|
1248
|
+
super(problem);
|
|
1249
|
+
this.name = "IdempotencyConflictError";
|
|
1250
|
+
this.conflict = conflict;
|
|
1330
1251
|
}
|
|
1331
|
-
}
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1252
|
+
};
|
|
1253
|
+
var NoWalletAvailableError = class extends ProblemError {
|
|
1254
|
+
wallets;
|
|
1255
|
+
constructor(problem, wallets) {
|
|
1256
|
+
super({ ...problem, type: NO_WALLET_AVAILABLE });
|
|
1257
|
+
this.name = "NoWalletAvailableError";
|
|
1258
|
+
this.wallets = wallets;
|
|
1335
1259
|
}
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
{ name: "AES-GCM", length: 256 },
|
|
1347
|
-
false,
|
|
1348
|
-
["encrypt", "decrypt"]
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
// src/verify.ts
|
|
1263
|
+
var HTTP_TIMEOUT_MS = 15e3;
|
|
1264
|
+
var DEFAULT_WRAP_PROPORTION = 0.01;
|
|
1265
|
+
var DEFAULT_WRAP_BASE_MSAT = 1e3;
|
|
1266
|
+
async function proveOrigin(payment, request) {
|
|
1267
|
+
const cheat = (code) => new GatewayCheatError(code, payment.id);
|
|
1268
|
+
const listed = request.lnAddresses.find(
|
|
1269
|
+
(address) => equalIgnoringCase(address, payment.lnAddress)
|
|
1349
1270
|
);
|
|
1271
|
+
if (listed === void 0) {
|
|
1272
|
+
throw cheat("address_not_requested");
|
|
1273
|
+
}
|
|
1274
|
+
if (payment.amountMsat !== request.amountMsat) {
|
|
1275
|
+
throw cheat("amount_mismatch");
|
|
1276
|
+
}
|
|
1277
|
+
const invoice = decodeInvoice(payment.bolt11);
|
|
1278
|
+
if (invoice.paymentHash === null || !equalIgnoringCase(invoice.paymentHash, payment.paymentHash)) {
|
|
1279
|
+
throw cheat("hash_mismatch");
|
|
1280
|
+
}
|
|
1281
|
+
if (invoice.amountMsat !== request.amountMsat) {
|
|
1282
|
+
throw cheat("amount_mismatch");
|
|
1283
|
+
}
|
|
1284
|
+
const payRequest = await payRequestFor(listed, payment);
|
|
1285
|
+
if (typeof payRequest.metadata !== "string" || typeof payRequest.callback !== "string") {
|
|
1286
|
+
throw new UnverifiedRecipientError(payment.lnAddress, payment.id, "no payRequest served");
|
|
1287
|
+
}
|
|
1288
|
+
if (invoice.descriptionHash !== sha256Hex(payRequest.metadata)) {
|
|
1289
|
+
throw cheat("description_hash_mismatch");
|
|
1290
|
+
}
|
|
1291
|
+
if (!sameOrigin(payment.verifyUrl, payRequest.callback)) {
|
|
1292
|
+
throw cheat("verify_url_foreign");
|
|
1293
|
+
}
|
|
1294
|
+
const issued = await reachable(payment.verifyUrl, payment);
|
|
1295
|
+
if (typeof issued.pr !== "string" || !equalIgnoringCase(issued.pr, payment.bolt11)) {
|
|
1296
|
+
throw cheat("invoice_not_issued");
|
|
1297
|
+
}
|
|
1350
1298
|
}
|
|
1351
|
-
function
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
}
|
|
1356
|
-
function fromBase64Url2(text2) {
|
|
1357
|
-
if (text2.length === 0 || !/^[A-Za-z0-9_-]+$/.test(text2)) return null;
|
|
1358
|
-
try {
|
|
1359
|
-
const binary = atob(text2.replace(/-/g, "+").replace(/_/g, "/"));
|
|
1360
|
-
const bytes = new Uint8Array(binary.length);
|
|
1361
|
-
for (let at = 0; at < bytes.length; at++) bytes[at] = binary.charCodeAt(at);
|
|
1362
|
-
return bytes;
|
|
1363
|
-
} catch {
|
|
1299
|
+
async function proveSettlement(payment, request) {
|
|
1300
|
+
await proveOrigin(payment, request);
|
|
1301
|
+
const verified = await reachable(payment.verifyUrl, payment);
|
|
1302
|
+
if (verified.settled !== true || typeof verified.preimage !== "string") {
|
|
1364
1303
|
return null;
|
|
1365
1304
|
}
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
// src/currency.ts
|
|
1369
|
-
var ISO_4217_MINOR_UNITS = {
|
|
1370
|
-
BHD: 3,
|
|
1371
|
-
BIF: 0,
|
|
1372
|
-
CLP: 0,
|
|
1373
|
-
CZK: 2,
|
|
1374
|
-
DJF: 0,
|
|
1375
|
-
EUR: 2,
|
|
1376
|
-
GBP: 2,
|
|
1377
|
-
ISK: 0,
|
|
1378
|
-
IQD: 3,
|
|
1379
|
-
JOD: 3,
|
|
1380
|
-
JPY: 0,
|
|
1381
|
-
KRW: 0,
|
|
1382
|
-
KWD: 3,
|
|
1383
|
-
LYD: 3,
|
|
1384
|
-
OMR: 3,
|
|
1385
|
-
PLN: 2,
|
|
1386
|
-
PYG: 0,
|
|
1387
|
-
RWF: 0,
|
|
1388
|
-
TND: 3,
|
|
1389
|
-
UGX: 0,
|
|
1390
|
-
USD: 2,
|
|
1391
|
-
VND: 0,
|
|
1392
|
-
VUV: 0,
|
|
1393
|
-
XAF: 0,
|
|
1394
|
-
XOF: 0,
|
|
1395
|
-
XPF: 0
|
|
1396
|
-
};
|
|
1397
|
-
function minorUnitsOf(currency) {
|
|
1398
|
-
const digits = ISO_4217_MINOR_UNITS[currency.toUpperCase()];
|
|
1399
|
-
if (digits === void 0) {
|
|
1400
|
-
throw new Error(
|
|
1401
|
-
`${currency.toUpperCase()} is not a currency this knows the ISO 4217 minor unit of`
|
|
1402
|
-
);
|
|
1305
|
+
if (!preimageMatchesHash(verified.preimage, payment.paymentHash)) {
|
|
1306
|
+
throw new GatewayCheatError("preimage_mismatch", payment.id);
|
|
1403
1307
|
}
|
|
1404
|
-
return
|
|
1405
|
-
}
|
|
1406
|
-
function minorScaleOf(currency) {
|
|
1407
|
-
return 10 ** minorUnitsOf(currency);
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
// src/webhook.ts
|
|
1411
|
-
var SIGNATURE_HEADER2 = "x-signature";
|
|
1412
|
-
var TIMESTAMP_HEADER2 = "x-timestamp";
|
|
1413
|
-
var GATEWAY_KEY_PREFIX = "ed25519=";
|
|
1414
|
-
var DEFAULT_TOLERANCE_SECS = 300;
|
|
1415
|
-
var CHALLENGE = "webhook-challenge";
|
|
1416
|
-
var VERIFY_CHALLENGE = "verify-challenge";
|
|
1417
|
-
async function verifyWebhookSignature(body, signature, credential, timestamp, options = {}) {
|
|
1418
|
-
if (!recent(timestamp, options.toleranceSecs ?? DEFAULT_TOLERANCE_SECS)) return false;
|
|
1419
|
-
if (!signature.startsWith(GATEWAY_KEY_PREFIX)) return false;
|
|
1420
|
-
return await verifyHex(
|
|
1421
|
-
credential.publicKey.toLowerCase(),
|
|
1422
|
-
signature.slice(GATEWAY_KEY_PREFIX.length).toLowerCase(),
|
|
1423
|
-
signed(timestamp, body)
|
|
1424
|
-
);
|
|
1308
|
+
return verified.preimage;
|
|
1425
1309
|
}
|
|
1426
|
-
|
|
1427
|
-
if (
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
return
|
|
1310
|
+
function isProvablyPaid(payment) {
|
|
1311
|
+
if (payment.status !== "paid" || payment.preimage === null) {
|
|
1312
|
+
return false;
|
|
1313
|
+
}
|
|
1314
|
+
const invoiceHash = decodeInvoice(payment.bolt11).paymentHash;
|
|
1315
|
+
if (invoiceHash === null || !equalIgnoringCase(invoiceHash, payment.paymentHash)) {
|
|
1316
|
+
return false;
|
|
1433
1317
|
}
|
|
1318
|
+
return preimageMatchesHash(payment.preimage, invoiceHash);
|
|
1434
1319
|
}
|
|
1435
|
-
|
|
1436
|
-
const
|
|
1437
|
-
|
|
1438
|
-
if (signature === null || timestamp === null) return null;
|
|
1439
|
-
return parseWebhook(await request.text(), signature, credential, timestamp, options);
|
|
1320
|
+
function wrapFeeCeiling(amountMsat, allowance) {
|
|
1321
|
+
const proportional = amountMsat * (allowance?.proportion ?? DEFAULT_WRAP_PROPORTION);
|
|
1322
|
+
return Math.max(allowance?.baseMsat ?? DEFAULT_WRAP_BASE_MSAT, Math.floor(proportional));
|
|
1440
1323
|
}
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
const
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
}
|
|
1447
|
-
|
|
1324
|
+
function proveWrapped(wrapped, recipient, allowance) {
|
|
1325
|
+
const offered = decodeInvoice(wrapped);
|
|
1326
|
+
const owed = decodeInvoice(recipient);
|
|
1327
|
+
const refuse = (code, detail) => {
|
|
1328
|
+
throw new WrapRefusedError(code, detail);
|
|
1329
|
+
};
|
|
1330
|
+
if (offered.paymentHash === null || offered.amountMsat === null || offered.expiresAt === null) {
|
|
1331
|
+
refuse("undecodable", "the wrapped invoice carries no hash, amount or expiry");
|
|
1332
|
+
}
|
|
1333
|
+
if (owed.paymentHash === null || owed.amountMsat === null || owed.expiresAt === null) {
|
|
1334
|
+
refuse("undecodable", "the recipient's invoice carries no hash, amount or expiry");
|
|
1335
|
+
}
|
|
1336
|
+
if (offered.paymentHash?.toLowerCase() !== owed.paymentHash?.toLowerCase()) {
|
|
1337
|
+
refuse("hash_mismatch", "settling the wrap would not settle the recipient");
|
|
1338
|
+
}
|
|
1339
|
+
const asked = offered.amountMsat ?? 0;
|
|
1340
|
+
const due = owed.amountMsat ?? 0;
|
|
1341
|
+
if (asked < due) {
|
|
1342
|
+
refuse("amount_below_recipient", `${asked} msat cannot forward ${due} msat`);
|
|
1343
|
+
}
|
|
1344
|
+
const ceiling = wrapFeeCeiling(due, allowance);
|
|
1345
|
+
if (asked - due > ceiling) {
|
|
1346
|
+
refuse("fee_above_allowance", `${asked - due} msat over ${due}, and ${ceiling} was allowed`);
|
|
1347
|
+
}
|
|
1348
|
+
if ((owed.expiresAt ?? 0) <= (offered.expiresAt ?? 0)) {
|
|
1349
|
+
refuse("recipient_expires_first", "the operator could be paid and find it cannot deliver");
|
|
1448
1350
|
}
|
|
1449
1351
|
}
|
|
1450
|
-
async function
|
|
1451
|
-
const
|
|
1452
|
-
const
|
|
1453
|
-
|
|
1454
|
-
|
|
1352
|
+
async function payRequestFor(listed, payment) {
|
|
1353
|
+
const at = listed.indexOf("@");
|
|
1354
|
+
const name = listed.slice(0, at);
|
|
1355
|
+
const domain = listed.slice(at + 1).toLowerCase();
|
|
1356
|
+
if (at < 1 || !publicHttps(`https://${domain}/`)) {
|
|
1357
|
+
throw new UnverifiedRecipientError(payment.lnAddress, payment.id, "not a usable address");
|
|
1358
|
+
}
|
|
1359
|
+
return reachable(`https://${domain}/.well-known/lnurlp/${name}`, payment);
|
|
1455
1360
|
}
|
|
1456
|
-
async function
|
|
1457
|
-
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) return null;
|
|
1361
|
+
async function reachable(url, payment) {
|
|
1458
1362
|
try {
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1363
|
+
if (!publicHttps(url)) {
|
|
1364
|
+
throw new Error(`${url} is not a public https URL`);
|
|
1365
|
+
}
|
|
1366
|
+
const response = await fetch(url, {
|
|
1367
|
+
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
|
|
1368
|
+
headers: { accept: "application/json" }
|
|
1369
|
+
});
|
|
1370
|
+
if (!response.ok) {
|
|
1371
|
+
throw new Error(`answered ${response.status}`);
|
|
1372
|
+
}
|
|
1373
|
+
const body = await response.json();
|
|
1374
|
+
if (body === null || typeof body !== "object") {
|
|
1375
|
+
throw new Error("answered with no JSON object");
|
|
1376
|
+
}
|
|
1377
|
+
return body;
|
|
1378
|
+
} catch (cause) {
|
|
1379
|
+
throw new UnverifiedRecipientError(payment.lnAddress, payment.id, cause);
|
|
1462
1380
|
}
|
|
1463
1381
|
}
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
const timestamp = request.headers.get(TIMESTAMP_HEADER2);
|
|
1467
|
-
if (signature === null || timestamp === null) return null;
|
|
1468
|
-
return await parseSettlement(await request.text(), signature, credential, timestamp, options);
|
|
1469
|
-
}
|
|
1470
|
-
function isProvablySettled(settled) {
|
|
1471
|
-
if (settled.status !== "paid" || settled.preimage === null) return false;
|
|
1472
|
-
return preimageMatchesHash(settled.preimage, settled.paymentHash);
|
|
1473
|
-
}
|
|
1474
|
-
async function answerWebhookChallenge(body, signature, credential, timestamp, options = {}) {
|
|
1475
|
-
if (!await verifyWebhookSignature(body, signature, credential, timestamp, options)) return null;
|
|
1476
|
-
const nonce = challenged(typeof body === "string" ? body : new TextDecoder().decode(body));
|
|
1477
|
-
return nonce === null ? null : JSON.stringify({ nonce });
|
|
1478
|
-
}
|
|
1479
|
-
async function answerWebhookChallengeRequest(request, credential, options = {}) {
|
|
1480
|
-
const signature = request.headers.get(SIGNATURE_HEADER2);
|
|
1481
|
-
const timestamp = request.headers.get(TIMESTAMP_HEADER2);
|
|
1482
|
-
if (signature === null || timestamp === null) return null;
|
|
1483
|
-
const answer = await answerWebhookChallenge(
|
|
1484
|
-
await request.clone().text(),
|
|
1485
|
-
signature,
|
|
1486
|
-
credential,
|
|
1487
|
-
timestamp,
|
|
1488
|
-
options
|
|
1489
|
-
);
|
|
1490
|
-
return answer === null ? null : new Response(answer, { headers: { "content-type": "application/json" } });
|
|
1382
|
+
function equalIgnoringCase(one, other) {
|
|
1383
|
+
return one.toLowerCase() === other.toLowerCase();
|
|
1491
1384
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1385
|
+
|
|
1386
|
+
// src/client.ts
|
|
1387
|
+
var TERMINAL = /* @__PURE__ */ new Set(["paid", "expired"]);
|
|
1388
|
+
var RECONNECT_DELAY_MS = 3e3;
|
|
1389
|
+
var RECONNECT_CAP_MS = 3e4;
|
|
1390
|
+
var UNANSWERED_ATTEMPTS = 5;
|
|
1391
|
+
var TRIGGER_MIN_CHARS = 16;
|
|
1392
|
+
var STRANGER_PROBE = "is-this-gateway-yours";
|
|
1393
|
+
function unguessable(trigger) {
|
|
1394
|
+
if (trigger.length < TRIGGER_MIN_CHARS) {
|
|
1395
|
+
throw new Error(
|
|
1396
|
+
`a trigger secret is the only thing guarding its stream, and nothing rate limits a guess at it, so it has to be at least ${TRIGGER_MIN_CHARS} characters nobody can predict`
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
return trigger;
|
|
1494
1400
|
}
|
|
1495
|
-
function
|
|
1496
|
-
|
|
1401
|
+
function backoffMs(firstDelay, attempt) {
|
|
1402
|
+
const grown = Math.min(firstDelay * 2 ** (attempt - 1), RECONNECT_CAP_MS);
|
|
1403
|
+
return Math.round(grown * (0.5 + Math.random() / 2));
|
|
1497
1404
|
}
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1405
|
+
var ThunderBridge = class {
|
|
1406
|
+
baseUrl;
|
|
1407
|
+
verify;
|
|
1408
|
+
token;
|
|
1409
|
+
secret;
|
|
1410
|
+
strangers = null;
|
|
1411
|
+
speaks = null;
|
|
1412
|
+
constructor(baseUrl, options) {
|
|
1413
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
1414
|
+
this.verify = options?.verify ?? true;
|
|
1415
|
+
this.token = options?.token ?? null;
|
|
1416
|
+
this.secret = options?.secret ?? null;
|
|
1505
1417
|
}
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
const
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1418
|
+
/**
|
|
1419
|
+
* Whether a token was given, which is what makes an instance yours: a gateway
|
|
1420
|
+
* started with `GATEWAY_TOKEN` answers nobody else, so anything you hand it
|
|
1421
|
+
* stays between you and it
|
|
1422
|
+
*/
|
|
1423
|
+
get isPrivate() {
|
|
1424
|
+
return this.token !== null;
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Whether the gateway turns away a caller carrying no token, asked by making
|
|
1428
|
+
* one unauthenticated read it would have to refuse. `isPrivate` answers only
|
|
1429
|
+
* whether you configured a token, which is your side of the arrangement and
|
|
1430
|
+
* says nothing about the gateway's, so a made-up token against a public
|
|
1431
|
+
* instance reads as private and is not. Asked once and remembered, because an
|
|
1432
|
+
* instance does not change its mind. Anything other than a refusal counts as
|
|
1433
|
+
* open, so an unreachable gateway fails closed
|
|
1434
|
+
*/
|
|
1435
|
+
async refusesStrangers() {
|
|
1436
|
+
this.strangers ??= fetch(`${this.baseUrl}/incoming-payments/${STRANGER_PROBE}`, {
|
|
1437
|
+
headers: { accept: "application/json" }
|
|
1438
|
+
}).then((answer) => answer.status === 401).catch(() => false);
|
|
1439
|
+
return await this.strangers;
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Ask the gateway for an invoice payable to the first address on your list
|
|
1443
|
+
* that can issue a provable one, throws `NoWalletAvailableError` when none can
|
|
1444
|
+
* and `GatewayCheatError` when what comes back is not what you asked for
|
|
1445
|
+
*/
|
|
1446
|
+
async createPayment(params, options) {
|
|
1447
|
+
const sent = createRequestBody(
|
|
1448
|
+
params,
|
|
1449
|
+
options?.trigger ? sha256Hex(unguessable(options.trigger)) : null,
|
|
1450
|
+
options?.replay
|
|
1451
|
+
);
|
|
1452
|
+
const headers = await this.sending("/incoming-payments", sent);
|
|
1453
|
+
if (options?.idempotencyKey) {
|
|
1454
|
+
headers["idempotency-key"] = options.idempotencyKey;
|
|
1455
|
+
}
|
|
1456
|
+
const response = await fetch(`${this.baseUrl}/incoming-payments`, {
|
|
1457
|
+
method: "POST",
|
|
1458
|
+
headers,
|
|
1459
|
+
body: sent
|
|
1460
|
+
});
|
|
1461
|
+
if (!response.ok) {
|
|
1462
|
+
throw await problemFrom(response);
|
|
1463
|
+
}
|
|
1464
|
+
const payment = await paymentFrom(response);
|
|
1465
|
+
if (this.verify) {
|
|
1466
|
+
await proveOrigin(payment, params);
|
|
1467
|
+
}
|
|
1468
|
+
return payment;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Ask which address would serve an amount without minting anything, throws
|
|
1472
|
+
* `NoWalletAvailableError` when none would. A quote is a probe and not a
|
|
1473
|
+
* promise: the address it names can still be refused at create time, because
|
|
1474
|
+
* whether a wallet returns a provable invoice cannot be known without asking
|
|
1475
|
+
* it for one, and asking mints it
|
|
1476
|
+
*/
|
|
1477
|
+
async createQuote(params) {
|
|
1478
|
+
const sent = quoteRequestBody(params);
|
|
1479
|
+
const response = await fetch(`${this.baseUrl}/quotes`, {
|
|
1480
|
+
method: "POST",
|
|
1481
|
+
headers: await this.sending("/quotes", sent),
|
|
1482
|
+
body: sent
|
|
1483
|
+
});
|
|
1484
|
+
if (!response.ok) {
|
|
1485
|
+
throw await problemFrom(response);
|
|
1486
|
+
}
|
|
1487
|
+
const quote = quoteFromWire(await response.json().catch(() => null));
|
|
1488
|
+
if (quote === null) {
|
|
1489
|
+
throw new ProblemError({
|
|
1490
|
+
status: response.status,
|
|
1491
|
+
title: "The gateway answered with something that is not a quote"
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
return quote;
|
|
1495
|
+
}
|
|
1496
|
+
/** Read a payment back, null when the gateway has never heard of it */
|
|
1497
|
+
/**
|
|
1498
|
+
* The key this gateway signs webhooks with when you registered none of your own,
|
|
1499
|
+
* ready to hand to `parseWebhookRequest` as `{ publicKey }`. Fetch it once and
|
|
1500
|
+
* keep it: it is the same for every instance in the cluster
|
|
1501
|
+
*/
|
|
1502
|
+
async webhookKey() {
|
|
1503
|
+
const response = await fetch(`${this.baseUrl}/webhook-key`);
|
|
1504
|
+
if (!response.ok) {
|
|
1505
|
+
throw await problemFrom(response);
|
|
1506
|
+
}
|
|
1507
|
+
const body = await response.json().catch(() => null);
|
|
1508
|
+
if (body?.algorithm !== "ed25519" || typeof body.public_key !== "string") {
|
|
1509
|
+
throw new ProblemError({
|
|
1510
|
+
status: response.status,
|
|
1511
|
+
title: "The gateway published no ed25519 webhook key"
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
return body.public_key;
|
|
1515
|
+
}
|
|
1516
|
+
async getPayment(id) {
|
|
1517
|
+
const path = `/incoming-payments/${encodeURIComponent(id)}`;
|
|
1518
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
1519
|
+
headers: await this.reading("GET", path)
|
|
1520
|
+
});
|
|
1521
|
+
if (response.status === 404) {
|
|
1522
|
+
return null;
|
|
1523
|
+
}
|
|
1524
|
+
if (!response.ok) {
|
|
1525
|
+
throw await problemFrom(response);
|
|
1526
|
+
}
|
|
1527
|
+
return this.checked(await paymentFrom(response));
|
|
1528
|
+
}
|
|
1529
|
+
/**
|
|
1530
|
+
* Read back a payment the gateway is only watching, null when it has never
|
|
1531
|
+
* heard of it. A watched payment carries no address, amount or invoice, so
|
|
1532
|
+
* `getPayment` refuses it and this reads the shape both rails share
|
|
1533
|
+
*/
|
|
1534
|
+
async getWatched(id) {
|
|
1535
|
+
const path = `/incoming-payments/${encodeURIComponent(id)}`;
|
|
1536
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
1537
|
+
headers: await this.reading("GET", path)
|
|
1538
|
+
});
|
|
1539
|
+
if (response.status === 404) {
|
|
1540
|
+
return null;
|
|
1541
|
+
}
|
|
1542
|
+
if (!response.ok) {
|
|
1543
|
+
throw await problemFrom(response);
|
|
1544
|
+
}
|
|
1545
|
+
const watched = triggerEventFromWire(await response.json().catch(() => null));
|
|
1546
|
+
if (watched === null) {
|
|
1547
|
+
throw new ProblemError({
|
|
1548
|
+
status: response.status,
|
|
1549
|
+
title: "The gateway answered with something that is not a payment"
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
return this.proven(watched);
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* List what this gateway is watching, newest first. Only a gateway started
|
|
1556
|
+
* with `GATEWAY_TOKEN` serves this, because on a shared one it would hand
|
|
1557
|
+
* every caller everyone else's payments, so a public gateway answers 404.
|
|
1558
|
+
*
|
|
1559
|
+
* `scanned` says how many settled records were looked at to build the page.
|
|
1560
|
+
* Anything older than that window is not in the answer, and the list does not
|
|
1561
|
+
* pretend otherwise
|
|
1562
|
+
*/
|
|
1563
|
+
async listPayments(limit) {
|
|
1564
|
+
const path = `/incoming-payments${limit === void 0 ? "" : `?limit=${limit}`}`;
|
|
1565
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
1566
|
+
headers: await this.reading("GET", path)
|
|
1567
|
+
});
|
|
1568
|
+
if (!response.ok) {
|
|
1569
|
+
throw await problemFrom(response);
|
|
1570
|
+
}
|
|
1571
|
+
const body = await response.json().catch(() => null);
|
|
1572
|
+
const listed = Array.isArray(body?.payments) ? body.payments.map(triggerEventFromWire).filter((one) => one !== null) : null;
|
|
1573
|
+
if (listed === null || typeof body?.settled_scanned !== "number") {
|
|
1574
|
+
throw new ProblemError({
|
|
1575
|
+
status: response.status,
|
|
1576
|
+
title: "The gateway answered with something that is not a payment list"
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
return { payments: listed, scanned: body.settled_scanned };
|
|
1580
|
+
}
|
|
1581
|
+
/**
|
|
1582
|
+
* Follow a payment over WebSocket until it is paid or expired, reconnecting
|
|
1583
|
+
* through a drop. A payment that never answers gives up after a few tries, and
|
|
1584
|
+
* one that has answered is followed until its own expiry, so the wait always
|
|
1585
|
+
* ends by itself
|
|
1586
|
+
*/
|
|
1587
|
+
async waitForPayment(id, options) {
|
|
1588
|
+
const payment = paymentFromWire(await this.followed(id, options));
|
|
1589
|
+
if (payment === null) {
|
|
1590
|
+
throw new ProblemError({
|
|
1591
|
+
status: 200,
|
|
1592
|
+
title: `payment ${id} is watched rather than minted here, read it with waitForWatched`
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
return this.checked(payment);
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* Follow a payment the gateway is only watching, one it did not mint, until it
|
|
1599
|
+
* is paid or expired.
|
|
1600
|
+
*
|
|
1601
|
+
* A watched payment carries no address, no amount and no invoice, because the
|
|
1602
|
+
* gateway was told none of them, so it reads back as the shape a trigger
|
|
1603
|
+
* streams rather than as a `Payment`. That is every bank transfer, and every
|
|
1604
|
+
* Lightning invoice registered with `watchPayment` instead of `createPayment`.
|
|
1605
|
+
*/
|
|
1606
|
+
async waitForWatched(id, options) {
|
|
1607
|
+
const watched = triggerEventFromWire(await this.followed(id, options));
|
|
1608
|
+
if (watched === null) {
|
|
1609
|
+
throw new ProblemError({
|
|
1610
|
+
status: 200,
|
|
1611
|
+
title: "The gateway answered with something that is not a payment"
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
return this.proven(watched);
|
|
1615
|
+
}
|
|
1616
|
+
followed(id, options) {
|
|
1617
|
+
const base = this.baseUrl.replace(/^http/, "ws");
|
|
1618
|
+
const direct = `${base}/ws/incoming-payments/${encodeURIComponent(id)}`;
|
|
1619
|
+
return new Promise((resolve2, reject) => {
|
|
1620
|
+
const aborted = () => new Error(`waiting for payment ${id} was aborted`);
|
|
1621
|
+
if (options?.signal?.aborted) {
|
|
1622
|
+
reject(aborted());
|
|
1623
|
+
return;
|
|
1624
|
+
}
|
|
1625
|
+
let socket = null;
|
|
1626
|
+
let settled = false;
|
|
1627
|
+
let attempt = 0;
|
|
1628
|
+
let expiresAt = null;
|
|
1629
|
+
let retry;
|
|
1630
|
+
const abort = () => settle(() => reject(aborted()));
|
|
1631
|
+
const settle = (finish) => {
|
|
1632
|
+
if (settled) {
|
|
1633
|
+
return;
|
|
1634
|
+
}
|
|
1635
|
+
settled = true;
|
|
1636
|
+
options?.signal?.removeEventListener("abort", abort);
|
|
1637
|
+
clearTimeout(retry);
|
|
1638
|
+
finish();
|
|
1639
|
+
socket?.close();
|
|
1640
|
+
};
|
|
1641
|
+
const again = () => {
|
|
1642
|
+
if (settled) {
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
if (expiresAt === null && attempt >= UNANSWERED_ATTEMPTS) {
|
|
1646
|
+
settle(() => reject(new Error(`no gateway answered for payment ${id}`)));
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
if (expiresAt !== null && Date.now() >= expiresAt * 1e3) {
|
|
1650
|
+
settle(() => reject(new Error(`payment ${id} went unreported past its expiry`)));
|
|
1651
|
+
return;
|
|
1652
|
+
}
|
|
1653
|
+
retry = setTimeout(() => void connect(), backoffMs(RECONNECT_DELAY_MS, attempt));
|
|
1654
|
+
};
|
|
1655
|
+
const connect = async () => {
|
|
1656
|
+
if (settled) {
|
|
1657
|
+
return;
|
|
1658
|
+
}
|
|
1659
|
+
attempt += 1;
|
|
1660
|
+
let url = direct;
|
|
1661
|
+
if (this.needsTicket(options?.tickets)) {
|
|
1662
|
+
try {
|
|
1663
|
+
url = `${base}/ws/tickets/${await this.wsTicket({ payment_id: id })}`;
|
|
1664
|
+
} catch (refused) {
|
|
1665
|
+
if (refused instanceof ProblemError) {
|
|
1666
|
+
settle(() => reject(refused));
|
|
1667
|
+
} else {
|
|
1668
|
+
again();
|
|
1669
|
+
}
|
|
1670
|
+
return;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
if (settled) {
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
const opened = new WebSocket(url);
|
|
1677
|
+
socket = opened;
|
|
1678
|
+
opened.onmessage = (event) => {
|
|
1679
|
+
try {
|
|
1680
|
+
const frame = JSON.parse(String(event.data));
|
|
1681
|
+
const watched = triggerEventFromWire(frame);
|
|
1682
|
+
if (watched === null) {
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
expiresAt = watched.expiresAt;
|
|
1686
|
+
attempt = 1;
|
|
1687
|
+
if (!TERMINAL.has(watched.status)) {
|
|
1688
|
+
return;
|
|
1689
|
+
}
|
|
1690
|
+
settle(() => resolve2(frame));
|
|
1691
|
+
} catch (refused) {
|
|
1692
|
+
settle(() => reject(refused));
|
|
1693
|
+
}
|
|
1694
|
+
};
|
|
1695
|
+
opened.onclose = again;
|
|
1696
|
+
};
|
|
1697
|
+
options?.signal?.addEventListener("abort", abort, { once: true });
|
|
1698
|
+
void connect();
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Wait on several payments and keep the first one that is really paid, then stop
|
|
1703
|
+
* waiting on the losers, which closes their sockets.
|
|
1704
|
+
*
|
|
1705
|
+
* This is how one order offers two rails. A Lightning invoice and a bank
|
|
1706
|
+
* transfer for the same thing are two payments here, and the payer picks one, so
|
|
1707
|
+
* what you want is the one that arrives and nothing further from the other.
|
|
1708
|
+
*
|
|
1709
|
+
* A leg that expires is a loser, not a winner, which is the whole reason this is
|
|
1710
|
+
* not a race: `waitForPayment` ends on `paid` and on `expired` alike, and a
|
|
1711
|
+
* Lightning invoice expires in an hour while a bank transfer takes days. `null`
|
|
1712
|
+
* means every leg ended without being paid.
|
|
1713
|
+
*
|
|
1714
|
+
* Stopping the wait is not revoking the invoice. Nobody can revoke one, because
|
|
1715
|
+
* the recipient's own wallet minted it, so a payer who pays the loser afterwards
|
|
1716
|
+
* really does pay twice and that shows up on `followTrigger` as a second
|
|
1717
|
+
* settlement to refund.
|
|
1718
|
+
*/
|
|
1719
|
+
async firstToSettle(ids, options) {
|
|
1720
|
+
if (ids.length === 0) {
|
|
1721
|
+
return null;
|
|
1722
|
+
}
|
|
1723
|
+
const stopLosers = new AbortController();
|
|
1724
|
+
const signal = options?.signal ? AbortSignal.any([stopLosers.signal, options.signal]) : stopLosers.signal;
|
|
1725
|
+
let refused = null;
|
|
1726
|
+
try {
|
|
1727
|
+
const winner = await new Promise((resolve2) => {
|
|
1728
|
+
let waiting = ids.length;
|
|
1729
|
+
const lost = () => {
|
|
1730
|
+
waiting -= 1;
|
|
1731
|
+
if (waiting === 0) {
|
|
1732
|
+
resolve2(null);
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
for (const id of ids) {
|
|
1736
|
+
this.waitForWatched(id, { ...options, signal }).then((watched) => watched.status === "paid" ? resolve2(watched) : lost()).catch((failure) => {
|
|
1737
|
+
refused ??= failure;
|
|
1738
|
+
lost();
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
});
|
|
1742
|
+
if (winner === null && refused !== null) {
|
|
1743
|
+
throw refused;
|
|
1744
|
+
}
|
|
1745
|
+
return winner;
|
|
1746
|
+
} finally {
|
|
1747
|
+
stopLosers.abort();
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
/**
|
|
1751
|
+
* Hand over an invoice you obtained yourself so the gateway watches it without
|
|
1752
|
+
* being told the address or the amount. It can then only refuse everyone
|
|
1753
|
+
* rather than one recipient, which is what makes leaving it cheap. Anything
|
|
1754
|
+
* the watcher needs goes in `sealed`, which the gateway cannot read
|
|
1755
|
+
*/
|
|
1756
|
+
async watchPayment(params) {
|
|
1757
|
+
const sent = watchRequestBody(
|
|
1758
|
+
params,
|
|
1759
|
+
params.trigger ? sha256Hex(unguessable(params.trigger)) : null
|
|
1760
|
+
);
|
|
1761
|
+
const response = await fetch(`${this.baseUrl}/watched-payments`, {
|
|
1762
|
+
method: "POST",
|
|
1763
|
+
headers: await this.sending("/watched-payments", sent),
|
|
1764
|
+
body: sent
|
|
1765
|
+
});
|
|
1766
|
+
if (!response.ok) {
|
|
1767
|
+
throw await problemFrom(response);
|
|
1768
|
+
}
|
|
1769
|
+
const watched = triggerEventFromWire(await response.json().catch(() => null));
|
|
1770
|
+
if (watched === null) {
|
|
1771
|
+
throw new ProblemError({
|
|
1772
|
+
status: response.status,
|
|
1773
|
+
title: "The gateway answered with something that is not a watched payment"
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
const named = await this.nameFor(params.paymentHash);
|
|
1777
|
+
if (named !== null && watched.id !== named) {
|
|
1778
|
+
throw new GatewayCheatError("id_not_mine", watched.id);
|
|
1779
|
+
}
|
|
1780
|
+
return watched;
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* What this payment is called, which you can work out before any gateway has
|
|
1784
|
+
* heard of it. Every gateway you hand the same invoice to answers with the same
|
|
1785
|
+
* name, so watching at several of them adds up to one payment rather than
|
|
1786
|
+
* several, and no gateway's key is in the answer. Null when no secret was given,
|
|
1787
|
+
* because then the gateway names the payment and only it can
|
|
1788
|
+
*/
|
|
1789
|
+
async nameFor(paymentHash) {
|
|
1790
|
+
return this.secret === null ? null : paymentNamedBy((await this.speaking()).publicKeyHex, paymentHash);
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* Follow every payment made to one trigger, replayed from the recent ones on
|
|
1794
|
+
* connect and then live, reconnecting on its own until the returned function
|
|
1795
|
+
* is called. A trigger has no terminal state, so this never resolves
|
|
1796
|
+
*/
|
|
1797
|
+
followTrigger(secret, options) {
|
|
1798
|
+
const base = this.baseUrl.replace(/^http/, "ws");
|
|
1799
|
+
const asked = options.replay === void 0 ? "" : `?replay=${options.replay}`;
|
|
1800
|
+
const direct = `${base}/ws/triggers/${encodeURIComponent(unguessable(secret))}${asked}`;
|
|
1801
|
+
const firstDelay = options.reconnectDelayMs ?? RECONNECT_DELAY_MS;
|
|
1802
|
+
let socket = null;
|
|
1803
|
+
let retry;
|
|
1804
|
+
let stopped = false;
|
|
1805
|
+
let attempt = 0;
|
|
1806
|
+
const again = () => {
|
|
1807
|
+
if (stopped || options.reconnect === false) {
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
retry = setTimeout(() => void connect(), backoffMs(firstDelay, attempt));
|
|
1811
|
+
};
|
|
1812
|
+
const connect = async () => {
|
|
1813
|
+
attempt += 1;
|
|
1814
|
+
let url = direct;
|
|
1815
|
+
if (this.needsTicket(options.tickets)) {
|
|
1816
|
+
try {
|
|
1817
|
+
url = `${base}/ws/tickets/${await this.wsTicket({
|
|
1818
|
+
trigger_secret: secret,
|
|
1819
|
+
replay: options.replay
|
|
1820
|
+
})}`;
|
|
1821
|
+
} catch (refused) {
|
|
1822
|
+
options.onError?.(refused);
|
|
1823
|
+
again();
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
if (stopped) {
|
|
1828
|
+
return;
|
|
1829
|
+
}
|
|
1830
|
+
socket = new WebSocket(url);
|
|
1831
|
+
socket.onopen = () => {
|
|
1832
|
+
attempt = 1;
|
|
1833
|
+
};
|
|
1834
|
+
socket.onmessage = (event) => {
|
|
1835
|
+
try {
|
|
1836
|
+
const settled = triggerEventFromWire(JSON.parse(String(event.data)));
|
|
1837
|
+
if (settled !== null) {
|
|
1838
|
+
options.onPayment(this.proven(settled));
|
|
1839
|
+
}
|
|
1840
|
+
} catch (refused) {
|
|
1841
|
+
options.onError?.(refused);
|
|
1842
|
+
}
|
|
1843
|
+
};
|
|
1844
|
+
socket.onerror = () => options.onError?.(new Error(`could not follow trigger at ${base}`));
|
|
1845
|
+
socket.onclose = again;
|
|
1846
|
+
};
|
|
1847
|
+
void connect();
|
|
1848
|
+
return () => {
|
|
1849
|
+
stopped = true;
|
|
1850
|
+
clearTimeout(retry);
|
|
1851
|
+
socket?.close();
|
|
1852
|
+
};
|
|
1853
|
+
}
|
|
1854
|
+
/**
|
|
1855
|
+
* A one minute pass onto one trigger's stream, for something that must hold
|
|
1856
|
+
* neither the token nor the trigger secret. Mint it in a handler and answer
|
|
1857
|
+
* with the ticket alone, because that is all a browser needs to connect and
|
|
1858
|
+
* all it can do anything with. `watchTicketEndpoint` is this method already
|
|
1859
|
+
* wrapped in a route
|
|
1860
|
+
*/
|
|
1861
|
+
async createSocketTicket(params) {
|
|
1862
|
+
return await this.mintedTicket({
|
|
1863
|
+
trigger_secret: unguessable(params.trigger),
|
|
1864
|
+
replay: params.replay
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
needsTicket(asked) {
|
|
1868
|
+
return asked === true || this.token !== null;
|
|
1869
|
+
}
|
|
1870
|
+
async wsTicket(body) {
|
|
1871
|
+
return encodeURIComponent((await this.mintedTicket(body)).ticket);
|
|
1872
|
+
}
|
|
1873
|
+
async mintedTicket(body) {
|
|
1874
|
+
const sent = JSON.stringify(body);
|
|
1875
|
+
const response = await fetch(`${this.baseUrl}/ws-tickets`, {
|
|
1876
|
+
method: "POST",
|
|
1877
|
+
headers: await this.sending("/ws-tickets", sent),
|
|
1878
|
+
body: sent
|
|
1879
|
+
});
|
|
1880
|
+
if (!response.ok) {
|
|
1881
|
+
throw await problemFrom(response);
|
|
1572
1882
|
}
|
|
1573
|
-
const
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
}
|
|
1582
|
-
function readQuery(url) {
|
|
1583
|
-
const reference = url.searchParams.get("ref");
|
|
1584
|
-
const minor = Number(url.searchParams.get("minor"));
|
|
1585
|
-
const currency = url.searchParams.get("cc");
|
|
1586
|
-
const signature = url.searchParams.get("sig");
|
|
1587
|
-
if (!reference || !currency || !signature) return null;
|
|
1588
|
-
if (!Number.isInteger(minor) || minor <= 0) return null;
|
|
1589
|
-
return { reference, amountMinor: minor, currency, signature };
|
|
1590
|
-
}
|
|
1591
|
-
function pays(credit, asked) {
|
|
1592
|
-
return credit.amountMinor === asked.amountMinor && credit.currency.toUpperCase() === asked.currency.toUpperCase() && credit.reference.toUpperCase().includes(asked.reference.toUpperCase());
|
|
1593
|
-
}
|
|
1594
|
-
function subjectOf(reference, amountMinor, currency) {
|
|
1595
|
-
return `${reference}|${amountMinor}|${currency.toUpperCase()}`;
|
|
1596
|
-
}
|
|
1597
|
-
function hashOf(preimage) {
|
|
1598
|
-
return bytesToHex(sha256(hexToBytes(preimage)));
|
|
1599
|
-
}
|
|
1600
|
-
function shortPaymentDescriptor(params, currency) {
|
|
1601
|
-
const fields = [
|
|
1602
|
-
`ACC:${params.iban}`,
|
|
1603
|
-
`AM:${major(params.amountMinor, currency)}`,
|
|
1604
|
-
`CC:${currency.toUpperCase()}`,
|
|
1605
|
-
`MSG:${params.reference}`
|
|
1606
|
-
];
|
|
1607
|
-
if (params.variableSymbol) fields.push(`X-VS:${params.variableSymbol}`);
|
|
1608
|
-
return `SPD*1.0*${fields.join("*")}`;
|
|
1609
|
-
}
|
|
1610
|
-
function major(amountMinor, currency) {
|
|
1611
|
-
return (amountMinor / minorScaleOf(currency)).toFixed(minorUnitsOf(currency));
|
|
1612
|
-
}
|
|
1613
|
-
async function refuseAnOpenGateway(params) {
|
|
1614
|
-
if (params.allowPublicGateway === true) return;
|
|
1615
|
-
if (await params.gateway.refusesStrangers()) return;
|
|
1616
|
-
throw new Error(
|
|
1617
|
-
"this gateway serves callers with no token, so it is not yours, and its operator would read the amount and the reference off every verify URL. Point at one that answers 401 to a stranger, or say allowPublicGateway"
|
|
1618
|
-
);
|
|
1619
|
-
}
|
|
1620
|
-
function refuseUnusable(params, currency) {
|
|
1621
|
-
if (!IBAN.test(params.iban)) throw new Error(`${params.iban} is not an IBAN`);
|
|
1622
|
-
if (!Number.isInteger(params.amountMinor) || params.amountMinor <= 0) {
|
|
1623
|
-
throw new Error("amountMinor must be a whole number of minor units above zero");
|
|
1883
|
+
const ticket = socketTicketFromWire(await response.json().catch(() => null));
|
|
1884
|
+
if (ticket === null) {
|
|
1885
|
+
throw new ProblemError({
|
|
1886
|
+
status: response.status,
|
|
1887
|
+
title: "The gateway answered with something that is not a ticket"
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
return ticket;
|
|
1624
1891
|
}
|
|
1625
|
-
|
|
1626
|
-
|
|
1892
|
+
async sending(path, body) {
|
|
1893
|
+
return { "content-type": "application/json", ...await this.reading("POST", path, body) };
|
|
1627
1894
|
}
|
|
1628
|
-
|
|
1629
|
-
|
|
1895
|
+
async reading(method, path, body = "") {
|
|
1896
|
+
return {
|
|
1897
|
+
...this.token === null ? {} : { authorization: `Bearer ${this.token}` },
|
|
1898
|
+
...this.secret === null ? {} : await signedAs(await this.speaking(), method, path, body)
|
|
1899
|
+
};
|
|
1630
1900
|
}
|
|
1631
|
-
|
|
1632
|
-
|
|
1901
|
+
async speaking() {
|
|
1902
|
+
this.speaks ??= callerKey(this.secret ?? "");
|
|
1903
|
+
return await this.speaks;
|
|
1904
|
+
}
|
|
1905
|
+
proven(settled) {
|
|
1906
|
+
const unproven = settled.status === "paid" && (settled.preimage === null || !preimageMatchesHash(settled.preimage, settled.paymentHash));
|
|
1907
|
+
if (this.verify && unproven) {
|
|
1908
|
+
throw new GatewayCheatError("preimage_mismatch", settled.id);
|
|
1909
|
+
}
|
|
1910
|
+
return settled;
|
|
1911
|
+
}
|
|
1912
|
+
checked(payment) {
|
|
1913
|
+
if (this.verify && payment.status === "paid" && !isProvablyPaid(payment)) {
|
|
1914
|
+
throw new GatewayCheatError("preimage_mismatch", payment.id);
|
|
1915
|
+
}
|
|
1916
|
+
return payment;
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
async function paymentFrom(response) {
|
|
1920
|
+
const payment = paymentFromWire(await response.json().catch(() => null));
|
|
1921
|
+
if (payment === null) {
|
|
1922
|
+
throw new ProblemError({
|
|
1923
|
+
status: response.status,
|
|
1924
|
+
title: "The gateway answered with something that is not a payment"
|
|
1925
|
+
});
|
|
1633
1926
|
}
|
|
1927
|
+
return payment;
|
|
1634
1928
|
}
|
|
1635
|
-
function
|
|
1636
|
-
|
|
1929
|
+
async function problemFrom(response) {
|
|
1930
|
+
const problem = await response.json().catch(() => ({}));
|
|
1931
|
+
const document = { ...problem, status: response.status };
|
|
1932
|
+
if (isProblemType(problem, NO_WALLET_AVAILABLE)) {
|
|
1933
|
+
return new NoWalletAvailableError(document, refusals(problem.wallets));
|
|
1934
|
+
}
|
|
1935
|
+
if (isProblemType(problem, REQUEST_IN_FLIGHT)) {
|
|
1936
|
+
return new IdempotencyConflictError(document, "request-in-flight");
|
|
1937
|
+
}
|
|
1938
|
+
if (isProblemType(problem, IDEMPOTENCY_KEY_REUSED)) {
|
|
1939
|
+
return new IdempotencyConflictError(document, "key-reused");
|
|
1940
|
+
}
|
|
1941
|
+
return new ProblemError(document);
|
|
1942
|
+
}
|
|
1943
|
+
function refusals(wallets) {
|
|
1944
|
+
if (!Array.isArray(wallets)) {
|
|
1945
|
+
return [];
|
|
1946
|
+
}
|
|
1947
|
+
return wallets.filter((wallet) => {
|
|
1948
|
+
return typeof wallet === "object" && wallet !== null && "address" in wallet;
|
|
1949
|
+
});
|
|
1637
1950
|
}
|
|
1638
1951
|
|
|
1639
1952
|
// src/fio.ts
|
|
@@ -1659,7 +1972,9 @@ var WHERE_A_PAYER_WRITES = [
|
|
|
1659
1972
|
var UTC_OFFSET = /^[+-]\d{4}$/;
|
|
1660
1973
|
function fioStatement(config) {
|
|
1661
1974
|
const named = typeof config.token === "string" ? [config.token] : config.token;
|
|
1662
|
-
if (named.length === 0)
|
|
1975
|
+
if (named.length === 0) {
|
|
1976
|
+
throw new Error("fioStatement needs at least one token to read with");
|
|
1977
|
+
}
|
|
1663
1978
|
const usedAt = new Map(named.map((token) => [token, Number.NEGATIVE_INFINITY]));
|
|
1664
1979
|
const tokenWindowMs = (config.minIntervalSecs ?? DEFAULT_MIN_INTERVAL_SECS) * MILLIS;
|
|
1665
1980
|
const paceMs = tokenWindowMs / usedAt.size;
|
|
@@ -1667,9 +1982,13 @@ function fioStatement(config) {
|
|
|
1667
1982
|
let credits = [];
|
|
1668
1983
|
return async (sinceUnix) => {
|
|
1669
1984
|
const now = Date.now();
|
|
1670
|
-
if (now - lastRead < paceMs)
|
|
1985
|
+
if (now - lastRead < paceMs) {
|
|
1986
|
+
return credits;
|
|
1987
|
+
}
|
|
1671
1988
|
const idlest = longestUnused(usedAt);
|
|
1672
|
-
if (now - idlest.usedAt < tokenWindowMs)
|
|
1989
|
+
if (now - idlest.usedAt < tokenWindowMs) {
|
|
1990
|
+
return credits;
|
|
1991
|
+
}
|
|
1673
1992
|
usedAt.set(idlest.token, now);
|
|
1674
1993
|
lastRead = now;
|
|
1675
1994
|
const url = [
|
|
@@ -1684,7 +2003,9 @@ function fioStatement(config) {
|
|
|
1684
2003
|
if (answer.status === TOO_SOON) {
|
|
1685
2004
|
throw new Error("fio refuses a second read of this token inside its 30 second window");
|
|
1686
2005
|
}
|
|
1687
|
-
if (!answer.ok)
|
|
2006
|
+
if (!answer.ok) {
|
|
2007
|
+
throw new Error(`fio answered ${answer.status} reading the statement`);
|
|
2008
|
+
}
|
|
1688
2009
|
const read = await answer.json();
|
|
1689
2010
|
credits = (read.accountStatement?.transactionList?.transaction ?? []).filter(isCredit).map(asCredit);
|
|
1690
2011
|
return credits;
|
|
@@ -1714,86 +2035,250 @@ function asCredit(transaction) {
|
|
|
1714
2035
|
}
|
|
1715
2036
|
function bookedAtIn(cell) {
|
|
1716
2037
|
const value = cell?.value;
|
|
1717
|
-
if (typeof value === "number")
|
|
2038
|
+
if (typeof value === "number") {
|
|
2039
|
+
return Math.floor(value / MILLIS);
|
|
2040
|
+
}
|
|
1718
2041
|
const at = Date.parse(asIso8601(textIn(cell)));
|
|
1719
2042
|
return Number.isFinite(at) ? Math.floor(at / MILLIS) : 0;
|
|
1720
2043
|
}
|
|
1721
2044
|
function asIso8601(booked) {
|
|
1722
2045
|
const day = booked.slice(0, DATE_CHARS);
|
|
1723
2046
|
const zone = booked.slice(DATE_CHARS);
|
|
1724
|
-
if (!UTC_OFFSET.test(zone))
|
|
2047
|
+
if (!UTC_OFFSET.test(zone)) {
|
|
2048
|
+
return `${day}T00:00:00Z`;
|
|
2049
|
+
}
|
|
1725
2050
|
return `${day}T00:00:00${zone.slice(0, 3)}:${zone.slice(3)}`;
|
|
1726
2051
|
}
|
|
1727
|
-
function numberIn(cell) {
|
|
1728
|
-
const value = Number(cell?.value ?? Number.NaN);
|
|
1729
|
-
return Number.isFinite(value) ? value : 0;
|
|
2052
|
+
function numberIn(cell) {
|
|
2053
|
+
const value = Number(cell?.value ?? Number.NaN);
|
|
2054
|
+
return Number.isFinite(value) ? value : 0;
|
|
2055
|
+
}
|
|
2056
|
+
function textIn(cell) {
|
|
2057
|
+
const value = cell?.value;
|
|
2058
|
+
return value === null || value === void 0 ? "" : String(value).trim();
|
|
2059
|
+
}
|
|
2060
|
+
function asDate(unix) {
|
|
2061
|
+
return new Date(unix * MILLIS).toISOString().slice(0, DATE_CHARS);
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
// src/gateways.ts
|
|
2065
|
+
var Gateways = class {
|
|
2066
|
+
each;
|
|
2067
|
+
urls;
|
|
2068
|
+
onRefused;
|
|
2069
|
+
constructor(baseUrls, options) {
|
|
2070
|
+
if (baseUrls.length === 0) {
|
|
2071
|
+
throw new Error("name at least one gateway to watch at");
|
|
2072
|
+
}
|
|
2073
|
+
this.urls = [...baseUrls];
|
|
2074
|
+
this.each = baseUrls.map((baseUrl) => new ThunderBridge(baseUrl, options));
|
|
2075
|
+
this.onRefused = options?.onRefused ?? (() => {
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
/** What this payment is called, which every gateway here will agree on */
|
|
2079
|
+
async nameFor(paymentHash) {
|
|
2080
|
+
return await this.each[0].nameFor(paymentHash);
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Hand the same invoice to every gateway. Throws only when none of them took it,
|
|
2084
|
+
* carrying the first refusal, because one gateway that agreed is enough to be
|
|
2085
|
+
* watched
|
|
2086
|
+
*/
|
|
2087
|
+
async watchPayment(params) {
|
|
2088
|
+
const asked = await Promise.allSettled(
|
|
2089
|
+
this.each.map((gateway) => gateway.watchPayment(params))
|
|
2090
|
+
);
|
|
2091
|
+
const taken = [];
|
|
2092
|
+
const refusals3 = [];
|
|
2093
|
+
for (const [at, answer] of asked.entries()) {
|
|
2094
|
+
if (answer.status === "fulfilled") {
|
|
2095
|
+
taken.push(answer.value);
|
|
2096
|
+
continue;
|
|
2097
|
+
}
|
|
2098
|
+
refusals3.push(answer.reason);
|
|
2099
|
+
this.onRefused(this.urls[at], answer.reason);
|
|
2100
|
+
}
|
|
2101
|
+
if (taken[0] === void 0) {
|
|
2102
|
+
throw refusals3[0];
|
|
2103
|
+
}
|
|
2104
|
+
return taken[0];
|
|
2105
|
+
}
|
|
2106
|
+
/**
|
|
2107
|
+
* Wait for whichever gateway speaks first. A settlement from any of them is the
|
|
2108
|
+
* settlement, and each has already proved the preimage against the hash before
|
|
2109
|
+
* saying so. When they all end without a payment, the first ending is the answer,
|
|
2110
|
+
* and when they all fail, the first failure is thrown
|
|
2111
|
+
*/
|
|
2112
|
+
async waitForWatched(id, options) {
|
|
2113
|
+
const stopLosers = new AbortController();
|
|
2114
|
+
const signal = options?.signal ? AbortSignal.any([stopLosers.signal, options.signal]) : stopLosers.signal;
|
|
2115
|
+
const unpaid = [];
|
|
2116
|
+
let refused = null;
|
|
2117
|
+
try {
|
|
2118
|
+
const settled = await new Promise((resolve2) => {
|
|
2119
|
+
let waiting = this.each.length;
|
|
2120
|
+
const lost = () => {
|
|
2121
|
+
waiting -= 1;
|
|
2122
|
+
if (waiting === 0) {
|
|
2123
|
+
resolve2(null);
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
for (const gateway of this.each) {
|
|
2127
|
+
gateway.waitForWatched(id, { ...options, signal }).then((watched) => {
|
|
2128
|
+
if (watched.status === "paid") {
|
|
2129
|
+
return resolve2(watched);
|
|
2130
|
+
}
|
|
2131
|
+
unpaid.push(watched);
|
|
2132
|
+
lost();
|
|
2133
|
+
}).catch((failure) => {
|
|
2134
|
+
refused ??= failure;
|
|
2135
|
+
lost();
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
});
|
|
2139
|
+
if (settled !== null) {
|
|
2140
|
+
return settled;
|
|
2141
|
+
}
|
|
2142
|
+
if (unpaid.length > 0) {
|
|
2143
|
+
return unpaid[0];
|
|
2144
|
+
}
|
|
2145
|
+
throw refused;
|
|
2146
|
+
} finally {
|
|
2147
|
+
stopLosers.abort();
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
};
|
|
2151
|
+
|
|
2152
|
+
// src/price.ts
|
|
2153
|
+
var MSAT_PER_BTC2 = 1e11;
|
|
2154
|
+
var BASIS_POINTS = 1e4;
|
|
2155
|
+
var DEFAULT_HOLD_SECS = 60;
|
|
2156
|
+
var DEFAULT_MIN_VENUES = 2;
|
|
2157
|
+
var DEFAULT_MAX_SPREAD_BPS = 200;
|
|
2158
|
+
var MILLIS2 = 1e3;
|
|
2159
|
+
function coinbase(baseUrl = "https://api.coinbase.com") {
|
|
2160
|
+
return async (currency) => {
|
|
2161
|
+
const asked = currency.toUpperCase();
|
|
2162
|
+
const answer = await asJson(`${baseUrl}/v2/prices/BTC-${asked}/spot`, "coinbase");
|
|
2163
|
+
const quoted = answer.data;
|
|
2164
|
+
if (quoted?.currency !== asked) {
|
|
2165
|
+
throw new Error(`coinbase quoted ${quoted?.currency} when asked for ${asked}`);
|
|
2166
|
+
}
|
|
2167
|
+
return asMinor(quoted.amount, "coinbase", asked);
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
function kraken(baseUrl = "https://api.kraken.com") {
|
|
2171
|
+
return async (currency) => {
|
|
2172
|
+
const asked = currency.toUpperCase();
|
|
2173
|
+
const answer = await asJson(`${baseUrl}/0/public/Ticker?pair=XBT${asked}`, "kraken");
|
|
2174
|
+
if (answer.error?.length) {
|
|
2175
|
+
throw new Error(`kraken refused XBT${asked}: ${answer.error[0]}`);
|
|
2176
|
+
}
|
|
2177
|
+
const pairs = Object.values(answer.result ?? {});
|
|
2178
|
+
if (pairs.length !== 1) {
|
|
2179
|
+
throw new Error(`kraken answered ${pairs.length} pairs for XBT${asked}`);
|
|
2180
|
+
}
|
|
2181
|
+
return asMinor(pairs[0]?.c?.[0], "kraken", asked);
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
function bitstamp(baseUrl = "https://www.bitstamp.net") {
|
|
2185
|
+
return async (currency) => {
|
|
2186
|
+
const pair = `btc${currency.toLowerCase()}`;
|
|
2187
|
+
const answer = await asJson(`${baseUrl}/api/v2/ticker/${pair}/`, "bitstamp");
|
|
2188
|
+
if (Array.isArray(answer)) {
|
|
2189
|
+
throw new Error(`bitstamp has no ${pair} pair`);
|
|
2190
|
+
}
|
|
2191
|
+
return asMinor(answer.last, "bitstamp", currency);
|
|
2192
|
+
};
|
|
1730
2193
|
}
|
|
1731
|
-
function
|
|
1732
|
-
|
|
1733
|
-
|
|
2194
|
+
function coinmate(baseUrl = "https://coinmate.io") {
|
|
2195
|
+
return async (currency) => {
|
|
2196
|
+
const pair = `BTC_${currency.toUpperCase()}`;
|
|
2197
|
+
const answer = await asJson(`${baseUrl}/api/ticker?currencyPair=${pair}`, "coinmate");
|
|
2198
|
+
if (answer.error !== false) {
|
|
2199
|
+
throw new Error(`coinmate refused ${pair}: ${answer.errorMessage ?? "no reason"}`);
|
|
2200
|
+
}
|
|
2201
|
+
return asMinor(answer.data?.last, "coinmate", currency);
|
|
2202
|
+
};
|
|
1734
2203
|
}
|
|
1735
|
-
function
|
|
1736
|
-
|
|
2204
|
+
function medianOf(tickers = [coinbase(), kraken(), bitstamp(), coinmate()], options = {}) {
|
|
2205
|
+
const holdFor = (options.holdForSecs ?? DEFAULT_HOLD_SECS) * MILLIS2;
|
|
2206
|
+
const minVenues = options.minVenues ?? DEFAULT_MIN_VENUES;
|
|
2207
|
+
const maxSpread = options.maxSpreadBps ?? DEFAULT_MAX_SPREAD_BPS;
|
|
2208
|
+
const held = /* @__PURE__ */ new Map();
|
|
2209
|
+
return async (currency) => {
|
|
2210
|
+
const asked = currency.toUpperCase();
|
|
2211
|
+
const remembered = held.get(asked);
|
|
2212
|
+
if (remembered && Date.now() - remembered.at < holdFor) {
|
|
2213
|
+
return remembered.price;
|
|
2214
|
+
}
|
|
2215
|
+
const answers = await Promise.allSettled(tickers.map((ticker) => ticker(asked)));
|
|
2216
|
+
const quoted = answers.filter((answer) => answer.status === "fulfilled").map((answer) => answer.value).sort((one, other) => one - other);
|
|
2217
|
+
if (quoted.length < minVenues) {
|
|
2218
|
+
throw new Error(
|
|
2219
|
+
`${quoted.length} of ${tickers.length} venues quoted ${asked}, ${minVenues} wanted: ${refusals2(answers)}`
|
|
2220
|
+
);
|
|
2221
|
+
}
|
|
2222
|
+
const spread = spreadBpsOf(quoted);
|
|
2223
|
+
if (spread > maxSpread) {
|
|
2224
|
+
throw new Error(
|
|
2225
|
+
`venues disagree on ${asked} by ${Math.round(spread)} bps, more than the ${maxSpread} allowed: ${quoted.join(", ")}`
|
|
2226
|
+
);
|
|
2227
|
+
}
|
|
2228
|
+
const price = middleOf(quoted);
|
|
2229
|
+
held.set(asked, { at: Date.now(), price });
|
|
2230
|
+
return price;
|
|
2231
|
+
};
|
|
1737
2232
|
}
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
var BECH32_GENERATOR = [996825010, 642813549, 513874426, 1027748829, 705979059];
|
|
1742
|
-
var CHECKSUM_SLOTS = [0, 1, 2, 3, 4, 5];
|
|
1743
|
-
var LNURL_HRP = "lnurl";
|
|
1744
|
-
function toLnurl(endpoint) {
|
|
1745
|
-
const scheme = parsedScheme(endpoint);
|
|
1746
|
-
if (scheme !== "https:" && scheme !== "http:") {
|
|
1747
|
-
throw new Error(`${endpoint} is not an http or https URL`);
|
|
2233
|
+
function msatFor(amountMinor, priceMinorPerBtc, options = {}) {
|
|
2234
|
+
if (!Number.isInteger(amountMinor) || amountMinor <= 0) {
|
|
2235
|
+
throw new Error("amountMinor must be a whole number of minor units above zero");
|
|
1748
2236
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
2237
|
+
if (!Number.isFinite(priceMinorPerBtc) || priceMinorPerBtc <= 0) {
|
|
2238
|
+
throw new Error(`${priceMinorPerBtc} is not a usable price`);
|
|
2239
|
+
}
|
|
2240
|
+
const spreadBps = options.spreadBps ?? 0;
|
|
2241
|
+
if (!Number.isInteger(spreadBps) || spreadBps < 0) {
|
|
2242
|
+
throw new Error("spreadBps must be a whole number of basis points, none or more");
|
|
2243
|
+
}
|
|
2244
|
+
const wanted = BigInt(amountMinor) * BigInt(MSAT_PER_BTC2) * BigInt(BASIS_POINTS + spreadBps);
|
|
2245
|
+
const per = BigInt(Math.round(priceMinorPerBtc)) * BigInt(BASIS_POINTS);
|
|
2246
|
+
const msat = (wanted + per - 1n) / per;
|
|
2247
|
+
if (msat > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
2248
|
+
throw new Error(`${amountMinor} at ${priceMinorPerBtc} is more millisatoshi than exist`);
|
|
2249
|
+
}
|
|
2250
|
+
return Number(msat);
|
|
1752
2251
|
}
|
|
1753
|
-
function
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
return null;
|
|
2252
|
+
async function asJson(url, venue) {
|
|
2253
|
+
const answer = await fetch(url, { headers: { accept: "application/json" } });
|
|
2254
|
+
if (!answer.ok) {
|
|
2255
|
+
throw new Error(`${venue} answered ${answer.status}`);
|
|
1758
2256
|
}
|
|
2257
|
+
return answer.json();
|
|
1759
2258
|
}
|
|
1760
|
-
function
|
|
1761
|
-
const
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
for (const byte of bytes) {
|
|
1765
|
-
accumulator = accumulator << 8 | byte;
|
|
1766
|
-
bits += 8;
|
|
1767
|
-
while (bits >= 5) {
|
|
1768
|
-
bits -= 5;
|
|
1769
|
-
words.push(accumulator >> bits & 31);
|
|
1770
|
-
}
|
|
2259
|
+
function asMinor(quoted, venue, currency) {
|
|
2260
|
+
const major2 = Number(quoted);
|
|
2261
|
+
if (!Number.isFinite(major2) || major2 <= 0) {
|
|
2262
|
+
throw new Error(`${venue} quoted ${String(quoted)} for ${currency.toUpperCase()}`);
|
|
1771
2263
|
}
|
|
1772
|
-
|
|
1773
|
-
return words;
|
|
2264
|
+
return Math.round(major2 * minorScaleOf(currency));
|
|
1774
2265
|
}
|
|
1775
|
-
function
|
|
1776
|
-
const
|
|
1777
|
-
const
|
|
1778
|
-
|
|
1779
|
-
0,
|
|
1780
|
-
...expanded.map((code) => code & 31),
|
|
1781
|
-
...words,
|
|
1782
|
-
...CHECKSUM_SLOTS.map(() => 0)
|
|
1783
|
-
];
|
|
1784
|
-
const polymod = bech32Polymod(values) ^ 1;
|
|
1785
|
-
return CHECKSUM_SLOTS.map((slot) => polymod >> 5 * (5 - slot) & 31);
|
|
2266
|
+
function spreadBpsOf(sorted) {
|
|
2267
|
+
const lowest = sorted[0] ?? 0;
|
|
2268
|
+
const highest = sorted[sorted.length - 1] ?? 0;
|
|
2269
|
+
return lowest === 0 ? Number.POSITIVE_INFINITY : (highest - lowest) / lowest * BASIS_POINTS;
|
|
1786
2270
|
}
|
|
1787
|
-
function
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
checksum = (checksum & 33554431) << 5 ^ value;
|
|
1792
|
-
for (let bit = 0; bit < 5; bit++) {
|
|
1793
|
-
if (top >> bit & 1) checksum ^= BECH32_GENERATOR[bit];
|
|
1794
|
-
}
|
|
2271
|
+
function middleOf(sorted) {
|
|
2272
|
+
const middle = Math.floor(sorted.length / 2);
|
|
2273
|
+
if (sorted.length % 2 === 1) {
|
|
2274
|
+
return sorted[middle] ?? 0;
|
|
1795
2275
|
}
|
|
1796
|
-
return
|
|
2276
|
+
return Math.round(((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2);
|
|
2277
|
+
}
|
|
2278
|
+
function refusals2(answers) {
|
|
2279
|
+
return answers.filter((answer) => answer.status === "rejected").map(
|
|
2280
|
+
(answer) => answer.reason instanceof Error ? answer.reason.message : String(answer.reason)
|
|
2281
|
+
).join("; ");
|
|
1797
2282
|
}
|
|
1798
2283
|
|
|
1799
2284
|
// src/qr.ts
|
|
@@ -1830,7 +2315,9 @@ function qrToDataUrl(payload, options) {
|
|
|
1830
2315
|
function svgOf(scanned, options) {
|
|
1831
2316
|
const size = options?.size ?? 256;
|
|
1832
2317
|
const color = options?.color ?? "#000";
|
|
1833
|
-
if (!SAFE_COLOR.test(color))
|
|
2318
|
+
if (!SAFE_COLOR.test(color)) {
|
|
2319
|
+
throw new Error(`Invalid color: ${color}`);
|
|
2320
|
+
}
|
|
1834
2321
|
return renderSvg(scanned, size, color);
|
|
1835
2322
|
}
|
|
1836
2323
|
function asDataUrl(svg) {
|
|
@@ -1876,6 +2363,7 @@ function bankRail(config) {
|
|
|
1876
2363
|
currency: order.currency,
|
|
1877
2364
|
expiresAt,
|
|
1878
2365
|
trigger: config.trigger,
|
|
2366
|
+
replay: config.replay,
|
|
1879
2367
|
sealed: await config.sealed?.(order),
|
|
1880
2368
|
variableSymbol: config.variableSymbol?.(order),
|
|
1881
2369
|
webhookUrl: config.webhookUrl,
|
|
@@ -1898,7 +2386,11 @@ function lightningRail(config) {
|
|
|
1898
2386
|
amountMsat: await config.amountMsat(order),
|
|
1899
2387
|
webhookUrl: config.webhookUrl
|
|
1900
2388
|
},
|
|
1901
|
-
{
|
|
2389
|
+
{
|
|
2390
|
+
idempotencyKey: config.idempotencyKey?.(order),
|
|
2391
|
+
trigger: config.trigger,
|
|
2392
|
+
replay: config.replay
|
|
2393
|
+
}
|
|
1902
2394
|
);
|
|
1903
2395
|
return {
|
|
1904
2396
|
id: payment.id,
|
|
@@ -1909,128 +2401,6 @@ function lightningRail(config) {
|
|
|
1909
2401
|
};
|
|
1910
2402
|
};
|
|
1911
2403
|
}
|
|
1912
|
-
|
|
1913
|
-
// src/price.ts
|
|
1914
|
-
var MSAT_PER_BTC2 = 1e11;
|
|
1915
|
-
var BASIS_POINTS = 1e4;
|
|
1916
|
-
var DEFAULT_HOLD_SECS = 60;
|
|
1917
|
-
var DEFAULT_MIN_VENUES = 2;
|
|
1918
|
-
var DEFAULT_MAX_SPREAD_BPS = 200;
|
|
1919
|
-
var MILLIS2 = 1e3;
|
|
1920
|
-
function coinbase(baseUrl = "https://api.coinbase.com") {
|
|
1921
|
-
return async (currency) => {
|
|
1922
|
-
const asked = currency.toUpperCase();
|
|
1923
|
-
const answer = await asJson(`${baseUrl}/v2/prices/BTC-${asked}/spot`, "coinbase");
|
|
1924
|
-
const quoted = answer.data;
|
|
1925
|
-
if (quoted?.currency !== asked) {
|
|
1926
|
-
throw new Error(`coinbase quoted ${quoted?.currency} when asked for ${asked}`);
|
|
1927
|
-
}
|
|
1928
|
-
return asMinor(quoted.amount, "coinbase", asked);
|
|
1929
|
-
};
|
|
1930
|
-
}
|
|
1931
|
-
function kraken(baseUrl = "https://api.kraken.com") {
|
|
1932
|
-
return async (currency) => {
|
|
1933
|
-
const asked = currency.toUpperCase();
|
|
1934
|
-
const answer = await asJson(`${baseUrl}/0/public/Ticker?pair=XBT${asked}`, "kraken");
|
|
1935
|
-
if (answer.error?.length) throw new Error(`kraken refused XBT${asked}: ${answer.error[0]}`);
|
|
1936
|
-
const pairs = Object.values(answer.result ?? {});
|
|
1937
|
-
if (pairs.length !== 1) {
|
|
1938
|
-
throw new Error(`kraken answered ${pairs.length} pairs for XBT${asked}`);
|
|
1939
|
-
}
|
|
1940
|
-
return asMinor(pairs[0]?.c?.[0], "kraken", asked);
|
|
1941
|
-
};
|
|
1942
|
-
}
|
|
1943
|
-
function bitstamp(baseUrl = "https://www.bitstamp.net") {
|
|
1944
|
-
return async (currency) => {
|
|
1945
|
-
const pair = `btc${currency.toLowerCase()}`;
|
|
1946
|
-
const answer = await asJson(`${baseUrl}/api/v2/ticker/${pair}/`, "bitstamp");
|
|
1947
|
-
if (Array.isArray(answer)) throw new Error(`bitstamp has no ${pair} pair`);
|
|
1948
|
-
return asMinor(answer.last, "bitstamp", currency);
|
|
1949
|
-
};
|
|
1950
|
-
}
|
|
1951
|
-
function coinmate(baseUrl = "https://coinmate.io") {
|
|
1952
|
-
return async (currency) => {
|
|
1953
|
-
const pair = `BTC_${currency.toUpperCase()}`;
|
|
1954
|
-
const answer = await asJson(`${baseUrl}/api/ticker?currencyPair=${pair}`, "coinmate");
|
|
1955
|
-
if (answer.error !== false) {
|
|
1956
|
-
throw new Error(`coinmate refused ${pair}: ${answer.errorMessage ?? "no reason"}`);
|
|
1957
|
-
}
|
|
1958
|
-
return asMinor(answer.data?.last, "coinmate", currency);
|
|
1959
|
-
};
|
|
1960
|
-
}
|
|
1961
|
-
function medianOf(tickers = [coinbase(), kraken(), bitstamp(), coinmate()], options = {}) {
|
|
1962
|
-
const holdFor = (options.holdForSecs ?? DEFAULT_HOLD_SECS) * MILLIS2;
|
|
1963
|
-
const minVenues = options.minVenues ?? DEFAULT_MIN_VENUES;
|
|
1964
|
-
const maxSpread = options.maxSpreadBps ?? DEFAULT_MAX_SPREAD_BPS;
|
|
1965
|
-
const held = /* @__PURE__ */ new Map();
|
|
1966
|
-
return async (currency) => {
|
|
1967
|
-
const asked = currency.toUpperCase();
|
|
1968
|
-
const remembered = held.get(asked);
|
|
1969
|
-
if (remembered && Date.now() - remembered.at < holdFor) return remembered.price;
|
|
1970
|
-
const answers = await Promise.allSettled(tickers.map((ticker) => ticker(asked)));
|
|
1971
|
-
const quoted = answers.filter((answer) => answer.status === "fulfilled").map((answer) => answer.value).sort((one, other) => one - other);
|
|
1972
|
-
if (quoted.length < minVenues) {
|
|
1973
|
-
throw new Error(
|
|
1974
|
-
`${quoted.length} of ${tickers.length} venues quoted ${asked}, ${minVenues} wanted: ${refusals2(answers)}`
|
|
1975
|
-
);
|
|
1976
|
-
}
|
|
1977
|
-
const spread = spreadBpsOf(quoted);
|
|
1978
|
-
if (spread > maxSpread) {
|
|
1979
|
-
throw new Error(
|
|
1980
|
-
`venues disagree on ${asked} by ${Math.round(spread)} bps, more than the ${maxSpread} allowed: ${quoted.join(", ")}`
|
|
1981
|
-
);
|
|
1982
|
-
}
|
|
1983
|
-
const price = middleOf(quoted);
|
|
1984
|
-
held.set(asked, { at: Date.now(), price });
|
|
1985
|
-
return price;
|
|
1986
|
-
};
|
|
1987
|
-
}
|
|
1988
|
-
function msatFor(amountMinor, priceMinorPerBtc, options = {}) {
|
|
1989
|
-
if (!Number.isInteger(amountMinor) || amountMinor <= 0) {
|
|
1990
|
-
throw new Error("amountMinor must be a whole number of minor units above zero");
|
|
1991
|
-
}
|
|
1992
|
-
if (!Number.isFinite(priceMinorPerBtc) || priceMinorPerBtc <= 0) {
|
|
1993
|
-
throw new Error(`${priceMinorPerBtc} is not a usable price`);
|
|
1994
|
-
}
|
|
1995
|
-
const spreadBps = options.spreadBps ?? 0;
|
|
1996
|
-
if (!Number.isInteger(spreadBps) || spreadBps < 0) {
|
|
1997
|
-
throw new Error("spreadBps must be a whole number of basis points, none or more");
|
|
1998
|
-
}
|
|
1999
|
-
const wanted = BigInt(amountMinor) * BigInt(MSAT_PER_BTC2) * BigInt(BASIS_POINTS + spreadBps);
|
|
2000
|
-
const per = BigInt(Math.round(priceMinorPerBtc)) * BigInt(BASIS_POINTS);
|
|
2001
|
-
const msat = (wanted + per - 1n) / per;
|
|
2002
|
-
if (msat > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
2003
|
-
throw new Error(`${amountMinor} at ${priceMinorPerBtc} is more millisatoshi than exist`);
|
|
2004
|
-
}
|
|
2005
|
-
return Number(msat);
|
|
2006
|
-
}
|
|
2007
|
-
async function asJson(url, venue) {
|
|
2008
|
-
const answer = await fetch(url, { headers: { accept: "application/json" } });
|
|
2009
|
-
if (!answer.ok) throw new Error(`${venue} answered ${answer.status}`);
|
|
2010
|
-
return answer.json();
|
|
2011
|
-
}
|
|
2012
|
-
function asMinor(quoted, venue, currency) {
|
|
2013
|
-
const major2 = Number(quoted);
|
|
2014
|
-
if (!Number.isFinite(major2) || major2 <= 0) {
|
|
2015
|
-
throw new Error(`${venue} quoted ${String(quoted)} for ${currency.toUpperCase()}`);
|
|
2016
|
-
}
|
|
2017
|
-
return Math.round(major2 * minorScaleOf(currency));
|
|
2018
|
-
}
|
|
2019
|
-
function spreadBpsOf(sorted) {
|
|
2020
|
-
const lowest = sorted[0] ?? 0;
|
|
2021
|
-
const highest = sorted[sorted.length - 1] ?? 0;
|
|
2022
|
-
return lowest === 0 ? Number.POSITIVE_INFINITY : (highest - lowest) / lowest * BASIS_POINTS;
|
|
2023
|
-
}
|
|
2024
|
-
function middleOf(sorted) {
|
|
2025
|
-
const middle = Math.floor(sorted.length / 2);
|
|
2026
|
-
if (sorted.length % 2 === 1) return sorted[middle] ?? 0;
|
|
2027
|
-
return Math.round(((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2);
|
|
2028
|
-
}
|
|
2029
|
-
function refusals2(answers) {
|
|
2030
|
-
return answers.filter((answer) => answer.status === "rejected").map(
|
|
2031
|
-
(answer) => answer.reason instanceof Error ? answer.reason.message : String(answer.reason)
|
|
2032
|
-
).join("; ");
|
|
2033
|
-
}
|
|
2034
2404
|
export {
|
|
2035
2405
|
GatewayCheatError,
|
|
2036
2406
|
Gateways,
|
|
@@ -2043,6 +2413,7 @@ export {
|
|
|
2043
2413
|
REQUEST_IN_FLIGHT,
|
|
2044
2414
|
ThunderBridge,
|
|
2045
2415
|
UnverifiedRecipientError,
|
|
2416
|
+
WrapRefusedError,
|
|
2046
2417
|
answerVerifyChallenge,
|
|
2047
2418
|
answerVerifyChallengeRequest,
|
|
2048
2419
|
answerWebhookChallenge,
|
|
@@ -2077,6 +2448,7 @@ export {
|
|
|
2077
2448
|
preimageMatchesHash,
|
|
2078
2449
|
proveOrigin,
|
|
2079
2450
|
proveSettlement,
|
|
2451
|
+
proveWrapped,
|
|
2080
2452
|
qrToDataUrl,
|
|
2081
2453
|
qrToSvg,
|
|
2082
2454
|
seal,
|
|
@@ -2084,5 +2456,6 @@ export {
|
|
|
2084
2456
|
spdToSvg,
|
|
2085
2457
|
toLnurl,
|
|
2086
2458
|
unseal,
|
|
2087
|
-
verifyWebhookSignature
|
|
2459
|
+
verifyWebhookSignature,
|
|
2460
|
+
wrapFeeCeiling
|
|
2088
2461
|
};
|