@getalby/lightning-tools 7.0.2 → 8.1.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.
Files changed (44) hide show
  1. package/README.md +108 -28
  2. package/dist/cjs/402/l402.cjs +157 -0
  3. package/dist/cjs/402/l402.cjs.map +1 -0
  4. package/dist/cjs/402/mpp.cjs +179 -0
  5. package/dist/cjs/402/mpp.cjs.map +1 -0
  6. package/dist/cjs/402/x402.cjs +1320 -0
  7. package/dist/cjs/402/x402.cjs.map +1 -0
  8. package/dist/cjs/402.cjs +1694 -0
  9. package/dist/cjs/402.cjs.map +1 -0
  10. package/dist/cjs/bolt11.cjs +534 -518
  11. package/dist/cjs/bolt11.cjs.map +1 -1
  12. package/dist/cjs/index.cjs +811 -453
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/lnurl.cjs +22 -7
  15. package/dist/cjs/lnurl.cjs.map +1 -1
  16. package/dist/esm/402/l402.js +150 -0
  17. package/dist/esm/402/l402.js.map +1 -0
  18. package/dist/esm/402/mpp.js +177 -0
  19. package/dist/esm/402/mpp.js.map +1 -0
  20. package/dist/esm/402/x402.js +1318 -0
  21. package/dist/esm/402/x402.js.map +1 -0
  22. package/dist/esm/402.js +1683 -0
  23. package/dist/esm/402.js.map +1 -0
  24. package/dist/esm/bolt11.js +534 -519
  25. package/dist/esm/bolt11.js.map +1 -1
  26. package/dist/esm/index.js +803 -451
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/lnurl.js +22 -7
  29. package/dist/esm/lnurl.js.map +1 -1
  30. package/dist/lightning-tools.umd.js +3 -3
  31. package/dist/lightning-tools.umd.js.map +1 -1
  32. package/dist/types/402/l402.d.ts +51 -0
  33. package/dist/types/402/mpp.d.ts +26 -0
  34. package/dist/types/402/x402.d.ts +13 -0
  35. package/dist/types/402.d.ts +78 -0
  36. package/dist/types/bolt11.d.ts +6 -1
  37. package/dist/types/index.d.ts +76 -28
  38. package/dist/types/lnurl.d.ts +2 -0
  39. package/package.json +20 -5
  40. package/dist/cjs/l402.cjs +0 -93
  41. package/dist/cjs/l402.cjs.map +0 -1
  42. package/dist/esm/l402.js +0 -87
  43. package/dist/esm/l402.js.map +0 -1
  44. package/dist/types/l402.d.ts +0 -35
@@ -0,0 +1,1318 @@
1
+ const buildX402PaymentSignature = (scheme, network, invoice, requirements) => {
2
+ const json = JSON.stringify({
3
+ x402Version: 2,
4
+ scheme,
5
+ network,
6
+ payload: { invoice },
7
+ accepted: requirements,
8
+ });
9
+ // btoa only handles latin1; encode via UTF-8 to be safe
10
+ return btoa(unescape(encodeURIComponent(json)));
11
+ };
12
+
13
+ function bytes(b, ...lengths) {
14
+ if (!(b instanceof Uint8Array))
15
+ throw new Error('Expected Uint8Array');
16
+ if (lengths.length > 0 && !lengths.includes(b.length))
17
+ throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
18
+ }
19
+ function exists(instance, checkFinished = true) {
20
+ if (instance.destroyed)
21
+ throw new Error('Hash instance has been destroyed');
22
+ if (checkFinished && instance.finished)
23
+ throw new Error('Hash#digest() has already been called');
24
+ }
25
+ function output(out, instance) {
26
+ bytes(out);
27
+ const min = instance.outputLen;
28
+ if (out.length < min) {
29
+ throw new Error(`digestInto() expects output buffer of length at least ${min}`);
30
+ }
31
+ }
32
+
33
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
34
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
35
+ // node.js versions earlier than v19 don't declare it in global scope.
36
+ // For node.js, package.json#exports field mapping rewrites import
37
+ // from `crypto` to `cryptoNode`, which imports native module.
38
+ // Makes the utils un-importable in browsers without a bundler.
39
+ // Once node.js 18 is deprecated, we can just drop the import.
40
+ const u8a = (a) => a instanceof Uint8Array;
41
+ // Cast array to view
42
+ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
43
+ // The rotate right (circular right shift) operation for uint32
44
+ const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
45
+ // big-endian hardware is rare. Just in case someone still decides to run hashes:
46
+ // early-throw an error because we don't support BE yet.
47
+ const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
48
+ if (!isLE)
49
+ throw new Error('Non little-endian hardware is not supported');
50
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
51
+ /**
52
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
53
+ */
54
+ function bytesToHex(bytes) {
55
+ if (!u8a(bytes))
56
+ throw new Error('Uint8Array expected');
57
+ // pre-caching improves the speed 6x
58
+ let hex = '';
59
+ for (let i = 0; i < bytes.length; i++) {
60
+ hex += hexes[bytes[i]];
61
+ }
62
+ return hex;
63
+ }
64
+ /**
65
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
66
+ */
67
+ function utf8ToBytes(str) {
68
+ if (typeof str !== 'string')
69
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
70
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
71
+ }
72
+ /**
73
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
74
+ * Warning: when Uint8Array is passed, it would NOT get copied.
75
+ * Keep in mind for future mutable operations.
76
+ */
77
+ function toBytes(data) {
78
+ if (typeof data === 'string')
79
+ data = utf8ToBytes(data);
80
+ if (!u8a(data))
81
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
82
+ return data;
83
+ }
84
+ // For runtime check if class implements interface
85
+ class Hash {
86
+ // Safe version that clones internal state
87
+ clone() {
88
+ return this._cloneInto();
89
+ }
90
+ }
91
+ function wrapConstructor(hashCons) {
92
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
93
+ const tmp = hashCons();
94
+ hashC.outputLen = tmp.outputLen;
95
+ hashC.blockLen = tmp.blockLen;
96
+ hashC.create = () => hashCons();
97
+ return hashC;
98
+ }
99
+
100
+ // Polyfill for Safari 14
101
+ function setBigUint64(view, byteOffset, value, isLE) {
102
+ if (typeof view.setBigUint64 === 'function')
103
+ return view.setBigUint64(byteOffset, value, isLE);
104
+ const _32n = BigInt(32);
105
+ const _u32_max = BigInt(0xffffffff);
106
+ const wh = Number((value >> _32n) & _u32_max);
107
+ const wl = Number(value & _u32_max);
108
+ const h = isLE ? 4 : 0;
109
+ const l = isLE ? 0 : 4;
110
+ view.setUint32(byteOffset + h, wh, isLE);
111
+ view.setUint32(byteOffset + l, wl, isLE);
112
+ }
113
+ // Base SHA2 class (RFC 6234)
114
+ class SHA2 extends Hash {
115
+ constructor(blockLen, outputLen, padOffset, isLE) {
116
+ super();
117
+ this.blockLen = blockLen;
118
+ this.outputLen = outputLen;
119
+ this.padOffset = padOffset;
120
+ this.isLE = isLE;
121
+ this.finished = false;
122
+ this.length = 0;
123
+ this.pos = 0;
124
+ this.destroyed = false;
125
+ this.buffer = new Uint8Array(blockLen);
126
+ this.view = createView(this.buffer);
127
+ }
128
+ update(data) {
129
+ exists(this);
130
+ const { view, buffer, blockLen } = this;
131
+ data = toBytes(data);
132
+ const len = data.length;
133
+ for (let pos = 0; pos < len;) {
134
+ const take = Math.min(blockLen - this.pos, len - pos);
135
+ // Fast path: we have at least one block in input, cast it to view and process
136
+ if (take === blockLen) {
137
+ const dataView = createView(data);
138
+ for (; blockLen <= len - pos; pos += blockLen)
139
+ this.process(dataView, pos);
140
+ continue;
141
+ }
142
+ buffer.set(data.subarray(pos, pos + take), this.pos);
143
+ this.pos += take;
144
+ pos += take;
145
+ if (this.pos === blockLen) {
146
+ this.process(view, 0);
147
+ this.pos = 0;
148
+ }
149
+ }
150
+ this.length += data.length;
151
+ this.roundClean();
152
+ return this;
153
+ }
154
+ digestInto(out) {
155
+ exists(this);
156
+ output(out, this);
157
+ this.finished = true;
158
+ // Padding
159
+ // We can avoid allocation of buffer for padding completely if it
160
+ // was previously not allocated here. But it won't change performance.
161
+ const { buffer, view, blockLen, isLE } = this;
162
+ let { pos } = this;
163
+ // append the bit '1' to the message
164
+ buffer[pos++] = 0b10000000;
165
+ this.buffer.subarray(pos).fill(0);
166
+ // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
167
+ if (this.padOffset > blockLen - pos) {
168
+ this.process(view, 0);
169
+ pos = 0;
170
+ }
171
+ // Pad until full block byte with zeros
172
+ for (let i = pos; i < blockLen; i++)
173
+ buffer[i] = 0;
174
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
175
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
176
+ // So we just write lowest 64 bits of that value.
177
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
178
+ this.process(view, 0);
179
+ const oview = createView(out);
180
+ const len = this.outputLen;
181
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
182
+ if (len % 4)
183
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
184
+ const outLen = len / 4;
185
+ const state = this.get();
186
+ if (outLen > state.length)
187
+ throw new Error('_sha2: outputLen bigger than state');
188
+ for (let i = 0; i < outLen; i++)
189
+ oview.setUint32(4 * i, state[i], isLE);
190
+ }
191
+ digest() {
192
+ const { buffer, outputLen } = this;
193
+ this.digestInto(buffer);
194
+ const res = buffer.slice(0, outputLen);
195
+ this.destroy();
196
+ return res;
197
+ }
198
+ _cloneInto(to) {
199
+ to || (to = new this.constructor());
200
+ to.set(...this.get());
201
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
202
+ to.length = length;
203
+ to.pos = pos;
204
+ to.finished = finished;
205
+ to.destroyed = destroyed;
206
+ if (length % blockLen)
207
+ to.buffer.set(buffer);
208
+ return to;
209
+ }
210
+ }
211
+
212
+ // SHA2-256 need to try 2^128 hashes to execute birthday attack.
213
+ // BTC network is doing 2^67 hashes/sec as per early 2023.
214
+ // Choice: a ? b : c
215
+ const Chi = (a, b, c) => (a & b) ^ (~a & c);
216
+ // Majority function, true if any two inpust is true
217
+ const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
218
+ // Round constants:
219
+ // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
220
+ // prettier-ignore
221
+ const SHA256_K = /* @__PURE__ */ new Uint32Array([
222
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
223
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
224
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
225
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
226
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
227
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
228
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
229
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
230
+ ]);
231
+ // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
232
+ // prettier-ignore
233
+ const IV = /* @__PURE__ */ new Uint32Array([
234
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
235
+ ]);
236
+ // Temporary buffer, not used to store anything between runs
237
+ // Named this way because it matches specification.
238
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
239
+ class SHA256 extends SHA2 {
240
+ constructor() {
241
+ super(64, 32, 8, false);
242
+ // We cannot use array here since array allows indexing by variable
243
+ // which means optimizer/compiler cannot use registers.
244
+ this.A = IV[0] | 0;
245
+ this.B = IV[1] | 0;
246
+ this.C = IV[2] | 0;
247
+ this.D = IV[3] | 0;
248
+ this.E = IV[4] | 0;
249
+ this.F = IV[5] | 0;
250
+ this.G = IV[6] | 0;
251
+ this.H = IV[7] | 0;
252
+ }
253
+ get() {
254
+ const { A, B, C, D, E, F, G, H } = this;
255
+ return [A, B, C, D, E, F, G, H];
256
+ }
257
+ // prettier-ignore
258
+ set(A, B, C, D, E, F, G, H) {
259
+ this.A = A | 0;
260
+ this.B = B | 0;
261
+ this.C = C | 0;
262
+ this.D = D | 0;
263
+ this.E = E | 0;
264
+ this.F = F | 0;
265
+ this.G = G | 0;
266
+ this.H = H | 0;
267
+ }
268
+ process(view, offset) {
269
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
270
+ for (let i = 0; i < 16; i++, offset += 4)
271
+ SHA256_W[i] = view.getUint32(offset, false);
272
+ for (let i = 16; i < 64; i++) {
273
+ const W15 = SHA256_W[i - 15];
274
+ const W2 = SHA256_W[i - 2];
275
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
276
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
277
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
278
+ }
279
+ // Compression function main loop, 64 rounds
280
+ let { A, B, C, D, E, F, G, H } = this;
281
+ for (let i = 0; i < 64; i++) {
282
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
283
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
284
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
285
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
286
+ H = G;
287
+ G = F;
288
+ F = E;
289
+ E = (D + T1) | 0;
290
+ D = C;
291
+ C = B;
292
+ B = A;
293
+ A = (T1 + T2) | 0;
294
+ }
295
+ // Add the compressed chunk to the current hash value
296
+ A = (A + this.A) | 0;
297
+ B = (B + this.B) | 0;
298
+ C = (C + this.C) | 0;
299
+ D = (D + this.D) | 0;
300
+ E = (E + this.E) | 0;
301
+ F = (F + this.F) | 0;
302
+ G = (G + this.G) | 0;
303
+ H = (H + this.H) | 0;
304
+ this.set(A, B, C, D, E, F, G, H);
305
+ }
306
+ roundClean() {
307
+ SHA256_W.fill(0);
308
+ }
309
+ destroy() {
310
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
311
+ this.buffer.fill(0);
312
+ }
313
+ }
314
+ /**
315
+ * SHA2-256 hash function
316
+ * @param message - data that would be hashed
317
+ */
318
+ const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
319
+
320
+ var lib = {};
321
+
322
+ var hasRequiredLib;
323
+
324
+ function requireLib () {
325
+ if (hasRequiredLib) return lib;
326
+ hasRequiredLib = 1;
327
+ (function (exports) {
328
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
329
+ Object.defineProperty(exports, "__esModule", { value: true });
330
+ exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0;
331
+ function assertNumber(n) {
332
+ if (!Number.isSafeInteger(n))
333
+ throw new Error(`Wrong integer: ${n}`);
334
+ }
335
+ exports.assertNumber = assertNumber;
336
+ function chain(...args) {
337
+ const wrap = (a, b) => (c) => a(b(c));
338
+ const encode = Array.from(args)
339
+ .reverse()
340
+ .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);
341
+ const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);
342
+ return { encode, decode };
343
+ }
344
+ function alphabet(alphabet) {
345
+ return {
346
+ encode: (digits) => {
347
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
348
+ throw new Error('alphabet.encode input should be an array of numbers');
349
+ return digits.map((i) => {
350
+ assertNumber(i);
351
+ if (i < 0 || i >= alphabet.length)
352
+ throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);
353
+ return alphabet[i];
354
+ });
355
+ },
356
+ decode: (input) => {
357
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
358
+ throw new Error('alphabet.decode input should be array of strings');
359
+ return input.map((letter) => {
360
+ if (typeof letter !== 'string')
361
+ throw new Error(`alphabet.decode: not string element=${letter}`);
362
+ const index = alphabet.indexOf(letter);
363
+ if (index === -1)
364
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`);
365
+ return index;
366
+ });
367
+ },
368
+ };
369
+ }
370
+ function join(separator = '') {
371
+ if (typeof separator !== 'string')
372
+ throw new Error('join separator should be string');
373
+ return {
374
+ encode: (from) => {
375
+ if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))
376
+ throw new Error('join.encode input should be array of strings');
377
+ for (let i of from)
378
+ if (typeof i !== 'string')
379
+ throw new Error(`join.encode: non-string input=${i}`);
380
+ return from.join(separator);
381
+ },
382
+ decode: (to) => {
383
+ if (typeof to !== 'string')
384
+ throw new Error('join.decode input should be string');
385
+ return to.split(separator);
386
+ },
387
+ };
388
+ }
389
+ function padding(bits, chr = '=') {
390
+ assertNumber(bits);
391
+ if (typeof chr !== 'string')
392
+ throw new Error('padding chr should be string');
393
+ return {
394
+ encode(data) {
395
+ if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))
396
+ throw new Error('padding.encode input should be array of strings');
397
+ for (let i of data)
398
+ if (typeof i !== 'string')
399
+ throw new Error(`padding.encode: non-string input=${i}`);
400
+ while ((data.length * bits) % 8)
401
+ data.push(chr);
402
+ return data;
403
+ },
404
+ decode(input) {
405
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
406
+ throw new Error('padding.encode input should be array of strings');
407
+ for (let i of input)
408
+ if (typeof i !== 'string')
409
+ throw new Error(`padding.decode: non-string input=${i}`);
410
+ let end = input.length;
411
+ if ((end * bits) % 8)
412
+ throw new Error('Invalid padding: string should have whole number of bytes');
413
+ for (; end > 0 && input[end - 1] === chr; end--) {
414
+ if (!(((end - 1) * bits) % 8))
415
+ throw new Error('Invalid padding: string has too much padding');
416
+ }
417
+ return input.slice(0, end);
418
+ },
419
+ };
420
+ }
421
+ function normalize(fn) {
422
+ if (typeof fn !== 'function')
423
+ throw new Error('normalize fn should be function');
424
+ return { encode: (from) => from, decode: (to) => fn(to) };
425
+ }
426
+ function convertRadix(data, from, to) {
427
+ if (from < 2)
428
+ throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
429
+ if (to < 2)
430
+ throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
431
+ if (!Array.isArray(data))
432
+ throw new Error('convertRadix: data should be array');
433
+ if (!data.length)
434
+ return [];
435
+ let pos = 0;
436
+ const res = [];
437
+ const digits = Array.from(data);
438
+ digits.forEach((d) => {
439
+ assertNumber(d);
440
+ if (d < 0 || d >= from)
441
+ throw new Error(`Wrong integer: ${d}`);
442
+ });
443
+ while (true) {
444
+ let carry = 0;
445
+ let done = true;
446
+ for (let i = pos; i < digits.length; i++) {
447
+ const digit = digits[i];
448
+ const digitBase = from * carry + digit;
449
+ if (!Number.isSafeInteger(digitBase) ||
450
+ (from * carry) / from !== carry ||
451
+ digitBase - digit !== from * carry) {
452
+ throw new Error('convertRadix: carry overflow');
453
+ }
454
+ carry = digitBase % to;
455
+ digits[i] = Math.floor(digitBase / to);
456
+ if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
457
+ throw new Error('convertRadix: carry overflow');
458
+ if (!done)
459
+ continue;
460
+ else if (!digits[i])
461
+ pos = i;
462
+ else
463
+ done = false;
464
+ }
465
+ res.push(carry);
466
+ if (done)
467
+ break;
468
+ }
469
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
470
+ res.push(0);
471
+ return res.reverse();
472
+ }
473
+ const gcd = (a, b) => (!b ? a : gcd(b, a % b));
474
+ const radix2carry = (from, to) => from + (to - gcd(from, to));
475
+ function convertRadix2(data, from, to, padding) {
476
+ if (!Array.isArray(data))
477
+ throw new Error('convertRadix2: data should be array');
478
+ if (from <= 0 || from > 32)
479
+ throw new Error(`convertRadix2: wrong from=${from}`);
480
+ if (to <= 0 || to > 32)
481
+ throw new Error(`convertRadix2: wrong to=${to}`);
482
+ if (radix2carry(from, to) > 32) {
483
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
484
+ }
485
+ let carry = 0;
486
+ let pos = 0;
487
+ const mask = 2 ** to - 1;
488
+ const res = [];
489
+ for (const n of data) {
490
+ assertNumber(n);
491
+ if (n >= 2 ** from)
492
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
493
+ carry = (carry << from) | n;
494
+ if (pos + from > 32)
495
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
496
+ pos += from;
497
+ for (; pos >= to; pos -= to)
498
+ res.push(((carry >> (pos - to)) & mask) >>> 0);
499
+ carry &= 2 ** pos - 1;
500
+ }
501
+ carry = (carry << (to - pos)) & mask;
502
+ if (!padding && pos >= from)
503
+ throw new Error('Excess padding');
504
+ if (!padding && carry)
505
+ throw new Error(`Non-zero padding: ${carry}`);
506
+ if (padding && pos > 0)
507
+ res.push(carry >>> 0);
508
+ return res;
509
+ }
510
+ function radix(num) {
511
+ assertNumber(num);
512
+ return {
513
+ encode: (bytes) => {
514
+ if (!(bytes instanceof Uint8Array))
515
+ throw new Error('radix.encode input should be Uint8Array');
516
+ return convertRadix(Array.from(bytes), 2 ** 8, num);
517
+ },
518
+ decode: (digits) => {
519
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
520
+ throw new Error('radix.decode input should be array of strings');
521
+ return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
522
+ },
523
+ };
524
+ }
525
+ function radix2(bits, revPadding = false) {
526
+ assertNumber(bits);
527
+ if (bits <= 0 || bits > 32)
528
+ throw new Error('radix2: bits should be in (0..32]');
529
+ if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
530
+ throw new Error('radix2: carry overflow');
531
+ return {
532
+ encode: (bytes) => {
533
+ if (!(bytes instanceof Uint8Array))
534
+ throw new Error('radix2.encode input should be Uint8Array');
535
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
536
+ },
537
+ decode: (digits) => {
538
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
539
+ throw new Error('radix2.decode input should be array of strings');
540
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
541
+ },
542
+ };
543
+ }
544
+ function unsafeWrapper(fn) {
545
+ if (typeof fn !== 'function')
546
+ throw new Error('unsafeWrapper fn should be function');
547
+ return function (...args) {
548
+ try {
549
+ return fn.apply(null, args);
550
+ }
551
+ catch (e) { }
552
+ };
553
+ }
554
+ function checksum(len, fn) {
555
+ assertNumber(len);
556
+ if (typeof fn !== 'function')
557
+ throw new Error('checksum fn should be function');
558
+ return {
559
+ encode(data) {
560
+ if (!(data instanceof Uint8Array))
561
+ throw new Error('checksum.encode: input should be Uint8Array');
562
+ const checksum = fn(data).slice(0, len);
563
+ const res = new Uint8Array(data.length + len);
564
+ res.set(data);
565
+ res.set(checksum, data.length);
566
+ return res;
567
+ },
568
+ decode(data) {
569
+ if (!(data instanceof Uint8Array))
570
+ throw new Error('checksum.decode: input should be Uint8Array');
571
+ const payload = data.slice(0, -len);
572
+ const newChecksum = fn(payload).slice(0, len);
573
+ const oldChecksum = data.slice(-len);
574
+ for (let i = 0; i < len; i++)
575
+ if (newChecksum[i] !== oldChecksum[i])
576
+ throw new Error('Invalid checksum');
577
+ return payload;
578
+ },
579
+ };
580
+ }
581
+ exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding };
582
+ exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
583
+ exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
584
+ exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
585
+ exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
586
+ exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
587
+ exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
588
+ const genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));
589
+ exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
590
+ exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
591
+ exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
592
+ const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
593
+ exports.base58xmr = {
594
+ encode(data) {
595
+ let res = '';
596
+ for (let i = 0; i < data.length; i += 8) {
597
+ const block = data.subarray(i, i + 8);
598
+ res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
599
+ }
600
+ return res;
601
+ },
602
+ decode(str) {
603
+ let res = [];
604
+ for (let i = 0; i < str.length; i += 11) {
605
+ const slice = str.slice(i, i + 11);
606
+ const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
607
+ const block = exports.base58.decode(slice);
608
+ for (let j = 0; j < block.length - blockLen; j++) {
609
+ if (block[j] !== 0)
610
+ throw new Error('base58xmr: wrong padding');
611
+ }
612
+ res = res.concat(Array.from(block.slice(block.length - blockLen)));
613
+ }
614
+ return Uint8Array.from(res);
615
+ },
616
+ };
617
+ const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);
618
+ exports.base58check = base58check;
619
+ const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
620
+ const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
621
+ function bech32Polymod(pre) {
622
+ const b = pre >> 25;
623
+ let chk = (pre & 0x1ffffff) << 5;
624
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
625
+ if (((b >> i) & 1) === 1)
626
+ chk ^= POLYMOD_GENERATORS[i];
627
+ }
628
+ return chk;
629
+ }
630
+ function bechChecksum(prefix, words, encodingConst = 1) {
631
+ const len = prefix.length;
632
+ let chk = 1;
633
+ for (let i = 0; i < len; i++) {
634
+ const c = prefix.charCodeAt(i);
635
+ if (c < 33 || c > 126)
636
+ throw new Error(`Invalid prefix (${prefix})`);
637
+ chk = bech32Polymod(chk) ^ (c >> 5);
638
+ }
639
+ chk = bech32Polymod(chk);
640
+ for (let i = 0; i < len; i++)
641
+ chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
642
+ for (let v of words)
643
+ chk = bech32Polymod(chk) ^ v;
644
+ for (let i = 0; i < 6; i++)
645
+ chk = bech32Polymod(chk);
646
+ chk ^= encodingConst;
647
+ return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
648
+ }
649
+ function genBech32(encoding) {
650
+ const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
651
+ const _words = radix2(5);
652
+ const fromWords = _words.decode;
653
+ const toWords = _words.encode;
654
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
655
+ function encode(prefix, words, limit = 90) {
656
+ if (typeof prefix !== 'string')
657
+ throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
658
+ if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))
659
+ throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
660
+ const actualLength = prefix.length + 7 + words.length;
661
+ if (limit !== false && actualLength > limit)
662
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
663
+ prefix = prefix.toLowerCase();
664
+ return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
665
+ }
666
+ function decode(str, limit = 90) {
667
+ if (typeof str !== 'string')
668
+ throw new Error(`bech32.decode input should be string, not ${typeof str}`);
669
+ if (str.length < 8 || (limit !== false && str.length > limit))
670
+ throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
671
+ const lowered = str.toLowerCase();
672
+ if (str !== lowered && str !== str.toUpperCase())
673
+ throw new Error(`String must be lowercase or uppercase`);
674
+ str = lowered;
675
+ const sepIndex = str.lastIndexOf('1');
676
+ if (sepIndex === 0 || sepIndex === -1)
677
+ throw new Error(`Letter "1" must be present between prefix and data only`);
678
+ const prefix = str.slice(0, sepIndex);
679
+ const _words = str.slice(sepIndex + 1);
680
+ if (_words.length < 6)
681
+ throw new Error('Data must be at least 6 characters long');
682
+ const words = BECH_ALPHABET.decode(_words).slice(0, -6);
683
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
684
+ if (!_words.endsWith(sum))
685
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
686
+ return { prefix, words };
687
+ }
688
+ const decodeUnsafe = unsafeWrapper(decode);
689
+ function decodeToBytes(str) {
690
+ const { prefix, words } = decode(str, false);
691
+ return { prefix, words, bytes: fromWords(words) };
692
+ }
693
+ return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
694
+ }
695
+ exports.bech32 = genBech32('bech32');
696
+ exports.bech32m = genBech32('bech32m');
697
+ exports.utf8 = {
698
+ encode: (data) => new TextDecoder().decode(data),
699
+ decode: (str) => new TextEncoder().encode(str),
700
+ };
701
+ exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
702
+ if (typeof s !== 'string' || s.length % 2)
703
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
704
+ return s.toLowerCase();
705
+ }));
706
+ const CODERS = {
707
+ utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr
708
+ };
709
+ const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;
710
+ const bytesToString = (type, bytes) => {
711
+ if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
712
+ throw new TypeError(coderTypeError);
713
+ if (!(bytes instanceof Uint8Array))
714
+ throw new TypeError('bytesToString() expects Uint8Array');
715
+ return CODERS[type].encode(bytes);
716
+ };
717
+ exports.bytesToString = bytesToString;
718
+ exports.str = exports.bytesToString;
719
+ const stringToBytes = (type, str) => {
720
+ if (!CODERS.hasOwnProperty(type))
721
+ throw new TypeError(coderTypeError);
722
+ if (typeof str !== 'string')
723
+ throw new TypeError('stringToBytes() expects string');
724
+ return CODERS[type].decode(str);
725
+ };
726
+ exports.stringToBytes = stringToBytes;
727
+ exports.bytes = exports.stringToBytes;
728
+ } (lib));
729
+ return lib;
730
+ }
731
+
732
+ var bolt11;
733
+ var hasRequiredBolt11;
734
+
735
+ function requireBolt11 () {
736
+ if (hasRequiredBolt11) return bolt11;
737
+ hasRequiredBolt11 = 1;
738
+ const {bech32, hex, utf8} = requireLib();
739
+
740
+ // defaults for encode; default timestamp is current time at call
741
+ const DEFAULTNETWORK = {
742
+ // default network is bitcoin
743
+ bech32: 'bc',
744
+ pubKeyHash: 0x00,
745
+ scriptHash: 0x05,
746
+ validWitnessVersions: [0]
747
+ };
748
+ const TESTNETWORK = {
749
+ bech32: 'tb',
750
+ pubKeyHash: 0x6f,
751
+ scriptHash: 0xc4,
752
+ validWitnessVersions: [0]
753
+ };
754
+ const SIGNETNETWORK = {
755
+ bech32: 'tbs',
756
+ pubKeyHash: 0x6f,
757
+ scriptHash: 0xc4,
758
+ validWitnessVersions: [0]
759
+ };
760
+ const REGTESTNETWORK = {
761
+ bech32: 'bcrt',
762
+ pubKeyHash: 0x6f,
763
+ scriptHash: 0xc4,
764
+ validWitnessVersions: [0]
765
+ };
766
+ const SIMNETWORK = {
767
+ bech32: 'sb',
768
+ pubKeyHash: 0x3f,
769
+ scriptHash: 0x7b,
770
+ validWitnessVersions: [0]
771
+ };
772
+
773
+ const FEATUREBIT_ORDER = [
774
+ 'option_data_loss_protect',
775
+ 'initial_routing_sync',
776
+ 'option_upfront_shutdown_script',
777
+ 'gossip_queries',
778
+ 'var_onion_optin',
779
+ 'gossip_queries_ex',
780
+ 'option_static_remotekey',
781
+ 'payment_secret',
782
+ 'basic_mpp',
783
+ 'option_support_large_channel'
784
+ ];
785
+
786
+ const DIVISORS = {
787
+ m: BigInt(1e3),
788
+ u: BigInt(1e6),
789
+ n: BigInt(1e9),
790
+ p: BigInt(1e12)
791
+ };
792
+
793
+ const MAX_MILLISATS = BigInt('2100000000000000000');
794
+
795
+ const MILLISATS_PER_BTC = BigInt(1e11);
796
+
797
+ const TAGCODES = {
798
+ payment_hash: 1,
799
+ payment_secret: 16,
800
+ description: 13,
801
+ payee: 19,
802
+ description_hash: 23, // commit to longer descriptions (used by lnurl-pay)
803
+ expiry: 6, // default: 3600 (1 hour)
804
+ min_final_cltv_expiry: 24, // default: 9
805
+ fallback_address: 9,
806
+ route_hint: 3, // for extra routing info (private etc.)
807
+ feature_bits: 5,
808
+ metadata: 27
809
+ };
810
+
811
+ // reverse the keys and values of TAGCODES and insert into TAGNAMES
812
+ const TAGNAMES = {};
813
+ for (let i = 0, keys = Object.keys(TAGCODES); i < keys.length; i++) {
814
+ const currentName = keys[i];
815
+ const currentCode = TAGCODES[keys[i]].toString();
816
+ TAGNAMES[currentCode] = currentName;
817
+ }
818
+
819
+ const TAGPARSERS = {
820
+ 1: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
821
+ 16: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
822
+ 13: words => utf8.encode(bech32.fromWordsUnsafe(words)), // string variable length
823
+ 19: words => hex.encode(bech32.fromWordsUnsafe(words)), // 264 bits
824
+ 23: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
825
+ 27: words => hex.encode(bech32.fromWordsUnsafe(words)), // variable
826
+ 6: wordsToIntBE, // default: 3600 (1 hour)
827
+ 24: wordsToIntBE, // default: 9
828
+ 3: routingInfoParser, // for extra routing info (private etc.)
829
+ 5: featureBitsParser // keep feature bits as array of 5 bit words
830
+ };
831
+
832
+ function getUnknownParser(tagCode) {
833
+ return words => ({
834
+ tagCode: parseInt(tagCode),
835
+ words: bech32.encode('unknown', words, Number.MAX_SAFE_INTEGER)
836
+ })
837
+ }
838
+
839
+ function wordsToIntBE(words) {
840
+ return words.reverse().reduce((total, item, index) => {
841
+ return total + item * Math.pow(32, index)
842
+ }, 0)
843
+ }
844
+
845
+ // first convert from words to buffer, trimming padding where necessary
846
+ // parse in 51 byte chunks. See encoder for details.
847
+ function routingInfoParser(words) {
848
+ const routes = [];
849
+ let pubkey,
850
+ shortChannelId,
851
+ feeBaseMSats,
852
+ feeProportionalMillionths,
853
+ cltvExpiryDelta;
854
+ let routesBuffer = bech32.fromWordsUnsafe(words);
855
+ while (routesBuffer.length > 0) {
856
+ pubkey = hex.encode(routesBuffer.slice(0, 33)); // 33 bytes
857
+ shortChannelId = hex.encode(routesBuffer.slice(33, 41)); // 8 bytes
858
+ feeBaseMSats = parseInt(hex.encode(routesBuffer.slice(41, 45)), 16); // 4 bytes
859
+ feeProportionalMillionths = parseInt(
860
+ hex.encode(routesBuffer.slice(45, 49)),
861
+ 16
862
+ ); // 4 bytes
863
+ cltvExpiryDelta = parseInt(hex.encode(routesBuffer.slice(49, 51)), 16); // 2 bytes
864
+
865
+ routesBuffer = routesBuffer.slice(51);
866
+
867
+ routes.push({
868
+ pubkey,
869
+ short_channel_id: shortChannelId,
870
+ fee_base_msat: feeBaseMSats,
871
+ fee_proportional_millionths: feeProportionalMillionths,
872
+ cltv_expiry_delta: cltvExpiryDelta
873
+ });
874
+ }
875
+ return routes
876
+ }
877
+
878
+ function featureBitsParser(words) {
879
+ const bools = words
880
+ .slice()
881
+ .reverse()
882
+ .map(word => [
883
+ !!(word & 0b1),
884
+ !!(word & 0b10),
885
+ !!(word & 0b100),
886
+ !!(word & 0b1000),
887
+ !!(word & 0b10000)
888
+ ])
889
+ .reduce((finalArr, itemArr) => finalArr.concat(itemArr), []);
890
+ while (bools.length < FEATUREBIT_ORDER.length * 2) {
891
+ bools.push(false);
892
+ }
893
+
894
+ const featureBits = {};
895
+
896
+ FEATUREBIT_ORDER.forEach((featureName, index) => {
897
+ let status;
898
+ if (bools[index * 2]) {
899
+ status = 'required';
900
+ } else if (bools[index * 2 + 1]) {
901
+ status = 'supported';
902
+ } else {
903
+ status = 'unsupported';
904
+ }
905
+ featureBits[featureName] = status;
906
+ });
907
+
908
+ const extraBits = bools.slice(FEATUREBIT_ORDER.length * 2);
909
+ featureBits.extra_bits = {
910
+ start_bit: FEATUREBIT_ORDER.length * 2,
911
+ bits: extraBits,
912
+ has_required: extraBits.reduce(
913
+ (result, bit, index) =>
914
+ index % 2 !== 0 ? result || false : result || bit,
915
+ false
916
+ )
917
+ };
918
+
919
+ return featureBits
920
+ }
921
+
922
+ function hrpToMillisat(hrpString, outputString) {
923
+ let divisor, value;
924
+ if (hrpString.slice(-1).match(/^[munp]$/)) {
925
+ divisor = hrpString.slice(-1);
926
+ value = hrpString.slice(0, -1);
927
+ } else if (hrpString.slice(-1).match(/^[^munp0-9]$/)) {
928
+ throw new Error('Not a valid multiplier for the amount')
929
+ } else {
930
+ value = hrpString;
931
+ }
932
+
933
+ if (!value.match(/^\d+$/))
934
+ throw new Error('Not a valid human readable amount')
935
+
936
+ const valueBN = BigInt(value);
937
+
938
+ const millisatoshisBN = divisor
939
+ ? (valueBN * MILLISATS_PER_BTC) / DIVISORS[divisor]
940
+ : valueBN * MILLISATS_PER_BTC;
941
+
942
+ if (
943
+ (divisor === 'p' && !(valueBN % BigInt(10) === BigInt(0))) ||
944
+ millisatoshisBN > MAX_MILLISATS
945
+ ) {
946
+ throw new Error('Amount is outside of valid range')
947
+ }
948
+
949
+ return outputString ? millisatoshisBN.toString() : millisatoshisBN
950
+ }
951
+
952
+ // decode will only have extra comments that aren't covered in encode comments.
953
+ // also if anything is hard to read I'll comment.
954
+ function decode(paymentRequest, network) {
955
+ if (typeof paymentRequest !== 'string')
956
+ throw new Error('Lightning Payment Request must be string')
957
+ if (paymentRequest.slice(0, 2).toLowerCase() !== 'ln')
958
+ throw new Error('Not a proper lightning payment request')
959
+
960
+ const sections = [];
961
+ const decoded = bech32.decode(paymentRequest, Number.MAX_SAFE_INTEGER);
962
+ paymentRequest = paymentRequest.toLowerCase();
963
+ const prefix = decoded.prefix;
964
+ let words = decoded.words;
965
+ let letters = paymentRequest.slice(prefix.length + 1);
966
+ let sigWords = words.slice(-104);
967
+ words = words.slice(0, -104);
968
+
969
+ // Without reverse lookups, can't say that the multipier at the end must
970
+ // have a number before it, so instead we parse, and if the second group
971
+ // doesn't have anything, there's a good chance the last letter of the
972
+ // coin type got captured by the third group, so just re-regex without
973
+ // the number.
974
+ let prefixMatches = prefix.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);
975
+ if (prefixMatches && !prefixMatches[2])
976
+ prefixMatches = prefix.match(/^ln(\S+)$/);
977
+ if (!prefixMatches) {
978
+ throw new Error('Not a proper lightning payment request')
979
+ }
980
+
981
+ // "ln" section
982
+ sections.push({
983
+ name: 'lightning_network',
984
+ letters: 'ln'
985
+ });
986
+
987
+ // "bc" section
988
+ const bech32Prefix = prefixMatches[1];
989
+ let coinNetwork;
990
+ if (!network) {
991
+ switch (bech32Prefix) {
992
+ case DEFAULTNETWORK.bech32:
993
+ coinNetwork = DEFAULTNETWORK;
994
+ break
995
+ case TESTNETWORK.bech32:
996
+ coinNetwork = TESTNETWORK;
997
+ break
998
+ case SIGNETNETWORK.bech32:
999
+ coinNetwork = SIGNETNETWORK;
1000
+ break
1001
+ case REGTESTNETWORK.bech32:
1002
+ coinNetwork = REGTESTNETWORK;
1003
+ break
1004
+ case SIMNETWORK.bech32:
1005
+ coinNetwork = SIMNETWORK;
1006
+ break
1007
+ }
1008
+ } else {
1009
+ if (
1010
+ network.bech32 === undefined ||
1011
+ network.pubKeyHash === undefined ||
1012
+ network.scriptHash === undefined ||
1013
+ !Array.isArray(network.validWitnessVersions)
1014
+ )
1015
+ throw new Error('Invalid network')
1016
+ coinNetwork = network;
1017
+ }
1018
+ if (!coinNetwork || coinNetwork.bech32 !== bech32Prefix) {
1019
+ throw new Error('Unknown coin bech32 prefix')
1020
+ }
1021
+ sections.push({
1022
+ name: 'coin_network',
1023
+ letters: bech32Prefix,
1024
+ value: coinNetwork
1025
+ });
1026
+
1027
+ // amount section
1028
+ const value = prefixMatches[2];
1029
+ let millisatoshis;
1030
+ if (value) {
1031
+ const divisor = prefixMatches[3];
1032
+ millisatoshis = hrpToMillisat(value + divisor, true);
1033
+ sections.push({
1034
+ name: 'amount',
1035
+ letters: prefixMatches[2] + prefixMatches[3],
1036
+ value: millisatoshis
1037
+ });
1038
+ } else {
1039
+ millisatoshis = null;
1040
+ }
1041
+
1042
+ // "1" separator
1043
+ sections.push({
1044
+ name: 'separator',
1045
+ letters: '1'
1046
+ });
1047
+
1048
+ // timestamp
1049
+ const timestamp = wordsToIntBE(words.slice(0, 7));
1050
+ words = words.slice(7); // trim off the left 7 words
1051
+ sections.push({
1052
+ name: 'timestamp',
1053
+ letters: letters.slice(0, 7),
1054
+ value: timestamp
1055
+ });
1056
+ letters = letters.slice(7);
1057
+
1058
+ let tagName, parser, tagLength, tagWords;
1059
+ // we have no tag count to go on, so just keep hacking off words
1060
+ // until we have none.
1061
+ while (words.length > 0) {
1062
+ const tagCode = words[0].toString();
1063
+ tagName = TAGNAMES[tagCode] || 'unknown_tag';
1064
+ parser = TAGPARSERS[tagCode] || getUnknownParser(tagCode);
1065
+ words = words.slice(1);
1066
+
1067
+ tagLength = wordsToIntBE(words.slice(0, 2));
1068
+ words = words.slice(2);
1069
+
1070
+ tagWords = words.slice(0, tagLength);
1071
+ words = words.slice(tagLength);
1072
+
1073
+ sections.push({
1074
+ name: tagName,
1075
+ tag: letters[0],
1076
+ letters: letters.slice(0, 1 + 2 + tagLength),
1077
+ value: parser(tagWords) // see: parsers for more comments
1078
+ });
1079
+ letters = letters.slice(1 + 2 + tagLength);
1080
+ }
1081
+
1082
+ // signature
1083
+ sections.push({
1084
+ name: 'signature',
1085
+ letters: letters.slice(0, 104),
1086
+ value: hex.encode(bech32.fromWordsUnsafe(sigWords))
1087
+ });
1088
+ letters = letters.slice(104);
1089
+
1090
+ // checksum
1091
+ sections.push({
1092
+ name: 'checksum',
1093
+ letters: letters
1094
+ });
1095
+
1096
+ let result = {
1097
+ paymentRequest,
1098
+ sections,
1099
+
1100
+ get expiry() {
1101
+ let exp = sections.find(s => s.name === 'expiry');
1102
+ if (exp) return getValue('timestamp') + exp.value
1103
+ },
1104
+
1105
+ get route_hints() {
1106
+ return sections.filter(s => s.name === 'route_hint').map(s => s.value)
1107
+ }
1108
+ };
1109
+
1110
+ for (let name in TAGCODES) {
1111
+ if (name === 'route_hint') {
1112
+ // route hints can be multiple, so this won't work for them
1113
+ continue
1114
+ }
1115
+
1116
+ Object.defineProperty(result, name, {
1117
+ get() {
1118
+ return getValue(name)
1119
+ }
1120
+ });
1121
+ }
1122
+
1123
+ return result
1124
+
1125
+ function getValue(name) {
1126
+ let section = sections.find(s => s.name === name);
1127
+ return section ? section.value : undefined
1128
+ }
1129
+ }
1130
+
1131
+ bolt11 = {
1132
+ decode,
1133
+ hrpToMillisat
1134
+ };
1135
+ return bolt11;
1136
+ }
1137
+
1138
+ var bolt11Exports = requireBolt11();
1139
+
1140
+ // from https://stackoverflow.com/a/50868276
1141
+ const fromHexString = (hexString) => Uint8Array.from(hexString.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
1142
+ const decodeInvoice = (paymentRequest) => {
1143
+ if (!paymentRequest)
1144
+ return null;
1145
+ try {
1146
+ const decoded = bolt11Exports.decode(paymentRequest);
1147
+ if (!decoded || !decoded.sections)
1148
+ return null;
1149
+ const hashTag = decoded.sections.find((value) => value.name === "payment_hash");
1150
+ if (hashTag?.name !== "payment_hash" || !hashTag.value)
1151
+ return null;
1152
+ const paymentHash = hashTag.value;
1153
+ let satoshi = 0;
1154
+ let millisatoshi = 0;
1155
+ let amountRaw = "0";
1156
+ const amountTag = decoded.sections.find((value) => value.name === "amount");
1157
+ if (amountTag?.name === "amount" && amountTag.value) {
1158
+ amountRaw = amountTag.value;
1159
+ millisatoshi = parseInt(amountTag.value);
1160
+ satoshi = parseInt(amountTag.value) / 1000; // millisats
1161
+ }
1162
+ const timestampTag = decoded.sections.find((value) => value.name === "timestamp");
1163
+ if (timestampTag?.name !== "timestamp" || !timestampTag.value)
1164
+ return null;
1165
+ const timestamp = timestampTag.value;
1166
+ let expiry;
1167
+ const expiryTag = decoded.sections.find((value) => value.name === "expiry");
1168
+ if (expiryTag?.name === "expiry") {
1169
+ expiry = expiryTag.value;
1170
+ }
1171
+ const descriptionTag = decoded.sections.find((value) => value.name === "description");
1172
+ const description = descriptionTag?.name === "description"
1173
+ ? descriptionTag?.value
1174
+ : undefined;
1175
+ return {
1176
+ paymentHash,
1177
+ satoshi,
1178
+ millisatoshi,
1179
+ amountRaw,
1180
+ timestamp,
1181
+ expiry,
1182
+ description,
1183
+ };
1184
+ }
1185
+ catch {
1186
+ return null;
1187
+ }
1188
+ };
1189
+ function validatePreimage(preimage, paymentHash) {
1190
+ try {
1191
+ if (!/^[0-9a-fA-F]{64}$/.test(preimage))
1192
+ return false;
1193
+ if (!/^[0-9a-fA-F]{64}$/.test(paymentHash))
1194
+ return false;
1195
+ const preimageHash = bytesToHex(sha256(fromHexString(preimage)));
1196
+ return paymentHash === preimageHash;
1197
+ }
1198
+ catch {
1199
+ return false;
1200
+ }
1201
+ }
1202
+
1203
+ class Invoice {
1204
+ constructor(args) {
1205
+ this.paymentRequest = args.pr;
1206
+ if (!this.paymentRequest) {
1207
+ throw new Error("Invalid payment request");
1208
+ }
1209
+ const decodedInvoice = decodeInvoice(this.paymentRequest);
1210
+ if (!decodedInvoice) {
1211
+ throw new Error("Failed to decode payment request");
1212
+ }
1213
+ this.paymentHash = decodedInvoice.paymentHash;
1214
+ this.satoshi = decodedInvoice.satoshi;
1215
+ this.millisatoshi = decodedInvoice.millisatoshi;
1216
+ this.amountRaw = decodedInvoice.amountRaw;
1217
+ this.timestamp = decodedInvoice.timestamp;
1218
+ this.expiry = decodedInvoice.expiry;
1219
+ this.createdDate = new Date(this.timestamp * 1000);
1220
+ this.expiryDate = this.expiry
1221
+ ? new Date((this.timestamp + this.expiry) * 1000)
1222
+ : undefined;
1223
+ this.description = decodedInvoice.description ?? null;
1224
+ this.verify = args.verify ?? null;
1225
+ this.preimage = args.preimage ?? null;
1226
+ this.successAction = args.successAction ?? null;
1227
+ }
1228
+ async isPaid() {
1229
+ if (this.preimage)
1230
+ return this.validatePreimage(this.preimage);
1231
+ else if (this.verify) {
1232
+ return await this.verifyPayment();
1233
+ }
1234
+ else {
1235
+ throw new Error("Could not verify payment");
1236
+ }
1237
+ }
1238
+ validatePreimage(preimage) {
1239
+ if (!preimage || !this.paymentHash)
1240
+ return false;
1241
+ return validatePreimage(preimage, this.paymentHash);
1242
+ }
1243
+ async verifyPayment() {
1244
+ try {
1245
+ if (!this.verify) {
1246
+ throw new Error("LNURL verify not available");
1247
+ }
1248
+ const response = await fetch(this.verify);
1249
+ if (!response.ok) {
1250
+ throw new Error(`Verification request failed: ${response.status} ${response.statusText}`);
1251
+ }
1252
+ const json = await response.json();
1253
+ if (json.preimage) {
1254
+ this.preimage = json.preimage;
1255
+ }
1256
+ return json.settled;
1257
+ }
1258
+ catch (error) {
1259
+ console.error("Failed to check LNURL-verify", error);
1260
+ return false;
1261
+ }
1262
+ }
1263
+ hasExpired() {
1264
+ const { expiryDate } = this;
1265
+ if (expiryDate) {
1266
+ return expiryDate.getTime() < Date.now();
1267
+ }
1268
+ return false;
1269
+ }
1270
+ }
1271
+
1272
+ const handleX402Payment = async (x402Header, url, fetchArgs, headers, wallet) => {
1273
+ let parsed;
1274
+ try {
1275
+ parsed = JSON.parse(decodeURIComponent(escape(atob(x402Header))));
1276
+ }
1277
+ catch (_) {
1278
+ throw new Error("x402: invalid PAYMENT-REQUIRED header (not valid base64-encoded JSON)");
1279
+ }
1280
+ if (!Array.isArray(parsed.accepts) || parsed.accepts.length === 0) {
1281
+ throw new Error("x402: PAYMENT-REQUIRED header contains no payment options");
1282
+ }
1283
+ const requirements = parsed.accepts.find((e) => {
1284
+ return e.extra?.paymentMethod === "lightning";
1285
+ });
1286
+ if (!requirements) {
1287
+ throw new Error("x402: unsupported x402 network, only Bitcoin lightning network is supported.");
1288
+ }
1289
+ if (!requirements.extra?.invoice) {
1290
+ throw new Error("x402: payment requirements missing lightning invoice");
1291
+ }
1292
+ const invoice = new Invoice({ pr: requirements.extra.invoice });
1293
+ if (invoice.amountRaw != requirements.amount) {
1294
+ throw new Error(`Invalid invoice amount: ${invoice.amountRaw}. expected ${requirements.amount}`);
1295
+ }
1296
+ await wallet.payInvoice({ invoice: invoice.paymentRequest });
1297
+ headers.set("payment-signature", buildX402PaymentSignature(requirements.scheme, requirements.network, invoice.paymentRequest, requirements));
1298
+ return fetch(url, fetchArgs);
1299
+ };
1300
+ const fetchWithX402 = async (url, fetchArgs, options) => {
1301
+ const wallet = options.wallet;
1302
+ if (!fetchArgs) {
1303
+ fetchArgs = {};
1304
+ }
1305
+ fetchArgs.cache = "no-store";
1306
+ fetchArgs.mode = "cors";
1307
+ const headers = new Headers(fetchArgs.headers ?? undefined);
1308
+ fetchArgs.headers = headers;
1309
+ const initResp = await fetch(url, fetchArgs);
1310
+ const header = initResp.headers.get("PAYMENT-REQUIRED");
1311
+ if (!header) {
1312
+ return initResp;
1313
+ }
1314
+ return handleX402Payment(header, url, fetchArgs, headers, wallet);
1315
+ };
1316
+
1317
+ export { fetchWithX402 };
1318
+ //# sourceMappingURL=x402.js.map