@getalby/lightning-tools 4.0.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +261 -0
  3. package/dist/index.browser.js +1833 -0
  4. package/dist/index.cjs +2 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.ts +11 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.modern.js +2 -0
  9. package/dist/index.modern.js.map +1 -0
  10. package/dist/index.module.js +2 -0
  11. package/dist/index.module.js.map +1 -0
  12. package/dist/index.umd.js +2 -0
  13. package/dist/index.umd.js.map +1 -0
  14. package/dist/invoice.d.ts +12 -0
  15. package/dist/invoice.d.ts.map +1 -0
  16. package/dist/l402/index.d.ts +4 -0
  17. package/dist/l402/index.d.ts.map +1 -0
  18. package/dist/l402/parse.d.ts +4 -0
  19. package/dist/l402/parse.d.ts.map +1 -0
  20. package/dist/lightning-address.d.ts +39 -0
  21. package/dist/lightning-address.d.ts.map +1 -0
  22. package/dist/lightning-address.test.d.ts +2 -0
  23. package/dist/lightning-address.test.d.ts.map +1 -0
  24. package/dist/podcasting2/boostagrams.d.ts +26 -0
  25. package/dist/podcasting2/boostagrams.d.ts.map +1 -0
  26. package/dist/types.d.ts +92 -0
  27. package/dist/types.d.ts.map +1 -0
  28. package/dist/utils/fiat.d.ts +15 -0
  29. package/dist/utils/fiat.d.ts.map +1 -0
  30. package/dist/utils/invoice.d.ts +2 -0
  31. package/dist/utils/invoice.d.ts.map +1 -0
  32. package/dist/utils/keysend.d.ts +3 -0
  33. package/dist/utils/keysend.d.ts.map +1 -0
  34. package/dist/utils/lnurl.d.ts +9 -0
  35. package/dist/utils/lnurl.d.ts.map +1 -0
  36. package/dist/utils/lnurl.test.d.ts +2 -0
  37. package/dist/utils/lnurl.test.d.ts.map +1 -0
  38. package/dist/utils/nostr.d.ts +7 -0
  39. package/dist/utils/nostr.d.ts.map +1 -0
  40. package/dist/utils/storage.d.ts +13 -0
  41. package/dist/utils/storage.d.ts.map +1 -0
  42. package/dist/window.d.ts +2 -0
  43. package/dist/window.d.ts.map +1 -0
  44. package/dist/window.js +3 -0
  45. package/package.json +61 -0
@@ -0,0 +1,1833 @@
1
+ (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
+ var e=require("crypto-js/enc-hex.js"),t=require("crypto-js/sha256.js"),r=require("light-bolt11-decoder");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/n(e),a=/*#__PURE__*/n(t),i=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var t=e.prototype;return t.getItem=function(e){return this.storage[e]},t.setItem=function(e,t){this.storage[e]=t},e}(),s={__proto__:null,MemoryStorage:i,NoStorage:/*#__PURE__*/function(){function e(e){}var t=e.prototype;return t.getItem=function(e){return null},t.setItem=function(e,t){},e}(),default:i},u=new i,c=function(e,t,r){try{var n,o=function(r){return n?r:(t.headers["Accept-Authenticate"]=a,Promise.resolve(fetch(e,t)).then(function(r){var n=r.headers.get("www-authenticate");if(!n)return r;var o,u=(o=n.replace("L402","").replace("LSAT","").split(",").map(function(e){var t=e.split("=").map(function(e){return e.trim()});return[t[0],t[1].match(/"?([^"]*)"?/)[1]]}),Object.fromEntries(o)),c=u.token||u.macaroon,l=u.invoice;return Promise.resolve(i.enable()).then(function(){return Promise.resolve(i.sendPayment(l)).then(function(r){return s.setItem(e,JSON.stringify({token:c,preimage:r.preimage})),t.headers.Authorization=a+" "+c+":"+r.preimage,Promise.resolve(fetch(e,t))})})}))};r||(r={});var a=r.headerKey||"L402",i=r.webln||globalThis.webln;if(!i)throw new Error("WebLN is missing");var s=r.store||u;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});var c=s.getItem(e),l=function(){if(c){var r=JSON.parse(c);return t.headers.Authorization=a+" "+r.token+":"+r.preimage,Promise.resolve(fetch(e,t)).then(function(e){return n=1,e})}}();return Promise.resolve(l&&l.then?l.then(o):o(l))}catch(e){return Promise.reject(e)}},l={__proto__:null,storage:s,fetchWithL402:c,default:c},h=function(e,t){try{var r=e.boost,n=e.amount;t||(t={});var o=t.webln||globalThis.webln;n||(n=Math.floor(r.value_msat/1e3));var a={destination:e.destination,amount:n,customRecords:{7629169:JSON.stringify(r)}};return e.customKey&&e.customValue&&(a.customRecords[e.customKey]=e.customValue),Promise.resolve(o.enable()).then(function(){return Promise.resolve(o.keysend(a))})}catch(e){return Promise.reject(e)}},m={__proto__:null,boost:h,default:h};function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},f.apply(this,arguments)}var v=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/,p=function(e){return!!e&&v.test(e)},d=function(e){var t=e.amount,r=e.min,n=e.max,o=t>0&&t>=r&&t<=n;return o&&r===n?t===r:o},y=/*#__PURE__*/function(){function e(e){var t,n;this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.paymentRequest=e.pr,this.paymentHash=function(e){if(!e)return null;try{var t=r.decode(e);if(!t||!t.sections)return null;var n=t.sections.find(function(e){return"payment_hash"===e.name});return n&&n.value?n.value.toString():null}catch(e){return null}}(this.paymentRequest),this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var t=e.prototype;return t.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},t.validatePreimage=function(e){if(!e||!this.paymentHash)return!1;try{var t=a.default(o.default.parse(e)).toString(o.default);return this.paymentHash===t}catch(e){return!1}},t.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(t){return Promise.resolve(t.json()).then(function(t){return t.preimage&&(e.preimage=t.preimage),t.settled})})}catch(e){return Promise.reject(e)}},e}(),w=function(e,t){var r=e.satoshi,n=e.comment,o=e.p,a=e.e,i=e.relays;void 0===t&&(t={});try{var s=t.nostr||globalThis.nostr;if(!s)throw new Error("nostr option or window.nostr is not available");var u=[["relays"].concat(i),["amount",r.toString()]];return o&&u.push(["p",o]),a&&u.push(["e",a]),Promise.resolve(s.getPublicKey()).then(function(e){var t={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:u,content:null!=n?n:""};return t.id=P(t),Promise.resolve(s.signEvent(t))})}catch(a){return Promise.reject(a)}};function g(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var t=0;t<e.tags.length;t++){var r=e.tags[t];if(!Array.isArray(r))return!1;for(var n=0;n<r.length;n++)if("object"==typeof r[n])return!1}return!0}function b(e){if(!g(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function P(e){return a.default(b(e)).toString(o.default)}function k(e,t){var r,n,o,a;return t&&e&&(n=(r=null==(o=e.names)?void 0:o[t])?null==(a=e.relays)?void 0:a[r]:void 0),[e,r,n]}var j={__proto__:null,generateZapEvent:w,validateEvent:g,serializeEvent:b,getEventHash:P,parseNostrResponse:k},x=/^((?:[^<>()\[\]\\.,;:\s@"]+(?:\.[^<>()\[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,D=/*#__PURE__*/function(){function e(e,t){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://lnaddressproxy.getalby.com",webln:globalThis.webln},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}var t=e.prototype;return t.parse=function(){var e=x.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},t.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},t.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(t){return Promise.resolve(t.json()).then(function(t){e.parseResponse(t.lnurlp,t.keysend,t.nostr)})})}catch(e){return Promise.reject(e)}},t.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(t){return Promise.resolve(fetch(e.keysendUrl())).then(function(r){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function t(){function t(){e.parseResponse(a,o,r)}var r,i=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){r=e})}();return i&&i.then?i.then(t):t()}var o,i=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){o=e})}();return i&&i.then?i.then(t):t()}var a,i=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){a=e})}();return i&&i.then?i.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},t.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},t.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},t.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},t.generateInvoice=function(e){try{var t,r=function(e){var r=t&&t.pr&&t.pr.toString();if(!r)throw new Error("Invalid pay service invoice");var n={pr:r};return t&&t.verify&&(n.verify=t.verify.toString()),new y(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(f({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){t=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!p(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var r=new URL(n.lnurlpData.callback);return r.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){t=e})})}();return Promise.resolve(o&&o.then?o.then(r):r())}catch(e){return Promise.reject(e)}},t.requestInvoice=function(e){try{var t=this;if(!t.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var r=1e3*e.satoshi,n=t.lnurlpData,o=n.commentAllowed;if(!d({amount:r,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var a={amount:r.toString()};return e.comment&&(a.comment=e.comment),e.payerdata&&(a.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(t.generateInvoice(a))}catch(e){return Promise.reject(e)}},t.boost=function(e,t){void 0===t&&(t=0);try{var r=this;if(!r.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=r.keysendData;return Promise.resolve(h({destination:n.destination,customKey:n.customKey,customValue:n.customValue,amount:t,boost:e},{webln:r.webln}))}catch(e){return Promise.reject(e)}},t.zapInvoice=function(e,t){var r=e.satoshi,n=e.comment,o=e.relays,a=e.e;void 0===t&&(t={});try{var i=this;if(!i.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!i.nostrPubkey)throw new Error("Nostr Pubkey is missing");var s=i.nostrPubkey,u=1e3*r,c=i.lnurlpData,l=c.allowsNostr;if(!d({amount:u,min:c.min,max:c.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(w({satoshi:u,comment:n,p:s,e:a,relays:o},t)).then(function(e){var t={amount:u.toString(),nostr:JSON.stringify(e)};return Promise.resolve(i.generateInvoice(t))})}catch(a){return Promise.reject(a)}},t.zap=function(e,t){void 0===t&&(t={});try{var r=this,n=r.zapInvoice(e,t);if(!r.webln)throw new Error("WebLN not available");return Promise.resolve(r.webln.enable()).then(function(){var e=r.webln,t=e.sendPayment;return Promise.resolve(n).then(function(r){return t.call(e,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},t.parseResponse=function(e,t,r){if(e&&(this.lnurlpData=function(e){if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!p(t))throw new Error("Callback must be a valid url");var r,n,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");try{r=JSON.parse(e.metadata+""),n=a.default(e.metadata+"").toString(o.default)}catch(e){r=[],n=a.default("[]").toString(o.default)}for(var u="",c="",l="",h=0;h<r.length;h++){var m=r[h],f=m[0],v=m[1];switch(f){case"text/plain":c=v;break;case"text/identifier":l=v;break;case"image/png;base64":case"image/jpeg;base64":u="data:"+f+","+v}}var d,y=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:r,metadataHash:n,identifier:l,description:c,image:u,payerData:y,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}}(e)),t&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!("customKey"in e.customData[0])||"696969"!=e.customData[0].customKey)throw new Error("Unable to find customKey");if(!("customValue"in e.customData[0])||!e.customData[0].customValue)throw new Error("Unable to find customValue");if(!e.pubkey)throw new Error("Pubkey does not exist");return{destination:e.pubkey,customKey:e.customData[0].customKey,customValue:e.customData[0].customValue}}(t)),r){var n=k(r,this.username);this.nostrData=n[0],this.nostrPubkey=n[1],this.nostrRelays=n[2]}},e}(),E=function(e){try{var t="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(t)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},S=function(e){var t=e.satoshi;return Promise.resolve(E(e.currency)).then(function(e){return Number(t)*e})},_={__proto__:null,getFiatBtcRate:E,getFiatValue:S,getSatoshiValue:function(e){var t=e.amount;return Promise.resolve(E(e.currency)).then(function(e){return Math.floor(Number(t)/e)})},getFormattedFiatValue:function(e){var t=e.currency,r=e.locale;return r||(r="en"),Promise.resolve(S({satoshi:e.satoshi,currency:t})).then(function(e){return e.toLocaleString(r,{style:"currency",currency:t})})}};exports.Invoice=y,exports.LightningAddress=D,exports.boostagrams=m,exports.fetchWithL402=c,exports.fiat=_,exports.l402=l,exports.nostr=j,exports.sendBoostagram=h;
3
+
4
+
5
+ },{"crypto-js/enc-hex.js":6,"crypto-js/sha256.js":7,"light-bolt11-decoder":8}],2:[function(require,module,exports){
6
+ // assign alby-tools exports to global window object (for index.browser.js)
7
+ // @ts-ignore
8
+ window["albyTools"] = require('./index.cjs');
9
+ },{"./index.cjs":1}],3:[function(require,module,exports){
10
+ "use strict";
11
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ 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;
14
+ function assertNumber(n) {
15
+ if (!Number.isSafeInteger(n))
16
+ throw new Error(`Wrong integer: ${n}`);
17
+ }
18
+ exports.assertNumber = assertNumber;
19
+ function chain(...args) {
20
+ const wrap = (a, b) => (c) => a(b(c));
21
+ const encode = Array.from(args)
22
+ .reverse()
23
+ .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);
24
+ const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);
25
+ return { encode, decode };
26
+ }
27
+ function alphabet(alphabet) {
28
+ return {
29
+ encode: (digits) => {
30
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
31
+ throw new Error('alphabet.encode input should be an array of numbers');
32
+ return digits.map((i) => {
33
+ assertNumber(i);
34
+ if (i < 0 || i >= alphabet.length)
35
+ throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);
36
+ return alphabet[i];
37
+ });
38
+ },
39
+ decode: (input) => {
40
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
41
+ throw new Error('alphabet.decode input should be array of strings');
42
+ return input.map((letter) => {
43
+ if (typeof letter !== 'string')
44
+ throw new Error(`alphabet.decode: not string element=${letter}`);
45
+ const index = alphabet.indexOf(letter);
46
+ if (index === -1)
47
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet}`);
48
+ return index;
49
+ });
50
+ },
51
+ };
52
+ }
53
+ function join(separator = '') {
54
+ if (typeof separator !== 'string')
55
+ throw new Error('join separator should be string');
56
+ return {
57
+ encode: (from) => {
58
+ if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))
59
+ throw new Error('join.encode input should be array of strings');
60
+ for (let i of from)
61
+ if (typeof i !== 'string')
62
+ throw new Error(`join.encode: non-string input=${i}`);
63
+ return from.join(separator);
64
+ },
65
+ decode: (to) => {
66
+ if (typeof to !== 'string')
67
+ throw new Error('join.decode input should be string');
68
+ return to.split(separator);
69
+ },
70
+ };
71
+ }
72
+ function padding(bits, chr = '=') {
73
+ assertNumber(bits);
74
+ if (typeof chr !== 'string')
75
+ throw new Error('padding chr should be string');
76
+ return {
77
+ encode(data) {
78
+ if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))
79
+ throw new Error('padding.encode input should be array of strings');
80
+ for (let i of data)
81
+ if (typeof i !== 'string')
82
+ throw new Error(`padding.encode: non-string input=${i}`);
83
+ while ((data.length * bits) % 8)
84
+ data.push(chr);
85
+ return data;
86
+ },
87
+ decode(input) {
88
+ if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))
89
+ throw new Error('padding.encode input should be array of strings');
90
+ for (let i of input)
91
+ if (typeof i !== 'string')
92
+ throw new Error(`padding.decode: non-string input=${i}`);
93
+ let end = input.length;
94
+ if ((end * bits) % 8)
95
+ throw new Error('Invalid padding: string should have whole number of bytes');
96
+ for (; end > 0 && input[end - 1] === chr; end--) {
97
+ if (!(((end - 1) * bits) % 8))
98
+ throw new Error('Invalid padding: string has too much padding');
99
+ }
100
+ return input.slice(0, end);
101
+ },
102
+ };
103
+ }
104
+ function normalize(fn) {
105
+ if (typeof fn !== 'function')
106
+ throw new Error('normalize fn should be function');
107
+ return { encode: (from) => from, decode: (to) => fn(to) };
108
+ }
109
+ function convertRadix(data, from, to) {
110
+ if (from < 2)
111
+ throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
112
+ if (to < 2)
113
+ throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
114
+ if (!Array.isArray(data))
115
+ throw new Error('convertRadix: data should be array');
116
+ if (!data.length)
117
+ return [];
118
+ let pos = 0;
119
+ const res = [];
120
+ const digits = Array.from(data);
121
+ digits.forEach((d) => {
122
+ assertNumber(d);
123
+ if (d < 0 || d >= from)
124
+ throw new Error(`Wrong integer: ${d}`);
125
+ });
126
+ while (true) {
127
+ let carry = 0;
128
+ let done = true;
129
+ for (let i = pos; i < digits.length; i++) {
130
+ const digit = digits[i];
131
+ const digitBase = from * carry + digit;
132
+ if (!Number.isSafeInteger(digitBase) ||
133
+ (from * carry) / from !== carry ||
134
+ digitBase - digit !== from * carry) {
135
+ throw new Error('convertRadix: carry overflow');
136
+ }
137
+ carry = digitBase % to;
138
+ digits[i] = Math.floor(digitBase / to);
139
+ if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
140
+ throw new Error('convertRadix: carry overflow');
141
+ if (!done)
142
+ continue;
143
+ else if (!digits[i])
144
+ pos = i;
145
+ else
146
+ done = false;
147
+ }
148
+ res.push(carry);
149
+ if (done)
150
+ break;
151
+ }
152
+ for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
153
+ res.push(0);
154
+ return res.reverse();
155
+ }
156
+ const gcd = (a, b) => (!b ? a : gcd(b, a % b));
157
+ const radix2carry = (from, to) => from + (to - gcd(from, to));
158
+ function convertRadix2(data, from, to, padding) {
159
+ if (!Array.isArray(data))
160
+ throw new Error('convertRadix2: data should be array');
161
+ if (from <= 0 || from > 32)
162
+ throw new Error(`convertRadix2: wrong from=${from}`);
163
+ if (to <= 0 || to > 32)
164
+ throw new Error(`convertRadix2: wrong to=${to}`);
165
+ if (radix2carry(from, to) > 32) {
166
+ throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
167
+ }
168
+ let carry = 0;
169
+ let pos = 0;
170
+ const mask = 2 ** to - 1;
171
+ const res = [];
172
+ for (const n of data) {
173
+ assertNumber(n);
174
+ if (n >= 2 ** from)
175
+ throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
176
+ carry = (carry << from) | n;
177
+ if (pos + from > 32)
178
+ throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
179
+ pos += from;
180
+ for (; pos >= to; pos -= to)
181
+ res.push(((carry >> (pos - to)) & mask) >>> 0);
182
+ carry &= 2 ** pos - 1;
183
+ }
184
+ carry = (carry << (to - pos)) & mask;
185
+ if (!padding && pos >= from)
186
+ throw new Error('Excess padding');
187
+ if (!padding && carry)
188
+ throw new Error(`Non-zero padding: ${carry}`);
189
+ if (padding && pos > 0)
190
+ res.push(carry >>> 0);
191
+ return res;
192
+ }
193
+ function radix(num) {
194
+ assertNumber(num);
195
+ return {
196
+ encode: (bytes) => {
197
+ if (!(bytes instanceof Uint8Array))
198
+ throw new Error('radix.encode input should be Uint8Array');
199
+ return convertRadix(Array.from(bytes), 2 ** 8, num);
200
+ },
201
+ decode: (digits) => {
202
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
203
+ throw new Error('radix.decode input should be array of strings');
204
+ return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
205
+ },
206
+ };
207
+ }
208
+ function radix2(bits, revPadding = false) {
209
+ assertNumber(bits);
210
+ if (bits <= 0 || bits > 32)
211
+ throw new Error('radix2: bits should be in (0..32]');
212
+ if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
213
+ throw new Error('radix2: carry overflow');
214
+ return {
215
+ encode: (bytes) => {
216
+ if (!(bytes instanceof Uint8Array))
217
+ throw new Error('radix2.encode input should be Uint8Array');
218
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
219
+ },
220
+ decode: (digits) => {
221
+ if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))
222
+ throw new Error('radix2.decode input should be array of strings');
223
+ return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
224
+ },
225
+ };
226
+ }
227
+ function unsafeWrapper(fn) {
228
+ if (typeof fn !== 'function')
229
+ throw new Error('unsafeWrapper fn should be function');
230
+ return function (...args) {
231
+ try {
232
+ return fn.apply(null, args);
233
+ }
234
+ catch (e) { }
235
+ };
236
+ }
237
+ function checksum(len, fn) {
238
+ assertNumber(len);
239
+ if (typeof fn !== 'function')
240
+ throw new Error('checksum fn should be function');
241
+ return {
242
+ encode(data) {
243
+ if (!(data instanceof Uint8Array))
244
+ throw new Error('checksum.encode: input should be Uint8Array');
245
+ const checksum = fn(data).slice(0, len);
246
+ const res = new Uint8Array(data.length + len);
247
+ res.set(data);
248
+ res.set(checksum, data.length);
249
+ return res;
250
+ },
251
+ decode(data) {
252
+ if (!(data instanceof Uint8Array))
253
+ throw new Error('checksum.decode: input should be Uint8Array');
254
+ const payload = data.slice(0, -len);
255
+ const newChecksum = fn(payload).slice(0, len);
256
+ const oldChecksum = data.slice(-len);
257
+ for (let i = 0; i < len; i++)
258
+ if (newChecksum[i] !== oldChecksum[i])
259
+ throw new Error('Invalid checksum');
260
+ return payload;
261
+ },
262
+ };
263
+ }
264
+ exports.utils = { alphabet, chain, checksum, radix, radix2, join, padding };
265
+ exports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
266
+ exports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
267
+ exports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
268
+ exports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
269
+ exports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
270
+ exports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
271
+ const genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));
272
+ exports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
273
+ exports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
274
+ exports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
275
+ const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
276
+ exports.base58xmr = {
277
+ encode(data) {
278
+ let res = '';
279
+ for (let i = 0; i < data.length; i += 8) {
280
+ const block = data.subarray(i, i + 8);
281
+ res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
282
+ }
283
+ return res;
284
+ },
285
+ decode(str) {
286
+ let res = [];
287
+ for (let i = 0; i < str.length; i += 11) {
288
+ const slice = str.slice(i, i + 11);
289
+ const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
290
+ const block = exports.base58.decode(slice);
291
+ for (let j = 0; j < block.length - blockLen; j++) {
292
+ if (block[j] !== 0)
293
+ throw new Error('base58xmr: wrong padding');
294
+ }
295
+ res = res.concat(Array.from(block.slice(block.length - blockLen)));
296
+ }
297
+ return Uint8Array.from(res);
298
+ },
299
+ };
300
+ const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);
301
+ exports.base58check = base58check;
302
+ const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
303
+ const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
304
+ function bech32Polymod(pre) {
305
+ const b = pre >> 25;
306
+ let chk = (pre & 0x1ffffff) << 5;
307
+ for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
308
+ if (((b >> i) & 1) === 1)
309
+ chk ^= POLYMOD_GENERATORS[i];
310
+ }
311
+ return chk;
312
+ }
313
+ function bechChecksum(prefix, words, encodingConst = 1) {
314
+ const len = prefix.length;
315
+ let chk = 1;
316
+ for (let i = 0; i < len; i++) {
317
+ const c = prefix.charCodeAt(i);
318
+ if (c < 33 || c > 126)
319
+ throw new Error(`Invalid prefix (${prefix})`);
320
+ chk = bech32Polymod(chk) ^ (c >> 5);
321
+ }
322
+ chk = bech32Polymod(chk);
323
+ for (let i = 0; i < len; i++)
324
+ chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
325
+ for (let v of words)
326
+ chk = bech32Polymod(chk) ^ v;
327
+ for (let i = 0; i < 6; i++)
328
+ chk = bech32Polymod(chk);
329
+ chk ^= encodingConst;
330
+ return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
331
+ }
332
+ function genBech32(encoding) {
333
+ const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
334
+ const _words = radix2(5);
335
+ const fromWords = _words.decode;
336
+ const toWords = _words.encode;
337
+ const fromWordsUnsafe = unsafeWrapper(fromWords);
338
+ function encode(prefix, words, limit = 90) {
339
+ if (typeof prefix !== 'string')
340
+ throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
341
+ if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))
342
+ throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
343
+ const actualLength = prefix.length + 7 + words.length;
344
+ if (limit !== false && actualLength > limit)
345
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
346
+ prefix = prefix.toLowerCase();
347
+ return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
348
+ }
349
+ function decode(str, limit = 90) {
350
+ if (typeof str !== 'string')
351
+ throw new Error(`bech32.decode input should be string, not ${typeof str}`);
352
+ if (str.length < 8 || (limit !== false && str.length > limit))
353
+ throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
354
+ const lowered = str.toLowerCase();
355
+ if (str !== lowered && str !== str.toUpperCase())
356
+ throw new Error(`String must be lowercase or uppercase`);
357
+ str = lowered;
358
+ const sepIndex = str.lastIndexOf('1');
359
+ if (sepIndex === 0 || sepIndex === -1)
360
+ throw new Error(`Letter "1" must be present between prefix and data only`);
361
+ const prefix = str.slice(0, sepIndex);
362
+ const _words = str.slice(sepIndex + 1);
363
+ if (_words.length < 6)
364
+ throw new Error('Data must be at least 6 characters long');
365
+ const words = BECH_ALPHABET.decode(_words).slice(0, -6);
366
+ const sum = bechChecksum(prefix, words, ENCODING_CONST);
367
+ if (!_words.endsWith(sum))
368
+ throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
369
+ return { prefix, words };
370
+ }
371
+ const decodeUnsafe = unsafeWrapper(decode);
372
+ function decodeToBytes(str) {
373
+ const { prefix, words } = decode(str, false);
374
+ return { prefix, words, bytes: fromWords(words) };
375
+ }
376
+ return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
377
+ }
378
+ exports.bech32 = genBech32('bech32');
379
+ exports.bech32m = genBech32('bech32m');
380
+ exports.utf8 = {
381
+ encode: (data) => new TextDecoder().decode(data),
382
+ decode: (str) => new TextEncoder().encode(str),
383
+ };
384
+ exports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
385
+ if (typeof s !== 'string' || s.length % 2)
386
+ throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
387
+ return s.toLowerCase();
388
+ }));
389
+ const CODERS = {
390
+ utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr
391
+ };
392
+ const coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;
393
+ const bytesToString = (type, bytes) => {
394
+ if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
395
+ throw new TypeError(coderTypeError);
396
+ if (!(bytes instanceof Uint8Array))
397
+ throw new TypeError('bytesToString() expects Uint8Array');
398
+ return CODERS[type].encode(bytes);
399
+ };
400
+ exports.bytesToString = bytesToString;
401
+ exports.str = exports.bytesToString;
402
+ const stringToBytes = (type, str) => {
403
+ if (!CODERS.hasOwnProperty(type))
404
+ throw new TypeError(coderTypeError);
405
+ if (typeof str !== 'string')
406
+ throw new TypeError('stringToBytes() expects string');
407
+ return CODERS[type].decode(str);
408
+ };
409
+ exports.stringToBytes = stringToBytes;
410
+ exports.bytes = exports.stringToBytes;
411
+
412
+ },{}],4:[function(require,module,exports){
413
+
414
+ },{}],5:[function(require,module,exports){
415
+ (function (global){(function (){
416
+ ;(function (root, factory) {
417
+ if (typeof exports === "object") {
418
+ // CommonJS
419
+ module.exports = exports = factory();
420
+ }
421
+ else if (typeof define === "function" && define.amd) {
422
+ // AMD
423
+ define([], factory);
424
+ }
425
+ else {
426
+ // Global (browser)
427
+ root.CryptoJS = factory();
428
+ }
429
+ }(this, function () {
430
+
431
+ /*globals window, global, require*/
432
+
433
+ /**
434
+ * CryptoJS core components.
435
+ */
436
+ var CryptoJS = CryptoJS || (function (Math, undefined) {
437
+
438
+ var crypto;
439
+
440
+ // Native crypto from window (Browser)
441
+ if (typeof window !== 'undefined' && window.crypto) {
442
+ crypto = window.crypto;
443
+ }
444
+
445
+ // Native crypto in web worker (Browser)
446
+ if (typeof self !== 'undefined' && self.crypto) {
447
+ crypto = self.crypto;
448
+ }
449
+
450
+ // Native crypto from worker
451
+ if (typeof globalThis !== 'undefined' && globalThis.crypto) {
452
+ crypto = globalThis.crypto;
453
+ }
454
+
455
+ // Native (experimental IE 11) crypto from window (Browser)
456
+ if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
457
+ crypto = window.msCrypto;
458
+ }
459
+
460
+ // Native crypto from global (NodeJS)
461
+ if (!crypto && typeof global !== 'undefined' && global.crypto) {
462
+ crypto = global.crypto;
463
+ }
464
+
465
+ // Native crypto import via require (NodeJS)
466
+ if (!crypto && typeof require === 'function') {
467
+ try {
468
+ crypto = require('crypto');
469
+ } catch (err) {}
470
+ }
471
+
472
+ /*
473
+ * Cryptographically secure pseudorandom number generator
474
+ *
475
+ * As Math.random() is cryptographically not safe to use
476
+ */
477
+ var cryptoSecureRandomInt = function () {
478
+ if (crypto) {
479
+ // Use getRandomValues method (Browser)
480
+ if (typeof crypto.getRandomValues === 'function') {
481
+ try {
482
+ return crypto.getRandomValues(new Uint32Array(1))[0];
483
+ } catch (err) {}
484
+ }
485
+
486
+ // Use randomBytes method (NodeJS)
487
+ if (typeof crypto.randomBytes === 'function') {
488
+ try {
489
+ return crypto.randomBytes(4).readInt32LE();
490
+ } catch (err) {}
491
+ }
492
+ }
493
+
494
+ throw new Error('Native crypto module could not be used to get secure random number.');
495
+ };
496
+
497
+ /*
498
+ * Local polyfill of Object.create
499
+
500
+ */
501
+ var create = Object.create || (function () {
502
+ function F() {}
503
+
504
+ return function (obj) {
505
+ var subtype;
506
+
507
+ F.prototype = obj;
508
+
509
+ subtype = new F();
510
+
511
+ F.prototype = null;
512
+
513
+ return subtype;
514
+ };
515
+ }());
516
+
517
+ /**
518
+ * CryptoJS namespace.
519
+ */
520
+ var C = {};
521
+
522
+ /**
523
+ * Library namespace.
524
+ */
525
+ var C_lib = C.lib = {};
526
+
527
+ /**
528
+ * Base object for prototypal inheritance.
529
+ */
530
+ var Base = C_lib.Base = (function () {
531
+
532
+
533
+ return {
534
+ /**
535
+ * Creates a new object that inherits from this object.
536
+ *
537
+ * @param {Object} overrides Properties to copy into the new object.
538
+ *
539
+ * @return {Object} The new object.
540
+ *
541
+ * @static
542
+ *
543
+ * @example
544
+ *
545
+ * var MyType = CryptoJS.lib.Base.extend({
546
+ * field: 'value',
547
+ *
548
+ * method: function () {
549
+ * }
550
+ * });
551
+ */
552
+ extend: function (overrides) {
553
+ // Spawn
554
+ var subtype = create(this);
555
+
556
+ // Augment
557
+ if (overrides) {
558
+ subtype.mixIn(overrides);
559
+ }
560
+
561
+ // Create default initializer
562
+ if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
563
+ subtype.init = function () {
564
+ subtype.$super.init.apply(this, arguments);
565
+ };
566
+ }
567
+
568
+ // Initializer's prototype is the subtype object
569
+ subtype.init.prototype = subtype;
570
+
571
+ // Reference supertype
572
+ subtype.$super = this;
573
+
574
+ return subtype;
575
+ },
576
+
577
+ /**
578
+ * Extends this object and runs the init method.
579
+ * Arguments to create() will be passed to init().
580
+ *
581
+ * @return {Object} The new object.
582
+ *
583
+ * @static
584
+ *
585
+ * @example
586
+ *
587
+ * var instance = MyType.create();
588
+ */
589
+ create: function () {
590
+ var instance = this.extend();
591
+ instance.init.apply(instance, arguments);
592
+
593
+ return instance;
594
+ },
595
+
596
+ /**
597
+ * Initializes a newly created object.
598
+ * Override this method to add some logic when your objects are created.
599
+ *
600
+ * @example
601
+ *
602
+ * var MyType = CryptoJS.lib.Base.extend({
603
+ * init: function () {
604
+ * // ...
605
+ * }
606
+ * });
607
+ */
608
+ init: function () {
609
+ },
610
+
611
+ /**
612
+ * Copies properties into this object.
613
+ *
614
+ * @param {Object} properties The properties to mix in.
615
+ *
616
+ * @example
617
+ *
618
+ * MyType.mixIn({
619
+ * field: 'value'
620
+ * });
621
+ */
622
+ mixIn: function (properties) {
623
+ for (var propertyName in properties) {
624
+ if (properties.hasOwnProperty(propertyName)) {
625
+ this[propertyName] = properties[propertyName];
626
+ }
627
+ }
628
+
629
+ // IE won't copy toString using the loop above
630
+ if (properties.hasOwnProperty('toString')) {
631
+ this.toString = properties.toString;
632
+ }
633
+ },
634
+
635
+ /**
636
+ * Creates a copy of this object.
637
+ *
638
+ * @return {Object} The clone.
639
+ *
640
+ * @example
641
+ *
642
+ * var clone = instance.clone();
643
+ */
644
+ clone: function () {
645
+ return this.init.prototype.extend(this);
646
+ }
647
+ };
648
+ }());
649
+
650
+ /**
651
+ * An array of 32-bit words.
652
+ *
653
+ * @property {Array} words The array of 32-bit words.
654
+ * @property {number} sigBytes The number of significant bytes in this word array.
655
+ */
656
+ var WordArray = C_lib.WordArray = Base.extend({
657
+ /**
658
+ * Initializes a newly created word array.
659
+ *
660
+ * @param {Array} words (Optional) An array of 32-bit words.
661
+ * @param {number} sigBytes (Optional) The number of significant bytes in the words.
662
+ *
663
+ * @example
664
+ *
665
+ * var wordArray = CryptoJS.lib.WordArray.create();
666
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
667
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
668
+ */
669
+ init: function (words, sigBytes) {
670
+ words = this.words = words || [];
671
+
672
+ if (sigBytes != undefined) {
673
+ this.sigBytes = sigBytes;
674
+ } else {
675
+ this.sigBytes = words.length * 4;
676
+ }
677
+ },
678
+
679
+ /**
680
+ * Converts this word array to a string.
681
+ *
682
+ * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
683
+ *
684
+ * @return {string} The stringified word array.
685
+ *
686
+ * @example
687
+ *
688
+ * var string = wordArray + '';
689
+ * var string = wordArray.toString();
690
+ * var string = wordArray.toString(CryptoJS.enc.Utf8);
691
+ */
692
+ toString: function (encoder) {
693
+ return (encoder || Hex).stringify(this);
694
+ },
695
+
696
+ /**
697
+ * Concatenates a word array to this word array.
698
+ *
699
+ * @param {WordArray} wordArray The word array to append.
700
+ *
701
+ * @return {WordArray} This word array.
702
+ *
703
+ * @example
704
+ *
705
+ * wordArray1.concat(wordArray2);
706
+ */
707
+ concat: function (wordArray) {
708
+ // Shortcuts
709
+ var thisWords = this.words;
710
+ var thatWords = wordArray.words;
711
+ var thisSigBytes = this.sigBytes;
712
+ var thatSigBytes = wordArray.sigBytes;
713
+
714
+ // Clamp excess bits
715
+ this.clamp();
716
+
717
+ // Concat
718
+ if (thisSigBytes % 4) {
719
+ // Copy one byte at a time
720
+ for (var i = 0; i < thatSigBytes; i++) {
721
+ var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
722
+ thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
723
+ }
724
+ } else {
725
+ // Copy one word at a time
726
+ for (var j = 0; j < thatSigBytes; j += 4) {
727
+ thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
728
+ }
729
+ }
730
+ this.sigBytes += thatSigBytes;
731
+
732
+ // Chainable
733
+ return this;
734
+ },
735
+
736
+ /**
737
+ * Removes insignificant bits.
738
+ *
739
+ * @example
740
+ *
741
+ * wordArray.clamp();
742
+ */
743
+ clamp: function () {
744
+ // Shortcuts
745
+ var words = this.words;
746
+ var sigBytes = this.sigBytes;
747
+
748
+ // Clamp
749
+ words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
750
+ words.length = Math.ceil(sigBytes / 4);
751
+ },
752
+
753
+ /**
754
+ * Creates a copy of this word array.
755
+ *
756
+ * @return {WordArray} The clone.
757
+ *
758
+ * @example
759
+ *
760
+ * var clone = wordArray.clone();
761
+ */
762
+ clone: function () {
763
+ var clone = Base.clone.call(this);
764
+ clone.words = this.words.slice(0);
765
+
766
+ return clone;
767
+ },
768
+
769
+ /**
770
+ * Creates a word array filled with random bytes.
771
+ *
772
+ * @param {number} nBytes The number of random bytes to generate.
773
+ *
774
+ * @return {WordArray} The random word array.
775
+ *
776
+ * @static
777
+ *
778
+ * @example
779
+ *
780
+ * var wordArray = CryptoJS.lib.WordArray.random(16);
781
+ */
782
+ random: function (nBytes) {
783
+ var words = [];
784
+
785
+ for (var i = 0; i < nBytes; i += 4) {
786
+ words.push(cryptoSecureRandomInt());
787
+ }
788
+
789
+ return new WordArray.init(words, nBytes);
790
+ }
791
+ });
792
+
793
+ /**
794
+ * Encoder namespace.
795
+ */
796
+ var C_enc = C.enc = {};
797
+
798
+ /**
799
+ * Hex encoding strategy.
800
+ */
801
+ var Hex = C_enc.Hex = {
802
+ /**
803
+ * Converts a word array to a hex string.
804
+ *
805
+ * @param {WordArray} wordArray The word array.
806
+ *
807
+ * @return {string} The hex string.
808
+ *
809
+ * @static
810
+ *
811
+ * @example
812
+ *
813
+ * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
814
+ */
815
+ stringify: function (wordArray) {
816
+ // Shortcuts
817
+ var words = wordArray.words;
818
+ var sigBytes = wordArray.sigBytes;
819
+
820
+ // Convert
821
+ var hexChars = [];
822
+ for (var i = 0; i < sigBytes; i++) {
823
+ var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
824
+ hexChars.push((bite >>> 4).toString(16));
825
+ hexChars.push((bite & 0x0f).toString(16));
826
+ }
827
+
828
+ return hexChars.join('');
829
+ },
830
+
831
+ /**
832
+ * Converts a hex string to a word array.
833
+ *
834
+ * @param {string} hexStr The hex string.
835
+ *
836
+ * @return {WordArray} The word array.
837
+ *
838
+ * @static
839
+ *
840
+ * @example
841
+ *
842
+ * var wordArray = CryptoJS.enc.Hex.parse(hexString);
843
+ */
844
+ parse: function (hexStr) {
845
+ // Shortcut
846
+ var hexStrLength = hexStr.length;
847
+
848
+ // Convert
849
+ var words = [];
850
+ for (var i = 0; i < hexStrLength; i += 2) {
851
+ words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
852
+ }
853
+
854
+ return new WordArray.init(words, hexStrLength / 2);
855
+ }
856
+ };
857
+
858
+ /**
859
+ * Latin1 encoding strategy.
860
+ */
861
+ var Latin1 = C_enc.Latin1 = {
862
+ /**
863
+ * Converts a word array to a Latin1 string.
864
+ *
865
+ * @param {WordArray} wordArray The word array.
866
+ *
867
+ * @return {string} The Latin1 string.
868
+ *
869
+ * @static
870
+ *
871
+ * @example
872
+ *
873
+ * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
874
+ */
875
+ stringify: function (wordArray) {
876
+ // Shortcuts
877
+ var words = wordArray.words;
878
+ var sigBytes = wordArray.sigBytes;
879
+
880
+ // Convert
881
+ var latin1Chars = [];
882
+ for (var i = 0; i < sigBytes; i++) {
883
+ var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
884
+ latin1Chars.push(String.fromCharCode(bite));
885
+ }
886
+
887
+ return latin1Chars.join('');
888
+ },
889
+
890
+ /**
891
+ * Converts a Latin1 string to a word array.
892
+ *
893
+ * @param {string} latin1Str The Latin1 string.
894
+ *
895
+ * @return {WordArray} The word array.
896
+ *
897
+ * @static
898
+ *
899
+ * @example
900
+ *
901
+ * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
902
+ */
903
+ parse: function (latin1Str) {
904
+ // Shortcut
905
+ var latin1StrLength = latin1Str.length;
906
+
907
+ // Convert
908
+ var words = [];
909
+ for (var i = 0; i < latin1StrLength; i++) {
910
+ words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
911
+ }
912
+
913
+ return new WordArray.init(words, latin1StrLength);
914
+ }
915
+ };
916
+
917
+ /**
918
+ * UTF-8 encoding strategy.
919
+ */
920
+ var Utf8 = C_enc.Utf8 = {
921
+ /**
922
+ * Converts a word array to a UTF-8 string.
923
+ *
924
+ * @param {WordArray} wordArray The word array.
925
+ *
926
+ * @return {string} The UTF-8 string.
927
+ *
928
+ * @static
929
+ *
930
+ * @example
931
+ *
932
+ * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
933
+ */
934
+ stringify: function (wordArray) {
935
+ try {
936
+ return decodeURIComponent(escape(Latin1.stringify(wordArray)));
937
+ } catch (e) {
938
+ throw new Error('Malformed UTF-8 data');
939
+ }
940
+ },
941
+
942
+ /**
943
+ * Converts a UTF-8 string to a word array.
944
+ *
945
+ * @param {string} utf8Str The UTF-8 string.
946
+ *
947
+ * @return {WordArray} The word array.
948
+ *
949
+ * @static
950
+ *
951
+ * @example
952
+ *
953
+ * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
954
+ */
955
+ parse: function (utf8Str) {
956
+ return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
957
+ }
958
+ };
959
+
960
+ /**
961
+ * Abstract buffered block algorithm template.
962
+ *
963
+ * The property blockSize must be implemented in a concrete subtype.
964
+ *
965
+ * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
966
+ */
967
+ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
968
+ /**
969
+ * Resets this block algorithm's data buffer to its initial state.
970
+ *
971
+ * @example
972
+ *
973
+ * bufferedBlockAlgorithm.reset();
974
+ */
975
+ reset: function () {
976
+ // Initial values
977
+ this._data = new WordArray.init();
978
+ this._nDataBytes = 0;
979
+ },
980
+
981
+ /**
982
+ * Adds new data to this block algorithm's buffer.
983
+ *
984
+ * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
985
+ *
986
+ * @example
987
+ *
988
+ * bufferedBlockAlgorithm._append('data');
989
+ * bufferedBlockAlgorithm._append(wordArray);
990
+ */
991
+ _append: function (data) {
992
+ // Convert string to WordArray, else assume WordArray already
993
+ if (typeof data == 'string') {
994
+ data = Utf8.parse(data);
995
+ }
996
+
997
+ // Append
998
+ this._data.concat(data);
999
+ this._nDataBytes += data.sigBytes;
1000
+ },
1001
+
1002
+ /**
1003
+ * Processes available data blocks.
1004
+ *
1005
+ * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
1006
+ *
1007
+ * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
1008
+ *
1009
+ * @return {WordArray} The processed data.
1010
+ *
1011
+ * @example
1012
+ *
1013
+ * var processedData = bufferedBlockAlgorithm._process();
1014
+ * var processedData = bufferedBlockAlgorithm._process(!!'flush');
1015
+ */
1016
+ _process: function (doFlush) {
1017
+ var processedWords;
1018
+
1019
+ // Shortcuts
1020
+ var data = this._data;
1021
+ var dataWords = data.words;
1022
+ var dataSigBytes = data.sigBytes;
1023
+ var blockSize = this.blockSize;
1024
+ var blockSizeBytes = blockSize * 4;
1025
+
1026
+ // Count blocks ready
1027
+ var nBlocksReady = dataSigBytes / blockSizeBytes;
1028
+ if (doFlush) {
1029
+ // Round up to include partial blocks
1030
+ nBlocksReady = Math.ceil(nBlocksReady);
1031
+ } else {
1032
+ // Round down to include only full blocks,
1033
+ // less the number of blocks that must remain in the buffer
1034
+ nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
1035
+ }
1036
+
1037
+ // Count words ready
1038
+ var nWordsReady = nBlocksReady * blockSize;
1039
+
1040
+ // Count bytes ready
1041
+ var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
1042
+
1043
+ // Process blocks
1044
+ if (nWordsReady) {
1045
+ for (var offset = 0; offset < nWordsReady; offset += blockSize) {
1046
+ // Perform concrete-algorithm logic
1047
+ this._doProcessBlock(dataWords, offset);
1048
+ }
1049
+
1050
+ // Remove processed words
1051
+ processedWords = dataWords.splice(0, nWordsReady);
1052
+ data.sigBytes -= nBytesReady;
1053
+ }
1054
+
1055
+ // Return processed words
1056
+ return new WordArray.init(processedWords, nBytesReady);
1057
+ },
1058
+
1059
+ /**
1060
+ * Creates a copy of this object.
1061
+ *
1062
+ * @return {Object} The clone.
1063
+ *
1064
+ * @example
1065
+ *
1066
+ * var clone = bufferedBlockAlgorithm.clone();
1067
+ */
1068
+ clone: function () {
1069
+ var clone = Base.clone.call(this);
1070
+ clone._data = this._data.clone();
1071
+
1072
+ return clone;
1073
+ },
1074
+
1075
+ _minBufferSize: 0
1076
+ });
1077
+
1078
+ /**
1079
+ * Abstract hasher template.
1080
+ *
1081
+ * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
1082
+ */
1083
+ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
1084
+ /**
1085
+ * Configuration options.
1086
+ */
1087
+ cfg: Base.extend(),
1088
+
1089
+ /**
1090
+ * Initializes a newly created hasher.
1091
+ *
1092
+ * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
1093
+ *
1094
+ * @example
1095
+ *
1096
+ * var hasher = CryptoJS.algo.SHA256.create();
1097
+ */
1098
+ init: function (cfg) {
1099
+ // Apply config defaults
1100
+ this.cfg = this.cfg.extend(cfg);
1101
+
1102
+ // Set initial values
1103
+ this.reset();
1104
+ },
1105
+
1106
+ /**
1107
+ * Resets this hasher to its initial state.
1108
+ *
1109
+ * @example
1110
+ *
1111
+ * hasher.reset();
1112
+ */
1113
+ reset: function () {
1114
+ // Reset data buffer
1115
+ BufferedBlockAlgorithm.reset.call(this);
1116
+
1117
+ // Perform concrete-hasher logic
1118
+ this._doReset();
1119
+ },
1120
+
1121
+ /**
1122
+ * Updates this hasher with a message.
1123
+ *
1124
+ * @param {WordArray|string} messageUpdate The message to append.
1125
+ *
1126
+ * @return {Hasher} This hasher.
1127
+ *
1128
+ * @example
1129
+ *
1130
+ * hasher.update('message');
1131
+ * hasher.update(wordArray);
1132
+ */
1133
+ update: function (messageUpdate) {
1134
+ // Append
1135
+ this._append(messageUpdate);
1136
+
1137
+ // Update the hash
1138
+ this._process();
1139
+
1140
+ // Chainable
1141
+ return this;
1142
+ },
1143
+
1144
+ /**
1145
+ * Finalizes the hash computation.
1146
+ * Note that the finalize operation is effectively a destructive, read-once operation.
1147
+ *
1148
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
1149
+ *
1150
+ * @return {WordArray} The hash.
1151
+ *
1152
+ * @example
1153
+ *
1154
+ * var hash = hasher.finalize();
1155
+ * var hash = hasher.finalize('message');
1156
+ * var hash = hasher.finalize(wordArray);
1157
+ */
1158
+ finalize: function (messageUpdate) {
1159
+ // Final message update
1160
+ if (messageUpdate) {
1161
+ this._append(messageUpdate);
1162
+ }
1163
+
1164
+ // Perform concrete-hasher logic
1165
+ var hash = this._doFinalize();
1166
+
1167
+ return hash;
1168
+ },
1169
+
1170
+ blockSize: 512/32,
1171
+
1172
+ /**
1173
+ * Creates a shortcut function to a hasher's object interface.
1174
+ *
1175
+ * @param {Hasher} hasher The hasher to create a helper for.
1176
+ *
1177
+ * @return {Function} The shortcut function.
1178
+ *
1179
+ * @static
1180
+ *
1181
+ * @example
1182
+ *
1183
+ * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
1184
+ */
1185
+ _createHelper: function (hasher) {
1186
+ return function (message, cfg) {
1187
+ return new hasher.init(cfg).finalize(message);
1188
+ };
1189
+ },
1190
+
1191
+ /**
1192
+ * Creates a shortcut function to the HMAC's object interface.
1193
+ *
1194
+ * @param {Hasher} hasher The hasher to use in this HMAC helper.
1195
+ *
1196
+ * @return {Function} The shortcut function.
1197
+ *
1198
+ * @static
1199
+ *
1200
+ * @example
1201
+ *
1202
+ * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
1203
+ */
1204
+ _createHmacHelper: function (hasher) {
1205
+ return function (message, key) {
1206
+ return new C_algo.HMAC.init(hasher, key).finalize(message);
1207
+ };
1208
+ }
1209
+ });
1210
+
1211
+ /**
1212
+ * Algorithm namespace.
1213
+ */
1214
+ var C_algo = C.algo = {};
1215
+
1216
+ return C;
1217
+ }(Math));
1218
+
1219
+
1220
+ return CryptoJS;
1221
+
1222
+ }));
1223
+ }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
1224
+ },{"crypto":4}],6:[function(require,module,exports){
1225
+ ;(function (root, factory) {
1226
+ if (typeof exports === "object") {
1227
+ // CommonJS
1228
+ module.exports = exports = factory(require("./core"));
1229
+ }
1230
+ else if (typeof define === "function" && define.amd) {
1231
+ // AMD
1232
+ define(["./core"], factory);
1233
+ }
1234
+ else {
1235
+ // Global (browser)
1236
+ factory(root.CryptoJS);
1237
+ }
1238
+ }(this, function (CryptoJS) {
1239
+
1240
+ return CryptoJS.enc.Hex;
1241
+
1242
+ }));
1243
+ },{"./core":5}],7:[function(require,module,exports){
1244
+ ;(function (root, factory) {
1245
+ if (typeof exports === "object") {
1246
+ // CommonJS
1247
+ module.exports = exports = factory(require("./core"));
1248
+ }
1249
+ else if (typeof define === "function" && define.amd) {
1250
+ // AMD
1251
+ define(["./core"], factory);
1252
+ }
1253
+ else {
1254
+ // Global (browser)
1255
+ factory(root.CryptoJS);
1256
+ }
1257
+ }(this, function (CryptoJS) {
1258
+
1259
+ (function (Math) {
1260
+ // Shortcuts
1261
+ var C = CryptoJS;
1262
+ var C_lib = C.lib;
1263
+ var WordArray = C_lib.WordArray;
1264
+ var Hasher = C_lib.Hasher;
1265
+ var C_algo = C.algo;
1266
+
1267
+ // Initialization and round constants tables
1268
+ var H = [];
1269
+ var K = [];
1270
+
1271
+ // Compute constants
1272
+ (function () {
1273
+ function isPrime(n) {
1274
+ var sqrtN = Math.sqrt(n);
1275
+ for (var factor = 2; factor <= sqrtN; factor++) {
1276
+ if (!(n % factor)) {
1277
+ return false;
1278
+ }
1279
+ }
1280
+
1281
+ return true;
1282
+ }
1283
+
1284
+ function getFractionalBits(n) {
1285
+ return ((n - (n | 0)) * 0x100000000) | 0;
1286
+ }
1287
+
1288
+ var n = 2;
1289
+ var nPrime = 0;
1290
+ while (nPrime < 64) {
1291
+ if (isPrime(n)) {
1292
+ if (nPrime < 8) {
1293
+ H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
1294
+ }
1295
+ K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
1296
+
1297
+ nPrime++;
1298
+ }
1299
+
1300
+ n++;
1301
+ }
1302
+ }());
1303
+
1304
+ // Reusable object
1305
+ var W = [];
1306
+
1307
+ /**
1308
+ * SHA-256 hash algorithm.
1309
+ */
1310
+ var SHA256 = C_algo.SHA256 = Hasher.extend({
1311
+ _doReset: function () {
1312
+ this._hash = new WordArray.init(H.slice(0));
1313
+ },
1314
+
1315
+ _doProcessBlock: function (M, offset) {
1316
+ // Shortcut
1317
+ var H = this._hash.words;
1318
+
1319
+ // Working variables
1320
+ var a = H[0];
1321
+ var b = H[1];
1322
+ var c = H[2];
1323
+ var d = H[3];
1324
+ var e = H[4];
1325
+ var f = H[5];
1326
+ var g = H[6];
1327
+ var h = H[7];
1328
+
1329
+ // Computation
1330
+ for (var i = 0; i < 64; i++) {
1331
+ if (i < 16) {
1332
+ W[i] = M[offset + i] | 0;
1333
+ } else {
1334
+ var gamma0x = W[i - 15];
1335
+ var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
1336
+ ((gamma0x << 14) | (gamma0x >>> 18)) ^
1337
+ (gamma0x >>> 3);
1338
+
1339
+ var gamma1x = W[i - 2];
1340
+ var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
1341
+ ((gamma1x << 13) | (gamma1x >>> 19)) ^
1342
+ (gamma1x >>> 10);
1343
+
1344
+ W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
1345
+ }
1346
+
1347
+ var ch = (e & f) ^ (~e & g);
1348
+ var maj = (a & b) ^ (a & c) ^ (b & c);
1349
+
1350
+ var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
1351
+ var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
1352
+
1353
+ var t1 = h + sigma1 + ch + K[i] + W[i];
1354
+ var t2 = sigma0 + maj;
1355
+
1356
+ h = g;
1357
+ g = f;
1358
+ f = e;
1359
+ e = (d + t1) | 0;
1360
+ d = c;
1361
+ c = b;
1362
+ b = a;
1363
+ a = (t1 + t2) | 0;
1364
+ }
1365
+
1366
+ // Intermediate hash value
1367
+ H[0] = (H[0] + a) | 0;
1368
+ H[1] = (H[1] + b) | 0;
1369
+ H[2] = (H[2] + c) | 0;
1370
+ H[3] = (H[3] + d) | 0;
1371
+ H[4] = (H[4] + e) | 0;
1372
+ H[5] = (H[5] + f) | 0;
1373
+ H[6] = (H[6] + g) | 0;
1374
+ H[7] = (H[7] + h) | 0;
1375
+ },
1376
+
1377
+ _doFinalize: function () {
1378
+ // Shortcuts
1379
+ var data = this._data;
1380
+ var dataWords = data.words;
1381
+
1382
+ var nBitsTotal = this._nDataBytes * 8;
1383
+ var nBitsLeft = data.sigBytes * 8;
1384
+
1385
+ // Add padding
1386
+ dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
1387
+ dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
1388
+ dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
1389
+ data.sigBytes = dataWords.length * 4;
1390
+
1391
+ // Hash final blocks
1392
+ this._process();
1393
+
1394
+ // Return final computed hash
1395
+ return this._hash;
1396
+ },
1397
+
1398
+ clone: function () {
1399
+ var clone = Hasher.clone.call(this);
1400
+ clone._hash = this._hash.clone();
1401
+
1402
+ return clone;
1403
+ }
1404
+ });
1405
+
1406
+ /**
1407
+ * Shortcut function to the hasher's object interface.
1408
+ *
1409
+ * @param {WordArray|string} message The message to hash.
1410
+ *
1411
+ * @return {WordArray} The hash.
1412
+ *
1413
+ * @static
1414
+ *
1415
+ * @example
1416
+ *
1417
+ * var hash = CryptoJS.SHA256('message');
1418
+ * var hash = CryptoJS.SHA256(wordArray);
1419
+ */
1420
+ C.SHA256 = Hasher._createHelper(SHA256);
1421
+
1422
+ /**
1423
+ * Shortcut function to the HMAC's object interface.
1424
+ *
1425
+ * @param {WordArray|string} message The message to hash.
1426
+ * @param {WordArray|string} key The secret key.
1427
+ *
1428
+ * @return {WordArray} The HMAC.
1429
+ *
1430
+ * @static
1431
+ *
1432
+ * @example
1433
+ *
1434
+ * var hmac = CryptoJS.HmacSHA256(message, key);
1435
+ */
1436
+ C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
1437
+ }(Math));
1438
+
1439
+
1440
+ return CryptoJS.SHA256;
1441
+
1442
+ }));
1443
+ },{"./core":5}],8:[function(require,module,exports){
1444
+ const {bech32, hex, utf8} = require('@scure/base')
1445
+
1446
+ // defaults for encode; default timestamp is current time at call
1447
+ const DEFAULTNETWORK = {
1448
+ // default network is bitcoin
1449
+ bech32: 'bc',
1450
+ pubKeyHash: 0x00,
1451
+ scriptHash: 0x05,
1452
+ validWitnessVersions: [0]
1453
+ }
1454
+ const TESTNETWORK = {
1455
+ bech32: 'tb',
1456
+ pubKeyHash: 0x6f,
1457
+ scriptHash: 0xc4,
1458
+ validWitnessVersions: [0]
1459
+ }
1460
+ const REGTESTNETWORK = {
1461
+ bech32: 'bcrt',
1462
+ pubKeyHash: 0x6f,
1463
+ scriptHash: 0xc4,
1464
+ validWitnessVersions: [0]
1465
+ }
1466
+ const SIMNETWORK = {
1467
+ bech32: 'sb',
1468
+ pubKeyHash: 0x3f,
1469
+ scriptHash: 0x7b,
1470
+ validWitnessVersions: [0]
1471
+ }
1472
+
1473
+ const FEATUREBIT_ORDER = [
1474
+ 'option_data_loss_protect',
1475
+ 'initial_routing_sync',
1476
+ 'option_upfront_shutdown_script',
1477
+ 'gossip_queries',
1478
+ 'var_onion_optin',
1479
+ 'gossip_queries_ex',
1480
+ 'option_static_remotekey',
1481
+ 'payment_secret',
1482
+ 'basic_mpp',
1483
+ 'option_support_large_channel'
1484
+ ]
1485
+
1486
+ const DIVISORS = {
1487
+ m: BigInt(1e3),
1488
+ u: BigInt(1e6),
1489
+ n: BigInt(1e9),
1490
+ p: BigInt(1e12)
1491
+ }
1492
+
1493
+ const MAX_MILLISATS = BigInt('2100000000000000000')
1494
+
1495
+ const MILLISATS_PER_BTC = BigInt(1e11)
1496
+
1497
+ const TAGCODES = {
1498
+ payment_hash: 1,
1499
+ payment_secret: 16,
1500
+ description: 13,
1501
+ payee: 19,
1502
+ description_hash: 23, // commit to longer descriptions (used by lnurl-pay)
1503
+ expiry: 6, // default: 3600 (1 hour)
1504
+ min_final_cltv_expiry: 24, // default: 9
1505
+ fallback_address: 9,
1506
+ route_hint: 3, // for extra routing info (private etc.)
1507
+ feature_bits: 5,
1508
+ metadata: 27
1509
+ }
1510
+
1511
+ // reverse the keys and values of TAGCODES and insert into TAGNAMES
1512
+ const TAGNAMES = {}
1513
+ for (let i = 0, keys = Object.keys(TAGCODES); i < keys.length; i++) {
1514
+ const currentName = keys[i]
1515
+ const currentCode = TAGCODES[keys[i]].toString()
1516
+ TAGNAMES[currentCode] = currentName
1517
+ }
1518
+
1519
+ const TAGPARSERS = {
1520
+ 1: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
1521
+ 16: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
1522
+ 13: words => utf8.encode(bech32.fromWordsUnsafe(words)), // string variable length
1523
+ 19: words => hex.encode(bech32.fromWordsUnsafe(words)), // 264 bits
1524
+ 23: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits
1525
+ 27: words => hex.encode(bech32.fromWordsUnsafe(words)), // variable
1526
+ 6: wordsToIntBE, // default: 3600 (1 hour)
1527
+ 24: wordsToIntBE, // default: 9
1528
+ 3: routingInfoParser, // for extra routing info (private etc.)
1529
+ 5: featureBitsParser // keep feature bits as array of 5 bit words
1530
+ }
1531
+
1532
+ function getUnknownParser(tagCode) {
1533
+ return words => ({
1534
+ tagCode: parseInt(tagCode),
1535
+ words: bech32.encode('unknown', words, Number.MAX_SAFE_INTEGER)
1536
+ })
1537
+ }
1538
+
1539
+ function wordsToIntBE(words) {
1540
+ return words.reverse().reduce((total, item, index) => {
1541
+ return total + item * Math.pow(32, index)
1542
+ }, 0)
1543
+ }
1544
+
1545
+ // first convert from words to buffer, trimming padding where necessary
1546
+ // parse in 51 byte chunks. See encoder for details.
1547
+ function routingInfoParser(words) {
1548
+ const routes = []
1549
+ let pubkey,
1550
+ shortChannelId,
1551
+ feeBaseMSats,
1552
+ feeProportionalMillionths,
1553
+ cltvExpiryDelta
1554
+ let routesBuffer = bech32.fromWordsUnsafe(words)
1555
+ while (routesBuffer.length > 0) {
1556
+ pubkey = hex.encode(routesBuffer.slice(0, 33)) // 33 bytes
1557
+ shortChannelId = hex.encode(routesBuffer.slice(33, 41)) // 8 bytes
1558
+ feeBaseMSats = parseInt(hex.encode(routesBuffer.slice(41, 45)), 16) // 4 bytes
1559
+ feeProportionalMillionths = parseInt(
1560
+ hex.encode(routesBuffer.slice(45, 49)),
1561
+ 16
1562
+ ) // 4 bytes
1563
+ cltvExpiryDelta = parseInt(hex.encode(routesBuffer.slice(49, 51)), 16) // 2 bytes
1564
+
1565
+ routesBuffer = routesBuffer.slice(51)
1566
+
1567
+ routes.push({
1568
+ pubkey,
1569
+ short_channel_id: shortChannelId,
1570
+ fee_base_msat: feeBaseMSats,
1571
+ fee_proportional_millionths: feeProportionalMillionths,
1572
+ cltv_expiry_delta: cltvExpiryDelta
1573
+ })
1574
+ }
1575
+ return routes
1576
+ }
1577
+
1578
+ function featureBitsParser(words) {
1579
+ const bools = words
1580
+ .slice()
1581
+ .reverse()
1582
+ .map(word => [
1583
+ !!(word & 0b1),
1584
+ !!(word & 0b10),
1585
+ !!(word & 0b100),
1586
+ !!(word & 0b1000),
1587
+ !!(word & 0b10000)
1588
+ ])
1589
+ .reduce((finalArr, itemArr) => finalArr.concat(itemArr), [])
1590
+ while (bools.length < FEATUREBIT_ORDER.length * 2) {
1591
+ bools.push(false)
1592
+ }
1593
+
1594
+ const featureBits = {}
1595
+
1596
+ FEATUREBIT_ORDER.forEach((featureName, index) => {
1597
+ let status
1598
+ if (bools[index * 2]) {
1599
+ status = 'required'
1600
+ } else if (bools[index * 2 + 1]) {
1601
+ status = 'supported'
1602
+ } else {
1603
+ status = 'unsupported'
1604
+ }
1605
+ featureBits[featureName] = status
1606
+ })
1607
+
1608
+ const extraBits = bools.slice(FEATUREBIT_ORDER.length * 2)
1609
+ featureBits.extra_bits = {
1610
+ start_bit: FEATUREBIT_ORDER.length * 2,
1611
+ bits: extraBits,
1612
+ has_required: extraBits.reduce(
1613
+ (result, bit, index) =>
1614
+ index % 2 !== 0 ? result || false : result || bit,
1615
+ false
1616
+ )
1617
+ }
1618
+
1619
+ return featureBits
1620
+ }
1621
+
1622
+ function hrpToMillisat(hrpString, outputString) {
1623
+ let divisor, value
1624
+ if (hrpString.slice(-1).match(/^[munp]$/)) {
1625
+ divisor = hrpString.slice(-1)
1626
+ value = hrpString.slice(0, -1)
1627
+ } else if (hrpString.slice(-1).match(/^[^munp0-9]$/)) {
1628
+ throw new Error('Not a valid multiplier for the amount')
1629
+ } else {
1630
+ value = hrpString
1631
+ }
1632
+
1633
+ if (!value.match(/^\d+$/))
1634
+ throw new Error('Not a valid human readable amount')
1635
+
1636
+ const valueBN = BigInt(value)
1637
+
1638
+ const millisatoshisBN = divisor
1639
+ ? (valueBN * MILLISATS_PER_BTC) / DIVISORS[divisor]
1640
+ : valueBN * MILLISATS_PER_BTC
1641
+
1642
+ if (
1643
+ (divisor === 'p' && !(valueBN % BigInt(10) === BigInt(0))) ||
1644
+ millisatoshisBN > MAX_MILLISATS
1645
+ ) {
1646
+ throw new Error('Amount is outside of valid range')
1647
+ }
1648
+
1649
+ return outputString ? millisatoshisBN.toString() : millisatoshisBN
1650
+ }
1651
+
1652
+ // decode will only have extra comments that aren't covered in encode comments.
1653
+ // also if anything is hard to read I'll comment.
1654
+ function decode(paymentRequest, network) {
1655
+ if (typeof paymentRequest !== 'string')
1656
+ throw new Error('Lightning Payment Request must be string')
1657
+ if (paymentRequest.slice(0, 2).toLowerCase() !== 'ln')
1658
+ throw new Error('Not a proper lightning payment request')
1659
+
1660
+ const sections = []
1661
+ const decoded = bech32.decode(paymentRequest, Number.MAX_SAFE_INTEGER)
1662
+ paymentRequest = paymentRequest.toLowerCase()
1663
+ const prefix = decoded.prefix
1664
+ let words = decoded.words
1665
+ let letters = paymentRequest.slice(prefix.length + 1)
1666
+ let sigWords = words.slice(-104)
1667
+ words = words.slice(0, -104)
1668
+
1669
+ // Without reverse lookups, can't say that the multipier at the end must
1670
+ // have a number before it, so instead we parse, and if the second group
1671
+ // doesn't have anything, there's a good chance the last letter of the
1672
+ // coin type got captured by the third group, so just re-regex without
1673
+ // the number.
1674
+ let prefixMatches = prefix.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/)
1675
+ if (prefixMatches && !prefixMatches[2])
1676
+ prefixMatches = prefix.match(/^ln(\S+)$/)
1677
+ if (!prefixMatches) {
1678
+ throw new Error('Not a proper lightning payment request')
1679
+ }
1680
+
1681
+ // "ln" section
1682
+ sections.push({
1683
+ name: 'lightning_network',
1684
+ letters: 'ln'
1685
+ })
1686
+
1687
+ // "bc" section
1688
+ const bech32Prefix = prefixMatches[1]
1689
+ let coinNetwork
1690
+ if (!network) {
1691
+ switch (bech32Prefix) {
1692
+ case DEFAULTNETWORK.bech32:
1693
+ coinNetwork = DEFAULTNETWORK
1694
+ break
1695
+ case TESTNETWORK.bech32:
1696
+ coinNetwork = TESTNETWORK
1697
+ break
1698
+ case REGTESTNETWORK.bech32:
1699
+ coinNetwork = REGTESTNETWORK
1700
+ break
1701
+ case SIMNETWORK.bech32:
1702
+ coinNetwork = SIMNETWORK
1703
+ break
1704
+ }
1705
+ } else {
1706
+ if (
1707
+ network.bech32 === undefined ||
1708
+ network.pubKeyHash === undefined ||
1709
+ network.scriptHash === undefined ||
1710
+ !Array.isArray(network.validWitnessVersions)
1711
+ )
1712
+ throw new Error('Invalid network')
1713
+ coinNetwork = network
1714
+ }
1715
+ if (!coinNetwork || coinNetwork.bech32 !== bech32Prefix) {
1716
+ throw new Error('Unknown coin bech32 prefix')
1717
+ }
1718
+ sections.push({
1719
+ name: 'coin_network',
1720
+ letters: bech32Prefix,
1721
+ value: coinNetwork
1722
+ })
1723
+
1724
+ // amount section
1725
+ const value = prefixMatches[2]
1726
+ let millisatoshis
1727
+ if (value) {
1728
+ const divisor = prefixMatches[3]
1729
+ millisatoshis = hrpToMillisat(value + divisor, true)
1730
+ sections.push({
1731
+ name: 'amount',
1732
+ letters: prefixMatches[2] + prefixMatches[3],
1733
+ value: millisatoshis
1734
+ })
1735
+ } else {
1736
+ millisatoshis = null
1737
+ }
1738
+
1739
+ // "1" separator
1740
+ sections.push({
1741
+ name: 'separator',
1742
+ letters: '1'
1743
+ })
1744
+
1745
+ // timestamp
1746
+ const timestamp = wordsToIntBE(words.slice(0, 7))
1747
+ words = words.slice(7) // trim off the left 7 words
1748
+ sections.push({
1749
+ name: 'timestamp',
1750
+ letters: letters.slice(0, 7),
1751
+ value: timestamp
1752
+ })
1753
+ letters = letters.slice(7)
1754
+
1755
+ let tagName, parser, tagLength, tagWords
1756
+ // we have no tag count to go on, so just keep hacking off words
1757
+ // until we have none.
1758
+ while (words.length > 0) {
1759
+ const tagCode = words[0].toString()
1760
+ tagName = TAGNAMES[tagCode] || 'unknown_tag'
1761
+ parser = TAGPARSERS[tagCode] || getUnknownParser(tagCode)
1762
+ words = words.slice(1)
1763
+
1764
+ tagLength = wordsToIntBE(words.slice(0, 2))
1765
+ words = words.slice(2)
1766
+
1767
+ tagWords = words.slice(0, tagLength)
1768
+ words = words.slice(tagLength)
1769
+
1770
+ sections.push({
1771
+ name: tagName,
1772
+ tag: letters[0],
1773
+ letters: letters.slice(0, 1 + 2 + tagLength),
1774
+ value: parser(tagWords) // see: parsers for more comments
1775
+ })
1776
+ letters = letters.slice(1 + 2 + tagLength)
1777
+ }
1778
+
1779
+ // signature
1780
+ sections.push({
1781
+ name: 'signature',
1782
+ letters: letters.slice(0, 104),
1783
+ value: hex.encode(bech32.fromWordsUnsafe(sigWords))
1784
+ })
1785
+ letters = letters.slice(104)
1786
+
1787
+ // checksum
1788
+ sections.push({
1789
+ name: 'checksum',
1790
+ letters: letters
1791
+ })
1792
+
1793
+ let result = {
1794
+ paymentRequest,
1795
+ sections,
1796
+
1797
+ get expiry() {
1798
+ let exp = sections.find(s => s.name === 'expiry')
1799
+ if (exp) return getValue('timestamp') + exp.value
1800
+ },
1801
+
1802
+ get route_hints() {
1803
+ return sections.filter(s => s.name === 'route_hint').map(s => s.value)
1804
+ }
1805
+ }
1806
+
1807
+ for (let name in TAGCODES) {
1808
+ if (name === 'route_hint') {
1809
+ // route hints can be multiple, so this won't work for them
1810
+ continue
1811
+ }
1812
+
1813
+ Object.defineProperty(result, name, {
1814
+ get() {
1815
+ return getValue(name)
1816
+ }
1817
+ })
1818
+ }
1819
+
1820
+ return result
1821
+
1822
+ function getValue(name) {
1823
+ let section = sections.find(s => s.name === name)
1824
+ return section ? section.value : undefined
1825
+ }
1826
+ }
1827
+
1828
+ module.exports = {
1829
+ decode,
1830
+ hrpToMillisat
1831
+ }
1832
+
1833
+ },{"@scure/base":3}]},{},[2]);