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